Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / webapp / app / fusion / notebook-integration / scripts / dependency / angular.js
1 /**
2  * @license AngularJS v1.5.0-beta.2
3  * (c) 2010-2015 Google, Inc. http://angularjs.org
4  * License: MIT
5  */
6 (function(window, document, undefined) {'use strict';
7
8 /**
9  * @description
10  *
11  * This object provides a utility for producing rich Error messages within
12  * Angular. It can be called as follows:
13  *
14  * var exampleMinErr = minErr('example');
15  * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
16  *
17  * The above creates an instance of minErr in the example namespace. The
18  * resulting error will have a namespaced error code of example.one.  The
19  * resulting error will replace {0} with the value of foo, and {1} with the
20  * value of bar. The object is not restricted in the number of arguments it can
21  * take.
22  *
23  * If fewer arguments are specified than necessary for interpolation, the extra
24  * interpolation markers will be preserved in the final string.
25  *
26  * Since data will be parsed statically during a build step, some restrictions
27  * are applied with respect to how minErr instances are created and called.
28  * Instances should have names of the form namespaceMinErr for a minErr created
29  * using minErr('namespace') . Error codes, namespaces and template strings
30  * should all be static strings, not variables or general expressions.
31  *
32  * @param {string} module The namespace to use for the new minErr instance.
33  * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
34  *   error from returned function, for cases when a particular type of error is useful.
35  * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
36  */
37
38 function minErr(module, ErrorConstructor) {
39   ErrorConstructor = ErrorConstructor || Error;
40   return function() {
41     var SKIP_INDEXES = 2;
42
43     var templateArgs = arguments,
44       code = templateArgs[0],
45       message = '[' + (module ? module + ':' : '') + code + '] ',
46       template = templateArgs[1],
47       paramPrefix, i;
48
49     message += template.replace(/\{\d+\}/g, function(match) {
50       var index = +match.slice(1, -1),
51         shiftedIndex = index + SKIP_INDEXES;
52
53       if (shiftedIndex < templateArgs.length) {
54         return toDebugString(templateArgs[shiftedIndex]);
55       }
56
57       return match;
58     });
59
60     message += '\nhttp://errors.angularjs.org/1.5.0-beta.2/' +
61       (module ? module + '/' : '') + code;
62
63     for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
64       message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
65         encodeURIComponent(toDebugString(templateArgs[i]));
66     }
67
68     return new ErrorConstructor(message);
69   };
70 }
71
72 /* We need to tell jshint what variables are being exported */
73 /* global angular: true,
74   msie: true,
75   jqLite: true,
76   jQuery: true,
77   slice: true,
78   splice: true,
79   push: true,
80   toString: true,
81   ngMinErr: true,
82   angularModule: true,
83   uid: true,
84   REGEX_STRING_REGEXP: true,
85   VALIDITY_STATE_PROPERTY: true,
86
87   lowercase: true,
88   uppercase: true,
89   manualLowercase: true,
90   manualUppercase: true,
91   nodeName_: true,
92   isArrayLike: true,
93   forEach: true,
94   forEachSorted: true,
95   reverseParams: true,
96   nextUid: true,
97   setHashKey: true,
98   extend: true,
99   toInt: true,
100   inherit: true,
101   merge: true,
102   noop: true,
103   identity: true,
104   valueFn: true,
105   isUndefined: true,
106   isDefined: true,
107   isObject: true,
108   isBlankObject: true,
109   isString: true,
110   isNumber: true,
111   isDate: true,
112   isArray: true,
113   isFunction: true,
114   isRegExp: true,
115   isWindow: true,
116   isScope: true,
117   isFile: true,
118   isFormData: true,
119   isBlob: true,
120   isBoolean: true,
121   isPromiseLike: true,
122   trim: true,
123   escapeForRegexp: true,
124   isElement: true,
125   makeMap: true,
126   includes: true,
127   arrayRemove: true,
128   copy: true,
129   shallowCopy: true,
130   equals: true,
131   csp: true,
132   jq: true,
133   concat: true,
134   sliceArgs: true,
135   bind: true,
136   toJsonReplacer: true,
137   toJson: true,
138   fromJson: true,
139   convertTimezoneToLocal: true,
140   timezoneToOffset: true,
141   startingTag: true,
142   tryDecodeURIComponent: true,
143   parseKeyValue: true,
144   toKeyValue: true,
145   encodeUriSegment: true,
146   encodeUriQuery: true,
147   angularInit: true,
148   bootstrap: true,
149   getTestability: true,
150   snake_case: true,
151   bindJQuery: true,
152   assertArg: true,
153   assertArgFn: true,
154   assertNotHasOwnProperty: true,
155   getter: true,
156   getBlockNodes: true,
157   hasOwnProperty: true,
158   createMap: true,
159
160   NODE_TYPE_ELEMENT: true,
161   NODE_TYPE_ATTRIBUTE: true,
162   NODE_TYPE_TEXT: true,
163   NODE_TYPE_COMMENT: true,
164   NODE_TYPE_DOCUMENT: true,
165   NODE_TYPE_DOCUMENT_FRAGMENT: true,
166 */
167
168 ////////////////////////////////////
169
170 /**
171  * @ngdoc module
172  * @name ng
173  * @module ng
174  * @description
175  *
176  * # ng (core module)
177  * The ng module is loaded by default when an AngularJS application is started. The module itself
178  * contains the essential components for an AngularJS application to function. The table below
179  * lists a high level breakdown of each of the services/factories, filters, directives and testing
180  * components available within this core module.
181  *
182  * <div doc-module-components="ng"></div>
183  */
184
185 var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
186
187 // The name of a form control's ValidityState property.
188 // This is used so that it's possible for internal tests to create mock ValidityStates.
189 var VALIDITY_STATE_PROPERTY = 'validity';
190
191 /**
192  * @ngdoc function
193  * @name angular.lowercase
194  * @module ng
195  * @kind function
196  *
197  * @description Converts the specified string to lowercase.
198  * @param {string} string String to be converted to lowercase.
199  * @returns {string} Lowercased string.
200  */
201 var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
202 var hasOwnProperty = Object.prototype.hasOwnProperty;
203
204 /**
205  * @ngdoc function
206  * @name angular.uppercase
207  * @module ng
208  * @kind function
209  *
210  * @description Converts the specified string to uppercase.
211  * @param {string} string String to be converted to uppercase.
212  * @returns {string} Uppercased string.
213  */
214 var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
215
216
217 var manualLowercase = function(s) {
218   /* jshint bitwise: false */
219   return isString(s)
220       ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
221       : s;
222 };
223 var manualUppercase = function(s) {
224   /* jshint bitwise: false */
225   return isString(s)
226       ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
227       : s;
228 };
229
230
231 // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
232 // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
233 // with correct but slower alternatives.
234 if ('i' !== 'I'.toLowerCase()) {
235   lowercase = manualLowercase;
236   uppercase = manualUppercase;
237 }
238
239
240 var
241     msie,             // holds major version number for IE, or NaN if UA is not IE.
242     jqLite,           // delay binding since jQuery could be loaded after us.
243     jQuery,           // delay binding
244     slice             = [].slice,
245     splice            = [].splice,
246     push              = [].push,
247     toString          = Object.prototype.toString,
248     getPrototypeOf    = Object.getPrototypeOf,
249     ngMinErr          = minErr('ng'),
250
251     /** @name angular */
252     angular           = window.angular || (window.angular = {}),
253     angularModule,
254     uid               = 0;
255
256 /**
257  * documentMode is an IE-only property
258  * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
259  */
260 msie = document.documentMode;
261
262
263 /**
264  * @private
265  * @param {*} obj
266  * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
267  *                   String ...)
268  */
269 function isArrayLike(obj) {
270
271   // `null`, `undefined` and `window` are not array-like
272   if (obj == null || isWindow(obj)) return false;
273
274   // arrays, strings and jQuery/jqLite objects are array like
275   // * jqLite is either the jQuery or jqLite constructor function
276   // * we have to check the existance of jqLite first as this method is called
277   //   via the forEach method when constructing the jqLite object in the first place
278   if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
279
280   // Support: iOS 8.2 (not reproducible in simulator)
281   // "length" in obj used to prevent JIT error (gh-11508)
282   var length = "length" in Object(obj) && obj.length;
283
284   // NodeList objects (with `item` method) and
285   // other objects with suitable length characteristics are array-like
286   return isNumber(length) &&
287     (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
288 }
289
290 /**
291  * @ngdoc function
292  * @name angular.forEach
293  * @module ng
294  * @kind function
295  *
296  * @description
297  * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
298  * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
299  * is the value of an object property or an array element, `key` is the object property key or
300  * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
301  *
302  * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
303  * using the `hasOwnProperty` method.
304  *
305  * Unlike ES262's
306  * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
307  * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
308  * return the value provided.
309  *
310    ```js
311      var values = {name: 'misko', gender: 'male'};
312      var log = [];
313      angular.forEach(values, function(value, key) {
314        this.push(key + ': ' + value);
315      }, log);
316      expect(log).toEqual(['name: misko', 'gender: male']);
317    ```
318  *
319  * @param {Object|Array} obj Object to iterate over.
320  * @param {Function} iterator Iterator function.
321  * @param {Object=} context Object to become context (`this`) for the iterator function.
322  * @returns {Object|Array} Reference to `obj`.
323  */
324
325 function forEach(obj, iterator, context) {
326   var key, length;
327   if (obj) {
328     if (isFunction(obj)) {
329       for (key in obj) {
330         // Need to check if hasOwnProperty exists,
331         // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
332         if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
333           iterator.call(context, obj[key], key, obj);
334         }
335       }
336     } else if (isArray(obj) || isArrayLike(obj)) {
337       var isPrimitive = typeof obj !== 'object';
338       for (key = 0, length = obj.length; key < length; key++) {
339         if (isPrimitive || key in obj) {
340           iterator.call(context, obj[key], key, obj);
341         }
342       }
343     } else if (obj.forEach && obj.forEach !== forEach) {
344         obj.forEach(iterator, context, obj);
345     } else if (isBlankObject(obj)) {
346       // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
347       for (key in obj) {
348         iterator.call(context, obj[key], key, obj);
349       }
350     } else if (typeof obj.hasOwnProperty === 'function') {
351       // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
352       for (key in obj) {
353         if (obj.hasOwnProperty(key)) {
354           iterator.call(context, obj[key], key, obj);
355         }
356       }
357     } else {
358       // Slow path for objects which do not have a method `hasOwnProperty`
359       for (key in obj) {
360         if (hasOwnProperty.call(obj, key)) {
361           iterator.call(context, obj[key], key, obj);
362         }
363       }
364     }
365   }
366   return obj;
367 }
368
369 function forEachSorted(obj, iterator, context) {
370   var keys = Object.keys(obj).sort();
371   for (var i = 0; i < keys.length; i++) {
372     iterator.call(context, obj[keys[i]], keys[i]);
373   }
374   return keys;
375 }
376
377
378 /**
379  * when using forEach the params are value, key, but it is often useful to have key, value.
380  * @param {function(string, *)} iteratorFn
381  * @returns {function(*, string)}
382  */
383 function reverseParams(iteratorFn) {
384   return function(value, key) { iteratorFn(key, value); };
385 }
386
387 /**
388  * A consistent way of creating unique IDs in angular.
389  *
390  * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
391  * we hit number precision issues in JavaScript.
392  *
393  * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
394  *
395  * @returns {number} an unique alpha-numeric string
396  */
397 function nextUid() {
398   return ++uid;
399 }
400
401
402 /**
403  * Set or clear the hashkey for an object.
404  * @param obj object
405  * @param h the hashkey (!truthy to delete the hashkey)
406  */
407 function setHashKey(obj, h) {
408   if (h) {
409     obj.$$hashKey = h;
410   } else {
411     delete obj.$$hashKey;
412   }
413 }
414
415
416 function baseExtend(dst, objs, deep) {
417   var h = dst.$$hashKey;
418
419   for (var i = 0, ii = objs.length; i < ii; ++i) {
420     var obj = objs[i];
421     if (!isObject(obj) && !isFunction(obj)) continue;
422     var keys = Object.keys(obj);
423     for (var j = 0, jj = keys.length; j < jj; j++) {
424       var key = keys[j];
425       var src = obj[key];
426
427       if (deep && isObject(src)) {
428         if (isDate(src)) {
429           dst[key] = new Date(src.valueOf());
430         } else if (isRegExp(src)) {
431           dst[key] = new RegExp(src);
432         } else if (src.nodeName) {
433           dst[key] = src.cloneNode(true);
434         } else if (isElement(src)) {
435           dst[key] = src.clone();
436         } else {
437           if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
438           baseExtend(dst[key], [src], true);
439         }
440       } else {
441         dst[key] = src;
442       }
443     }
444   }
445
446   setHashKey(dst, h);
447   return dst;
448 }
449
450 /**
451  * @ngdoc function
452  * @name angular.extend
453  * @module ng
454  * @kind function
455  *
456  * @description
457  * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
458  * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
459  * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
460  *
461  * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
462  * {@link angular.merge} for this.
463  *
464  * @param {Object} dst Destination object.
465  * @param {...Object} src Source object(s).
466  * @returns {Object} Reference to `dst`.
467  */
468 function extend(dst) {
469   return baseExtend(dst, slice.call(arguments, 1), false);
470 }
471
472
473 /**
474 * @ngdoc function
475 * @name angular.merge
476 * @module ng
477 * @kind function
478 *
479 * @description
480 * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
481 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
482 * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
483 *
484 * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
485 * objects, performing a deep copy.
486 *
487 * @param {Object} dst Destination object.
488 * @param {...Object} src Source object(s).
489 * @returns {Object} Reference to `dst`.
490 */
491 function merge(dst) {
492   return baseExtend(dst, slice.call(arguments, 1), true);
493 }
494
495
496
497 function toInt(str) {
498   return parseInt(str, 10);
499 }
500
501
502 function inherit(parent, extra) {
503   return extend(Object.create(parent), extra);
504 }
505
506 /**
507  * @ngdoc function
508  * @name angular.noop
509  * @module ng
510  * @kind function
511  *
512  * @description
513  * A function that performs no operations. This function can be useful when writing code in the
514  * functional style.
515    ```js
516      function foo(callback) {
517        var result = calculateResult();
518        (callback || angular.noop)(result);
519      }
520    ```
521  */
522 function noop() {}
523 noop.$inject = [];
524
525
526 /**
527  * @ngdoc function
528  * @name angular.identity
529  * @module ng
530  * @kind function
531  *
532  * @description
533  * A function that returns its first argument. This function is useful when writing code in the
534  * functional style.
535  *
536    ```js
537      function transformer(transformationFn, value) {
538        return (transformationFn || angular.identity)(value);
539      };
540    ```
541   * @param {*} value to be returned.
542   * @returns {*} the value passed in.
543  */
544 function identity($) {return $;}
545 identity.$inject = [];
546
547
548 function valueFn(value) {return function() {return value;};}
549
550 function hasCustomToString(obj) {
551   return isFunction(obj.toString) && obj.toString !== toString;
552 }
553
554
555 /**
556  * @ngdoc function
557  * @name angular.isUndefined
558  * @module ng
559  * @kind function
560  *
561  * @description
562  * Determines if a reference is undefined.
563  *
564  * @param {*} value Reference to check.
565  * @returns {boolean} True if `value` is undefined.
566  */
567 function isUndefined(value) {return typeof value === 'undefined';}
568
569
570 /**
571  * @ngdoc function
572  * @name angular.isDefined
573  * @module ng
574  * @kind function
575  *
576  * @description
577  * Determines if a reference is defined.
578  *
579  * @param {*} value Reference to check.
580  * @returns {boolean} True if `value` is defined.
581  */
582 function isDefined(value) {return typeof value !== 'undefined';}
583
584
585 /**
586  * @ngdoc function
587  * @name angular.isObject
588  * @module ng
589  * @kind function
590  *
591  * @description
592  * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
593  * considered to be objects. Note that JavaScript arrays are objects.
594  *
595  * @param {*} value Reference to check.
596  * @returns {boolean} True if `value` is an `Object` but not `null`.
597  */
598 function isObject(value) {
599   // http://jsperf.com/isobject4
600   return value !== null && typeof value === 'object';
601 }
602
603
604 /**
605  * Determine if a value is an object with a null prototype
606  *
607  * @returns {boolean} True if `value` is an `Object` with a null prototype
608  */
609 function isBlankObject(value) {
610   return value !== null && typeof value === 'object' && !getPrototypeOf(value);
611 }
612
613
614 /**
615  * @ngdoc function
616  * @name angular.isString
617  * @module ng
618  * @kind function
619  *
620  * @description
621  * Determines if a reference is a `String`.
622  *
623  * @param {*} value Reference to check.
624  * @returns {boolean} True if `value` is a `String`.
625  */
626 function isString(value) {return typeof value === 'string';}
627
628
629 /**
630  * @ngdoc function
631  * @name angular.isNumber
632  * @module ng
633  * @kind function
634  *
635  * @description
636  * Determines if a reference is a `Number`.
637  *
638  * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
639  *
640  * If you wish to exclude these then you can use the native
641  * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
642  * method.
643  *
644  * @param {*} value Reference to check.
645  * @returns {boolean} True if `value` is a `Number`.
646  */
647 function isNumber(value) {return typeof value === 'number';}
648
649
650 /**
651  * @ngdoc function
652  * @name angular.isDate
653  * @module ng
654  * @kind function
655  *
656  * @description
657  * Determines if a value is a date.
658  *
659  * @param {*} value Reference to check.
660  * @returns {boolean} True if `value` is a `Date`.
661  */
662 function isDate(value) {
663   return toString.call(value) === '[object Date]';
664 }
665
666
667 /**
668  * @ngdoc function
669  * @name angular.isArray
670  * @module ng
671  * @kind function
672  *
673  * @description
674  * Determines if a reference is an `Array`.
675  *
676  * @param {*} value Reference to check.
677  * @returns {boolean} True if `value` is an `Array`.
678  */
679 var isArray = Array.isArray;
680
681 /**
682  * @ngdoc function
683  * @name angular.isFunction
684  * @module ng
685  * @kind function
686  *
687  * @description
688  * Determines if a reference is a `Function`.
689  *
690  * @param {*} value Reference to check.
691  * @returns {boolean} True if `value` is a `Function`.
692  */
693 function isFunction(value) {return typeof value === 'function';}
694
695
696 /**
697  * Determines if a value is a regular expression object.
698  *
699  * @private
700  * @param {*} value Reference to check.
701  * @returns {boolean} True if `value` is a `RegExp`.
702  */
703 function isRegExp(value) {
704   return toString.call(value) === '[object RegExp]';
705 }
706
707
708 /**
709  * Checks if `obj` is a window object.
710  *
711  * @private
712  * @param {*} obj Object to check
713  * @returns {boolean} True if `obj` is a window obj.
714  */
715 function isWindow(obj) {
716   return obj && obj.window === obj;
717 }
718
719
720 function isScope(obj) {
721   return obj && obj.$evalAsync && obj.$watch;
722 }
723
724
725 function isFile(obj) {
726   return toString.call(obj) === '[object File]';
727 }
728
729
730 function isFormData(obj) {
731   return toString.call(obj) === '[object FormData]';
732 }
733
734
735 function isBlob(obj) {
736   return toString.call(obj) === '[object Blob]';
737 }
738
739
740 function isBoolean(value) {
741   return typeof value === 'boolean';
742 }
743
744
745 function isPromiseLike(obj) {
746   return obj && isFunction(obj.then);
747 }
748
749
750 var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
751 function isTypedArray(value) {
752   return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
753 }
754
755
756 var trim = function(value) {
757   return isString(value) ? value.trim() : value;
758 };
759
760 // Copied from:
761 // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
762 // Prereq: s is a string.
763 var escapeForRegexp = function(s) {
764   return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
765            replace(/\x08/g, '\\x08');
766 };
767
768
769 /**
770  * @ngdoc function
771  * @name angular.isElement
772  * @module ng
773  * @kind function
774  *
775  * @description
776  * Determines if a reference is a DOM element (or wrapped jQuery element).
777  *
778  * @param {*} value Reference to check.
779  * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
780  */
781 function isElement(node) {
782   return !!(node &&
783     (node.nodeName  // we are a direct element
784     || (node.prop && node.attr && node.find)));  // we have an on and find method part of jQuery API
785 }
786
787 /**
788  * @param str 'key1,key2,...'
789  * @returns {object} in the form of {key1:true, key2:true, ...}
790  */
791 function makeMap(str) {
792   var obj = {}, items = str.split(","), i;
793   for (i = 0; i < items.length; i++) {
794     obj[items[i]] = true;
795   }
796   return obj;
797 }
798
799
800 function nodeName_(element) {
801   return lowercase(element.nodeName || (element[0] && element[0].nodeName));
802 }
803
804 function includes(array, obj) {
805   return Array.prototype.indexOf.call(array, obj) != -1;
806 }
807
808 function arrayRemove(array, value) {
809   var index = array.indexOf(value);
810   if (index >= 0) {
811     array.splice(index, 1);
812   }
813   return index;
814 }
815
816 /**
817  * @ngdoc function
818  * @name angular.copy
819  * @module ng
820  * @kind function
821  *
822  * @description
823  * Creates a deep copy of `source`, which should be an object or an array.
824  *
825  * * If no destination is supplied, a copy of the object or array is created.
826  * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
827  *   are deleted and then all elements/properties from the source are copied to it.
828  * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
829  * * If `source` is identical to 'destination' an exception will be thrown.
830  *
831  * @param {*} source The source that will be used to make a copy.
832  *                   Can be any type, including primitives, `null`, and `undefined`.
833  * @param {(Object|Array)=} destination Destination into which the source is copied. If
834  *     provided, must be of the same type as `source`.
835  * @returns {*} The copy or updated `destination`, if `destination` was specified.
836  *
837  * @example
838  <example module="copyExample">
839  <file name="index.html">
840  <div ng-controller="ExampleController">
841  <form novalidate class="simple-form">
842  Name: <input type="text" ng-model="user.name" /><br />
843  E-mail: <input type="email" ng-model="user.email" /><br />
844  Gender: <input type="radio" ng-model="user.gender" value="male" />male
845  <input type="radio" ng-model="user.gender" value="female" />female<br />
846  <button ng-click="reset()">RESET</button>
847  <button ng-click="update(user)">SAVE</button>
848  </form>
849  <pre>form = {{user | json}}</pre>
850  <pre>master = {{master | json}}</pre>
851  </div>
852
853  <script>
854   angular.module('copyExample', [])
855     .controller('ExampleController', ['$scope', function($scope) {
856       $scope.master= {};
857
858       $scope.update = function(user) {
859         // Example with 1 argument
860         $scope.master= angular.copy(user);
861       };
862
863       $scope.reset = function() {
864         // Example with 2 arguments
865         angular.copy($scope.master, $scope.user);
866       };
867
868       $scope.reset();
869     }]);
870  </script>
871  </file>
872  </example>
873  */
874 function copy(source, destination) {
875   var stackSource = [];
876   var stackDest = [];
877
878   if (destination) {
879     if (isTypedArray(destination)) {
880       throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
881     }
882     if (source === destination) {
883       throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
884     }
885
886     // Empty the destination object
887     if (isArray(destination)) {
888       destination.length = 0;
889     } else {
890       forEach(destination, function(value, key) {
891         if (key !== '$$hashKey') {
892           delete destination[key];
893         }
894       });
895     }
896
897     stackSource.push(source);
898     stackDest.push(destination);
899     return copyRecurse(source, destination);
900   }
901
902   return copyElement(source);
903
904   function copyRecurse(source, destination) {
905     var h = destination.$$hashKey;
906     var result, key;
907     if (isArray(source)) {
908       for (var i = 0, ii = source.length; i < ii; i++) {
909         destination.push(copyElement(source[i]));
910       }
911     } else if (isBlankObject(source)) {
912       // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
913       for (key in source) {
914         destination[key] = copyElement(source[key]);
915       }
916     } else if (source && typeof source.hasOwnProperty === 'function') {
917       // Slow path, which must rely on hasOwnProperty
918       for (key in source) {
919         if (source.hasOwnProperty(key)) {
920           destination[key] = copyElement(source[key]);
921         }
922       }
923     } else {
924       // Slowest path --- hasOwnProperty can't be called as a method
925       for (key in source) {
926         if (hasOwnProperty.call(source, key)) {
927           destination[key] = copyElement(source[key]);
928         }
929       }
930     }
931     setHashKey(destination, h);
932     return destination;
933   }
934
935   function copyElement(source) {
936     // Simple values
937     if (!isObject(source)) {
938       return source;
939     }
940
941     // Already copied values
942     var index = stackSource.indexOf(source);
943     if (index !== -1) {
944       return stackDest[index];
945     }
946
947     if (isWindow(source) || isScope(source)) {
948       throw ngMinErr('cpws',
949         "Can't copy! Making copies of Window or Scope instances is not supported.");
950     }
951
952     var needsRecurse = false;
953     var destination;
954
955     if (isArray(source)) {
956       destination = [];
957       needsRecurse = true;
958     } else if (isTypedArray(source)) {
959       destination = new source.constructor(source);
960     } else if (isDate(source)) {
961       destination = new Date(source.getTime());
962     } else if (isRegExp(source)) {
963       destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
964       destination.lastIndex = source.lastIndex;
965     } else if (isFunction(source.cloneNode)) {
966         destination = source.cloneNode(true);
967     } else {
968       destination = Object.create(getPrototypeOf(source));
969       needsRecurse = true;
970     }
971
972     stackSource.push(source);
973     stackDest.push(destination);
974
975     return needsRecurse
976       ? copyRecurse(source, destination)
977       : destination;
978   }
979 }
980
981 /**
982  * Creates a shallow copy of an object, an array or a primitive.
983  *
984  * Assumes that there are no proto properties for objects.
985  */
986 function shallowCopy(src, dst) {
987   if (isArray(src)) {
988     dst = dst || [];
989
990     for (var i = 0, ii = src.length; i < ii; i++) {
991       dst[i] = src[i];
992     }
993   } else if (isObject(src)) {
994     dst = dst || {};
995
996     for (var key in src) {
997       if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
998         dst[key] = src[key];
999       }
1000     }
1001   }
1002
1003   return dst || src;
1004 }
1005
1006
1007 /**
1008  * @ngdoc function
1009  * @name angular.equals
1010  * @module ng
1011  * @kind function
1012  *
1013  * @description
1014  * Determines if two objects or two values are equivalent. Supports value types, regular
1015  * expressions, arrays and objects.
1016  *
1017  * Two objects or values are considered equivalent if at least one of the following is true:
1018  *
1019  * * Both objects or values pass `===` comparison.
1020  * * Both objects or values are of the same type and all of their properties are equal by
1021  *   comparing them with `angular.equals`.
1022  * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
1023  * * Both values represent the same regular expression (In JavaScript,
1024  *   /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
1025  *   representation matches).
1026  *
1027  * During a property comparison, properties of `function` type and properties with names
1028  * that begin with `$` are ignored.
1029  *
1030  * Scope and DOMWindow objects are being compared only by identify (`===`).
1031  *
1032  * @param {*} o1 Object or value to compare.
1033  * @param {*} o2 Object or value to compare.
1034  * @returns {boolean} True if arguments are equal.
1035  */
1036 function equals(o1, o2) {
1037   if (o1 === o2) return true;
1038   if (o1 === null || o2 === null) return false;
1039   if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
1040   var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
1041   if (t1 == t2) {
1042     if (t1 == 'object') {
1043       if (isArray(o1)) {
1044         if (!isArray(o2)) return false;
1045         if ((length = o1.length) == o2.length) {
1046           for (key = 0; key < length; key++) {
1047             if (!equals(o1[key], o2[key])) return false;
1048           }
1049           return true;
1050         }
1051       } else if (isDate(o1)) {
1052         if (!isDate(o2)) return false;
1053         return equals(o1.getTime(), o2.getTime());
1054       } else if (isRegExp(o1)) {
1055         return isRegExp(o2) ? o1.toString() == o2.toString() : false;
1056       } else {
1057         if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
1058           isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
1059         keySet = createMap();
1060         for (key in o1) {
1061           if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
1062           if (!equals(o1[key], o2[key])) return false;
1063           keySet[key] = true;
1064         }
1065         for (key in o2) {
1066           if (!(key in keySet) &&
1067               key.charAt(0) !== '$' &&
1068               isDefined(o2[key]) &&
1069               !isFunction(o2[key])) return false;
1070         }
1071         return true;
1072       }
1073     }
1074   }
1075   return false;
1076 }
1077
1078 var csp = function() {
1079   if (!isDefined(csp.rules)) {
1080
1081
1082     var ngCspElement = (document.querySelector('[ng-csp]') ||
1083                     document.querySelector('[data-ng-csp]'));
1084
1085     if (ngCspElement) {
1086       var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
1087                     ngCspElement.getAttribute('data-ng-csp');
1088       csp.rules = {
1089         noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
1090         noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
1091       };
1092     } else {
1093       csp.rules = {
1094         noUnsafeEval: noUnsafeEval(),
1095         noInlineStyle: false
1096       };
1097     }
1098   }
1099
1100   return csp.rules;
1101
1102   function noUnsafeEval() {
1103     try {
1104       /* jshint -W031, -W054 */
1105       new Function('');
1106       /* jshint +W031, +W054 */
1107       return false;
1108     } catch (e) {
1109       return true;
1110     }
1111   }
1112 };
1113
1114 /**
1115  * @ngdoc directive
1116  * @module ng
1117  * @name ngJq
1118  *
1119  * @element ANY
1120  * @param {string=} ngJq the name of the library available under `window`
1121  * to be used for angular.element
1122  * @description
1123  * Use this directive to force the angular.element library.  This should be
1124  * used to force either jqLite by leaving ng-jq blank or setting the name of
1125  * the jquery variable under window (eg. jQuery).
1126  *
1127  * Since angular looks for this directive when it is loaded (doesn't wait for the
1128  * DOMContentLoaded event), it must be placed on an element that comes before the script
1129  * which loads angular. Also, only the first instance of `ng-jq` will be used and all
1130  * others ignored.
1131  *
1132  * @example
1133  * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
1134  ```html
1135  <!doctype html>
1136  <html ng-app ng-jq>
1137  ...
1138  ...
1139  </html>
1140  ```
1141  * @example
1142  * This example shows how to use a jQuery based library of a different name.
1143  * The library name must be available at the top most 'window'.
1144  ```html
1145  <!doctype html>
1146  <html ng-app ng-jq="jQueryLib">
1147  ...
1148  ...
1149  </html>
1150  ```
1151  */
1152 var jq = function() {
1153   if (isDefined(jq.name_)) return jq.name_;
1154   var el;
1155   var i, ii = ngAttrPrefixes.length, prefix, name;
1156   for (i = 0; i < ii; ++i) {
1157     prefix = ngAttrPrefixes[i];
1158     if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
1159       name = el.getAttribute(prefix + 'jq');
1160       break;
1161     }
1162   }
1163
1164   return (jq.name_ = name);
1165 };
1166
1167 function concat(array1, array2, index) {
1168   return array1.concat(slice.call(array2, index));
1169 }
1170
1171 function sliceArgs(args, startIndex) {
1172   return slice.call(args, startIndex || 0);
1173 }
1174
1175
1176 /* jshint -W101 */
1177 /**
1178  * @ngdoc function
1179  * @name angular.bind
1180  * @module ng
1181  * @kind function
1182  *
1183  * @description
1184  * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
1185  * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
1186  * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
1187  * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
1188  *
1189  * @param {Object} self Context which `fn` should be evaluated in.
1190  * @param {function()} fn Function to be bound.
1191  * @param {...*} args Optional arguments to be prebound to the `fn` function call.
1192  * @returns {function()} Function that wraps the `fn` with all the specified bindings.
1193  */
1194 /* jshint +W101 */
1195 function bind(self, fn) {
1196   var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
1197   if (isFunction(fn) && !(fn instanceof RegExp)) {
1198     return curryArgs.length
1199       ? function() {
1200           return arguments.length
1201             ? fn.apply(self, concat(curryArgs, arguments, 0))
1202             : fn.apply(self, curryArgs);
1203         }
1204       : function() {
1205           return arguments.length
1206             ? fn.apply(self, arguments)
1207             : fn.call(self);
1208         };
1209   } else {
1210     // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
1211     return fn;
1212   }
1213 }
1214
1215
1216 function toJsonReplacer(key, value) {
1217   var val = value;
1218
1219   if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
1220     val = undefined;
1221   } else if (isWindow(value)) {
1222     val = '$WINDOW';
1223   } else if (value &&  document === value) {
1224     val = '$DOCUMENT';
1225   } else if (isScope(value)) {
1226     val = '$SCOPE';
1227   }
1228
1229   return val;
1230 }
1231
1232
1233 /**
1234  * @ngdoc function
1235  * @name angular.toJson
1236  * @module ng
1237  * @kind function
1238  *
1239  * @description
1240  * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
1241  * stripped since angular uses this notation internally.
1242  *
1243  * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
1244  * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
1245  *    If set to an integer, the JSON output will contain that many spaces per indentation.
1246  * @returns {string|undefined} JSON-ified string representing `obj`.
1247  */
1248 function toJson(obj, pretty) {
1249   if (typeof obj === 'undefined') return undefined;
1250   if (!isNumber(pretty)) {
1251     pretty = pretty ? 2 : null;
1252   }
1253   return JSON.stringify(obj, toJsonReplacer, pretty);
1254 }
1255
1256
1257 /**
1258  * @ngdoc function
1259  * @name angular.fromJson
1260  * @module ng
1261  * @kind function
1262  *
1263  * @description
1264  * Deserializes a JSON string.
1265  *
1266  * @param {string} json JSON string to deserialize.
1267  * @returns {Object|Array|string|number} Deserialized JSON string.
1268  */
1269 function fromJson(json) {
1270   return isString(json)
1271       ? JSON.parse(json)
1272       : json;
1273 }
1274
1275
1276 function timezoneToOffset(timezone, fallback) {
1277   var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
1278   return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
1279 }
1280
1281
1282 function addDateMinutes(date, minutes) {
1283   date = new Date(date.getTime());
1284   date.setMinutes(date.getMinutes() + minutes);
1285   return date;
1286 }
1287
1288
1289 function convertTimezoneToLocal(date, timezone, reverse) {
1290   reverse = reverse ? -1 : 1;
1291   var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
1292   return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
1293 }
1294
1295
1296 /**
1297  * @returns {string} Returns the string representation of the element.
1298  */
1299 function startingTag(element) {
1300   element = jqLite(element).clone();
1301   try {
1302     // turns out IE does not let you set .html() on elements which
1303     // are not allowed to have children. So we just ignore it.
1304     element.empty();
1305   } catch (e) {}
1306   var elemHtml = jqLite('<div>').append(element).html();
1307   try {
1308     return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
1309         elemHtml.
1310           match(/^(<[^>]+>)/)[1].
1311           replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
1312   } catch (e) {
1313     return lowercase(elemHtml);
1314   }
1315
1316 }
1317
1318
1319 /////////////////////////////////////////////////
1320
1321 /**
1322  * Tries to decode the URI component without throwing an exception.
1323  *
1324  * @private
1325  * @param str value potential URI component to check.
1326  * @returns {boolean} True if `value` can be decoded
1327  * with the decodeURIComponent function.
1328  */
1329 function tryDecodeURIComponent(value) {
1330   try {
1331     return decodeURIComponent(value);
1332   } catch (e) {
1333     // Ignore any invalid uri component
1334   }
1335 }
1336
1337
1338 /**
1339  * Parses an escaped url query string into key-value pairs.
1340  * @returns {Object.<string,boolean|Array>}
1341  */
1342 function parseKeyValue(/**string*/keyValue) {
1343   var obj = {};
1344   forEach((keyValue || "").split('&'), function(keyValue) {
1345     var splitPoint, key, val;
1346     if (keyValue) {
1347       key = keyValue = keyValue.replace(/\+/g,'%20');
1348       splitPoint = keyValue.indexOf('=');
1349       if (splitPoint !== -1) {
1350         key = keyValue.substring(0, splitPoint);
1351         val = keyValue.substring(splitPoint + 1);
1352       }
1353       key = tryDecodeURIComponent(key);
1354       if (isDefined(key)) {
1355         val = isDefined(val) ? tryDecodeURIComponent(val) : true;
1356         if (!hasOwnProperty.call(obj, key)) {
1357           obj[key] = val;
1358         } else if (isArray(obj[key])) {
1359           obj[key].push(val);
1360         } else {
1361           obj[key] = [obj[key],val];
1362         }
1363       }
1364     }
1365   });
1366   return obj;
1367 }
1368
1369 function toKeyValue(obj) {
1370   var parts = [];
1371   forEach(obj, function(value, key) {
1372     if (isArray(value)) {
1373       forEach(value, function(arrayValue) {
1374         parts.push(encodeUriQuery(key, true) +
1375                    (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
1376       });
1377     } else {
1378     parts.push(encodeUriQuery(key, true) +
1379                (value === true ? '' : '=' + encodeUriQuery(value, true)));
1380     }
1381   });
1382   return parts.length ? parts.join('&') : '';
1383 }
1384
1385
1386 /**
1387  * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
1388  * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
1389  * segments:
1390  *    segment       = *pchar
1391  *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
1392  *    pct-encoded   = "%" HEXDIG HEXDIG
1393  *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
1394  *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
1395  *                     / "*" / "+" / "," / ";" / "="
1396  */
1397 function encodeUriSegment(val) {
1398   return encodeUriQuery(val, true).
1399              replace(/%26/gi, '&').
1400              replace(/%3D/gi, '=').
1401              replace(/%2B/gi, '+');
1402 }
1403
1404
1405 /**
1406  * This method is intended for encoding *key* or *value* parts of query component. We need a custom
1407  * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
1408  * encoded per http://tools.ietf.org/html/rfc3986:
1409  *    query       = *( pchar / "/" / "?" )
1410  *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
1411  *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
1412  *    pct-encoded   = "%" HEXDIG HEXDIG
1413  *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
1414  *                     / "*" / "+" / "," / ";" / "="
1415  */
1416 function encodeUriQuery(val, pctEncodeSpaces) {
1417   return encodeURIComponent(val).
1418              replace(/%40/gi, '@').
1419              replace(/%3A/gi, ':').
1420              replace(/%24/g, '$').
1421              replace(/%2C/gi, ',').
1422              replace(/%3B/gi, ';').
1423              replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
1424 }
1425
1426 var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
1427
1428 function getNgAttribute(element, ngAttr) {
1429   var attr, i, ii = ngAttrPrefixes.length;
1430   for (i = 0; i < ii; ++i) {
1431     attr = ngAttrPrefixes[i] + ngAttr;
1432     if (isString(attr = element.getAttribute(attr))) {
1433       return attr;
1434     }
1435   }
1436   return null;
1437 }
1438
1439 /**
1440  * @ngdoc directive
1441  * @name ngApp
1442  * @module ng
1443  *
1444  * @element ANY
1445  * @param {angular.Module} ngApp an optional application
1446  *   {@link angular.module module} name to load.
1447  * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
1448  *   created in "strict-di" mode. This means that the application will fail to invoke functions which
1449  *   do not use explicit function annotation (and are thus unsuitable for minification), as described
1450  *   in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
1451  *   tracking down the root of these bugs.
1452  *
1453  * @description
1454  *
1455  * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
1456  * designates the **root element** of the application and is typically placed near the root element
1457  * of the page - e.g. on the `<body>` or `<html>` tags.
1458  *
1459  * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
1460  * found in the document will be used to define the root element to auto-bootstrap as an
1461  * application. To run multiple applications in an HTML document you must manually bootstrap them using
1462  * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
1463  *
1464  * You can specify an **AngularJS module** to be used as the root module for the application.  This
1465  * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
1466  * should contain the application code needed or have dependencies on other modules that will
1467  * contain the code. See {@link angular.module} for more information.
1468  *
1469  * In the example below if the `ngApp` directive were not placed on the `html` element then the
1470  * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
1471  * would not be resolved to `3`.
1472  *
1473  * `ngApp` is the easiest, and most common way to bootstrap an application.
1474  *
1475  <example module="ngAppDemo">
1476    <file name="index.html">
1477    <div ng-controller="ngAppDemoController">
1478      I can add: {{a}} + {{b}} =  {{ a+b }}
1479    </div>
1480    </file>
1481    <file name="script.js">
1482    angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
1483      $scope.a = 1;
1484      $scope.b = 2;
1485    });
1486    </file>
1487  </example>
1488  *
1489  * Using `ngStrictDi`, you would see something like this:
1490  *
1491  <example ng-app-included="true">
1492    <file name="index.html">
1493    <div ng-app="ngAppStrictDemo" ng-strict-di>
1494        <div ng-controller="GoodController1">
1495            I can add: {{a}} + {{b}} =  {{ a+b }}
1496
1497            <p>This renders because the controller does not fail to
1498               instantiate, by using explicit annotation style (see
1499               script.js for details)
1500            </p>
1501        </div>
1502
1503        <div ng-controller="GoodController2">
1504            Name: <input ng-model="name"><br />
1505            Hello, {{name}}!
1506
1507            <p>This renders because the controller does not fail to
1508               instantiate, by using explicit annotation style
1509               (see script.js for details)
1510            </p>
1511        </div>
1512
1513        <div ng-controller="BadController">
1514            I can add: {{a}} + {{b}} =  {{ a+b }}
1515
1516            <p>The controller could not be instantiated, due to relying
1517               on automatic function annotations (which are disabled in
1518               strict mode). As such, the content of this section is not
1519               interpolated, and there should be an error in your web console.
1520            </p>
1521        </div>
1522    </div>
1523    </file>
1524    <file name="script.js">
1525    angular.module('ngAppStrictDemo', [])
1526      // BadController will fail to instantiate, due to relying on automatic function annotation,
1527      // rather than an explicit annotation
1528      .controller('BadController', function($scope) {
1529        $scope.a = 1;
1530        $scope.b = 2;
1531      })
1532      // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
1533      // due to using explicit annotations using the array style and $inject property, respectively.
1534      .controller('GoodController1', ['$scope', function($scope) {
1535        $scope.a = 1;
1536        $scope.b = 2;
1537      }])
1538      .controller('GoodController2', GoodController2);
1539      function GoodController2($scope) {
1540        $scope.name = "World";
1541      }
1542      GoodController2.$inject = ['$scope'];
1543    </file>
1544    <file name="style.css">
1545    div[ng-controller] {
1546        margin-bottom: 1em;
1547        -webkit-border-radius: 4px;
1548        border-radius: 4px;
1549        border: 1px solid;
1550        padding: .5em;
1551    }
1552    div[ng-controller^=Good] {
1553        border-color: #d6e9c6;
1554        background-color: #dff0d8;
1555        color: #3c763d;
1556    }
1557    div[ng-controller^=Bad] {
1558        border-color: #ebccd1;
1559        background-color: #f2dede;
1560        color: #a94442;
1561        margin-bottom: 0;
1562    }
1563    </file>
1564  </example>
1565  */
1566 function angularInit(element, bootstrap) {
1567   var appElement,
1568       module,
1569       config = {};
1570
1571   // The element `element` has priority over any other element
1572   forEach(ngAttrPrefixes, function(prefix) {
1573     var name = prefix + 'app';
1574
1575     if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
1576       appElement = element;
1577       module = element.getAttribute(name);
1578     }
1579   });
1580   forEach(ngAttrPrefixes, function(prefix) {
1581     var name = prefix + 'app';
1582     var candidate;
1583
1584     if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
1585       appElement = candidate;
1586       module = candidate.getAttribute(name);
1587     }
1588   });
1589   if (appElement) {
1590     config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
1591     bootstrap(appElement, module ? [module] : [], config);
1592   }
1593 }
1594
1595 /**
1596  * @ngdoc function
1597  * @name angular.bootstrap
1598  * @module ng
1599  * @description
1600  * Use this function to manually start up angular application.
1601  *
1602  * See: {@link guide/bootstrap Bootstrap}
1603  *
1604  * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
1605  * They must use {@link ng.directive:ngApp ngApp}.
1606  *
1607  * Angular will detect if it has been loaded into the browser more than once and only allow the
1608  * first loaded script to be bootstrapped and will report a warning to the browser console for
1609  * each of the subsequent scripts. This prevents strange results in applications, where otherwise
1610  * multiple instances of Angular try to work on the DOM.
1611  *
1612  * ```html
1613  * <!doctype html>
1614  * <html>
1615  * <body>
1616  * <div ng-controller="WelcomeController">
1617  *   {{greeting}}
1618  * </div>
1619  *
1620  * <script src="angular.js"></script>
1621  * <script>
1622  *   var app = angular.module('demo', [])
1623  *   .controller('WelcomeController', function($scope) {
1624  *       $scope.greeting = 'Welcome!';
1625  *   });
1626  *   angular.bootstrap(document, ['demo']);
1627  * </script>
1628  * </body>
1629  * </html>
1630  * ```
1631  *
1632  * @param {DOMElement} element DOM element which is the root of angular application.
1633  * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
1634  *     Each item in the array should be the name of a predefined module or a (DI annotated)
1635  *     function that will be invoked by the injector as a `config` block.
1636  *     See: {@link angular.module modules}
1637  * @param {Object=} config an object for defining configuration options for the application. The
1638  *     following keys are supported:
1639  *
1640  * * `strictDi` - disable automatic function annotation for the application. This is meant to
1641  *   assist in finding bugs which break minified code. Defaults to `false`.
1642  *
1643  * @returns {auto.$injector} Returns the newly created injector for this app.
1644  */
1645 function bootstrap(element, modules, config) {
1646   if (!isObject(config)) config = {};
1647   var defaultConfig = {
1648     strictDi: false
1649   };
1650   config = extend(defaultConfig, config);
1651   var doBootstrap = function() {
1652     element = jqLite(element);
1653
1654     if (element.injector()) {
1655       var tag = (element[0] === document) ? 'document' : startingTag(element);
1656       //Encode angle brackets to prevent input from being sanitized to empty string #8683
1657       throw ngMinErr(
1658           'btstrpd',
1659           "App Already Bootstrapped with this Element '{0}'",
1660           tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
1661     }
1662
1663     modules = modules || [];
1664     modules.unshift(['$provide', function($provide) {
1665       $provide.value('$rootElement', element);
1666     }]);
1667
1668     if (config.debugInfoEnabled) {
1669       // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
1670       modules.push(['$compileProvider', function($compileProvider) {
1671         $compileProvider.debugInfoEnabled(true);
1672       }]);
1673     }
1674
1675     modules.unshift('ng');
1676     var injector = createInjector(modules, config.strictDi);
1677     injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
1678        function bootstrapApply(scope, element, compile, injector) {
1679         scope.$apply(function() {
1680           element.data('$injector', injector);
1681           compile(element)(scope);
1682         });
1683       }]
1684     );
1685     return injector;
1686   };
1687
1688   var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
1689   var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
1690
1691   if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
1692     config.debugInfoEnabled = true;
1693     window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
1694   }
1695
1696   if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
1697     return doBootstrap();
1698   }
1699
1700   window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
1701   angular.resumeBootstrap = function(extraModules) {
1702     forEach(extraModules, function(module) {
1703       modules.push(module);
1704     });
1705     return doBootstrap();
1706   };
1707
1708   if (isFunction(angular.resumeDeferredBootstrap)) {
1709     angular.resumeDeferredBootstrap();
1710   }
1711 }
1712
1713 /**
1714  * @ngdoc function
1715  * @name angular.reloadWithDebugInfo
1716  * @module ng
1717  * @description
1718  * Use this function to reload the current application with debug information turned on.
1719  * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
1720  *
1721  * See {@link ng.$compileProvider#debugInfoEnabled} for more.
1722  */
1723 function reloadWithDebugInfo() {
1724   window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
1725   window.location.reload();
1726 }
1727
1728 /**
1729  * @name angular.getTestability
1730  * @module ng
1731  * @description
1732  * Get the testability service for the instance of Angular on the given
1733  * element.
1734  * @param {DOMElement} element DOM element which is the root of angular application.
1735  */
1736 function getTestability(rootElement) {
1737   var injector = angular.element(rootElement).injector();
1738   if (!injector) {
1739     throw ngMinErr('test',
1740       'no injector found for element argument to getTestability');
1741   }
1742   return injector.get('$$testability');
1743 }
1744
1745 var SNAKE_CASE_REGEXP = /[A-Z]/g;
1746 function snake_case(name, separator) {
1747   separator = separator || '_';
1748   return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
1749     return (pos ? separator : '') + letter.toLowerCase();
1750   });
1751 }
1752
1753 var bindJQueryFired = false;
1754 function bindJQuery() {
1755   var originalCleanData;
1756
1757   if (bindJQueryFired) {
1758     return;
1759   }
1760
1761   // bind to jQuery if present;
1762   var jqName = jq();
1763   jQuery = isUndefined(jqName) ? window.jQuery :   // use jQuery (if present)
1764            !jqName             ? undefined     :   // use jqLite
1765                                  window[jqName];   // use jQuery specified by `ngJq`
1766
1767   // Use jQuery if it exists with proper functionality, otherwise default to us.
1768   // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
1769   // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
1770   // versions. It will not work for sure with jQuery <1.7, though.
1771   if (jQuery && jQuery.fn.on) {
1772     jqLite = jQuery;
1773     extend(jQuery.fn, {
1774       scope: JQLitePrototype.scope,
1775       isolateScope: JQLitePrototype.isolateScope,
1776       controller: JQLitePrototype.controller,
1777       injector: JQLitePrototype.injector,
1778       inheritedData: JQLitePrototype.inheritedData
1779     });
1780
1781     // All nodes removed from the DOM via various jQuery APIs like .remove()
1782     // are passed through jQuery.cleanData. Monkey-patch this method to fire
1783     // the $destroy event on all removed nodes.
1784     originalCleanData = jQuery.cleanData;
1785     jQuery.cleanData = function(elems) {
1786       var events;
1787       for (var i = 0, elem; (elem = elems[i]) != null; i++) {
1788         events = jQuery._data(elem, "events");
1789         if (events && events.$destroy) {
1790           jQuery(elem).triggerHandler('$destroy');
1791         }
1792       }
1793       originalCleanData(elems);
1794     };
1795   } else {
1796     jqLite = JQLite;
1797   }
1798
1799   angular.element = jqLite;
1800
1801   // Prevent double-proxying.
1802   bindJQueryFired = true;
1803 }
1804
1805 /**
1806  * throw error if the argument is falsy.
1807  */
1808 function assertArg(arg, name, reason) {
1809   if (!arg) {
1810     throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
1811   }
1812   return arg;
1813 }
1814
1815 function assertArgFn(arg, name, acceptArrayAnnotation) {
1816   if (acceptArrayAnnotation && isArray(arg)) {
1817       arg = arg[arg.length - 1];
1818   }
1819
1820   assertArg(isFunction(arg), name, 'not a function, got ' +
1821       (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
1822   return arg;
1823 }
1824
1825 /**
1826  * throw error if the name given is hasOwnProperty
1827  * @param  {String} name    the name to test
1828  * @param  {String} context the context in which the name is used, such as module or directive
1829  */
1830 function assertNotHasOwnProperty(name, context) {
1831   if (name === 'hasOwnProperty') {
1832     throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
1833   }
1834 }
1835
1836 /**
1837  * Return the value accessible from the object by path. Any undefined traversals are ignored
1838  * @param {Object} obj starting object
1839  * @param {String} path path to traverse
1840  * @param {boolean} [bindFnToScope=true]
1841  * @returns {Object} value as accessible by path
1842  */
1843 //TODO(misko): this function needs to be removed
1844 function getter(obj, path, bindFnToScope) {
1845   if (!path) return obj;
1846   var keys = path.split('.');
1847   var key;
1848   var lastInstance = obj;
1849   var len = keys.length;
1850
1851   for (var i = 0; i < len; i++) {
1852     key = keys[i];
1853     if (obj) {
1854       obj = (lastInstance = obj)[key];
1855     }
1856   }
1857   if (!bindFnToScope && isFunction(obj)) {
1858     return bind(lastInstance, obj);
1859   }
1860   return obj;
1861 }
1862
1863 /**
1864  * Return the DOM siblings between the first and last node in the given array.
1865  * @param {Array} array like object
1866  * @returns {Array} the inputted object or a jqLite collection containing the nodes
1867  */
1868 function getBlockNodes(nodes) {
1869   // TODO(perf): update `nodes` instead of creating a new object?
1870   var node = nodes[0];
1871   var endNode = nodes[nodes.length - 1];
1872   var blockNodes;
1873
1874   for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
1875     if (blockNodes || nodes[i] !== node) {
1876       if (!blockNodes) {
1877         blockNodes = jqLite(slice.call(nodes, 0, i));
1878       }
1879       blockNodes.push(node);
1880     }
1881   }
1882
1883   return blockNodes || nodes;
1884 }
1885
1886
1887 /**
1888  * Creates a new object without a prototype. This object is useful for lookup without having to
1889  * guard against prototypically inherited properties via hasOwnProperty.
1890  *
1891  * Related micro-benchmarks:
1892  * - http://jsperf.com/object-create2
1893  * - http://jsperf.com/proto-map-lookup/2
1894  * - http://jsperf.com/for-in-vs-object-keys2
1895  *
1896  * @returns {Object}
1897  */
1898 function createMap() {
1899   return Object.create(null);
1900 }
1901
1902 var NODE_TYPE_ELEMENT = 1;
1903 var NODE_TYPE_ATTRIBUTE = 2;
1904 var NODE_TYPE_TEXT = 3;
1905 var NODE_TYPE_COMMENT = 8;
1906 var NODE_TYPE_DOCUMENT = 9;
1907 var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
1908
1909 /**
1910  * @ngdoc type
1911  * @name angular.Module
1912  * @module ng
1913  * @description
1914  *
1915  * Interface for configuring angular {@link angular.module modules}.
1916  */
1917
1918 function setupModuleLoader(window) {
1919
1920   var $injectorMinErr = minErr('$injector');
1921   var ngMinErr = minErr('ng');
1922
1923   function ensure(obj, name, factory) {
1924     return obj[name] || (obj[name] = factory());
1925   }
1926
1927   var angular = ensure(window, 'angular', Object);
1928
1929   // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
1930   angular.$$minErr = angular.$$minErr || minErr;
1931
1932   return ensure(angular, 'module', function() {
1933     /** @type {Object.<string, angular.Module>} */
1934     var modules = {};
1935
1936     /**
1937      * @ngdoc function
1938      * @name angular.module
1939      * @module ng
1940      * @description
1941      *
1942      * The `angular.module` is a global place for creating, registering and retrieving Angular
1943      * modules.
1944      * All modules (angular core or 3rd party) that should be available to an application must be
1945      * registered using this mechanism.
1946      *
1947      * Passing one argument retrieves an existing {@link angular.Module},
1948      * whereas passing more than one argument creates a new {@link angular.Module}
1949      *
1950      *
1951      * # Module
1952      *
1953      * A module is a collection of services, directives, controllers, filters, and configuration information.
1954      * `angular.module` is used to configure the {@link auto.$injector $injector}.
1955      *
1956      * ```js
1957      * // Create a new module
1958      * var myModule = angular.module('myModule', []);
1959      *
1960      * // register a new service
1961      * myModule.value('appName', 'MyCoolApp');
1962      *
1963      * // configure existing services inside initialization blocks.
1964      * myModule.config(['$locationProvider', function($locationProvider) {
1965      *   // Configure existing providers
1966      *   $locationProvider.hashPrefix('!');
1967      * }]);
1968      * ```
1969      *
1970      * Then you can create an injector and load your modules like this:
1971      *
1972      * ```js
1973      * var injector = angular.injector(['ng', 'myModule'])
1974      * ```
1975      *
1976      * However it's more likely that you'll just use
1977      * {@link ng.directive:ngApp ngApp} or
1978      * {@link angular.bootstrap} to simplify this process for you.
1979      *
1980      * @param {!string} name The name of the module to create or retrieve.
1981      * @param {!Array.<string>=} requires If specified then new module is being created. If
1982      *        unspecified then the module is being retrieved for further configuration.
1983      * @param {Function=} configFn Optional configuration function for the module. Same as
1984      *        {@link angular.Module#config Module#config()}.
1985      * @returns {module} new module with the {@link angular.Module} api.
1986      */
1987     return function module(name, requires, configFn) {
1988       var assertNotHasOwnProperty = function(name, context) {
1989         if (name === 'hasOwnProperty') {
1990           throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
1991         }
1992       };
1993
1994       assertNotHasOwnProperty(name, 'module');
1995       if (requires && modules.hasOwnProperty(name)) {
1996         modules[name] = null;
1997       }
1998       return ensure(modules, name, function() {
1999         if (!requires) {
2000           throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
2001              "the module name or forgot to load it. If registering a module ensure that you " +
2002              "specify the dependencies as the second argument.", name);
2003         }
2004
2005         /** @type {!Array.<Array.<*>>} */
2006         var invokeQueue = [];
2007
2008         /** @type {!Array.<Function>} */
2009         var configBlocks = [];
2010
2011         /** @type {!Array.<Function>} */
2012         var runBlocks = [];
2013
2014         var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
2015
2016         /** @type {angular.Module} */
2017         var moduleInstance = {
2018           // Private state
2019           _invokeQueue: invokeQueue,
2020           _configBlocks: configBlocks,
2021           _runBlocks: runBlocks,
2022
2023           /**
2024            * @ngdoc property
2025            * @name angular.Module#requires
2026            * @module ng
2027            *
2028            * @description
2029            * Holds the list of modules which the injector will load before the current module is
2030            * loaded.
2031            */
2032           requires: requires,
2033
2034           /**
2035            * @ngdoc property
2036            * @name angular.Module#name
2037            * @module ng
2038            *
2039            * @description
2040            * Name of the module.
2041            */
2042           name: name,
2043
2044
2045           /**
2046            * @ngdoc method
2047            * @name angular.Module#provider
2048            * @module ng
2049            * @param {string} name service name
2050            * @param {Function} providerType Construction function for creating new instance of the
2051            *                                service.
2052            * @description
2053            * See {@link auto.$provide#provider $provide.provider()}.
2054            */
2055           provider: invokeLaterAndSetModuleName('$provide', 'provider'),
2056
2057           /**
2058            * @ngdoc method
2059            * @name angular.Module#factory
2060            * @module ng
2061            * @param {string} name service name
2062            * @param {Function} providerFunction Function for creating new instance of the service.
2063            * @description
2064            * See {@link auto.$provide#factory $provide.factory()}.
2065            */
2066           factory: invokeLaterAndSetModuleName('$provide', 'factory'),
2067
2068           /**
2069            * @ngdoc method
2070            * @name angular.Module#service
2071            * @module ng
2072            * @param {string} name service name
2073            * @param {Function} constructor A constructor function that will be instantiated.
2074            * @description
2075            * See {@link auto.$provide#service $provide.service()}.
2076            */
2077           service: invokeLaterAndSetModuleName('$provide', 'service'),
2078
2079           /**
2080            * @ngdoc method
2081            * @name angular.Module#value
2082            * @module ng
2083            * @param {string} name service name
2084            * @param {*} object Service instance object.
2085            * @description
2086            * See {@link auto.$provide#value $provide.value()}.
2087            */
2088           value: invokeLater('$provide', 'value'),
2089
2090           /**
2091            * @ngdoc method
2092            * @name angular.Module#constant
2093            * @module ng
2094            * @param {string} name constant name
2095            * @param {*} object Constant value.
2096            * @description
2097            * Because the constants are fixed, they get applied before other provide methods.
2098            * See {@link auto.$provide#constant $provide.constant()}.
2099            */
2100           constant: invokeLater('$provide', 'constant', 'unshift'),
2101
2102            /**
2103            * @ngdoc method
2104            * @name angular.Module#decorator
2105            * @module ng
2106            * @param {string} The name of the service to decorate.
2107            * @param {Function} This function will be invoked when the service needs to be
2108            *                                    instantiated and should return the decorated service instance.
2109            * @description
2110            * See {@link auto.$provide#decorator $provide.decorator()}.
2111            */
2112           decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
2113
2114           /**
2115            * @ngdoc method
2116            * @name angular.Module#animation
2117            * @module ng
2118            * @param {string} name animation name
2119            * @param {Function} animationFactory Factory function for creating new instance of an
2120            *                                    animation.
2121            * @description
2122            *
2123            * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
2124            *
2125            *
2126            * Defines an animation hook that can be later used with
2127            * {@link $animate $animate} service and directives that use this service.
2128            *
2129            * ```js
2130            * module.animation('.animation-name', function($inject1, $inject2) {
2131            *   return {
2132            *     eventName : function(element, done) {
2133            *       //code to run the animation
2134            *       //once complete, then run done()
2135            *       return function cancellationFunction(element) {
2136            *         //code to cancel the animation
2137            *       }
2138            *     }
2139            *   }
2140            * })
2141            * ```
2142            *
2143            * See {@link ng.$animateProvider#register $animateProvider.register()} and
2144            * {@link ngAnimate ngAnimate module} for more information.
2145            */
2146           animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
2147
2148           /**
2149            * @ngdoc method
2150            * @name angular.Module#filter
2151            * @module ng
2152            * @param {string} name Filter name - this must be a valid angular expression identifier
2153            * @param {Function} filterFactory Factory function for creating new instance of filter.
2154            * @description
2155            * See {@link ng.$filterProvider#register $filterProvider.register()}.
2156            *
2157            * <div class="alert alert-warning">
2158            * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
2159            * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
2160            * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
2161            * (`myapp_subsection_filterx`).
2162            * </div>
2163            */
2164           filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
2165
2166           /**
2167            * @ngdoc method
2168            * @name angular.Module#controller
2169            * @module ng
2170            * @param {string|Object} name Controller name, or an object map of controllers where the
2171            *    keys are the names and the values are the constructors.
2172            * @param {Function} constructor Controller constructor function.
2173            * @description
2174            * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
2175            */
2176           controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
2177
2178           /**
2179            * @ngdoc method
2180            * @name angular.Module#directive
2181            * @module ng
2182            * @param {string|Object} name Directive name, or an object map of directives where the
2183            *    keys are the names and the values are the factories.
2184            * @param {Function} directiveFactory Factory function for creating new instance of
2185            * directives.
2186            * @description
2187            * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
2188            */
2189           directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
2190
2191           /**
2192            * @ngdoc method
2193            * @name angular.Module#component
2194            * @module ng
2195            * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
2196            * @param {Object} options Component definition object (a simplified
2197            *    {@link ng.$compile#directive-definition-object directive definition object}),
2198            *    has the following properties (all optional):
2199            *
2200            *    - `controller` – `{(string|function()=}` – Controller constructor function that should be
2201            *      associated with newly created scope or the name of a {@link ng.$compile#-controller-
2202            *      registered controller} if passed as a string. Empty function by default.
2203            *    - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
2204            *      If present, the controller will be published to scope under the `controllerAs` name.
2205            *      If not present, this will default to be the same as the component name.
2206            *    - `template` – `{string=|function()=}` – html template as a string or a function that
2207            *      returns an html template as a string which should be used as the contents of this component.
2208            *      Empty string by default.
2209            *
2210            *      If `template` is a function, then it is {@link auto.$injector#invoke injected} with
2211            *      the following locals:
2212            *
2213            *      - `$element` - Current element
2214            *      - `$attrs` - Current attributes object for the element
2215            *
2216            *    - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
2217            *      template that should be used  as the contents of this component.
2218            *
2219            *      If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
2220            *      the following locals:
2221            *
2222            *      - `$element` - Current element
2223            *      - `$attrs` - Current attributes object for the element
2224            *    - `bindings` – `{object=}` – Define DOM attribute binding to component properties.
2225            *      Component properties are always bound to the component controller and not to the scope.
2226            *    - `transclude` – `{boolean=}` – Whether {@link $compile#transclusion transclusion} is enabled.
2227            *      Enabled by default.
2228            *    - `isolate` – `{boolean=}` – Whether the new scope is isolated. Isolated by default.
2229            *    - `restrict` - `{string=}` - String of subset of {@link ng.$compile#-restrict- EACM} which
2230            *      restricts the component to specific directive declaration style. If omitted, this defaults to 'E'.
2231            *    - `$canActivate` – `{function()=}` – TBD.
2232            *    - `$routeConfig` – `{object=}` – TBD.
2233            *
2234            * @description
2235            * Register a component definition with the compiler. This is short for registering a specific
2236            * subset of directives which represents actual UI components in your application. Component
2237            * definitions are very simple and do not require the complexity behind defining directives.
2238            * Component definitions usually consist only of the template and the controller backing it.
2239            * In order to make the definition easier, components enforce best practices like controllerAs
2240            * and default behaviors like scope isolation, restrict to elements and allow transclusion.
2241            *
2242            * Here are a few examples of how you would usually define components:
2243            *
2244            * ```js
2245            *   var myMod = angular.module(...);
2246            *   myMod.component('myComp', {
2247            *     template: '<div>My name is {{myComp.name}}</div>',
2248            *     controller: function() {
2249            *       this.name = 'shahar';
2250            *     }
2251            *   });
2252            *
2253            *   myMod.component('myComp', {
2254            *     template: '<div>My name is {{myComp.name}}</div>',
2255            *     bindings: {name: '@'}
2256            *   });
2257            *
2258            *   myMod.component('myComp', {
2259            *     templateUrl: 'views/my-comp.html',
2260            *     controller: 'MyCtrl as ctrl',
2261            *     bindings: {name: '@'}
2262            *   });
2263            *
2264            * ```
2265            *
2266            * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
2267            */
2268           component: function(name, options) {
2269             function factory($injector) {
2270               function makeInjectable(fn) {
2271                 if (angular.isFunction(fn)) {
2272                   return function(tElement, tAttrs) {
2273                     return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
2274                   };
2275                 } else {
2276                   return fn;
2277                 }
2278               }
2279
2280               var template = (!options.template && !options.templateUrl ? '' : options.template);
2281               return {
2282                 controller: options.controller || function() {},
2283                 controllerAs: identifierForController(options.controller) || options.controllerAs || name,
2284                 template: makeInjectable(template),
2285                 templateUrl: makeInjectable(options.templateUrl),
2286                 transclude: options.transclude === undefined ? true : options.transclude,
2287                 scope: options.isolate === false ? true : {},
2288                 bindToController: options.bindings || {},
2289                 restrict: options.restrict || 'E'
2290               };
2291             }
2292
2293             if (options.$canActivate) {
2294               factory.$canActivate = options.$canActivate;
2295             }
2296             if (options.$routeConfig) {
2297               factory.$routeConfig = options.$routeConfig;
2298             }
2299             factory.$inject = ['$injector'];
2300
2301             return moduleInstance.directive(name, factory);
2302           },
2303
2304           /**
2305            * @ngdoc method
2306            * @name angular.Module#config
2307            * @module ng
2308            * @param {Function} configFn Execute this function on module load. Useful for service
2309            *    configuration.
2310            * @description
2311            * Use this method to register work which needs to be performed on module loading.
2312            * For more about how to configure services, see
2313            * {@link providers#provider-recipe Provider Recipe}.
2314            */
2315           config: config,
2316
2317           /**
2318            * @ngdoc method
2319            * @name angular.Module#run
2320            * @module ng
2321            * @param {Function} initializationFn Execute this function after injector creation.
2322            *    Useful for application initialization.
2323            * @description
2324            * Use this method to register work which should be performed when the injector is done
2325            * loading all modules.
2326            */
2327           run: function(block) {
2328             runBlocks.push(block);
2329             return this;
2330           }
2331         };
2332
2333         if (configFn) {
2334           config(configFn);
2335         }
2336
2337         return moduleInstance;
2338
2339         /**
2340          * @param {string} provider
2341          * @param {string} method
2342          * @param {String=} insertMethod
2343          * @returns {angular.Module}
2344          */
2345         function invokeLater(provider, method, insertMethod, queue) {
2346           if (!queue) queue = invokeQueue;
2347           return function() {
2348             queue[insertMethod || 'push']([provider, method, arguments]);
2349             return moduleInstance;
2350           };
2351         }
2352
2353         /**
2354          * @param {string} provider
2355          * @param {string} method
2356          * @returns {angular.Module}
2357          */
2358         function invokeLaterAndSetModuleName(provider, method) {
2359           return function(recipeName, factoryFunction) {
2360             if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
2361             invokeQueue.push([provider, method, arguments]);
2362             return moduleInstance;
2363           };
2364         }
2365       });
2366     };
2367   });
2368
2369 }
2370
2371 /* global: toDebugString: true */
2372
2373 function serializeObject(obj) {
2374   var seen = [];
2375
2376   return JSON.stringify(obj, function(key, val) {
2377     val = toJsonReplacer(key, val);
2378     if (isObject(val)) {
2379
2380       if (seen.indexOf(val) >= 0) return '...';
2381
2382       seen.push(val);
2383     }
2384     return val;
2385   });
2386 }
2387
2388 function toDebugString(obj) {
2389   if (typeof obj === 'function') {
2390     return obj.toString().replace(/ \{[\s\S]*$/, '');
2391   } else if (isUndefined(obj)) {
2392     return 'undefined';
2393   } else if (typeof obj !== 'string') {
2394     return serializeObject(obj);
2395   }
2396   return obj;
2397 }
2398
2399 /* global angularModule: true,
2400   version: true,
2401
2402   $CompileProvider,
2403
2404   htmlAnchorDirective,
2405   inputDirective,
2406   inputDirective,
2407   formDirective,
2408   scriptDirective,
2409   selectDirective,
2410   styleDirective,
2411   optionDirective,
2412   ngBindDirective,
2413   ngBindHtmlDirective,
2414   ngBindTemplateDirective,
2415   ngClassDirective,
2416   ngClassEvenDirective,
2417   ngClassOddDirective,
2418   ngCloakDirective,
2419   ngControllerDirective,
2420   ngFormDirective,
2421   ngHideDirective,
2422   ngIfDirective,
2423   ngIncludeDirective,
2424   ngIncludeFillContentDirective,
2425   ngInitDirective,
2426   ngNonBindableDirective,
2427   ngPluralizeDirective,
2428   ngRepeatDirective,
2429   ngShowDirective,
2430   ngStyleDirective,
2431   ngSwitchDirective,
2432   ngSwitchWhenDirective,
2433   ngSwitchDefaultDirective,
2434   ngOptionsDirective,
2435   ngTranscludeDirective,
2436   ngModelDirective,
2437   ngListDirective,
2438   ngChangeDirective,
2439   patternDirective,
2440   patternDirective,
2441   requiredDirective,
2442   requiredDirective,
2443   minlengthDirective,
2444   minlengthDirective,
2445   maxlengthDirective,
2446   maxlengthDirective,
2447   ngValueDirective,
2448   ngModelOptionsDirective,
2449   ngAttributeAliasDirectives,
2450   ngEventDirectives,
2451
2452   $AnchorScrollProvider,
2453   $AnimateProvider,
2454   $CoreAnimateCssProvider,
2455   $$CoreAnimateQueueProvider,
2456   $$CoreAnimateRunnerProvider,
2457   $BrowserProvider,
2458   $CacheFactoryProvider,
2459   $ControllerProvider,
2460   $DateProvider,
2461   $DocumentProvider,
2462   $ExceptionHandlerProvider,
2463   $FilterProvider,
2464   $$ForceReflowProvider,
2465   $InterpolateProvider,
2466   $IntervalProvider,
2467   $$HashMapProvider,
2468   $HttpProvider,
2469   $HttpParamSerializerProvider,
2470   $HttpParamSerializerJQLikeProvider,
2471   $HttpBackendProvider,
2472   $xhrFactoryProvider,
2473   $LocationProvider,
2474   $LogProvider,
2475   $ParseProvider,
2476   $RootScopeProvider,
2477   $QProvider,
2478   $$QProvider,
2479   $$SanitizeUriProvider,
2480   $SceProvider,
2481   $SceDelegateProvider,
2482   $SnifferProvider,
2483   $TemplateCacheProvider,
2484   $TemplateRequestProvider,
2485   $$TestabilityProvider,
2486   $TimeoutProvider,
2487   $$RAFProvider,
2488   $WindowProvider,
2489   $$jqLiteProvider,
2490   $$CookieReaderProvider
2491 */
2492
2493
2494 /**
2495  * @ngdoc object
2496  * @name angular.version
2497  * @module ng
2498  * @description
2499  * An object that contains information about the current AngularJS version.
2500  *
2501  * This object has the following properties:
2502  *
2503  * - `full` – `{string}` – Full version string, such as "0.9.18".
2504  * - `major` – `{number}` – Major version number, such as "0".
2505  * - `minor` – `{number}` – Minor version number, such as "9".
2506  * - `dot` – `{number}` – Dot version number, such as "18".
2507  * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
2508  */
2509 var version = {
2510   full: '1.5.0-beta.2',    // all of these placeholder strings will be replaced by grunt's
2511   major: 1,    // package task
2512   minor: 5,
2513   dot: 0,
2514   codeName: 'effective-delegation'
2515 };
2516
2517
2518 function publishExternalAPI(angular) {
2519   extend(angular, {
2520     'bootstrap': bootstrap,
2521     'copy': copy,
2522     'extend': extend,
2523     'merge': merge,
2524     'equals': equals,
2525     'element': jqLite,
2526     'forEach': forEach,
2527     'injector': createInjector,
2528     'noop': noop,
2529     'bind': bind,
2530     'toJson': toJson,
2531     'fromJson': fromJson,
2532     'identity': identity,
2533     'isUndefined': isUndefined,
2534     'isDefined': isDefined,
2535     'isString': isString,
2536     'isFunction': isFunction,
2537     'isObject': isObject,
2538     'isNumber': isNumber,
2539     'isElement': isElement,
2540     'isArray': isArray,
2541     'version': version,
2542     'isDate': isDate,
2543     'lowercase': lowercase,
2544     'uppercase': uppercase,
2545     'callbacks': {counter: 0},
2546     'getTestability': getTestability,
2547     '$$minErr': minErr,
2548     '$$csp': csp,
2549     'reloadWithDebugInfo': reloadWithDebugInfo
2550   });
2551
2552   angularModule = setupModuleLoader(window);
2553
2554   angularModule('ng', ['ngLocale'], ['$provide',
2555     function ngModule($provide) {
2556       // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
2557       $provide.provider({
2558         $$sanitizeUri: $$SanitizeUriProvider
2559       });
2560       $provide.provider('$compile', $CompileProvider).
2561         directive({
2562             a: htmlAnchorDirective,
2563             input: inputDirective,
2564             textarea: inputDirective,
2565             form: formDirective,
2566             script: scriptDirective,
2567             select: selectDirective,
2568             style: styleDirective,
2569             option: optionDirective,
2570             ngBind: ngBindDirective,
2571             ngBindHtml: ngBindHtmlDirective,
2572             ngBindTemplate: ngBindTemplateDirective,
2573             ngClass: ngClassDirective,
2574             ngClassEven: ngClassEvenDirective,
2575             ngClassOdd: ngClassOddDirective,
2576             ngCloak: ngCloakDirective,
2577             ngController: ngControllerDirective,
2578             ngForm: ngFormDirective,
2579             ngHide: ngHideDirective,
2580             ngIf: ngIfDirective,
2581             ngInclude: ngIncludeDirective,
2582             ngInit: ngInitDirective,
2583             ngNonBindable: ngNonBindableDirective,
2584             ngPluralize: ngPluralizeDirective,
2585             ngRepeat: ngRepeatDirective,
2586             ngShow: ngShowDirective,
2587             ngStyle: ngStyleDirective,
2588             ngSwitch: ngSwitchDirective,
2589             ngSwitchWhen: ngSwitchWhenDirective,
2590             ngSwitchDefault: ngSwitchDefaultDirective,
2591             ngOptions: ngOptionsDirective,
2592             ngTransclude: ngTranscludeDirective,
2593             ngModel: ngModelDirective,
2594             ngList: ngListDirective,
2595             ngChange: ngChangeDirective,
2596             pattern: patternDirective,
2597             ngPattern: patternDirective,
2598             required: requiredDirective,
2599             ngRequired: requiredDirective,
2600             minlength: minlengthDirective,
2601             ngMinlength: minlengthDirective,
2602             maxlength: maxlengthDirective,
2603             ngMaxlength: maxlengthDirective,
2604             ngValue: ngValueDirective,
2605             ngModelOptions: ngModelOptionsDirective
2606         }).
2607         directive({
2608           ngInclude: ngIncludeFillContentDirective
2609         }).
2610         directive(ngAttributeAliasDirectives).
2611         directive(ngEventDirectives);
2612       $provide.provider({
2613         $anchorScroll: $AnchorScrollProvider,
2614         $animate: $AnimateProvider,
2615         $animateCss: $CoreAnimateCssProvider,
2616         $$animateQueue: $$CoreAnimateQueueProvider,
2617         $$AnimateRunner: $$CoreAnimateRunnerProvider,
2618         $browser: $BrowserProvider,
2619         $cacheFactory: $CacheFactoryProvider,
2620         $controller: $ControllerProvider,
2621         $document: $DocumentProvider,
2622         $exceptionHandler: $ExceptionHandlerProvider,
2623         $filter: $FilterProvider,
2624         $$forceReflow: $$ForceReflowProvider,
2625         $interpolate: $InterpolateProvider,
2626         $interval: $IntervalProvider,
2627         $http: $HttpProvider,
2628         $httpParamSerializer: $HttpParamSerializerProvider,
2629         $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
2630         $httpBackend: $HttpBackendProvider,
2631         $xhrFactory: $xhrFactoryProvider,
2632         $location: $LocationProvider,
2633         $log: $LogProvider,
2634         $parse: $ParseProvider,
2635         $rootScope: $RootScopeProvider,
2636         $q: $QProvider,
2637         $$q: $$QProvider,
2638         $sce: $SceProvider,
2639         $sceDelegate: $SceDelegateProvider,
2640         $sniffer: $SnifferProvider,
2641         $templateCache: $TemplateCacheProvider,
2642         $templateRequest: $TemplateRequestProvider,
2643         $$testability: $$TestabilityProvider,
2644         $timeout: $TimeoutProvider,
2645         $window: $WindowProvider,
2646         $$rAF: $$RAFProvider,
2647         $$jqLite: $$jqLiteProvider,
2648         $$HashMap: $$HashMapProvider,
2649         $$cookieReader: $$CookieReaderProvider
2650       });
2651     }
2652   ]);
2653 }
2654
2655 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2656  *     Any commits to this file should be reviewed with security in mind.  *
2657  *   Changes to this file can potentially create security vulnerabilities. *
2658  *          An approval from 2 Core members with history of modifying      *
2659  *                         this file is required.                          *
2660  *                                                                         *
2661  *  Does the change somehow allow for arbitrary javascript to be executed? *
2662  *    Or allows for someone to change the prototype of built-in objects?   *
2663  *     Or gives undesired access to variables likes document or window?    *
2664  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2665
2666 /* global JQLitePrototype: true,
2667   addEventListenerFn: true,
2668   removeEventListenerFn: true,
2669   BOOLEAN_ATTR: true,
2670   ALIASED_ATTR: true,
2671 */
2672
2673 //////////////////////////////////
2674 //JQLite
2675 //////////////////////////////////
2676
2677 /**
2678  * @ngdoc function
2679  * @name angular.element
2680  * @module ng
2681  * @kind function
2682  *
2683  * @description
2684  * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
2685  *
2686  * If jQuery is available, `angular.element` is an alias for the
2687  * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
2688  * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
2689  *
2690  * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
2691  * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
2692  * commonly needed functionality with the goal of having a very small footprint.</div>
2693  *
2694  * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
2695  *
2696  * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
2697  * jqLite; they are never raw DOM references.</div>
2698  *
2699  * ## Angular's jqLite
2700  * jqLite provides only the following jQuery methods:
2701  *
2702  * - [`addClass()`](http://api.jquery.com/addClass/)
2703  * - [`after()`](http://api.jquery.com/after/)
2704  * - [`append()`](http://api.jquery.com/append/)
2705  * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
2706  * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
2707  * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
2708  * - [`clone()`](http://api.jquery.com/clone/)
2709  * - [`contents()`](http://api.jquery.com/contents/)
2710  * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
2711  * - [`data()`](http://api.jquery.com/data/)
2712  * - [`detach()`](http://api.jquery.com/detach/)
2713  * - [`empty()`](http://api.jquery.com/empty/)
2714  * - [`eq()`](http://api.jquery.com/eq/)
2715  * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
2716  * - [`hasClass()`](http://api.jquery.com/hasClass/)
2717  * - [`html()`](http://api.jquery.com/html/)
2718  * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
2719  * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
2720  * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
2721  * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
2722  * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
2723  * - [`prepend()`](http://api.jquery.com/prepend/)
2724  * - [`prop()`](http://api.jquery.com/prop/)
2725  * - [`ready()`](http://api.jquery.com/ready/)
2726  * - [`remove()`](http://api.jquery.com/remove/)
2727  * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
2728  * - [`removeClass()`](http://api.jquery.com/removeClass/)
2729  * - [`removeData()`](http://api.jquery.com/removeData/)
2730  * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
2731  * - [`text()`](http://api.jquery.com/text/)
2732  * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
2733  * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
2734  * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
2735  * - [`val()`](http://api.jquery.com/val/)
2736  * - [`wrap()`](http://api.jquery.com/wrap/)
2737  *
2738  * ## jQuery/jqLite Extras
2739  * Angular also provides the following additional methods and events to both jQuery and jqLite:
2740  *
2741  * ### Events
2742  * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
2743  *    on all DOM nodes being removed.  This can be used to clean up any 3rd party bindings to the DOM
2744  *    element before it is removed.
2745  *
2746  * ### Methods
2747  * - `controller(name)` - retrieves the controller of the current element or its parent. By default
2748  *   retrieves controller associated with the `ngController` directive. If `name` is provided as
2749  *   camelCase directive name, then the controller for this directive will be retrieved (e.g.
2750  *   `'ngModel'`).
2751  * - `injector()` - retrieves the injector of the current element or its parent.
2752  * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
2753  *   element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
2754  *   be enabled.
2755  * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
2756  *   current element. This getter should be used only on elements that contain a directive which starts a new isolate
2757  *   scope. Calling `scope()` on this element always returns the original non-isolate scope.
2758  *   Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
2759  * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
2760  *   parent element is reached.
2761  *
2762  * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
2763  * @returns {Object} jQuery object.
2764  */
2765
2766 JQLite.expando = 'ng339';
2767
2768 var jqCache = JQLite.cache = {},
2769     jqId = 1,
2770     addEventListenerFn = function(element, type, fn) {
2771       element.addEventListener(type, fn, false);
2772     },
2773     removeEventListenerFn = function(element, type, fn) {
2774       element.removeEventListener(type, fn, false);
2775     };
2776
2777 /*
2778  * !!! This is an undocumented "private" function !!!
2779  */
2780 JQLite._data = function(node) {
2781   //jQuery always returns an object on cache miss
2782   return this.cache[node[this.expando]] || {};
2783 };
2784
2785 function jqNextId() { return ++jqId; }
2786
2787
2788 var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
2789 var MOZ_HACK_REGEXP = /^moz([A-Z])/;
2790 var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
2791 var jqLiteMinErr = minErr('jqLite');
2792
2793 /**
2794  * Converts snake_case to camelCase.
2795  * Also there is special case for Moz prefix starting with upper case letter.
2796  * @param name Name to normalize
2797  */
2798 function camelCase(name) {
2799   return name.
2800     replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
2801       return offset ? letter.toUpperCase() : letter;
2802     }).
2803     replace(MOZ_HACK_REGEXP, 'Moz$1');
2804 }
2805
2806 var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
2807 var HTML_REGEXP = /<|&#?\w+;/;
2808 var TAG_NAME_REGEXP = /<([\w:-]+)/;
2809 var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
2810
2811 var wrapMap = {
2812   'option': [1, '<select multiple="multiple">', '</select>'],
2813
2814   'thead': [1, '<table>', '</table>'],
2815   'col': [2, '<table><colgroup>', '</colgroup></table>'],
2816   'tr': [2, '<table><tbody>', '</tbody></table>'],
2817   'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
2818   '_default': [0, "", ""]
2819 };
2820
2821 wrapMap.optgroup = wrapMap.option;
2822 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
2823 wrapMap.th = wrapMap.td;
2824
2825
2826 function jqLiteIsTextNode(html) {
2827   return !HTML_REGEXP.test(html);
2828 }
2829
2830 function jqLiteAcceptsData(node) {
2831   // The window object can accept data but has no nodeType
2832   // Otherwise we are only interested in elements (1) and documents (9)
2833   var nodeType = node.nodeType;
2834   return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
2835 }
2836
2837 function jqLiteHasData(node) {
2838   for (var key in jqCache[node.ng339]) {
2839     return true;
2840   }
2841   return false;
2842 }
2843
2844 function jqLiteCleanData(nodes) {
2845   for (var i = 0, ii = nodes.length; i < ii; i++) {
2846     jqLiteRemoveData(nodes[i]);
2847   }
2848 }
2849
2850 function jqLiteBuildFragment(html, context) {
2851   var tmp, tag, wrap,
2852       fragment = context.createDocumentFragment(),
2853       nodes = [], i;
2854
2855   if (jqLiteIsTextNode(html)) {
2856     // Convert non-html into a text node
2857     nodes.push(context.createTextNode(html));
2858   } else {
2859     // Convert html into DOM nodes
2860     tmp = tmp || fragment.appendChild(context.createElement("div"));
2861     tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
2862     wrap = wrapMap[tag] || wrapMap._default;
2863     tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
2864
2865     // Descend through wrappers to the right content
2866     i = wrap[0];
2867     while (i--) {
2868       tmp = tmp.lastChild;
2869     }
2870
2871     nodes = concat(nodes, tmp.childNodes);
2872
2873     tmp = fragment.firstChild;
2874     tmp.textContent = "";
2875   }
2876
2877   // Remove wrapper from fragment
2878   fragment.textContent = "";
2879   fragment.innerHTML = ""; // Clear inner HTML
2880   forEach(nodes, function(node) {
2881     fragment.appendChild(node);
2882   });
2883
2884   return fragment;
2885 }
2886
2887 function jqLiteParseHTML(html, context) {
2888   context = context || document;
2889   var parsed;
2890
2891   if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
2892     return [context.createElement(parsed[1])];
2893   }
2894
2895   if ((parsed = jqLiteBuildFragment(html, context))) {
2896     return parsed.childNodes;
2897   }
2898
2899   return [];
2900 }
2901
2902
2903 // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
2904 var jqLiteContains = Node.prototype.contains || function(arg) {
2905   // jshint bitwise: false
2906   return !!(this.compareDocumentPosition(arg) & 16);
2907   // jshint bitwise: true
2908 };
2909
2910 /////////////////////////////////////////////
2911 function JQLite(element) {
2912   if (element instanceof JQLite) {
2913     return element;
2914   }
2915
2916   var argIsString;
2917
2918   if (isString(element)) {
2919     element = trim(element);
2920     argIsString = true;
2921   }
2922   if (!(this instanceof JQLite)) {
2923     if (argIsString && element.charAt(0) != '<') {
2924       throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
2925     }
2926     return new JQLite(element);
2927   }
2928
2929   if (argIsString) {
2930     jqLiteAddNodes(this, jqLiteParseHTML(element));
2931   } else {
2932     jqLiteAddNodes(this, element);
2933   }
2934 }
2935
2936 function jqLiteClone(element) {
2937   return element.cloneNode(true);
2938 }
2939
2940 function jqLiteDealoc(element, onlyDescendants) {
2941   if (!onlyDescendants) jqLiteRemoveData(element);
2942
2943   if (element.querySelectorAll) {
2944     var descendants = element.querySelectorAll('*');
2945     for (var i = 0, l = descendants.length; i < l; i++) {
2946       jqLiteRemoveData(descendants[i]);
2947     }
2948   }
2949 }
2950
2951 function jqLiteOff(element, type, fn, unsupported) {
2952   if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
2953
2954   var expandoStore = jqLiteExpandoStore(element);
2955   var events = expandoStore && expandoStore.events;
2956   var handle = expandoStore && expandoStore.handle;
2957
2958   if (!handle) return; //no listeners registered
2959
2960   if (!type) {
2961     for (type in events) {
2962       if (type !== '$destroy') {
2963         removeEventListenerFn(element, type, handle);
2964       }
2965       delete events[type];
2966     }
2967   } else {
2968
2969     var removeHandler = function(type) {
2970       var listenerFns = events[type];
2971       if (isDefined(fn)) {
2972         arrayRemove(listenerFns || [], fn);
2973       }
2974       if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
2975         removeEventListenerFn(element, type, handle);
2976         delete events[type];
2977       }
2978     };
2979
2980     forEach(type.split(' '), function(type) {
2981       removeHandler(type);
2982       if (MOUSE_EVENT_MAP[type]) {
2983         removeHandler(MOUSE_EVENT_MAP[type]);
2984       }
2985     });
2986   }
2987 }
2988
2989 function jqLiteRemoveData(element, name) {
2990   var expandoId = element.ng339;
2991   var expandoStore = expandoId && jqCache[expandoId];
2992
2993   if (expandoStore) {
2994     if (name) {
2995       delete expandoStore.data[name];
2996       return;
2997     }
2998
2999     if (expandoStore.handle) {
3000       if (expandoStore.events.$destroy) {
3001         expandoStore.handle({}, '$destroy');
3002       }
3003       jqLiteOff(element);
3004     }
3005     delete jqCache[expandoId];
3006     element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
3007   }
3008 }
3009
3010
3011 function jqLiteExpandoStore(element, createIfNecessary) {
3012   var expandoId = element.ng339,
3013       expandoStore = expandoId && jqCache[expandoId];
3014
3015   if (createIfNecessary && !expandoStore) {
3016     element.ng339 = expandoId = jqNextId();
3017     expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
3018   }
3019
3020   return expandoStore;
3021 }
3022
3023
3024 function jqLiteData(element, key, value) {
3025   if (jqLiteAcceptsData(element)) {
3026
3027     var isSimpleSetter = isDefined(value);
3028     var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
3029     var massGetter = !key;
3030     var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
3031     var data = expandoStore && expandoStore.data;
3032
3033     if (isSimpleSetter) { // data('key', value)
3034       data[key] = value;
3035     } else {
3036       if (massGetter) {  // data()
3037         return data;
3038       } else {
3039         if (isSimpleGetter) { // data('key')
3040           // don't force creation of expandoStore if it doesn't exist yet
3041           return data && data[key];
3042         } else { // mass-setter: data({key1: val1, key2: val2})
3043           extend(data, key);
3044         }
3045       }
3046     }
3047   }
3048 }
3049
3050 function jqLiteHasClass(element, selector) {
3051   if (!element.getAttribute) return false;
3052   return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
3053       indexOf(" " + selector + " ") > -1);
3054 }
3055
3056 function jqLiteRemoveClass(element, cssClasses) {
3057   if (cssClasses && element.setAttribute) {
3058     forEach(cssClasses.split(' '), function(cssClass) {
3059       element.setAttribute('class', trim(
3060           (" " + (element.getAttribute('class') || '') + " ")
3061           .replace(/[\n\t]/g, " ")
3062           .replace(" " + trim(cssClass) + " ", " "))
3063       );
3064     });
3065   }
3066 }
3067
3068 function jqLiteAddClass(element, cssClasses) {
3069   if (cssClasses && element.setAttribute) {
3070     var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
3071                             .replace(/[\n\t]/g, " ");
3072
3073     forEach(cssClasses.split(' '), function(cssClass) {
3074       cssClass = trim(cssClass);
3075       if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
3076         existingClasses += cssClass + ' ';
3077       }
3078     });
3079
3080     element.setAttribute('class', trim(existingClasses));
3081   }
3082 }
3083
3084
3085 function jqLiteAddNodes(root, elements) {
3086   // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
3087
3088   if (elements) {
3089
3090     // if a Node (the most common case)
3091     if (elements.nodeType) {
3092       root[root.length++] = elements;
3093     } else {
3094       var length = elements.length;
3095
3096       // if an Array or NodeList and not a Window
3097       if (typeof length === 'number' && elements.window !== elements) {
3098         if (length) {
3099           for (var i = 0; i < length; i++) {
3100             root[root.length++] = elements[i];
3101           }
3102         }
3103       } else {
3104         root[root.length++] = elements;
3105       }
3106     }
3107   }
3108 }
3109
3110
3111 function jqLiteController(element, name) {
3112   return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
3113 }
3114
3115 function jqLiteInheritedData(element, name, value) {
3116   // if element is the document object work with the html element instead
3117   // this makes $(document).scope() possible
3118   if (element.nodeType == NODE_TYPE_DOCUMENT) {
3119     element = element.documentElement;
3120   }
3121   var names = isArray(name) ? name : [name];
3122
3123   while (element) {
3124     for (var i = 0, ii = names.length; i < ii; i++) {
3125       if (isDefined(value = jqLite.data(element, names[i]))) return value;
3126     }
3127
3128     // If dealing with a document fragment node with a host element, and no parent, use the host
3129     // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
3130     // to lookup parent controllers.
3131     element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
3132   }
3133 }
3134
3135 function jqLiteEmpty(element) {
3136   jqLiteDealoc(element, true);
3137   while (element.firstChild) {
3138     element.removeChild(element.firstChild);
3139   }
3140 }
3141
3142 function jqLiteRemove(element, keepData) {
3143   if (!keepData) jqLiteDealoc(element);
3144   var parent = element.parentNode;
3145   if (parent) parent.removeChild(element);
3146 }
3147
3148
3149 function jqLiteDocumentLoaded(action, win) {
3150   win = win || window;
3151   if (win.document.readyState === 'complete') {
3152     // Force the action to be run async for consistent behaviour
3153     // from the action's point of view
3154     // i.e. it will definitely not be in a $apply
3155     win.setTimeout(action);
3156   } else {
3157     // No need to unbind this handler as load is only ever called once
3158     jqLite(win).on('load', action);
3159   }
3160 }
3161
3162 //////////////////////////////////////////
3163 // Functions which are declared directly.
3164 //////////////////////////////////////////
3165 var JQLitePrototype = JQLite.prototype = {
3166   ready: function(fn) {
3167     var fired = false;
3168
3169     function trigger() {
3170       if (fired) return;
3171       fired = true;
3172       fn();
3173     }
3174
3175     // check if document is already loaded
3176     if (document.readyState === 'complete') {
3177       setTimeout(trigger);
3178     } else {
3179       this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
3180       // we can not use jqLite since we are not done loading and jQuery could be loaded later.
3181       // jshint -W064
3182       JQLite(window).on('load', trigger); // fallback to window.onload for others
3183       // jshint +W064
3184     }
3185   },
3186   toString: function() {
3187     var value = [];
3188     forEach(this, function(e) { value.push('' + e);});
3189     return '[' + value.join(', ') + ']';
3190   },
3191
3192   eq: function(index) {
3193       return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
3194   },
3195
3196   length: 0,
3197   push: push,
3198   sort: [].sort,
3199   splice: [].splice
3200 };
3201
3202 //////////////////////////////////////////
3203 // Functions iterating getter/setters.
3204 // these functions return self on setter and
3205 // value on get.
3206 //////////////////////////////////////////
3207 var BOOLEAN_ATTR = {};
3208 forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
3209   BOOLEAN_ATTR[lowercase(value)] = value;
3210 });
3211 var BOOLEAN_ELEMENTS = {};
3212 forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
3213   BOOLEAN_ELEMENTS[value] = true;
3214 });
3215 var ALIASED_ATTR = {
3216   'ngMinlength': 'minlength',
3217   'ngMaxlength': 'maxlength',
3218   'ngMin': 'min',
3219   'ngMax': 'max',
3220   'ngPattern': 'pattern'
3221 };
3222
3223 function getBooleanAttrName(element, name) {
3224   // check dom last since we will most likely fail on name
3225   var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
3226
3227   // booleanAttr is here twice to minimize DOM access
3228   return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
3229 }
3230
3231 function getAliasedAttrName(name) {
3232   return ALIASED_ATTR[name];
3233 }
3234
3235 forEach({
3236   data: jqLiteData,
3237   removeData: jqLiteRemoveData,
3238   hasData: jqLiteHasData,
3239   cleanData: jqLiteCleanData
3240 }, function(fn, name) {
3241   JQLite[name] = fn;
3242 });
3243
3244 forEach({
3245   data: jqLiteData,
3246   inheritedData: jqLiteInheritedData,
3247
3248   scope: function(element) {
3249     // Can't use jqLiteData here directly so we stay compatible with jQuery!
3250     return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
3251   },
3252
3253   isolateScope: function(element) {
3254     // Can't use jqLiteData here directly so we stay compatible with jQuery!
3255     return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
3256   },
3257
3258   controller: jqLiteController,
3259
3260   injector: function(element) {
3261     return jqLiteInheritedData(element, '$injector');
3262   },
3263
3264   removeAttr: function(element, name) {
3265     element.removeAttribute(name);
3266   },
3267
3268   hasClass: jqLiteHasClass,
3269
3270   css: function(element, name, value) {
3271     name = camelCase(name);
3272
3273     if (isDefined(value)) {
3274       element.style[name] = value;
3275     } else {
3276       return element.style[name];
3277     }
3278   },
3279
3280   attr: function(element, name, value) {
3281     var nodeType = element.nodeType;
3282     if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
3283       return;
3284     }
3285     var lowercasedName = lowercase(name);
3286     if (BOOLEAN_ATTR[lowercasedName]) {
3287       if (isDefined(value)) {
3288         if (!!value) {
3289           element[name] = true;
3290           element.setAttribute(name, lowercasedName);
3291         } else {
3292           element[name] = false;
3293           element.removeAttribute(lowercasedName);
3294         }
3295       } else {
3296         return (element[name] ||
3297                  (element.attributes.getNamedItem(name) || noop).specified)
3298                ? lowercasedName
3299                : undefined;
3300       }
3301     } else if (isDefined(value)) {
3302       element.setAttribute(name, value);
3303     } else if (element.getAttribute) {
3304       // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
3305       // some elements (e.g. Document) don't have get attribute, so return undefined
3306       var ret = element.getAttribute(name, 2);
3307       // normalize non-existing attributes to undefined (as jQuery)
3308       return ret === null ? undefined : ret;
3309     }
3310   },
3311
3312   prop: function(element, name, value) {
3313     if (isDefined(value)) {
3314       element[name] = value;
3315     } else {
3316       return element[name];
3317     }
3318   },
3319
3320   text: (function() {
3321     getText.$dv = '';
3322     return getText;
3323
3324     function getText(element, value) {
3325       if (isUndefined(value)) {
3326         var nodeType = element.nodeType;
3327         return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
3328       }
3329       element.textContent = value;
3330     }
3331   })(),
3332
3333   val: function(element, value) {
3334     if (isUndefined(value)) {
3335       if (element.multiple && nodeName_(element) === 'select') {
3336         var result = [];
3337         forEach(element.options, function(option) {
3338           if (option.selected) {
3339             result.push(option.value || option.text);
3340           }
3341         });
3342         return result.length === 0 ? null : result;
3343       }
3344       return element.value;
3345     }
3346     element.value = value;
3347   },
3348
3349   html: function(element, value) {
3350     if (isUndefined(value)) {
3351       return element.innerHTML;
3352     }
3353     jqLiteDealoc(element, true);
3354     element.innerHTML = value;
3355   },
3356
3357   empty: jqLiteEmpty
3358 }, function(fn, name) {
3359   /**
3360    * Properties: writes return selection, reads return first value
3361    */
3362   JQLite.prototype[name] = function(arg1, arg2) {
3363     var i, key;
3364     var nodeCount = this.length;
3365
3366     // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
3367     // in a way that survives minification.
3368     // jqLiteEmpty takes no arguments but is a setter.
3369     if (fn !== jqLiteEmpty &&
3370         (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
3371       if (isObject(arg1)) {
3372
3373         // we are a write, but the object properties are the key/values
3374         for (i = 0; i < nodeCount; i++) {
3375           if (fn === jqLiteData) {
3376             // data() takes the whole object in jQuery
3377             fn(this[i], arg1);
3378           } else {
3379             for (key in arg1) {
3380               fn(this[i], key, arg1[key]);
3381             }
3382           }
3383         }
3384         // return self for chaining
3385         return this;
3386       } else {
3387         // we are a read, so read the first child.
3388         // TODO: do we still need this?
3389         var value = fn.$dv;
3390         // Only if we have $dv do we iterate over all, otherwise it is just the first element.
3391         var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
3392         for (var j = 0; j < jj; j++) {
3393           var nodeValue = fn(this[j], arg1, arg2);
3394           value = value ? value + nodeValue : nodeValue;
3395         }
3396         return value;
3397       }
3398     } else {
3399       // we are a write, so apply to all children
3400       for (i = 0; i < nodeCount; i++) {
3401         fn(this[i], arg1, arg2);
3402       }
3403       // return self for chaining
3404       return this;
3405     }
3406   };
3407 });
3408
3409 function createEventHandler(element, events) {
3410   var eventHandler = function(event, type) {
3411     // jQuery specific api
3412     event.isDefaultPrevented = function() {
3413       return event.defaultPrevented;
3414     };
3415
3416     var eventFns = events[type || event.type];
3417     var eventFnsLength = eventFns ? eventFns.length : 0;
3418
3419     if (!eventFnsLength) return;
3420
3421     if (isUndefined(event.immediatePropagationStopped)) {
3422       var originalStopImmediatePropagation = event.stopImmediatePropagation;
3423       event.stopImmediatePropagation = function() {
3424         event.immediatePropagationStopped = true;
3425
3426         if (event.stopPropagation) {
3427           event.stopPropagation();
3428         }
3429
3430         if (originalStopImmediatePropagation) {
3431           originalStopImmediatePropagation.call(event);
3432         }
3433       };
3434     }
3435
3436     event.isImmediatePropagationStopped = function() {
3437       return event.immediatePropagationStopped === true;
3438     };
3439
3440     // Some events have special handlers that wrap the real handler
3441     var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
3442
3443     // Copy event handlers in case event handlers array is modified during execution.
3444     if ((eventFnsLength > 1)) {
3445       eventFns = shallowCopy(eventFns);
3446     }
3447
3448     for (var i = 0; i < eventFnsLength; i++) {
3449       if (!event.isImmediatePropagationStopped()) {
3450         handlerWrapper(element, event, eventFns[i]);
3451       }
3452     }
3453   };
3454
3455   // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
3456   //       events on `element`
3457   eventHandler.elem = element;
3458   return eventHandler;
3459 }
3460
3461 function defaultHandlerWrapper(element, event, handler) {
3462   handler.call(element, event);
3463 }
3464
3465 function specialMouseHandlerWrapper(target, event, handler) {
3466   // Refer to jQuery's implementation of mouseenter & mouseleave
3467   // Read about mouseenter and mouseleave:
3468   // http://www.quirksmode.org/js/events_mouse.html#link8
3469   var related = event.relatedTarget;
3470   // For mousenter/leave call the handler if related is outside the target.
3471   // NB: No relatedTarget if the mouse left/entered the browser window
3472   if (!related || (related !== target && !jqLiteContains.call(target, related))) {
3473     handler.call(target, event);
3474   }
3475 }
3476
3477 //////////////////////////////////////////
3478 // Functions iterating traversal.
3479 // These functions chain results into a single
3480 // selector.
3481 //////////////////////////////////////////
3482 forEach({
3483   removeData: jqLiteRemoveData,
3484
3485   on: function jqLiteOn(element, type, fn, unsupported) {
3486     if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
3487
3488     // Do not add event handlers to non-elements because they will not be cleaned up.
3489     if (!jqLiteAcceptsData(element)) {
3490       return;
3491     }
3492
3493     var expandoStore = jqLiteExpandoStore(element, true);
3494     var events = expandoStore.events;
3495     var handle = expandoStore.handle;
3496
3497     if (!handle) {
3498       handle = expandoStore.handle = createEventHandler(element, events);
3499     }
3500
3501     // http://jsperf.com/string-indexof-vs-split
3502     var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
3503     var i = types.length;
3504
3505     var addHandler = function(type, specialHandlerWrapper, noEventListener) {
3506       var eventFns = events[type];
3507
3508       if (!eventFns) {
3509         eventFns = events[type] = [];
3510         eventFns.specialHandlerWrapper = specialHandlerWrapper;
3511         if (type !== '$destroy' && !noEventListener) {
3512           addEventListenerFn(element, type, handle);
3513         }
3514       }
3515
3516       eventFns.push(fn);
3517     };
3518
3519     while (i--) {
3520       type = types[i];
3521       if (MOUSE_EVENT_MAP[type]) {
3522         addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
3523         addHandler(type, undefined, true);
3524       } else {
3525         addHandler(type);
3526       }
3527     }
3528   },
3529
3530   off: jqLiteOff,
3531
3532   one: function(element, type, fn) {
3533     element = jqLite(element);
3534
3535     //add the listener twice so that when it is called
3536     //you can remove the original function and still be
3537     //able to call element.off(ev, fn) normally
3538     element.on(type, function onFn() {
3539       element.off(type, fn);
3540       element.off(type, onFn);
3541     });
3542     element.on(type, fn);
3543   },
3544
3545   replaceWith: function(element, replaceNode) {
3546     var index, parent = element.parentNode;
3547     jqLiteDealoc(element);
3548     forEach(new JQLite(replaceNode), function(node) {
3549       if (index) {
3550         parent.insertBefore(node, index.nextSibling);
3551       } else {
3552         parent.replaceChild(node, element);
3553       }
3554       index = node;
3555     });
3556   },
3557
3558   children: function(element) {
3559     var children = [];
3560     forEach(element.childNodes, function(element) {
3561       if (element.nodeType === NODE_TYPE_ELEMENT) {
3562         children.push(element);
3563       }
3564     });
3565     return children;
3566   },
3567
3568   contents: function(element) {
3569     return element.contentDocument || element.childNodes || [];
3570   },
3571
3572   append: function(element, node) {
3573     var nodeType = element.nodeType;
3574     if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
3575
3576     node = new JQLite(node);
3577
3578     for (var i = 0, ii = node.length; i < ii; i++) {
3579       var child = node[i];
3580       element.appendChild(child);
3581     }
3582   },
3583
3584   prepend: function(element, node) {
3585     if (element.nodeType === NODE_TYPE_ELEMENT) {
3586       var index = element.firstChild;
3587       forEach(new JQLite(node), function(child) {
3588         element.insertBefore(child, index);
3589       });
3590     }
3591   },
3592
3593   wrap: function(element, wrapNode) {
3594     wrapNode = jqLite(wrapNode).eq(0).clone()[0];
3595     var parent = element.parentNode;
3596     if (parent) {
3597       parent.replaceChild(wrapNode, element);
3598     }
3599     wrapNode.appendChild(element);
3600   },
3601
3602   remove: jqLiteRemove,
3603
3604   detach: function(element) {
3605     jqLiteRemove(element, true);
3606   },
3607
3608   after: function(element, newElement) {
3609     var index = element, parent = element.parentNode;
3610     newElement = new JQLite(newElement);
3611
3612     for (var i = 0, ii = newElement.length; i < ii; i++) {
3613       var node = newElement[i];
3614       parent.insertBefore(node, index.nextSibling);
3615       index = node;
3616     }
3617   },
3618
3619   addClass: jqLiteAddClass,
3620   removeClass: jqLiteRemoveClass,
3621
3622   toggleClass: function(element, selector, condition) {
3623     if (selector) {
3624       forEach(selector.split(' '), function(className) {
3625         var classCondition = condition;
3626         if (isUndefined(classCondition)) {
3627           classCondition = !jqLiteHasClass(element, className);
3628         }
3629         (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
3630       });
3631     }
3632   },
3633
3634   parent: function(element) {
3635     var parent = element.parentNode;
3636     return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
3637   },
3638
3639   next: function(element) {
3640     return element.nextElementSibling;
3641   },
3642
3643   find: function(element, selector) {
3644     if (element.getElementsByTagName) {
3645       return element.getElementsByTagName(selector);
3646     } else {
3647       return [];
3648     }
3649   },
3650
3651   clone: jqLiteClone,
3652
3653   triggerHandler: function(element, event, extraParameters) {
3654
3655     var dummyEvent, eventFnsCopy, handlerArgs;
3656     var eventName = event.type || event;
3657     var expandoStore = jqLiteExpandoStore(element);
3658     var events = expandoStore && expandoStore.events;
3659     var eventFns = events && events[eventName];
3660
3661     if (eventFns) {
3662       // Create a dummy event to pass to the handlers
3663       dummyEvent = {
3664         preventDefault: function() { this.defaultPrevented = true; },
3665         isDefaultPrevented: function() { return this.defaultPrevented === true; },
3666         stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
3667         isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
3668         stopPropagation: noop,
3669         type: eventName,
3670         target: element
3671       };
3672
3673       // If a custom event was provided then extend our dummy event with it
3674       if (event.type) {
3675         dummyEvent = extend(dummyEvent, event);
3676       }
3677
3678       // Copy event handlers in case event handlers array is modified during execution.
3679       eventFnsCopy = shallowCopy(eventFns);
3680       handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
3681
3682       forEach(eventFnsCopy, function(fn) {
3683         if (!dummyEvent.isImmediatePropagationStopped()) {
3684           fn.apply(element, handlerArgs);
3685         }
3686       });
3687     }
3688   }
3689 }, function(fn, name) {
3690   /**
3691    * chaining functions
3692    */
3693   JQLite.prototype[name] = function(arg1, arg2, arg3) {
3694     var value;
3695
3696     for (var i = 0, ii = this.length; i < ii; i++) {
3697       if (isUndefined(value)) {
3698         value = fn(this[i], arg1, arg2, arg3);
3699         if (isDefined(value)) {
3700           // any function which returns a value needs to be wrapped
3701           value = jqLite(value);
3702         }
3703       } else {
3704         jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
3705       }
3706     }
3707     return isDefined(value) ? value : this;
3708   };
3709
3710   // bind legacy bind/unbind to on/off
3711   JQLite.prototype.bind = JQLite.prototype.on;
3712   JQLite.prototype.unbind = JQLite.prototype.off;
3713 });
3714
3715
3716 // Provider for private $$jqLite service
3717 function $$jqLiteProvider() {
3718   this.$get = function $$jqLite() {
3719     return extend(JQLite, {
3720       hasClass: function(node, classes) {
3721         if (node.attr) node = node[0];
3722         return jqLiteHasClass(node, classes);
3723       },
3724       addClass: function(node, classes) {
3725         if (node.attr) node = node[0];
3726         return jqLiteAddClass(node, classes);
3727       },
3728       removeClass: function(node, classes) {
3729         if (node.attr) node = node[0];
3730         return jqLiteRemoveClass(node, classes);
3731       }
3732     });
3733   };
3734 }
3735
3736 /**
3737  * Computes a hash of an 'obj'.
3738  * Hash of a:
3739  *  string is string
3740  *  number is number as string
3741  *  object is either result of calling $$hashKey function on the object or uniquely generated id,
3742  *         that is also assigned to the $$hashKey property of the object.
3743  *
3744  * @param obj
3745  * @returns {string} hash string such that the same input will have the same hash string.
3746  *         The resulting string key is in 'type:hashKey' format.
3747  */
3748 function hashKey(obj, nextUidFn) {
3749   var key = obj && obj.$$hashKey;
3750
3751   if (key) {
3752     if (typeof key === 'function') {
3753       key = obj.$$hashKey();
3754     }
3755     return key;
3756   }
3757
3758   var objType = typeof obj;
3759   if (objType == 'function' || (objType == 'object' && obj !== null)) {
3760     key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
3761   } else {
3762     key = objType + ':' + obj;
3763   }
3764
3765   return key;
3766 }
3767
3768 /**
3769  * HashMap which can use objects as keys
3770  */
3771 function HashMap(array, isolatedUid) {
3772   if (isolatedUid) {
3773     var uid = 0;
3774     this.nextUid = function() {
3775       return ++uid;
3776     };
3777   }
3778   forEach(array, this.put, this);
3779 }
3780 HashMap.prototype = {
3781   /**
3782    * Store key value pair
3783    * @param key key to store can be any type
3784    * @param value value to store can be any type
3785    */
3786   put: function(key, value) {
3787     this[hashKey(key, this.nextUid)] = value;
3788   },
3789
3790   /**
3791    * @param key
3792    * @returns {Object} the value for the key
3793    */
3794   get: function(key) {
3795     return this[hashKey(key, this.nextUid)];
3796   },
3797
3798   /**
3799    * Remove the key/value pair
3800    * @param key
3801    */
3802   remove: function(key) {
3803     var value = this[key = hashKey(key, this.nextUid)];
3804     delete this[key];
3805     return value;
3806   }
3807 };
3808
3809 var $$HashMapProvider = [function() {
3810   this.$get = [function() {
3811     return HashMap;
3812   }];
3813 }];
3814
3815 /**
3816  * @ngdoc function
3817  * @module ng
3818  * @name angular.injector
3819  * @kind function
3820  *
3821  * @description
3822  * Creates an injector object that can be used for retrieving services as well as for
3823  * dependency injection (see {@link guide/di dependency injection}).
3824  *
3825  * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
3826  *     {@link angular.module}. The `ng` module must be explicitly added.
3827  * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
3828  *     disallows argument name annotation inference.
3829  * @returns {injector} Injector object. See {@link auto.$injector $injector}.
3830  *
3831  * @example
3832  * Typical usage
3833  * ```js
3834  *   // create an injector
3835  *   var $injector = angular.injector(['ng']);
3836  *
3837  *   // use the injector to kick off your application
3838  *   // use the type inference to auto inject arguments, or use implicit injection
3839  *   $injector.invoke(function($rootScope, $compile, $document) {
3840  *     $compile($document)($rootScope);
3841  *     $rootScope.$digest();
3842  *   });
3843  * ```
3844  *
3845  * Sometimes you want to get access to the injector of a currently running Angular app
3846  * from outside Angular. Perhaps, you want to inject and compile some markup after the
3847  * application has been bootstrapped. You can do this using the extra `injector()` added
3848  * to JQuery/jqLite elements. See {@link angular.element}.
3849  *
3850  * *This is fairly rare but could be the case if a third party library is injecting the
3851  * markup.*
3852  *
3853  * In the following example a new block of HTML containing a `ng-controller`
3854  * directive is added to the end of the document body by JQuery. We then compile and link
3855  * it into the current AngularJS scope.
3856  *
3857  * ```js
3858  * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
3859  * $(document.body).append($div);
3860  *
3861  * angular.element(document).injector().invoke(function($compile) {
3862  *   var scope = angular.element($div).scope();
3863  *   $compile($div)(scope);
3864  * });
3865  * ```
3866  */
3867
3868
3869 /**
3870  * @ngdoc module
3871  * @name auto
3872  * @description
3873  *
3874  * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
3875  */
3876
3877 var ARROW_ARG = /^([^\(]+?)=>/;
3878 var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
3879 var FN_ARG_SPLIT = /,/;
3880 var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
3881 var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
3882 var $injectorMinErr = minErr('$injector');
3883
3884 function extractArgs(fn) {
3885   var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
3886       args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
3887   return args;
3888 }
3889
3890 function anonFn(fn) {
3891   // For anonymous functions, showing at the very least the function signature can help in
3892   // debugging.
3893   var args = extractArgs(fn);
3894   if (args) {
3895     return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
3896   }
3897   return 'fn';
3898 }
3899
3900 function annotate(fn, strictDi, name) {
3901   var $inject,
3902       argDecl,
3903       last;
3904
3905   if (typeof fn === 'function') {
3906     if (!($inject = fn.$inject)) {
3907       $inject = [];
3908       if (fn.length) {
3909         if (strictDi) {
3910           if (!isString(name) || !name) {
3911             name = fn.name || anonFn(fn);
3912           }
3913           throw $injectorMinErr('strictdi',
3914             '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
3915         }
3916         argDecl = extractArgs(fn);
3917         forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
3918           arg.replace(FN_ARG, function(all, underscore, name) {
3919             $inject.push(name);
3920           });
3921         });
3922       }
3923       fn.$inject = $inject;
3924     }
3925   } else if (isArray(fn)) {
3926     last = fn.length - 1;
3927     assertArgFn(fn[last], 'fn');
3928     $inject = fn.slice(0, last);
3929   } else {
3930     assertArgFn(fn, 'fn', true);
3931   }
3932   return $inject;
3933 }
3934
3935 ///////////////////////////////////////
3936
3937 /**
3938  * @ngdoc service
3939  * @name $injector
3940  *
3941  * @description
3942  *
3943  * `$injector` is used to retrieve object instances as defined by
3944  * {@link auto.$provide provider}, instantiate types, invoke methods,
3945  * and load modules.
3946  *
3947  * The following always holds true:
3948  *
3949  * ```js
3950  *   var $injector = angular.injector();
3951  *   expect($injector.get('$injector')).toBe($injector);
3952  *   expect($injector.invoke(function($injector) {
3953  *     return $injector;
3954  *   })).toBe($injector);
3955  * ```
3956  *
3957  * # Injection Function Annotation
3958  *
3959  * JavaScript does not have annotations, and annotations are needed for dependency injection. The
3960  * following are all valid ways of annotating function with injection arguments and are equivalent.
3961  *
3962  * ```js
3963  *   // inferred (only works if code not minified/obfuscated)
3964  *   $injector.invoke(function(serviceA){});
3965  *
3966  *   // annotated
3967  *   function explicit(serviceA) {};
3968  *   explicit.$inject = ['serviceA'];
3969  *   $injector.invoke(explicit);
3970  *
3971  *   // inline
3972  *   $injector.invoke(['serviceA', function(serviceA){}]);
3973  * ```
3974  *
3975  * ## Inference
3976  *
3977  * In JavaScript calling `toString()` on a function returns the function definition. The definition
3978  * can then be parsed and the function arguments can be extracted. This method of discovering
3979  * annotations is disallowed when the injector is in strict mode.
3980  * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
3981  * argument names.
3982  *
3983  * ## `$inject` Annotation
3984  * By adding an `$inject` property onto a function the injection parameters can be specified.
3985  *
3986  * ## Inline
3987  * As an array of injection names, where the last item in the array is the function to call.
3988  */
3989
3990 /**
3991  * @ngdoc method
3992  * @name $injector#get
3993  *
3994  * @description
3995  * Return an instance of the service.
3996  *
3997  * @param {string} name The name of the instance to retrieve.
3998  * @param {string=} caller An optional string to provide the origin of the function call for error messages.
3999  * @return {*} The instance.
4000  */
4001
4002 /**
4003  * @ngdoc method
4004  * @name $injector#invoke
4005  *
4006  * @description
4007  * Invoke the method and supply the method arguments from the `$injector`.
4008  *
4009  * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
4010  *   injected according to the {@link guide/di $inject Annotation} rules.
4011  * @param {Object=} self The `this` for the invoked method.
4012  * @param {Object=} locals Optional object. If preset then any argument names are read from this
4013  *                         object first, before the `$injector` is consulted.
4014  * @returns {*} the value returned by the invoked `fn` function.
4015  */
4016
4017 /**
4018  * @ngdoc method
4019  * @name $injector#has
4020  *
4021  * @description
4022  * Allows the user to query if the particular service exists.
4023  *
4024  * @param {string} name Name of the service to query.
4025  * @returns {boolean} `true` if injector has given service.
4026  */
4027
4028 /**
4029  * @ngdoc method
4030  * @name $injector#instantiate
4031  * @description
4032  * Create a new instance of JS type. The method takes a constructor function, invokes the new
4033  * operator, and supplies all of the arguments to the constructor function as specified by the
4034  * constructor annotation.
4035  *
4036  * @param {Function} Type Annotated constructor function.
4037  * @param {Object=} locals Optional object. If preset then any argument names are read from this
4038  * object first, before the `$injector` is consulted.
4039  * @returns {Object} new instance of `Type`.
4040  */
4041
4042 /**
4043  * @ngdoc method
4044  * @name $injector#annotate
4045  *
4046  * @description
4047  * Returns an array of service names which the function is requesting for injection. This API is
4048  * used by the injector to determine which services need to be injected into the function when the
4049  * function is invoked. There are three ways in which the function can be annotated with the needed
4050  * dependencies.
4051  *
4052  * # Argument names
4053  *
4054  * The simplest form is to extract the dependencies from the arguments of the function. This is done
4055  * by converting the function into a string using `toString()` method and extracting the argument
4056  * names.
4057  * ```js
4058  *   // Given
4059  *   function MyController($scope, $route) {
4060  *     // ...
4061  *   }
4062  *
4063  *   // Then
4064  *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
4065  * ```
4066  *
4067  * You can disallow this method by using strict injection mode.
4068  *
4069  * This method does not work with code minification / obfuscation. For this reason the following
4070  * annotation strategies are supported.
4071  *
4072  * # The `$inject` property
4073  *
4074  * If a function has an `$inject` property and its value is an array of strings, then the strings
4075  * represent names of services to be injected into the function.
4076  * ```js
4077  *   // Given
4078  *   var MyController = function(obfuscatedScope, obfuscatedRoute) {
4079  *     // ...
4080  *   }
4081  *   // Define function dependencies
4082  *   MyController['$inject'] = ['$scope', '$route'];
4083  *
4084  *   // Then
4085  *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
4086  * ```
4087  *
4088  * # The array notation
4089  *
4090  * It is often desirable to inline Injected functions and that's when setting the `$inject` property
4091  * is very inconvenient. In these situations using the array notation to specify the dependencies in
4092  * a way that survives minification is a better choice:
4093  *
4094  * ```js
4095  *   // We wish to write this (not minification / obfuscation safe)
4096  *   injector.invoke(function($compile, $rootScope) {
4097  *     // ...
4098  *   });
4099  *
4100  *   // We are forced to write break inlining
4101  *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
4102  *     // ...
4103  *   };
4104  *   tmpFn.$inject = ['$compile', '$rootScope'];
4105  *   injector.invoke(tmpFn);
4106  *
4107  *   // To better support inline function the inline annotation is supported
4108  *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
4109  *     // ...
4110  *   }]);
4111  *
4112  *   // Therefore
4113  *   expect(injector.annotate(
4114  *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
4115  *    ).toEqual(['$compile', '$rootScope']);
4116  * ```
4117  *
4118  * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
4119  * be retrieved as described above.
4120  *
4121  * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
4122  *
4123  * @returns {Array.<string>} The names of the services which the function requires.
4124  */
4125
4126
4127
4128
4129 /**
4130  * @ngdoc service
4131  * @name $provide
4132  *
4133  * @description
4134  *
4135  * The {@link auto.$provide $provide} service has a number of methods for registering components
4136  * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
4137  * {@link angular.Module}.
4138  *
4139  * An Angular **service** is a singleton object created by a **service factory**.  These **service
4140  * factories** are functions which, in turn, are created by a **service provider**.
4141  * The **service providers** are constructor functions. When instantiated they must contain a
4142  * property called `$get`, which holds the **service factory** function.
4143  *
4144  * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
4145  * correct **service provider**, instantiating it and then calling its `$get` **service factory**
4146  * function to get the instance of the **service**.
4147  *
4148  * Often services have no configuration options and there is no need to add methods to the service
4149  * provider.  The provider will be no more than a constructor function with a `$get` property. For
4150  * these cases the {@link auto.$provide $provide} service has additional helper methods to register
4151  * services without specifying a provider.
4152  *
4153  * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
4154  *     {@link auto.$injector $injector}
4155  * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
4156  *     providers and services.
4157  * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
4158  *     services, not providers.
4159  * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
4160  *     that will be wrapped in a **service provider** object, whose `$get` property will contain the
4161  *     given factory function.
4162  * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
4163  *     that will be wrapped in a **service provider** object, whose `$get` property will instantiate
4164  *      a new object using the given constructor function.
4165  *
4166  * See the individual methods for more information and examples.
4167  */
4168
4169 /**
4170  * @ngdoc method
4171  * @name $provide#provider
4172  * @description
4173  *
4174  * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
4175  * are constructor functions, whose instances are responsible for "providing" a factory for a
4176  * service.
4177  *
4178  * Service provider names start with the name of the service they provide followed by `Provider`.
4179  * For example, the {@link ng.$log $log} service has a provider called
4180  * {@link ng.$logProvider $logProvider}.
4181  *
4182  * Service provider objects can have additional methods which allow configuration of the provider
4183  * and its service. Importantly, you can configure what kind of service is created by the `$get`
4184  * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
4185  * method {@link ng.$logProvider#debugEnabled debugEnabled}
4186  * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
4187  * console or not.
4188  *
4189  * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
4190                         'Provider'` key.
4191  * @param {(Object|function())} provider If the provider is:
4192  *
4193  *   - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
4194  *     {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
4195  *   - `Constructor`: a new instance of the provider will be created using
4196  *     {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
4197  *
4198  * @returns {Object} registered provider instance
4199
4200  * @example
4201  *
4202  * The following example shows how to create a simple event tracking service and register it using
4203  * {@link auto.$provide#provider $provide.provider()}.
4204  *
4205  * ```js
4206  *  // Define the eventTracker provider
4207  *  function EventTrackerProvider() {
4208  *    var trackingUrl = '/track';
4209  *
4210  *    // A provider method for configuring where the tracked events should been saved
4211  *    this.setTrackingUrl = function(url) {
4212  *      trackingUrl = url;
4213  *    };
4214  *
4215  *    // The service factory function
4216  *    this.$get = ['$http', function($http) {
4217  *      var trackedEvents = {};
4218  *      return {
4219  *        // Call this to track an event
4220  *        event: function(event) {
4221  *          var count = trackedEvents[event] || 0;
4222  *          count += 1;
4223  *          trackedEvents[event] = count;
4224  *          return count;
4225  *        },
4226  *        // Call this to save the tracked events to the trackingUrl
4227  *        save: function() {
4228  *          $http.post(trackingUrl, trackedEvents);
4229  *        }
4230  *      };
4231  *    }];
4232  *  }
4233  *
4234  *  describe('eventTracker', function() {
4235  *    var postSpy;
4236  *
4237  *    beforeEach(module(function($provide) {
4238  *      // Register the eventTracker provider
4239  *      $provide.provider('eventTracker', EventTrackerProvider);
4240  *    }));
4241  *
4242  *    beforeEach(module(function(eventTrackerProvider) {
4243  *      // Configure eventTracker provider
4244  *      eventTrackerProvider.setTrackingUrl('/custom-track');
4245  *    }));
4246  *
4247  *    it('tracks events', inject(function(eventTracker) {
4248  *      expect(eventTracker.event('login')).toEqual(1);
4249  *      expect(eventTracker.event('login')).toEqual(2);
4250  *    }));
4251  *
4252  *    it('saves to the tracking url', inject(function(eventTracker, $http) {
4253  *      postSpy = spyOn($http, 'post');
4254  *      eventTracker.event('login');
4255  *      eventTracker.save();
4256  *      expect(postSpy).toHaveBeenCalled();
4257  *      expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
4258  *      expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
4259  *      expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
4260  *    }));
4261  *  });
4262  * ```
4263  */
4264
4265 /**
4266  * @ngdoc method
4267  * @name $provide#factory
4268  * @description
4269  *
4270  * Register a **service factory**, which will be called to return the service instance.
4271  * This is short for registering a service where its provider consists of only a `$get` property,
4272  * which is the given service factory function.
4273  * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
4274  * configure your service in a provider.
4275  *
4276  * @param {string} name The name of the instance.
4277  * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
4278  *                      Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
4279  * @returns {Object} registered provider instance
4280  *
4281  * @example
4282  * Here is an example of registering a service
4283  * ```js
4284  *   $provide.factory('ping', ['$http', function($http) {
4285  *     return function ping() {
4286  *       return $http.send('/ping');
4287  *     };
4288  *   }]);
4289  * ```
4290  * You would then inject and use this service like this:
4291  * ```js
4292  *   someModule.controller('Ctrl', ['ping', function(ping) {
4293  *     ping();
4294  *   }]);
4295  * ```
4296  */
4297
4298
4299 /**
4300  * @ngdoc method
4301  * @name $provide#service
4302  * @description
4303  *
4304  * Register a **service constructor**, which will be invoked with `new` to create the service
4305  * instance.
4306  * This is short for registering a service where its provider's `$get` property is the service
4307  * constructor function that will be used to instantiate the service instance.
4308  *
4309  * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
4310  * as a type/class.
4311  *
4312  * @param {string} name The name of the instance.
4313  * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
4314  *     that will be instantiated.
4315  * @returns {Object} registered provider instance
4316  *
4317  * @example
4318  * Here is an example of registering a service using
4319  * {@link auto.$provide#service $provide.service(class)}.
4320  * ```js
4321  *   var Ping = function($http) {
4322  *     this.$http = $http;
4323  *   };
4324  *
4325  *   Ping.$inject = ['$http'];
4326  *
4327  *   Ping.prototype.send = function() {
4328  *     return this.$http.get('/ping');
4329  *   };
4330  *   $provide.service('ping', Ping);
4331  * ```
4332  * You would then inject and use this service like this:
4333  * ```js
4334  *   someModule.controller('Ctrl', ['ping', function(ping) {
4335  *     ping.send();
4336  *   }]);
4337  * ```
4338  */
4339
4340
4341 /**
4342  * @ngdoc method
4343  * @name $provide#value
4344  * @description
4345  *
4346  * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
4347  * number, an array, an object or a function.  This is short for registering a service where its
4348  * provider's `$get` property is a factory function that takes no arguments and returns the **value
4349  * service**.
4350  *
4351  * Value services are similar to constant services, except that they cannot be injected into a
4352  * module configuration function (see {@link angular.Module#config}) but they can be overridden by
4353  * an Angular
4354  * {@link auto.$provide#decorator decorator}.
4355  *
4356  * @param {string} name The name of the instance.
4357  * @param {*} value The value.
4358  * @returns {Object} registered provider instance
4359  *
4360  * @example
4361  * Here are some examples of creating value services.
4362  * ```js
4363  *   $provide.value('ADMIN_USER', 'admin');
4364  *
4365  *   $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
4366  *
4367  *   $provide.value('halfOf', function(value) {
4368  *     return value / 2;
4369  *   });
4370  * ```
4371  */
4372
4373
4374 /**
4375  * @ngdoc method
4376  * @name $provide#constant
4377  * @description
4378  *
4379  * Register a **constant service**, such as a string, a number, an array, an object or a function,
4380  * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
4381  * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
4382  * be overridden by an Angular {@link auto.$provide#decorator decorator}.
4383  *
4384  * @param {string} name The name of the constant.
4385  * @param {*} value The constant value.
4386  * @returns {Object} registered instance
4387  *
4388  * @example
4389  * Here a some examples of creating constants:
4390  * ```js
4391  *   $provide.constant('SHARD_HEIGHT', 306);
4392  *
4393  *   $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
4394  *
4395  *   $provide.constant('double', function(value) {
4396  *     return value * 2;
4397  *   });
4398  * ```
4399  */
4400
4401
4402 /**
4403  * @ngdoc method
4404  * @name $provide#decorator
4405  * @description
4406  *
4407  * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
4408  * intercepts the creation of a service, allowing it to override or modify the behaviour of the
4409  * service. The object returned by the decorator may be the original service, or a new service
4410  * object which replaces or wraps and delegates to the original service.
4411  *
4412  * @param {string} name The name of the service to decorate.
4413  * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
4414  *    instantiated and should return the decorated service instance. The function is called using
4415  *    the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
4416  *    Local injection arguments:
4417  *
4418  *    * `$delegate` - The original service instance, which can be monkey patched, configured,
4419  *      decorated or delegated to.
4420  *
4421  * @example
4422  * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
4423  * calls to {@link ng.$log#error $log.warn()}.
4424  * ```js
4425  *   $provide.decorator('$log', ['$delegate', function($delegate) {
4426  *     $delegate.warn = $delegate.error;
4427  *     return $delegate;
4428  *   }]);
4429  * ```
4430  */
4431
4432
4433 function createInjector(modulesToLoad, strictDi) {
4434   strictDi = (strictDi === true);
4435   var INSTANTIATING = {},
4436       providerSuffix = 'Provider',
4437       path = [],
4438       loadedModules = new HashMap([], true),
4439       providerCache = {
4440         $provide: {
4441             provider: supportObject(provider),
4442             factory: supportObject(factory),
4443             service: supportObject(service),
4444             value: supportObject(value),
4445             constant: supportObject(constant),
4446             decorator: decorator
4447           }
4448       },
4449       providerInjector = (providerCache.$injector =
4450           createInternalInjector(providerCache, function(serviceName, caller) {
4451             if (angular.isString(caller)) {
4452               path.push(caller);
4453             }
4454             throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
4455           })),
4456       instanceCache = {},
4457       protoInstanceInjector =
4458           createInternalInjector(instanceCache, function(serviceName, caller) {
4459             var provider = providerInjector.get(serviceName + providerSuffix, caller);
4460             return instanceInjector.invoke(
4461                 provider.$get, provider, undefined, serviceName);
4462           }),
4463       instanceInjector = protoInstanceInjector;
4464
4465   providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
4466   var runBlocks = loadModules(modulesToLoad);
4467   instanceInjector = protoInstanceInjector.get('$injector');
4468   instanceInjector.strictDi = strictDi;
4469   forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
4470
4471   return instanceInjector;
4472
4473   ////////////////////////////////////
4474   // $provider
4475   ////////////////////////////////////
4476
4477   function supportObject(delegate) {
4478     return function(key, value) {
4479       if (isObject(key)) {
4480         forEach(key, reverseParams(delegate));
4481       } else {
4482         return delegate(key, value);
4483       }
4484     };
4485   }
4486
4487   function provider(name, provider_) {
4488     assertNotHasOwnProperty(name, 'service');
4489     if (isFunction(provider_) || isArray(provider_)) {
4490       provider_ = providerInjector.instantiate(provider_);
4491     }
4492     if (!provider_.$get) {
4493       throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
4494     }
4495     return providerCache[name + providerSuffix] = provider_;
4496   }
4497
4498   function enforceReturnValue(name, factory) {
4499     return function enforcedReturnValue() {
4500       var result = instanceInjector.invoke(factory, this);
4501       if (isUndefined(result)) {
4502         throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
4503       }
4504       return result;
4505     };
4506   }
4507
4508   function factory(name, factoryFn, enforce) {
4509     return provider(name, {
4510       $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
4511     });
4512   }
4513
4514   function service(name, constructor) {
4515     return factory(name, ['$injector', function($injector) {
4516       return $injector.instantiate(constructor);
4517     }]);
4518   }
4519
4520   function value(name, val) { return factory(name, valueFn(val), false); }
4521
4522   function constant(name, value) {
4523     assertNotHasOwnProperty(name, 'constant');
4524     providerCache[name] = value;
4525     instanceCache[name] = value;
4526   }
4527
4528   function decorator(serviceName, decorFn) {
4529     var origProvider = providerInjector.get(serviceName + providerSuffix),
4530         orig$get = origProvider.$get;
4531
4532     origProvider.$get = function() {
4533       var origInstance = instanceInjector.invoke(orig$get, origProvider);
4534       return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
4535     };
4536   }
4537
4538   ////////////////////////////////////
4539   // Module Loading
4540   ////////////////////////////////////
4541   function loadModules(modulesToLoad) {
4542     assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
4543     var runBlocks = [], moduleFn;
4544     forEach(modulesToLoad, function(module) {
4545       if (loadedModules.get(module)) return;
4546       loadedModules.put(module, true);
4547
4548       function runInvokeQueue(queue) {
4549         var i, ii;
4550         for (i = 0, ii = queue.length; i < ii; i++) {
4551           var invokeArgs = queue[i],
4552               provider = providerInjector.get(invokeArgs[0]);
4553
4554           provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
4555         }
4556       }
4557
4558       try {
4559         if (isString(module)) {
4560           moduleFn = angularModule(module);
4561           runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
4562           runInvokeQueue(moduleFn._invokeQueue);
4563           runInvokeQueue(moduleFn._configBlocks);
4564         } else if (isFunction(module)) {
4565             runBlocks.push(providerInjector.invoke(module));
4566         } else if (isArray(module)) {
4567             runBlocks.push(providerInjector.invoke(module));
4568         } else {
4569           assertArgFn(module, 'module');
4570         }
4571       } catch (e) {
4572         if (isArray(module)) {
4573           module = module[module.length - 1];
4574         }
4575         if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
4576           // Safari & FF's stack traces don't contain error.message content
4577           // unlike those of Chrome and IE
4578           // So if stack doesn't contain message, we create a new string that contains both.
4579           // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
4580           /* jshint -W022 */
4581           e = e.message + '\n' + e.stack;
4582         }
4583         throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
4584                   module, e.stack || e.message || e);
4585       }
4586     });
4587     return runBlocks;
4588   }
4589
4590   ////////////////////////////////////
4591   // internal Injector
4592   ////////////////////////////////////
4593
4594   function createInternalInjector(cache, factory) {
4595
4596     function getService(serviceName, caller) {
4597       if (cache.hasOwnProperty(serviceName)) {
4598         if (cache[serviceName] === INSTANTIATING) {
4599           throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
4600                     serviceName + ' <- ' + path.join(' <- '));
4601         }
4602         return cache[serviceName];
4603       } else {
4604         try {
4605           path.unshift(serviceName);
4606           cache[serviceName] = INSTANTIATING;
4607           return cache[serviceName] = factory(serviceName, caller);
4608         } catch (err) {
4609           if (cache[serviceName] === INSTANTIATING) {
4610             delete cache[serviceName];
4611           }
4612           throw err;
4613         } finally {
4614           path.shift();
4615         }
4616       }
4617     }
4618
4619     function invoke(fn, self, locals, serviceName) {
4620       if (typeof locals === 'string') {
4621         serviceName = locals;
4622         locals = null;
4623       }
4624
4625       var args = [],
4626           $inject = createInjector.$$annotate(fn, strictDi, serviceName),
4627           length, i,
4628           key;
4629
4630       for (i = 0, length = $inject.length; i < length; i++) {
4631         key = $inject[i];
4632         if (typeof key !== 'string') {
4633           throw $injectorMinErr('itkn',
4634                   'Incorrect injection token! Expected service name as string, got {0}', key);
4635         }
4636         args.push(
4637           locals && locals.hasOwnProperty(key)
4638           ? locals[key]
4639           : getService(key, serviceName)
4640         );
4641       }
4642       if (isArray(fn)) {
4643         fn = fn[length];
4644       }
4645
4646       // http://jsperf.com/angularjs-invoke-apply-vs-switch
4647       // #5388
4648       return fn.apply(self, args);
4649     }
4650
4651     function instantiate(Type, locals, serviceName) {
4652       // Check if Type is annotated and use just the given function at n-1 as parameter
4653       // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
4654       // Object creation: http://jsperf.com/create-constructor/2
4655       var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
4656       var returnedValue = invoke(Type, instance, locals, serviceName);
4657
4658       return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
4659     }
4660
4661     return {
4662       invoke: invoke,
4663       instantiate: instantiate,
4664       get: getService,
4665       annotate: createInjector.$$annotate,
4666       has: function(name) {
4667         return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
4668       }
4669     };
4670   }
4671 }
4672
4673 createInjector.$$annotate = annotate;
4674
4675 /**
4676  * @ngdoc provider
4677  * @name $anchorScrollProvider
4678  *
4679  * @description
4680  * Use `$anchorScrollProvider` to disable automatic scrolling whenever
4681  * {@link ng.$location#hash $location.hash()} changes.
4682  */
4683 function $AnchorScrollProvider() {
4684
4685   var autoScrollingEnabled = true;
4686
4687   /**
4688    * @ngdoc method
4689    * @name $anchorScrollProvider#disableAutoScrolling
4690    *
4691    * @description
4692    * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
4693    * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
4694    * Use this method to disable automatic scrolling.
4695    *
4696    * If automatic scrolling is disabled, one must explicitly call
4697    * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
4698    * current hash.
4699    */
4700   this.disableAutoScrolling = function() {
4701     autoScrollingEnabled = false;
4702   };
4703
4704   /**
4705    * @ngdoc service
4706    * @name $anchorScroll
4707    * @kind function
4708    * @requires $window
4709    * @requires $location
4710    * @requires $rootScope
4711    *
4712    * @description
4713    * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
4714    * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
4715    * in the
4716    * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
4717    *
4718    * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
4719    * match any anchor whenever it changes. This can be disabled by calling
4720    * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
4721    *
4722    * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
4723    * vertical scroll-offset (either fixed or dynamic).
4724    *
4725    * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
4726    *                       {@link ng.$location#hash $location.hash()} will be used.
4727    *
4728    * @property {(number|function|jqLite)} yOffset
4729    * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
4730    * positioned elements at the top of the page, such as navbars, headers etc.
4731    *
4732    * `yOffset` can be specified in various ways:
4733    * - **number**: A fixed number of pixels to be used as offset.<br /><br />
4734    * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
4735    *   a number representing the offset (in pixels).<br /><br />
4736    * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
4737    *   the top of the page to the element's bottom will be used as offset.<br />
4738    *   **Note**: The element will be taken into account only as long as its `position` is set to
4739    *   `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
4740    *   their height and/or positioning according to the viewport's size.
4741    *
4742    * <br />
4743    * <div class="alert alert-warning">
4744    * In order for `yOffset` to work properly, scrolling should take place on the document's root and
4745    * not some child element.
4746    * </div>
4747    *
4748    * @example
4749      <example module="anchorScrollExample">
4750        <file name="index.html">
4751          <div id="scrollArea" ng-controller="ScrollController">
4752            <a ng-click="gotoBottom()">Go to bottom</a>
4753            <a id="bottom"></a> You're at the bottom!
4754          </div>
4755        </file>
4756        <file name="script.js">
4757          angular.module('anchorScrollExample', [])
4758            .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
4759              function ($scope, $location, $anchorScroll) {
4760                $scope.gotoBottom = function() {
4761                  // set the location.hash to the id of
4762                  // the element you wish to scroll to.
4763                  $location.hash('bottom');
4764
4765                  // call $anchorScroll()
4766                  $anchorScroll();
4767                };
4768              }]);
4769        </file>
4770        <file name="style.css">
4771          #scrollArea {
4772            height: 280px;
4773            overflow: auto;
4774          }
4775
4776          #bottom {
4777            display: block;
4778            margin-top: 2000px;
4779          }
4780        </file>
4781      </example>
4782    *
4783    * <hr />
4784    * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
4785    * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
4786    *
4787    * @example
4788      <example module="anchorScrollOffsetExample">
4789        <file name="index.html">
4790          <div class="fixed-header" ng-controller="headerCtrl">
4791            <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
4792              Go to anchor {{x}}
4793            </a>
4794          </div>
4795          <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
4796            Anchor {{x}} of 5
4797          </div>
4798        </file>
4799        <file name="script.js">
4800          angular.module('anchorScrollOffsetExample', [])
4801            .run(['$anchorScroll', function($anchorScroll) {
4802              $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels
4803            }])
4804            .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
4805              function ($anchorScroll, $location, $scope) {
4806                $scope.gotoAnchor = function(x) {
4807                  var newHash = 'anchor' + x;
4808                  if ($location.hash() !== newHash) {
4809                    // set the $location.hash to `newHash` and
4810                    // $anchorScroll will automatically scroll to it
4811                    $location.hash('anchor' + x);
4812                  } else {
4813                    // call $anchorScroll() explicitly,
4814                    // since $location.hash hasn't changed
4815                    $anchorScroll();
4816                  }
4817                };
4818              }
4819            ]);
4820        </file>
4821        <file name="style.css">
4822          body {
4823            padding-top: 50px;
4824          }
4825
4826          .anchor {
4827            border: 2px dashed DarkOrchid;
4828            padding: 10px 10px 200px 10px;
4829          }
4830
4831          .fixed-header {
4832            background-color: rgba(0, 0, 0, 0.2);
4833            height: 50px;
4834            position: fixed;
4835            top: 0; left: 0; right: 0;
4836          }
4837
4838          .fixed-header > a {
4839            display: inline-block;
4840            margin: 5px 15px;
4841          }
4842        </file>
4843      </example>
4844    */
4845   this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
4846     var document = $window.document;
4847
4848     // Helper function to get first anchor from a NodeList
4849     // (using `Array#some()` instead of `angular#forEach()` since it's more performant
4850     //  and working in all supported browsers.)
4851     function getFirstAnchor(list) {
4852       var result = null;
4853       Array.prototype.some.call(list, function(element) {
4854         if (nodeName_(element) === 'a') {
4855           result = element;
4856           return true;
4857         }
4858       });
4859       return result;
4860     }
4861
4862     function getYOffset() {
4863
4864       var offset = scroll.yOffset;
4865
4866       if (isFunction(offset)) {
4867         offset = offset();
4868       } else if (isElement(offset)) {
4869         var elem = offset[0];
4870         var style = $window.getComputedStyle(elem);
4871         if (style.position !== 'fixed') {
4872           offset = 0;
4873         } else {
4874           offset = elem.getBoundingClientRect().bottom;
4875         }
4876       } else if (!isNumber(offset)) {
4877         offset = 0;
4878       }
4879
4880       return offset;
4881     }
4882
4883     function scrollTo(elem) {
4884       if (elem) {
4885         elem.scrollIntoView();
4886
4887         var offset = getYOffset();
4888
4889         if (offset) {
4890           // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
4891           // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
4892           // top of the viewport.
4893           //
4894           // IF the number of pixels from the top of `elem` to the end of the page's content is less
4895           // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
4896           // way down the page.
4897           //
4898           // This is often the case for elements near the bottom of the page.
4899           //
4900           // In such cases we do not need to scroll the whole `offset` up, just the difference between
4901           // the top of the element and the offset, which is enough to align the top of `elem` at the
4902           // desired position.
4903           var elemTop = elem.getBoundingClientRect().top;
4904           $window.scrollBy(0, elemTop - offset);
4905         }
4906       } else {
4907         $window.scrollTo(0, 0);
4908       }
4909     }
4910
4911     function scroll(hash) {
4912       hash = isString(hash) ? hash : $location.hash();
4913       var elm;
4914
4915       // empty hash, scroll to the top of the page
4916       if (!hash) scrollTo(null);
4917
4918       // element with given id
4919       else if ((elm = document.getElementById(hash))) scrollTo(elm);
4920
4921       // first anchor with given name :-D
4922       else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
4923
4924       // no element and hash == 'top', scroll to the top of the page
4925       else if (hash === 'top') scrollTo(null);
4926     }
4927
4928     // does not scroll when user clicks on anchor link that is currently on
4929     // (no url change, no $location.hash() change), browser native does scroll
4930     if (autoScrollingEnabled) {
4931       $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
4932         function autoScrollWatchAction(newVal, oldVal) {
4933           // skip the initial scroll if $location.hash is empty
4934           if (newVal === oldVal && newVal === '') return;
4935
4936           jqLiteDocumentLoaded(function() {
4937             $rootScope.$evalAsync(scroll);
4938           });
4939         });
4940     }
4941
4942     return scroll;
4943   }];
4944 }
4945
4946 var $animateMinErr = minErr('$animate');
4947 var ELEMENT_NODE = 1;
4948 var NG_ANIMATE_CLASSNAME = 'ng-animate';
4949
4950 function mergeClasses(a,b) {
4951   if (!a && !b) return '';
4952   if (!a) return b;
4953   if (!b) return a;
4954   if (isArray(a)) a = a.join(' ');
4955   if (isArray(b)) b = b.join(' ');
4956   return a + ' ' + b;
4957 }
4958
4959 function extractElementNode(element) {
4960   for (var i = 0; i < element.length; i++) {
4961     var elm = element[i];
4962     if (elm.nodeType === ELEMENT_NODE) {
4963       return elm;
4964     }
4965   }
4966 }
4967
4968 function splitClasses(classes) {
4969   if (isString(classes)) {
4970     classes = classes.split(' ');
4971   }
4972
4973   // Use createMap() to prevent class assumptions involving property names in
4974   // Object.prototype
4975   var obj = createMap();
4976   forEach(classes, function(klass) {
4977     // sometimes the split leaves empty string values
4978     // incase extra spaces were applied to the options
4979     if (klass.length) {
4980       obj[klass] = true;
4981     }
4982   });
4983   return obj;
4984 }
4985
4986 // if any other type of options value besides an Object value is
4987 // passed into the $animate.method() animation then this helper code
4988 // will be run which will ignore it. While this patch is not the
4989 // greatest solution to this, a lot of existing plugins depend on
4990 // $animate to either call the callback (< 1.2) or return a promise
4991 // that can be changed. This helper function ensures that the options
4992 // are wiped clean incase a callback function is provided.
4993 function prepareAnimateOptions(options) {
4994   return isObject(options)
4995       ? options
4996       : {};
4997 }
4998
4999 var $$CoreAnimateRunnerProvider = function() {
5000   this.$get = ['$q', '$$rAF', function($q, $$rAF) {
5001     function AnimateRunner() {}
5002     AnimateRunner.all = noop;
5003     AnimateRunner.chain = noop;
5004     AnimateRunner.prototype = {
5005       end: noop,
5006       cancel: noop,
5007       resume: noop,
5008       pause: noop,
5009       complete: noop,
5010       then: function(pass, fail) {
5011         return $q(function(resolve) {
5012           $$rAF(function() {
5013             resolve();
5014           });
5015         }).then(pass, fail);
5016       }
5017     };
5018     return AnimateRunner;
5019   }];
5020 };
5021
5022 // this is prefixed with Core since it conflicts with
5023 // the animateQueueProvider defined in ngAnimate/animateQueue.js
5024 var $$CoreAnimateQueueProvider = function() {
5025   var postDigestQueue = new HashMap();
5026   var postDigestElements = [];
5027
5028   this.$get = ['$$AnimateRunner', '$rootScope',
5029        function($$AnimateRunner,   $rootScope) {
5030     return {
5031       enabled: noop,
5032       on: noop,
5033       off: noop,
5034       pin: noop,
5035
5036       push: function(element, event, options, domOperation) {
5037         domOperation        && domOperation();
5038
5039         options = options || {};
5040         options.from        && element.css(options.from);
5041         options.to          && element.css(options.to);
5042
5043         if (options.addClass || options.removeClass) {
5044           addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
5045         }
5046
5047         return new $$AnimateRunner(); // jshint ignore:line
5048       }
5049     };
5050
5051
5052     function updateData(data, classes, value) {
5053       var changed = false;
5054       if (classes) {
5055         classes = isString(classes) ? classes.split(' ') :
5056                   isArray(classes) ? classes : [];
5057         forEach(classes, function(className) {
5058           if (className) {
5059             changed = true;
5060             data[className] = value;
5061           }
5062         });
5063       }
5064       return changed;
5065     }
5066
5067     function handleCSSClassChanges() {
5068       forEach(postDigestElements, function(element) {
5069         var data = postDigestQueue.get(element);
5070         if (data) {
5071           var existing = splitClasses(element.attr('class'));
5072           var toAdd = '';
5073           var toRemove = '';
5074           forEach(data, function(status, className) {
5075             var hasClass = !!existing[className];
5076             if (status !== hasClass) {
5077               if (status) {
5078                 toAdd += (toAdd.length ? ' ' : '') + className;
5079               } else {
5080                 toRemove += (toRemove.length ? ' ' : '') + className;
5081               }
5082             }
5083           });
5084
5085           forEach(element, function(elm) {
5086             toAdd    && jqLiteAddClass(elm, toAdd);
5087             toRemove && jqLiteRemoveClass(elm, toRemove);
5088           });
5089           postDigestQueue.remove(element);
5090         }
5091       });
5092       postDigestElements.length = 0;
5093     }
5094
5095
5096     function addRemoveClassesPostDigest(element, add, remove) {
5097       var data = postDigestQueue.get(element) || {};
5098
5099       var classesAdded = updateData(data, add, true);
5100       var classesRemoved = updateData(data, remove, false);
5101
5102       if (classesAdded || classesRemoved) {
5103
5104         postDigestQueue.put(element, data);
5105         postDigestElements.push(element);
5106
5107         if (postDigestElements.length === 1) {
5108           $rootScope.$$postDigest(handleCSSClassChanges);
5109         }
5110       }
5111     }
5112   }];
5113 };
5114
5115 /**
5116  * @ngdoc provider
5117  * @name $animateProvider
5118  *
5119  * @description
5120  * Default implementation of $animate that doesn't perform any animations, instead just
5121  * synchronously performs DOM updates and resolves the returned runner promise.
5122  *
5123  * In order to enable animations the `ngAnimate` module has to be loaded.
5124  *
5125  * To see the functional implementation check out `src/ngAnimate/animate.js`.
5126  */
5127 var $AnimateProvider = ['$provide', function($provide) {
5128   var provider = this;
5129
5130   this.$$registeredAnimations = Object.create(null);
5131
5132    /**
5133    * @ngdoc method
5134    * @name $animateProvider#register
5135    *
5136    * @description
5137    * Registers a new injectable animation factory function. The factory function produces the
5138    * animation object which contains callback functions for each event that is expected to be
5139    * animated.
5140    *
5141    *   * `eventFn`: `function(element, ... , doneFunction, options)`
5142    *   The element to animate, the `doneFunction` and the options fed into the animation. Depending
5143    *   on the type of animation additional arguments will be injected into the animation function. The
5144    *   list below explains the function signatures for the different animation methods:
5145    *
5146    *   - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
5147    *   - addClass: function(element, addedClasses, doneFunction, options)
5148    *   - removeClass: function(element, removedClasses, doneFunction, options)
5149    *   - enter, leave, move: function(element, doneFunction, options)
5150    *   - animate: function(element, fromStyles, toStyles, doneFunction, options)
5151    *
5152    *   Make sure to trigger the `doneFunction` once the animation is fully complete.
5153    *
5154    * ```js
5155    *   return {
5156    *     //enter, leave, move signature
5157    *     eventFn : function(element, done, options) {
5158    *       //code to run the animation
5159    *       //once complete, then run done()
5160    *       return function endFunction(wasCancelled) {
5161    *         //code to cancel the animation
5162    *       }
5163    *     }
5164    *   }
5165    * ```
5166    *
5167    * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
5168    * @param {Function} factory The factory function that will be executed to return the animation
5169    *                           object.
5170    */
5171   this.register = function(name, factory) {
5172     if (name && name.charAt(0) !== '.') {
5173       throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
5174     }
5175
5176     var key = name + '-animation';
5177     provider.$$registeredAnimations[name.substr(1)] = key;
5178     $provide.factory(key, factory);
5179   };
5180
5181   /**
5182    * @ngdoc method
5183    * @name $animateProvider#classNameFilter
5184    *
5185    * @description
5186    * Sets and/or returns the CSS class regular expression that is checked when performing
5187    * an animation. Upon bootstrap the classNameFilter value is not set at all and will
5188    * therefore enable $animate to attempt to perform an animation on any element that is triggered.
5189    * When setting the `classNameFilter` value, animations will only be performed on elements
5190    * that successfully match the filter expression. This in turn can boost performance
5191    * for low-powered devices as well as applications containing a lot of structural operations.
5192    * @param {RegExp=} expression The className expression which will be checked against all animations
5193    * @return {RegExp} The current CSS className expression value. If null then there is no expression value
5194    */
5195   this.classNameFilter = function(expression) {
5196     if (arguments.length === 1) {
5197       this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
5198       if (this.$$classNameFilter) {
5199         var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
5200         if (reservedRegex.test(this.$$classNameFilter.toString())) {
5201           throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
5202
5203         }
5204       }
5205     }
5206     return this.$$classNameFilter;
5207   };
5208
5209   this.$get = ['$$animateQueue', function($$animateQueue) {
5210     function domInsert(element, parentElement, afterElement) {
5211       // if for some reason the previous element was removed
5212       // from the dom sometime before this code runs then let's
5213       // just stick to using the parent element as the anchor
5214       if (afterElement) {
5215         var afterNode = extractElementNode(afterElement);
5216         if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
5217           afterElement = null;
5218         }
5219       }
5220       afterElement ? afterElement.after(element) : parentElement.prepend(element);
5221     }
5222
5223     /**
5224      * @ngdoc service
5225      * @name $animate
5226      * @description The $animate service exposes a series of DOM utility methods that provide support
5227      * for animation hooks. The default behavior is the application of DOM operations, however,
5228      * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
5229      * to ensure that animation runs with the triggered DOM operation.
5230      *
5231      * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
5232      * included and only when it is active then the animation hooks that `$animate` triggers will be
5233      * functional. Once active then all structural `ng-` directives will trigger animations as they perform
5234      * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
5235      * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
5236      *
5237      * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
5238      *
5239      * To learn more about enabling animation support, click here to visit the
5240      * {@link ngAnimate ngAnimate module page}.
5241      */
5242     return {
5243       // we don't call it directly since non-existant arguments may
5244       // be interpreted as null within the sub enabled function
5245
5246       /**
5247        *
5248        * @ngdoc method
5249        * @name $animate#on
5250        * @kind function
5251        * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
5252        *    has fired on the given element or among any of its children. Once the listener is fired, the provided callback
5253        *    is fired with the following params:
5254        *
5255        * ```js
5256        * $animate.on('enter', container,
5257        *    function callback(element, phase) {
5258        *      // cool we detected an enter animation within the container
5259        *    }
5260        * );
5261        * ```
5262        *
5263        * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
5264        * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
5265        *     as well as among its children
5266        * @param {Function} callback the callback function that will be fired when the listener is triggered
5267        *
5268        * The arguments present in the callback function are:
5269        * * `element` - The captured DOM element that the animation was fired on.
5270        * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
5271        */
5272       on: $$animateQueue.on,
5273
5274       /**
5275        *
5276        * @ngdoc method
5277        * @name $animate#off
5278        * @kind function
5279        * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
5280        * can be used in three different ways depending on the arguments:
5281        *
5282        * ```js
5283        * // remove all the animation event listeners listening for `enter`
5284        * $animate.off('enter');
5285        *
5286        * // remove all the animation event listeners listening for `enter` on the given element and its children
5287        * $animate.off('enter', container);
5288        *
5289        * // remove the event listener function provided by `listenerFn` that is set
5290        * // to listen for `enter` on the given `element` as well as its children
5291        * $animate.off('enter', container, callback);
5292        * ```
5293        *
5294        * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
5295        * @param {DOMElement=} container the container element the event listener was placed on
5296        * @param {Function=} callback the callback function that was registered as the listener
5297        */
5298       off: $$animateQueue.off,
5299
5300       /**
5301        * @ngdoc method
5302        * @name $animate#pin
5303        * @kind function
5304        * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
5305        *    outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
5306        *    element despite being outside the realm of the application or within another application. Say for example if the application
5307        *    was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
5308        *    as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
5309        *    that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
5310        *
5311        *    Note that this feature is only active when the `ngAnimate` module is used.
5312        *
5313        * @param {DOMElement} element the external element that will be pinned
5314        * @param {DOMElement} parentElement the host parent element that will be associated with the external element
5315        */
5316       pin: $$animateQueue.pin,
5317
5318       /**
5319        *
5320        * @ngdoc method
5321        * @name $animate#enabled
5322        * @kind function
5323        * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
5324        * function can be called in four ways:
5325        *
5326        * ```js
5327        * // returns true or false
5328        * $animate.enabled();
5329        *
5330        * // changes the enabled state for all animations
5331        * $animate.enabled(false);
5332        * $animate.enabled(true);
5333        *
5334        * // returns true or false if animations are enabled for an element
5335        * $animate.enabled(element);
5336        *
5337        * // changes the enabled state for an element and its children
5338        * $animate.enabled(element, true);
5339        * $animate.enabled(element, false);
5340        * ```
5341        *
5342        * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
5343        * @param {boolean=} enabled whether or not the animations will be enabled for the element
5344        *
5345        * @return {boolean} whether or not animations are enabled
5346        */
5347       enabled: $$animateQueue.enabled,
5348
5349       /**
5350        * @ngdoc method
5351        * @name $animate#cancel
5352        * @kind function
5353        * @description Cancels the provided animation.
5354        *
5355        * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
5356        */
5357       cancel: function(runner) {
5358         runner.end && runner.end();
5359       },
5360
5361       /**
5362        *
5363        * @ngdoc method
5364        * @name $animate#enter
5365        * @kind function
5366        * @description Inserts the element into the DOM either after the `after` element (if provided) or
5367        *   as the first child within the `parent` element and then triggers an animation.
5368        *   A promise is returned that will be resolved during the next digest once the animation
5369        *   has completed.
5370        *
5371        * @param {DOMElement} element the element which will be inserted into the DOM
5372        * @param {DOMElement} parent the parent element which will append the element as
5373        *   a child (so long as the after element is not present)
5374        * @param {DOMElement=} after the sibling element after which the element will be appended
5375        * @param {object=} options an optional collection of options/styles that will be applied to the element
5376        *
5377        * @return {Promise} the animation callback promise
5378        */
5379       enter: function(element, parent, after, options) {
5380         parent = parent && jqLite(parent);
5381         after = after && jqLite(after);
5382         parent = parent || after.parent();
5383         domInsert(element, parent, after);
5384         return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
5385       },
5386
5387       /**
5388        *
5389        * @ngdoc method
5390        * @name $animate#move
5391        * @kind function
5392        * @description Inserts (moves) the element into its new position in the DOM either after
5393        *   the `after` element (if provided) or as the first child within the `parent` element
5394        *   and then triggers an animation. A promise is returned that will be resolved
5395        *   during the next digest once the animation has completed.
5396        *
5397        * @param {DOMElement} element the element which will be moved into the new DOM position
5398        * @param {DOMElement} parent the parent element which will append the element as
5399        *   a child (so long as the after element is not present)
5400        * @param {DOMElement=} after the sibling element after which the element will be appended
5401        * @param {object=} options an optional collection of options/styles that will be applied to the element
5402        *
5403        * @return {Promise} the animation callback promise
5404        */
5405       move: function(element, parent, after, options) {
5406         parent = parent && jqLite(parent);
5407         after = after && jqLite(after);
5408         parent = parent || after.parent();
5409         domInsert(element, parent, after);
5410         return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
5411       },
5412
5413       /**
5414        * @ngdoc method
5415        * @name $animate#leave
5416        * @kind function
5417        * @description Triggers an animation and then removes the element from the DOM.
5418        * When the function is called a promise is returned that will be resolved during the next
5419        * digest once the animation has completed.
5420        *
5421        * @param {DOMElement} element the element which will be removed from the DOM
5422        * @param {object=} options an optional collection of options/styles that will be applied to the element
5423        *
5424        * @return {Promise} the animation callback promise
5425        */
5426       leave: function(element, options) {
5427         return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
5428           element.remove();
5429         });
5430       },
5431
5432       /**
5433        * @ngdoc method
5434        * @name $animate#addClass
5435        * @kind function
5436        *
5437        * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
5438        *   execution, the addClass operation will only be handled after the next digest and it will not trigger an
5439        *   animation if element already contains the CSS class or if the class is removed at a later step.
5440        *   Note that class-based animations are treated differently compared to structural animations
5441        *   (like enter, move and leave) since the CSS classes may be added/removed at different points
5442        *   depending if CSS or JavaScript animations are used.
5443        *
5444        * @param {DOMElement} element the element which the CSS classes will be applied to
5445        * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
5446        * @param {object=} options an optional collection of options/styles that will be applied to the element
5447        *
5448        * @return {Promise} the animation callback promise
5449        */
5450       addClass: function(element, className, options) {
5451         options = prepareAnimateOptions(options);
5452         options.addClass = mergeClasses(options.addclass, className);
5453         return $$animateQueue.push(element, 'addClass', options);
5454       },
5455
5456       /**
5457        * @ngdoc method
5458        * @name $animate#removeClass
5459        * @kind function
5460        *
5461        * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
5462        *   execution, the removeClass operation will only be handled after the next digest and it will not trigger an
5463        *   animation if element does not contain the CSS class or if the class is added at a later step.
5464        *   Note that class-based animations are treated differently compared to structural animations
5465        *   (like enter, move and leave) since the CSS classes may be added/removed at different points
5466        *   depending if CSS or JavaScript animations are used.
5467        *
5468        * @param {DOMElement} element the element which the CSS classes will be applied to
5469        * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
5470        * @param {object=} options an optional collection of options/styles that will be applied to the element
5471        *
5472        * @return {Promise} the animation callback promise
5473        */
5474       removeClass: function(element, className, options) {
5475         options = prepareAnimateOptions(options);
5476         options.removeClass = mergeClasses(options.removeClass, className);
5477         return $$animateQueue.push(element, 'removeClass', options);
5478       },
5479
5480       /**
5481        * @ngdoc method
5482        * @name $animate#setClass
5483        * @kind function
5484        *
5485        * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
5486        *    triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
5487        *    `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
5488        *    passed. Note that class-based animations are treated differently compared to structural animations
5489        *    (like enter, move and leave) since the CSS classes may be added/removed at different points
5490        *    depending if CSS or JavaScript animations are used.
5491        *
5492        * @param {DOMElement} element the element which the CSS classes will be applied to
5493        * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
5494        * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
5495        * @param {object=} options an optional collection of options/styles that will be applied to the element
5496        *
5497        * @return {Promise} the animation callback promise
5498        */
5499       setClass: function(element, add, remove, options) {
5500         options = prepareAnimateOptions(options);
5501         options.addClass = mergeClasses(options.addClass, add);
5502         options.removeClass = mergeClasses(options.removeClass, remove);
5503         return $$animateQueue.push(element, 'setClass', options);
5504       },
5505
5506       /**
5507        * @ngdoc method
5508        * @name $animate#animate
5509        * @kind function
5510        *
5511        * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
5512        * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
5513        * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
5514        * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
5515        * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
5516        *
5517        * @param {DOMElement} element the element which the CSS styles will be applied to
5518        * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
5519        * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
5520        * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
5521        *    this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
5522        *    (Note that if no animation is detected then this value will not be appplied to the element.)
5523        * @param {object=} options an optional collection of options/styles that will be applied to the element
5524        *
5525        * @return {Promise} the animation callback promise
5526        */
5527       animate: function(element, from, to, className, options) {
5528         options = prepareAnimateOptions(options);
5529         options.from = options.from ? extend(options.from, from) : from;
5530         options.to   = options.to   ? extend(options.to, to)     : to;
5531
5532         className = className || 'ng-inline-animate';
5533         options.tempClasses = mergeClasses(options.tempClasses, className);
5534         return $$animateQueue.push(element, 'animate', options);
5535       }
5536     };
5537   }];
5538 }];
5539
5540 /**
5541  * @ngdoc service
5542  * @name $animateCss
5543  * @kind object
5544  *
5545  * @description
5546  * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
5547  * then the `$animateCss` service will actually perform animations.
5548  *
5549  * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
5550  */
5551 var $CoreAnimateCssProvider = function() {
5552   this.$get = ['$$rAF', '$q', function($$rAF, $q) {
5553
5554     var RAFPromise = function() {};
5555     RAFPromise.prototype = {
5556       done: function(cancel) {
5557         this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
5558       },
5559       end: function() {
5560         this.done();
5561       },
5562       cancel: function() {
5563         this.done(true);
5564       },
5565       getPromise: function() {
5566         if (!this.defer) {
5567           this.defer = $q.defer();
5568         }
5569         return this.defer.promise;
5570       },
5571       then: function(f1,f2) {
5572         return this.getPromise().then(f1,f2);
5573       },
5574       'catch': function(f1) {
5575         return this.getPromise()['catch'](f1);
5576       },
5577       'finally': function(f1) {
5578         return this.getPromise()['finally'](f1);
5579       }
5580     };
5581
5582     return function(element, options) {
5583       // there is no point in applying the styles since
5584       // there is no animation that goes on at all in
5585       // this version of $animateCss.
5586       if (options.cleanupStyles) {
5587         options.from = options.to = null;
5588       }
5589
5590       if (options.from) {
5591         element.css(options.from);
5592         options.from = null;
5593       }
5594
5595       var closed, runner = new RAFPromise();
5596       return {
5597         start: run,
5598         end: run
5599       };
5600
5601       function run() {
5602         $$rAF(function() {
5603           close();
5604           if (!closed) {
5605             runner.done();
5606           }
5607           closed = true;
5608         });
5609         return runner;
5610       }
5611
5612       function close() {
5613         if (options.addClass) {
5614           element.addClass(options.addClass);
5615           options.addClass = null;
5616         }
5617         if (options.removeClass) {
5618           element.removeClass(options.removeClass);
5619           options.removeClass = null;
5620         }
5621         if (options.to) {
5622           element.css(options.to);
5623           options.to = null;
5624         }
5625       }
5626     };
5627   }];
5628 };
5629
5630 /* global stripHash: true */
5631
5632 /**
5633  * ! This is a private undocumented service !
5634  *
5635  * @name $browser
5636  * @requires $log
5637  * @description
5638  * This object has two goals:
5639  *
5640  * - hide all the global state in the browser caused by the window object
5641  * - abstract away all the browser specific features and inconsistencies
5642  *
5643  * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
5644  * service, which can be used for convenient testing of the application without the interaction with
5645  * the real browser apis.
5646  */
5647 /**
5648  * @param {object} window The global window object.
5649  * @param {object} document jQuery wrapped document.
5650  * @param {object} $log window.console or an object with the same interface.
5651  * @param {object} $sniffer $sniffer service
5652  */
5653 function Browser(window, document, $log, $sniffer) {
5654   var self = this,
5655       rawDocument = document[0],
5656       location = window.location,
5657       history = window.history,
5658       setTimeout = window.setTimeout,
5659       clearTimeout = window.clearTimeout,
5660       pendingDeferIds = {};
5661
5662   self.isMock = false;
5663
5664   var outstandingRequestCount = 0;
5665   var outstandingRequestCallbacks = [];
5666
5667   // TODO(vojta): remove this temporary api
5668   self.$$completeOutstandingRequest = completeOutstandingRequest;
5669   self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
5670
5671   /**
5672    * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
5673    * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
5674    */
5675   function completeOutstandingRequest(fn) {
5676     try {
5677       fn.apply(null, sliceArgs(arguments, 1));
5678     } finally {
5679       outstandingRequestCount--;
5680       if (outstandingRequestCount === 0) {
5681         while (outstandingRequestCallbacks.length) {
5682           try {
5683             outstandingRequestCallbacks.pop()();
5684           } catch (e) {
5685             $log.error(e);
5686           }
5687         }
5688       }
5689     }
5690   }
5691
5692   function getHash(url) {
5693     var index = url.indexOf('#');
5694     return index === -1 ? '' : url.substr(index);
5695   }
5696
5697   /**
5698    * @private
5699    * Note: this method is used only by scenario runner
5700    * TODO(vojta): prefix this method with $$ ?
5701    * @param {function()} callback Function that will be called when no outstanding request
5702    */
5703   self.notifyWhenNoOutstandingRequests = function(callback) {
5704     if (outstandingRequestCount === 0) {
5705       callback();
5706     } else {
5707       outstandingRequestCallbacks.push(callback);
5708     }
5709   };
5710
5711   //////////////////////////////////////////////////////////////
5712   // URL API
5713   //////////////////////////////////////////////////////////////
5714
5715   var cachedState, lastHistoryState,
5716       lastBrowserUrl = location.href,
5717       baseElement = document.find('base'),
5718       pendingLocation = null;
5719
5720   cacheState();
5721   lastHistoryState = cachedState;
5722
5723   /**
5724    * @name $browser#url
5725    *
5726    * @description
5727    * GETTER:
5728    * Without any argument, this method just returns current value of location.href.
5729    *
5730    * SETTER:
5731    * With at least one argument, this method sets url to new value.
5732    * If html5 history api supported, pushState/replaceState is used, otherwise
5733    * location.href/location.replace is used.
5734    * Returns its own instance to allow chaining
5735    *
5736    * NOTE: this api is intended for use only by the $location service. Please use the
5737    * {@link ng.$location $location service} to change url.
5738    *
5739    * @param {string} url New url (when used as setter)
5740    * @param {boolean=} replace Should new url replace current history record?
5741    * @param {object=} state object to use with pushState/replaceState
5742    */
5743   self.url = function(url, replace, state) {
5744     // In modern browsers `history.state` is `null` by default; treating it separately
5745     // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
5746     // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
5747     if (isUndefined(state)) {
5748       state = null;
5749     }
5750
5751     // Android Browser BFCache causes location, history reference to become stale.
5752     if (location !== window.location) location = window.location;
5753     if (history !== window.history) history = window.history;
5754
5755     // setter
5756     if (url) {
5757       var sameState = lastHistoryState === state;
5758
5759       // Don't change anything if previous and current URLs and states match. This also prevents
5760       // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
5761       // See https://github.com/angular/angular.js/commit/ffb2701
5762       if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
5763         return self;
5764       }
5765       var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
5766       lastBrowserUrl = url;
5767       lastHistoryState = state;
5768       // Don't use history API if only the hash changed
5769       // due to a bug in IE10/IE11 which leads
5770       // to not firing a `hashchange` nor `popstate` event
5771       // in some cases (see #9143).
5772       if ($sniffer.history && (!sameBase || !sameState)) {
5773         history[replace ? 'replaceState' : 'pushState'](state, '', url);
5774         cacheState();
5775         // Do the assignment again so that those two variables are referentially identical.
5776         lastHistoryState = cachedState;
5777       } else {
5778         if (!sameBase || pendingLocation) {
5779           pendingLocation = url;
5780         }
5781         if (replace) {
5782           location.replace(url);
5783         } else if (!sameBase) {
5784           location.href = url;
5785         } else {
5786           location.hash = getHash(url);
5787         }
5788         if (location.href !== url) {
5789           pendingLocation = url;
5790         }
5791       }
5792       return self;
5793     // getter
5794     } else {
5795       // - pendingLocation is needed as browsers don't allow to read out
5796       //   the new location.href if a reload happened or if there is a bug like in iOS 9 (see
5797       //   https://openradar.appspot.com/22186109).
5798       // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
5799       return pendingLocation || location.href.replace(/%27/g,"'");
5800     }
5801   };
5802
5803   /**
5804    * @name $browser#state
5805    *
5806    * @description
5807    * This method is a getter.
5808    *
5809    * Return history.state or null if history.state is undefined.
5810    *
5811    * @returns {object} state
5812    */
5813   self.state = function() {
5814     return cachedState;
5815   };
5816
5817   var urlChangeListeners = [],
5818       urlChangeInit = false;
5819
5820   function cacheStateAndFireUrlChange() {
5821     pendingLocation = null;
5822     cacheState();
5823     fireUrlChange();
5824   }
5825
5826   function getCurrentState() {
5827     try {
5828       return history.state;
5829     } catch (e) {
5830       // MSIE can reportedly throw when there is no state (UNCONFIRMED).
5831     }
5832   }
5833
5834   // This variable should be used *only* inside the cacheState function.
5835   var lastCachedState = null;
5836   function cacheState() {
5837     // This should be the only place in $browser where `history.state` is read.
5838     cachedState = getCurrentState();
5839     cachedState = isUndefined(cachedState) ? null : cachedState;
5840
5841     // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
5842     if (equals(cachedState, lastCachedState)) {
5843       cachedState = lastCachedState;
5844     }
5845     lastCachedState = cachedState;
5846   }
5847
5848   function fireUrlChange() {
5849     if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
5850       return;
5851     }
5852
5853     lastBrowserUrl = self.url();
5854     lastHistoryState = cachedState;
5855     forEach(urlChangeListeners, function(listener) {
5856       listener(self.url(), cachedState);
5857     });
5858   }
5859
5860   /**
5861    * @name $browser#onUrlChange
5862    *
5863    * @description
5864    * Register callback function that will be called, when url changes.
5865    *
5866    * It's only called when the url is changed from outside of angular:
5867    * - user types different url into address bar
5868    * - user clicks on history (forward/back) button
5869    * - user clicks on a link
5870    *
5871    * It's not called when url is changed by $browser.url() method
5872    *
5873    * The listener gets called with new url as parameter.
5874    *
5875    * NOTE: this api is intended for use only by the $location service. Please use the
5876    * {@link ng.$location $location service} to monitor url changes in angular apps.
5877    *
5878    * @param {function(string)} listener Listener function to be called when url changes.
5879    * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
5880    */
5881   self.onUrlChange = function(callback) {
5882     // TODO(vojta): refactor to use node's syntax for events
5883     if (!urlChangeInit) {
5884       // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
5885       // don't fire popstate when user change the address bar and don't fire hashchange when url
5886       // changed by push/replaceState
5887
5888       // html5 history api - popstate event
5889       if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
5890       // hashchange event
5891       jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
5892
5893       urlChangeInit = true;
5894     }
5895
5896     urlChangeListeners.push(callback);
5897     return callback;
5898   };
5899
5900   /**
5901    * @private
5902    * Remove popstate and hashchange handler from window.
5903    *
5904    * NOTE: this api is intended for use only by $rootScope.
5905    */
5906   self.$$applicationDestroyed = function() {
5907     jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
5908   };
5909
5910   /**
5911    * Checks whether the url has changed outside of Angular.
5912    * Needs to be exported to be able to check for changes that have been done in sync,
5913    * as hashchange/popstate events fire in async.
5914    */
5915   self.$$checkUrlChange = fireUrlChange;
5916
5917   //////////////////////////////////////////////////////////////
5918   // Misc API
5919   //////////////////////////////////////////////////////////////
5920
5921   /**
5922    * @name $browser#baseHref
5923    *
5924    * @description
5925    * Returns current <base href>
5926    * (always relative - without domain)
5927    *
5928    * @returns {string} The current base href
5929    */
5930   self.baseHref = function() {
5931     var href = baseElement.attr('href');
5932     return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
5933   };
5934
5935   /**
5936    * @name $browser#defer
5937    * @param {function()} fn A function, who's execution should be deferred.
5938    * @param {number=} [delay=0] of milliseconds to defer the function execution.
5939    * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
5940    *
5941    * @description
5942    * Executes a fn asynchronously via `setTimeout(fn, delay)`.
5943    *
5944    * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
5945    * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
5946    * via `$browser.defer.flush()`.
5947    *
5948    */
5949   self.defer = function(fn, delay) {
5950     var timeoutId;
5951     outstandingRequestCount++;
5952     timeoutId = setTimeout(function() {
5953       delete pendingDeferIds[timeoutId];
5954       completeOutstandingRequest(fn);
5955     }, delay || 0);
5956     pendingDeferIds[timeoutId] = true;
5957     return timeoutId;
5958   };
5959
5960
5961   /**
5962    * @name $browser#defer.cancel
5963    *
5964    * @description
5965    * Cancels a deferred task identified with `deferId`.
5966    *
5967    * @param {*} deferId Token returned by the `$browser.defer` function.
5968    * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
5969    *                    canceled.
5970    */
5971   self.defer.cancel = function(deferId) {
5972     if (pendingDeferIds[deferId]) {
5973       delete pendingDeferIds[deferId];
5974       clearTimeout(deferId);
5975       completeOutstandingRequest(noop);
5976       return true;
5977     }
5978     return false;
5979   };
5980
5981 }
5982
5983 function $BrowserProvider() {
5984   this.$get = ['$window', '$log', '$sniffer', '$document',
5985       function($window, $log, $sniffer, $document) {
5986         return new Browser($window, $document, $log, $sniffer);
5987       }];
5988 }
5989
5990 /**
5991  * @ngdoc service
5992  * @name $cacheFactory
5993  *
5994  * @description
5995  * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
5996  * them.
5997  *
5998  * ```js
5999  *
6000  *  var cache = $cacheFactory('cacheId');
6001  *  expect($cacheFactory.get('cacheId')).toBe(cache);
6002  *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
6003  *
6004  *  cache.put("key", "value");
6005  *  cache.put("another key", "another value");
6006  *
6007  *  // We've specified no options on creation
6008  *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});
6009  *
6010  * ```
6011  *
6012  *
6013  * @param {string} cacheId Name or id of the newly created cache.
6014  * @param {object=} options Options object that specifies the cache behavior. Properties:
6015  *
6016  *   - `{number=}` `capacity` — turns the cache into LRU cache.
6017  *
6018  * @returns {object} Newly created cache object with the following set of methods:
6019  *
6020  * - `{object}` `info()` — Returns id, size, and options of cache.
6021  * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
6022  *   it.
6023  * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
6024  * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
6025  * - `{void}` `removeAll()` — Removes all cached values.
6026  * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
6027  *
6028  * @example
6029    <example module="cacheExampleApp">
6030      <file name="index.html">
6031        <div ng-controller="CacheController">
6032          <input ng-model="newCacheKey" placeholder="Key">
6033          <input ng-model="newCacheValue" placeholder="Value">
6034          <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
6035
6036          <p ng-if="keys.length">Cached Values</p>
6037          <div ng-repeat="key in keys">
6038            <span ng-bind="key"></span>
6039            <span>: </span>
6040            <b ng-bind="cache.get(key)"></b>
6041          </div>
6042
6043          <p>Cache Info</p>
6044          <div ng-repeat="(key, value) in cache.info()">
6045            <span ng-bind="key"></span>
6046            <span>: </span>
6047            <b ng-bind="value"></b>
6048          </div>
6049        </div>
6050      </file>
6051      <file name="script.js">
6052        angular.module('cacheExampleApp', []).
6053          controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
6054            $scope.keys = [];
6055            $scope.cache = $cacheFactory('cacheId');
6056            $scope.put = function(key, value) {
6057              if (angular.isUndefined($scope.cache.get(key))) {
6058                $scope.keys.push(key);
6059              }
6060              $scope.cache.put(key, angular.isUndefined(value) ? null : value);
6061            };
6062          }]);
6063      </file>
6064      <file name="style.css">
6065        p {
6066          margin: 10px 0 3px;
6067        }
6068      </file>
6069    </example>
6070  */
6071 function $CacheFactoryProvider() {
6072
6073   this.$get = function() {
6074     var caches = {};
6075
6076     function cacheFactory(cacheId, options) {
6077       if (cacheId in caches) {
6078         throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
6079       }
6080
6081       var size = 0,
6082           stats = extend({}, options, {id: cacheId}),
6083           data = createMap(),
6084           capacity = (options && options.capacity) || Number.MAX_VALUE,
6085           lruHash = createMap(),
6086           freshEnd = null,
6087           staleEnd = null;
6088
6089       /**
6090        * @ngdoc type
6091        * @name $cacheFactory.Cache
6092        *
6093        * @description
6094        * A cache object used to store and retrieve data, primarily used by
6095        * {@link $http $http} and the {@link ng.directive:script script} directive to cache
6096        * templates and other data.
6097        *
6098        * ```js
6099        *  angular.module('superCache')
6100        *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {
6101        *      return $cacheFactory('super-cache');
6102        *    }]);
6103        * ```
6104        *
6105        * Example test:
6106        *
6107        * ```js
6108        *  it('should behave like a cache', inject(function(superCache) {
6109        *    superCache.put('key', 'value');
6110        *    superCache.put('another key', 'another value');
6111        *
6112        *    expect(superCache.info()).toEqual({
6113        *      id: 'super-cache',
6114        *      size: 2
6115        *    });
6116        *
6117        *    superCache.remove('another key');
6118        *    expect(superCache.get('another key')).toBeUndefined();
6119        *
6120        *    superCache.removeAll();
6121        *    expect(superCache.info()).toEqual({
6122        *      id: 'super-cache',
6123        *      size: 0
6124        *    });
6125        *  }));
6126        * ```
6127        */
6128       return caches[cacheId] = {
6129
6130         /**
6131          * @ngdoc method
6132          * @name $cacheFactory.Cache#put
6133          * @kind function
6134          *
6135          * @description
6136          * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
6137          * retrieved later, and incrementing the size of the cache if the key was not already
6138          * present in the cache. If behaving like an LRU cache, it will also remove stale
6139          * entries from the set.
6140          *
6141          * It will not insert undefined values into the cache.
6142          *
6143          * @param {string} key the key under which the cached data is stored.
6144          * @param {*} value the value to store alongside the key. If it is undefined, the key
6145          *    will not be stored.
6146          * @returns {*} the value stored.
6147          */
6148         put: function(key, value) {
6149           if (isUndefined(value)) return;
6150           if (capacity < Number.MAX_VALUE) {
6151             var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
6152
6153             refresh(lruEntry);
6154           }
6155
6156           if (!(key in data)) size++;
6157           data[key] = value;
6158
6159           if (size > capacity) {
6160             this.remove(staleEnd.key);
6161           }
6162
6163           return value;
6164         },
6165
6166         /**
6167          * @ngdoc method
6168          * @name $cacheFactory.Cache#get
6169          * @kind function
6170          *
6171          * @description
6172          * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
6173          *
6174          * @param {string} key the key of the data to be retrieved
6175          * @returns {*} the value stored.
6176          */
6177         get: function(key) {
6178           if (capacity < Number.MAX_VALUE) {
6179             var lruEntry = lruHash[key];
6180
6181             if (!lruEntry) return;
6182
6183             refresh(lruEntry);
6184           }
6185
6186           return data[key];
6187         },
6188
6189
6190         /**
6191          * @ngdoc method
6192          * @name $cacheFactory.Cache#remove
6193          * @kind function
6194          *
6195          * @description
6196          * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
6197          *
6198          * @param {string} key the key of the entry to be removed
6199          */
6200         remove: function(key) {
6201           if (capacity < Number.MAX_VALUE) {
6202             var lruEntry = lruHash[key];
6203
6204             if (!lruEntry) return;
6205
6206             if (lruEntry == freshEnd) freshEnd = lruEntry.p;
6207             if (lruEntry == staleEnd) staleEnd = lruEntry.n;
6208             link(lruEntry.n,lruEntry.p);
6209
6210             delete lruHash[key];
6211           }
6212
6213           if (!(key in data)) return;
6214
6215           delete data[key];
6216           size--;
6217         },
6218
6219
6220         /**
6221          * @ngdoc method
6222          * @name $cacheFactory.Cache#removeAll
6223          * @kind function
6224          *
6225          * @description
6226          * Clears the cache object of any entries.
6227          */
6228         removeAll: function() {
6229           data = createMap();
6230           size = 0;
6231           lruHash = createMap();
6232           freshEnd = staleEnd = null;
6233         },
6234
6235
6236         /**
6237          * @ngdoc method
6238          * @name $cacheFactory.Cache#destroy
6239          * @kind function
6240          *
6241          * @description
6242          * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
6243          * removing it from the {@link $cacheFactory $cacheFactory} set.
6244          */
6245         destroy: function() {
6246           data = null;
6247           stats = null;
6248           lruHash = null;
6249           delete caches[cacheId];
6250         },
6251
6252
6253         /**
6254          * @ngdoc method
6255          * @name $cacheFactory.Cache#info
6256          * @kind function
6257          *
6258          * @description
6259          * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
6260          *
6261          * @returns {object} an object with the following properties:
6262          *   <ul>
6263          *     <li>**id**: the id of the cache instance</li>
6264          *     <li>**size**: the number of entries kept in the cache instance</li>
6265          *     <li>**...**: any additional properties from the options object when creating the
6266          *       cache.</li>
6267          *   </ul>
6268          */
6269         info: function() {
6270           return extend({}, stats, {size: size});
6271         }
6272       };
6273
6274
6275       /**
6276        * makes the `entry` the freshEnd of the LRU linked list
6277        */
6278       function refresh(entry) {
6279         if (entry != freshEnd) {
6280           if (!staleEnd) {
6281             staleEnd = entry;
6282           } else if (staleEnd == entry) {
6283             staleEnd = entry.n;
6284           }
6285
6286           link(entry.n, entry.p);
6287           link(entry, freshEnd);
6288           freshEnd = entry;
6289           freshEnd.n = null;
6290         }
6291       }
6292
6293
6294       /**
6295        * bidirectionally links two entries of the LRU linked list
6296        */
6297       function link(nextEntry, prevEntry) {
6298         if (nextEntry != prevEntry) {
6299           if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
6300           if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
6301         }
6302       }
6303     }
6304
6305
6306   /**
6307    * @ngdoc method
6308    * @name $cacheFactory#info
6309    *
6310    * @description
6311    * Get information about all the caches that have been created
6312    *
6313    * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
6314    */
6315     cacheFactory.info = function() {
6316       var info = {};
6317       forEach(caches, function(cache, cacheId) {
6318         info[cacheId] = cache.info();
6319       });
6320       return info;
6321     };
6322
6323
6324   /**
6325    * @ngdoc method
6326    * @name $cacheFactory#get
6327    *
6328    * @description
6329    * Get access to a cache object by the `cacheId` used when it was created.
6330    *
6331    * @param {string} cacheId Name or id of a cache to access.
6332    * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
6333    */
6334     cacheFactory.get = function(cacheId) {
6335       return caches[cacheId];
6336     };
6337
6338
6339     return cacheFactory;
6340   };
6341 }
6342
6343 /**
6344  * @ngdoc service
6345  * @name $templateCache
6346  *
6347  * @description
6348  * The first time a template is used, it is loaded in the template cache for quick retrieval. You
6349  * can load templates directly into the cache in a `script` tag, or by consuming the
6350  * `$templateCache` service directly.
6351  *
6352  * Adding via the `script` tag:
6353  *
6354  * ```html
6355  *   <script type="text/ng-template" id="templateId.html">
6356  *     <p>This is the content of the template</p>
6357  *   </script>
6358  * ```
6359  *
6360  * **Note:** the `script` tag containing the template does not need to be included in the `head` of
6361  * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
6362  * element with ng-app attribute), otherwise the template will be ignored.
6363  *
6364  * Adding via the `$templateCache` service:
6365  *
6366  * ```js
6367  * var myApp = angular.module('myApp', []);
6368  * myApp.run(function($templateCache) {
6369  *   $templateCache.put('templateId.html', 'This is the content of the template');
6370  * });
6371  * ```
6372  *
6373  * To retrieve the template later, simply use it in your HTML:
6374  * ```html
6375  * <div ng-include=" 'templateId.html' "></div>
6376  * ```
6377  *
6378  * or get it via Javascript:
6379  * ```js
6380  * $templateCache.get('templateId.html')
6381  * ```
6382  *
6383  * See {@link ng.$cacheFactory $cacheFactory}.
6384  *
6385  */
6386 function $TemplateCacheProvider() {
6387   this.$get = ['$cacheFactory', function($cacheFactory) {
6388     return $cacheFactory('templates');
6389   }];
6390 }
6391
6392 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
6393  *     Any commits to this file should be reviewed with security in mind.  *
6394  *   Changes to this file can potentially create security vulnerabilities. *
6395  *          An approval from 2 Core members with history of modifying      *
6396  *                         this file is required.                          *
6397  *                                                                         *
6398  *  Does the change somehow allow for arbitrary javascript to be executed? *
6399  *    Or allows for someone to change the prototype of built-in objects?   *
6400  *     Or gives undesired access to variables likes document or window?    *
6401  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
6402
6403 /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
6404  *
6405  * DOM-related variables:
6406  *
6407  * - "node" - DOM Node
6408  * - "element" - DOM Element or Node
6409  * - "$node" or "$element" - jqLite-wrapped node or element
6410  *
6411  *
6412  * Compiler related stuff:
6413  *
6414  * - "linkFn" - linking fn of a single directive
6415  * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
6416  * - "childLinkFn" -  function that aggregates all linking fns for child nodes of a particular node
6417  * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
6418  */
6419
6420
6421 /**
6422  * @ngdoc service
6423  * @name $compile
6424  * @kind function
6425  *
6426  * @description
6427  * Compiles an HTML string or DOM into a template and produces a template function, which
6428  * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
6429  *
6430  * The compilation is a process of walking the DOM tree and matching DOM elements to
6431  * {@link ng.$compileProvider#directive directives}.
6432  *
6433  * <div class="alert alert-warning">
6434  * **Note:** This document is an in-depth reference of all directive options.
6435  * For a gentle introduction to directives with examples of common use cases,
6436  * see the {@link guide/directive directive guide}.
6437  * </div>
6438  *
6439  * ## Comprehensive Directive API
6440  *
6441  * There are many different options for a directive.
6442  *
6443  * The difference resides in the return value of the factory function.
6444  * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
6445  * or just the `postLink` function (all other properties will have the default values).
6446  *
6447  * <div class="alert alert-success">
6448  * **Best Practice:** It's recommended to use the "directive definition object" form.
6449  * </div>
6450  *
6451  * Here's an example directive declared with a Directive Definition Object:
6452  *
6453  * ```js
6454  *   var myModule = angular.module(...);
6455  *
6456  *   myModule.directive('directiveName', function factory(injectables) {
6457  *     var directiveDefinitionObject = {
6458  *       priority: 0,
6459  *       template: '<div></div>', // or // function(tElement, tAttrs) { ... },
6460  *       // or
6461  *       // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
6462  *       transclude: false,
6463  *       restrict: 'A',
6464  *       templateNamespace: 'html',
6465  *       scope: false,
6466  *       controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
6467  *       controllerAs: 'stringIdentifier',
6468  *       bindToController: false,
6469  *       require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
6470  *       compile: function compile(tElement, tAttrs, transclude) {
6471  *         return {
6472  *           pre: function preLink(scope, iElement, iAttrs, controller) { ... },
6473  *           post: function postLink(scope, iElement, iAttrs, controller) { ... }
6474  *         }
6475  *         // or
6476  *         // return function postLink( ... ) { ... }
6477  *       },
6478  *       // or
6479  *       // link: {
6480  *       //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },
6481  *       //  post: function postLink(scope, iElement, iAttrs, controller) { ... }
6482  *       // }
6483  *       // or
6484  *       // link: function postLink( ... ) { ... }
6485  *     };
6486  *     return directiveDefinitionObject;
6487  *   });
6488  * ```
6489  *
6490  * <div class="alert alert-warning">
6491  * **Note:** Any unspecified options will use the default value. You can see the default values below.
6492  * </div>
6493  *
6494  * Therefore the above can be simplified as:
6495  *
6496  * ```js
6497  *   var myModule = angular.module(...);
6498  *
6499  *   myModule.directive('directiveName', function factory(injectables) {
6500  *     var directiveDefinitionObject = {
6501  *       link: function postLink(scope, iElement, iAttrs) { ... }
6502  *     };
6503  *     return directiveDefinitionObject;
6504  *     // or
6505  *     // return function postLink(scope, iElement, iAttrs) { ... }
6506  *   });
6507  * ```
6508  *
6509  *
6510  *
6511  * ### Directive Definition Object
6512  *
6513  * The directive definition object provides instructions to the {@link ng.$compile
6514  * compiler}. The attributes are:
6515  *
6516  * #### `multiElement`
6517  * When this property is set to true, the HTML compiler will collect DOM nodes between
6518  * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
6519  * together as the directive elements. It is recommended that this feature be used on directives
6520  * which are not strictly behavioural (such as {@link ngClick}), and which
6521  * do not manipulate or replace child nodes (such as {@link ngInclude}).
6522  *
6523  * #### `priority`
6524  * When there are multiple directives defined on a single DOM element, sometimes it
6525  * is necessary to specify the order in which the directives are applied. The `priority` is used
6526  * to sort the directives before their `compile` functions get called. Priority is defined as a
6527  * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
6528  * are also run in priority order, but post-link functions are run in reverse order. The order
6529  * of directives with the same priority is undefined. The default priority is `0`.
6530  *
6531  * #### `terminal`
6532  * If set to true then the current `priority` will be the last set of directives
6533  * which will execute (any directives at the current priority will still execute
6534  * as the order of execution on same `priority` is undefined). Note that expressions
6535  * and other directives used in the directive's template will also be excluded from execution.
6536  *
6537  * #### `scope`
6538  * The scope property can be `true`, an object or a falsy value:
6539  *
6540  * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
6541  *
6542  * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
6543  * the directive's element. If multiple directives on the same element request a new scope,
6544  * only one new scope is created. The new scope rule does not apply for the root of the template
6545  * since the root of the template always gets a new scope.
6546  *
6547  * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
6548  * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
6549  * scope. This is useful when creating reusable components, which should not accidentally read or modify
6550  * data in the parent scope.
6551  *
6552  * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
6553  * directive's element. These local properties are useful for aliasing values for templates. The keys in
6554  * the object hash map to the name of the property on the isolate scope; the values define how the property
6555  * is bound to the parent scope, via matching attributes on the directive's element:
6556  *
6557  * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
6558  *   always a string since DOM attributes are strings. If no `attr` name is specified  then the
6559  *   attribute name is assumed to be the same as the local name.
6560  *   Given `<widget my-attr="hello {{name}}">` and widget definition
6561  *   of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
6562  *   the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
6563  *   `localName` property on the widget scope. The `name` is read from the parent scope (not
6564  *   component scope).
6565  *
6566  * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
6567  *   parent scope property of name defined via the value of the `attr` attribute. If no `attr`
6568  *   name is specified then the attribute name is assumed to be the same as the local name.
6569  *   Given `<widget my-attr="parentModel">` and widget definition of
6570  *   `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
6571  *   value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
6572  *   in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
6573  *   scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
6574  *   can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
6575  *   you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
6576  *   `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
6577  *
6578  * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
6579  *   If no `attr` name is specified then the attribute name is assumed to be the same as the
6580  *   local name. Given `<widget my-attr="count = count + value">` and widget definition of
6581  *   `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
6582  *   a function wrapper for the `count = count + value` expression. Often it's desirable to
6583  *   pass data from the isolated scope via an expression to the parent scope, this can be
6584  *   done by passing a map of local variable names and values into the expression wrapper fn.
6585  *   For example, if the expression is `increment(amount)` then we can specify the amount value
6586  *   by calling the `localFn` as `localFn({amount: 22})`.
6587  *
6588  * In general it's possible to apply more than one directive to one element, but there might be limitations
6589  * depending on the type of scope required by the directives. The following points will help explain these limitations.
6590  * For simplicity only two directives are taken into account, but it is also applicable for several directives:
6591  *
6592  * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
6593  * * **child scope** + **no scope** =>  Both directives will share one single child scope
6594  * * **child scope** + **child scope** =>  Both directives will share one single child scope
6595  * * **isolated scope** + **no scope** =>  The isolated directive will use it's own created isolated scope. The other directive will use
6596  * its parent's scope
6597  * * **isolated scope** + **child scope** =>  **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
6598  * be applied to the same element.
6599  * * **isolated scope** + **isolated scope**  =>  **Won't work!** Only one scope can be related to one element. Therefore these directives
6600  * cannot be applied to the same element.
6601  *
6602  *
6603  * #### `bindToController`
6604  * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
6605  * allow a component to have its properties bound to the controller, rather than to scope. When the controller
6606  * is instantiated, the initial values of the isolate scope bindings are already available.
6607  *
6608  * #### `controller`
6609  * Controller constructor function. The controller is instantiated before the
6610  * pre-linking phase and can be accessed by other directives (see
6611  * `require` attribute). This allows the directives to communicate with each other and augment
6612  * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
6613  *
6614  * * `$scope` - Current scope associated with the element
6615  * * `$element` - Current element
6616  * * `$attrs` - Current attributes object for the element
6617  * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
6618  *   `function([scope], cloneLinkingFn, futureParentElement)`.
6619  *    * `scope`: optional argument to override the scope.
6620  *    * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
6621  *    * `futureParentElement`:
6622  *        * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
6623  *        * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
6624  *        * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
6625  *          and when the `cloneLinkinFn` is passed,
6626  *          as those elements need to created and cloned in a special way when they are defined outside their
6627  *          usual containers (e.g. like `<svg>`).
6628  *        * See also the `directive.templateNamespace` property.
6629  *
6630  *
6631  * #### `require`
6632  * Require another directive and inject its controller as the fourth argument to the linking function. The
6633  * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
6634  * injected argument will be an array in corresponding order. If no such directive can be
6635  * found, or if the directive does not have a controller, then an error is raised (unless no link function
6636  * is specified, in which case error checking is skipped). The name can be prefixed with:
6637  *
6638  * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
6639  * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
6640  * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
6641  * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
6642  * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
6643  *   `null` to the `link` fn if not found.
6644  * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
6645  *   `null` to the `link` fn if not found.
6646  *
6647  *
6648  * #### `controllerAs`
6649  * Identifier name for a reference to the controller in the directive's scope.
6650  * This allows the controller to be referenced from the directive template. This is especially
6651  * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
6652  * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
6653  * `controllerAs` reference might overwrite a property that already exists on the parent scope.
6654  *
6655  *
6656  * #### `restrict`
6657  * String of subset of `EACM` which restricts the directive to a specific directive
6658  * declaration style. If omitted, the defaults (elements and attributes) are used.
6659  *
6660  * * `E` - Element name (default): `<my-directive></my-directive>`
6661  * * `A` - Attribute (default): `<div my-directive="exp"></div>`
6662  * * `C` - Class: `<div class="my-directive: exp;"></div>`
6663  * * `M` - Comment: `<!-- directive: my-directive exp -->`
6664  *
6665  *
6666  * #### `templateNamespace`
6667  * String representing the document type used by the markup in the template.
6668  * AngularJS needs this information as those elements need to be created and cloned
6669  * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
6670  *
6671  * * `html` - All root nodes in the template are HTML. Root nodes may also be
6672  *   top-level elements such as `<svg>` or `<math>`.
6673  * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
6674  * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
6675  *
6676  * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
6677  *
6678  * #### `template`
6679  * HTML markup that may:
6680  * * Replace the contents of the directive's element (default).
6681  * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
6682  * * Wrap the contents of the directive's element (if `transclude` is true).
6683  *
6684  * Value may be:
6685  *
6686  * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
6687  * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
6688  *   function api below) and returns a string value.
6689  *
6690  *
6691  * #### `templateUrl`
6692  * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
6693  *
6694  * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
6695  * for later when the template has been resolved.  In the meantime it will continue to compile and link
6696  * sibling and parent elements as though this element had not contained any directives.
6697  *
6698  * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
6699  * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
6700  * case when only one deeply nested directive has `templateUrl`.
6701  *
6702  * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
6703  *
6704  * You can specify `templateUrl` as a string representing the URL or as a function which takes two
6705  * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
6706  * a string value representing the url.  In either case, the template URL is passed through {@link
6707  * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
6708  *
6709  *
6710  * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
6711  * specify what the template should replace. Defaults to `false`.
6712  *
6713  * * `true` - the template will replace the directive's element.
6714  * * `false` - the template will replace the contents of the directive's element.
6715  *
6716  * The replacement process migrates all of the attributes / classes from the old element to the new
6717  * one. See the {@link guide/directive#template-expanding-directive
6718  * Directives Guide} for an example.
6719  *
6720  * There are very few scenarios where element replacement is required for the application function,
6721  * the main one being reusable custom components that are used within SVG contexts
6722  * (because SVG doesn't work with custom elements in the DOM tree).
6723  *
6724  * #### `transclude`
6725  * Extract the contents of the element where the directive appears and make it available to the directive.
6726  * The contents are compiled and provided to the directive as a **transclusion function**. See the
6727  * {@link $compile#transclusion Transclusion} section below.
6728  *
6729  * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
6730  * directive's element or the entire element:
6731  *
6732  * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
6733  * * `'element'` - transclude the whole of the directive's element including any directives on this
6734  *   element that defined at a lower priority than this directive. When used, the `template`
6735  *   property is ignored.
6736  *
6737  *
6738  * #### `compile`
6739  *
6740  * ```js
6741  *   function compile(tElement, tAttrs, transclude) { ... }
6742  * ```
6743  *
6744  * The compile function deals with transforming the template DOM. Since most directives do not do
6745  * template transformation, it is not used often. The compile function takes the following arguments:
6746  *
6747  *   * `tElement` - template element - The element where the directive has been declared. It is
6748  *     safe to do template transformation on the element and child elements only.
6749  *
6750  *   * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
6751  *     between all directive compile functions.
6752  *
6753  *   * `transclude` -  [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
6754  *
6755  * <div class="alert alert-warning">
6756  * **Note:** The template instance and the link instance may be different objects if the template has
6757  * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
6758  * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
6759  * should be done in a linking function rather than in a compile function.
6760  * </div>
6761
6762  * <div class="alert alert-warning">
6763  * **Note:** The compile function cannot handle directives that recursively use themselves in their
6764  * own templates or compile functions. Compiling these directives results in an infinite loop and a
6765  * stack overflow errors.
6766  *
6767  * This can be avoided by manually using $compile in the postLink function to imperatively compile
6768  * a directive's template instead of relying on automatic template compilation via `template` or
6769  * `templateUrl` declaration or manual compilation inside the compile function.
6770  * </div>
6771  *
6772  * <div class="alert alert-danger">
6773  * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
6774  *   e.g. does not know about the right outer scope. Please use the transclude function that is passed
6775  *   to the link function instead.
6776  * </div>
6777
6778  * A compile function can have a return value which can be either a function or an object.
6779  *
6780  * * returning a (post-link) function - is equivalent to registering the linking function via the
6781  *   `link` property of the config object when the compile function is empty.
6782  *
6783  * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
6784  *   control when a linking function should be called during the linking phase. See info about
6785  *   pre-linking and post-linking functions below.
6786  *
6787  *
6788  * #### `link`
6789  * This property is used only if the `compile` property is not defined.
6790  *
6791  * ```js
6792  *   function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
6793  * ```
6794  *
6795  * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
6796  * executed after the template has been cloned. This is where most of the directive logic will be
6797  * put.
6798  *
6799  *   * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
6800  *     directive for registering {@link ng.$rootScope.Scope#$watch watches}.
6801  *
6802  *   * `iElement` - instance element - The element where the directive is to be used. It is safe to
6803  *     manipulate the children of the element only in `postLink` function since the children have
6804  *     already been linked.
6805  *
6806  *   * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
6807  *     between all directive linking functions.
6808  *
6809  *   * `controller` - the directive's required controller instance(s) - Instances are shared
6810  *     among all directives, which allows the directives to use the controllers as a communication
6811  *     channel. The exact value depends on the directive's `require` property:
6812  *       * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
6813  *       * `string`: the controller instance
6814  *       * `array`: array of controller instances
6815  *
6816  *     If a required controller cannot be found, and it is optional, the instance is `null`,
6817  *     otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
6818  *
6819  *     Note that you can also require the directive's own controller - it will be made available like
6820  *     any other controller.
6821  *
6822  *   * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
6823  *     This is the same as the `$transclude`
6824  *     parameter of directive controllers, see there for details.
6825  *     `function([scope], cloneLinkingFn, futureParentElement)`.
6826  *
6827  * #### Pre-linking function
6828  *
6829  * Executed before the child elements are linked. Not safe to do DOM transformation since the
6830  * compiler linking function will fail to locate the correct elements for linking.
6831  *
6832  * #### Post-linking function
6833  *
6834  * Executed after the child elements are linked.
6835  *
6836  * Note that child elements that contain `templateUrl` directives will not have been compiled
6837  * and linked since they are waiting for their template to load asynchronously and their own
6838  * compilation and linking has been suspended until that occurs.
6839  *
6840  * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
6841  * for their async templates to be resolved.
6842  *
6843  *
6844  * ### Transclusion
6845  *
6846  * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
6847  * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
6848  * scope from where they were taken.
6849  *
6850  * Transclusion is used (often with {@link ngTransclude}) to insert the
6851  * original contents of a directive's element into a specified place in the template of the directive.
6852  * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
6853  * content has access to the properties on the scope from which it was taken, even if the directive
6854  * has isolated scope.
6855  * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
6856  *
6857  * This makes it possible for the widget to have private state for its template, while the transcluded
6858  * content has access to its originating scope.
6859  *
6860  * <div class="alert alert-warning">
6861  * **Note:** When testing an element transclude directive you must not place the directive at the root of the
6862  * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
6863  * Testing Transclusion Directives}.
6864  * </div>
6865  *
6866  * #### Transclusion Functions
6867  *
6868  * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
6869  * function** to the directive's `link` function and `controller`. This transclusion function is a special
6870  * **linking function** that will return the compiled contents linked to a new transclusion scope.
6871  *
6872  * <div class="alert alert-info">
6873  * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
6874  * ngTransclude will deal with it for us.
6875  * </div>
6876  *
6877  * If you want to manually control the insertion and removal of the transcluded content in your directive
6878  * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
6879  * object that contains the compiled DOM, which is linked to the correct transclusion scope.
6880  *
6881  * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
6882  * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
6883  * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
6884  *
6885  * <div class="alert alert-info">
6886  * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
6887  * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
6888  * </div>
6889  *
6890  * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
6891  * attach function**:
6892  *
6893  * ```js
6894  * var transcludedContent, transclusionScope;
6895  *
6896  * $transclude(function(clone, scope) {
6897  *   element.append(clone);
6898  *   transcludedContent = clone;
6899  *   transclusionScope = scope;
6900  * });
6901  * ```
6902  *
6903  * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
6904  * associated transclusion scope:
6905  *
6906  * ```js
6907  * transcludedContent.remove();
6908  * transclusionScope.$destroy();
6909  * ```
6910  *
6911  * <div class="alert alert-info">
6912  * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
6913  * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
6914  * then you are also responsible for calling `$destroy` on the transclusion scope.
6915  * </div>
6916  *
6917  * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
6918  * automatically destroy their transluded clones as necessary so you do not need to worry about this if
6919  * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
6920  *
6921  *
6922  * #### Transclusion Scopes
6923  *
6924  * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
6925  * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
6926  * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
6927  * was taken.
6928  *
6929  * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
6930  * like this:
6931  *
6932  * ```html
6933  * <div ng-app>
6934  *   <div isolate>
6935  *     <div transclusion>
6936  *     </div>
6937  *   </div>
6938  * </div>
6939  * ```
6940  *
6941  * The `$parent` scope hierarchy will look like this:
6942  *
6943  * ```
6944  * - $rootScope
6945  *   - isolate
6946  *     - transclusion
6947  * ```
6948  *
6949  * but the scopes will inherit prototypically from different scopes to their `$parent`.
6950  *
6951  * ```
6952  * - $rootScope
6953  *   - transclusion
6954  * - isolate
6955  * ```
6956  *
6957  *
6958  * ### Attributes
6959  *
6960  * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
6961  * `link()` or `compile()` functions. It has a variety of uses.
6962  *
6963  * accessing *Normalized attribute names:*
6964  * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
6965  * the attributes object allows for normalized access to
6966  *   the attributes.
6967  *
6968  * * *Directive inter-communication:* All directives share the same instance of the attributes
6969  *   object which allows the directives to use the attributes object as inter directive
6970  *   communication.
6971  *
6972  * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
6973  *   allowing other directives to read the interpolated value.
6974  *
6975  * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
6976  *   that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
6977  *   the only way to easily get the actual value because during the linking phase the interpolation
6978  *   hasn't been evaluated yet and so the value is at this time set to `undefined`.
6979  *
6980  * ```js
6981  * function linkingFn(scope, elm, attrs, ctrl) {
6982  *   // get the attribute value
6983  *   console.log(attrs.ngModel);
6984  *
6985  *   // change the attribute
6986  *   attrs.$set('ngModel', 'new value');
6987  *
6988  *   // observe changes to interpolated attribute
6989  *   attrs.$observe('ngModel', function(value) {
6990  *     console.log('ngModel has changed value to ' + value);
6991  *   });
6992  * }
6993  * ```
6994  *
6995  * ## Example
6996  *
6997  * <div class="alert alert-warning">
6998  * **Note**: Typically directives are registered with `module.directive`. The example below is
6999  * to illustrate how `$compile` works.
7000  * </div>
7001  *
7002  <example module="compileExample">
7003    <file name="index.html">
7004     <script>
7005       angular.module('compileExample', [], function($compileProvider) {
7006         // configure new 'compile' directive by passing a directive
7007         // factory function. The factory function injects the '$compile'
7008         $compileProvider.directive('compile', function($compile) {
7009           // directive factory creates a link function
7010           return function(scope, element, attrs) {
7011             scope.$watch(
7012               function(scope) {
7013                  // watch the 'compile' expression for changes
7014                 return scope.$eval(attrs.compile);
7015               },
7016               function(value) {
7017                 // when the 'compile' expression changes
7018                 // assign it into the current DOM
7019                 element.html(value);
7020
7021                 // compile the new DOM and link it to the current
7022                 // scope.
7023                 // NOTE: we only compile .childNodes so that
7024                 // we don't get into infinite loop compiling ourselves
7025                 $compile(element.contents())(scope);
7026               }
7027             );
7028           };
7029         });
7030       })
7031       .controller('GreeterController', ['$scope', function($scope) {
7032         $scope.name = 'Angular';
7033         $scope.html = 'Hello {{name}}';
7034       }]);
7035     </script>
7036     <div ng-controller="GreeterController">
7037       <input ng-model="name"> <br/>
7038       <textarea ng-model="html"></textarea> <br/>
7039       <div compile="html"></div>
7040     </div>
7041    </file>
7042    <file name="protractor.js" type="protractor">
7043      it('should auto compile', function() {
7044        var textarea = $('textarea');
7045        var output = $('div[compile]');
7046        // The initial state reads 'Hello Angular'.
7047        expect(output.getText()).toBe('Hello Angular');
7048        textarea.clear();
7049        textarea.sendKeys('{{name}}!');
7050        expect(output.getText()).toBe('Angular!');
7051      });
7052    </file>
7053  </example>
7054
7055  *
7056  *
7057  * @param {string|DOMElement} element Element or HTML string to compile into a template function.
7058  * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
7059  *
7060  * <div class="alert alert-danger">
7061  * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
7062  *   e.g. will not use the right outer scope. Please pass the transclude function as a
7063  *   `parentBoundTranscludeFn` to the link function instead.
7064  * </div>
7065  *
7066  * @param {number} maxPriority only apply directives lower than given priority (Only effects the
7067  *                 root element(s), not their children)
7068  * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
7069  * (a DOM element/tree) to a scope. Where:
7070  *
7071  *  * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
7072  *  * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
7073  *  `template` and call the `cloneAttachFn` function allowing the caller to attach the
7074  *  cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
7075  *  called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
7076  *
7077  *      * `clonedElement` - is a clone of the original `element` passed into the compiler.
7078  *      * `scope` - is the current scope with which the linking function is working with.
7079  *
7080  *  * `options` - An optional object hash with linking options. If `options` is provided, then the following
7081  *  keys may be used to control linking behavior:
7082  *
7083  *      * `parentBoundTranscludeFn` - the transclude function made available to
7084  *        directives; if given, it will be passed through to the link functions of
7085  *        directives found in `element` during compilation.
7086  *      * `transcludeControllers` - an object hash with keys that map controller names
7087  *        to controller instances; if given, it will make the controllers
7088  *        available to directives.
7089  *      * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
7090  *        the cloned elements; only needed for transcludes that are allowed to contain non html
7091  *        elements (e.g. SVG elements). See also the directive.controller property.
7092  *
7093  * Calling the linking function returns the element of the template. It is either the original
7094  * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
7095  *
7096  * After linking the view is not updated until after a call to $digest which typically is done by
7097  * Angular automatically.
7098  *
7099  * If you need access to the bound view, there are two ways to do it:
7100  *
7101  * - If you are not asking the linking function to clone the template, create the DOM element(s)
7102  *   before you send them to the compiler and keep this reference around.
7103  *   ```js
7104  *     var element = $compile('<p>{{total}}</p>')(scope);
7105  *   ```
7106  *
7107  * - if on the other hand, you need the element to be cloned, the view reference from the original
7108  *   example would not point to the clone, but rather to the original template that was cloned. In
7109  *   this case, you can access the clone via the cloneAttachFn:
7110  *   ```js
7111  *     var templateElement = angular.element('<p>{{total}}</p>'),
7112  *         scope = ....;
7113  *
7114  *     var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
7115  *       //attach the clone to DOM document at the right place
7116  *     });
7117  *
7118  *     //now we have reference to the cloned DOM via `clonedElement`
7119  *   ```
7120  *
7121  *
7122  * For information on how the compiler works, see the
7123  * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
7124  */
7125
7126 var $compileMinErr = minErr('$compile');
7127
7128 /**
7129  * @ngdoc provider
7130  * @name $compileProvider
7131  *
7132  * @description
7133  */
7134 $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
7135 function $CompileProvider($provide, $$sanitizeUriProvider) {
7136   var hasDirectives = {},
7137       Suffix = 'Directive',
7138       COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
7139       CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
7140       ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
7141       REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
7142
7143   // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
7144   // The assumption is that future DOM event attribute names will begin with
7145   // 'on' and be composed of only English letters.
7146   var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
7147
7148   function parseIsolateBindings(scope, directiveName, isController) {
7149     var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
7150
7151     var bindings = {};
7152
7153     forEach(scope, function(definition, scopeName) {
7154       var match = definition.match(LOCAL_REGEXP);
7155
7156       if (!match) {
7157         throw $compileMinErr('iscp',
7158             "Invalid {3} for directive '{0}'." +
7159             " Definition: {... {1}: '{2}' ...}",
7160             directiveName, scopeName, definition,
7161             (isController ? "controller bindings definition" :
7162             "isolate scope definition"));
7163       }
7164
7165       bindings[scopeName] = {
7166         mode: match[1][0],
7167         collection: match[2] === '*',
7168         optional: match[3] === '?',
7169         attrName: match[4] || scopeName
7170       };
7171     });
7172
7173     return bindings;
7174   }
7175
7176   function parseDirectiveBindings(directive, directiveName) {
7177     var bindings = {
7178       isolateScope: null,
7179       bindToController: null
7180     };
7181     if (isObject(directive.scope)) {
7182       if (directive.bindToController === true) {
7183         bindings.bindToController = parseIsolateBindings(directive.scope,
7184                                                          directiveName, true);
7185         bindings.isolateScope = {};
7186       } else {
7187         bindings.isolateScope = parseIsolateBindings(directive.scope,
7188                                                      directiveName, false);
7189       }
7190     }
7191     if (isObject(directive.bindToController)) {
7192       bindings.bindToController =
7193           parseIsolateBindings(directive.bindToController, directiveName, true);
7194     }
7195     if (isObject(bindings.bindToController)) {
7196       var controller = directive.controller;
7197       var controllerAs = directive.controllerAs;
7198       if (!controller) {
7199         // There is no controller, there may or may not be a controllerAs property
7200         throw $compileMinErr('noctrl',
7201               "Cannot bind to controller without directive '{0}'s controller.",
7202               directiveName);
7203       } else if (!identifierForController(controller, controllerAs)) {
7204         // There is a controller, but no identifier or controllerAs property
7205         throw $compileMinErr('noident',
7206               "Cannot bind to controller without identifier for directive '{0}'.",
7207               directiveName);
7208       }
7209     }
7210     return bindings;
7211   }
7212
7213   function assertValidDirectiveName(name) {
7214     var letter = name.charAt(0);
7215     if (!letter || letter !== lowercase(letter)) {
7216       throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
7217     }
7218     if (name !== name.trim()) {
7219       throw $compileMinErr('baddir',
7220             "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
7221             name);
7222     }
7223   }
7224
7225   /**
7226    * @ngdoc method
7227    * @name $compileProvider#directive
7228    * @kind function
7229    *
7230    * @description
7231    * Register a new directive with the compiler.
7232    *
7233    * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
7234    *    will match as <code>ng-bind</code>), or an object map of directives where the keys are the
7235    *    names and the values are the factories.
7236    * @param {Function|Array} directiveFactory An injectable directive factory function. See
7237    *    {@link guide/directive} for more info.
7238    * @returns {ng.$compileProvider} Self for chaining.
7239    */
7240    this.directive = function registerDirective(name, directiveFactory) {
7241     assertNotHasOwnProperty(name, 'directive');
7242     if (isString(name)) {
7243       assertValidDirectiveName(name);
7244       assertArg(directiveFactory, 'directiveFactory');
7245       if (!hasDirectives.hasOwnProperty(name)) {
7246         hasDirectives[name] = [];
7247         $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
7248           function($injector, $exceptionHandler) {
7249             var directives = [];
7250             forEach(hasDirectives[name], function(directiveFactory, index) {
7251               try {
7252                 var directive = $injector.invoke(directiveFactory);
7253                 if (isFunction(directive)) {
7254                   directive = { compile: valueFn(directive) };
7255                 } else if (!directive.compile && directive.link) {
7256                   directive.compile = valueFn(directive.link);
7257                 }
7258                 directive.priority = directive.priority || 0;
7259                 directive.index = index;
7260                 directive.name = directive.name || name;
7261                 directive.require = directive.require || (directive.controller && directive.name);
7262                 directive.restrict = directive.restrict || 'EA';
7263                 var bindings = directive.$$bindings =
7264                     parseDirectiveBindings(directive, directive.name);
7265                 if (isObject(bindings.isolateScope)) {
7266                   directive.$$isolateBindings = bindings.isolateScope;
7267                 }
7268                 directive.$$moduleName = directiveFactory.$$moduleName;
7269                 directives.push(directive);
7270               } catch (e) {
7271                 $exceptionHandler(e);
7272               }
7273             });
7274             return directives;
7275           }]);
7276       }
7277       hasDirectives[name].push(directiveFactory);
7278     } else {
7279       forEach(name, reverseParams(registerDirective));
7280     }
7281     return this;
7282   };
7283
7284
7285   /**
7286    * @ngdoc method
7287    * @name $compileProvider#aHrefSanitizationWhitelist
7288    * @kind function
7289    *
7290    * @description
7291    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
7292    * urls during a[href] sanitization.
7293    *
7294    * The sanitization is a security measure aimed at preventing XSS attacks via html links.
7295    *
7296    * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
7297    * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
7298    * regular expression. If a match is found, the original url is written into the dom. Otherwise,
7299    * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
7300    *
7301    * @param {RegExp=} regexp New regexp to whitelist urls with.
7302    * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
7303    *    chaining otherwise.
7304    */
7305   this.aHrefSanitizationWhitelist = function(regexp) {
7306     if (isDefined(regexp)) {
7307       $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
7308       return this;
7309     } else {
7310       return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
7311     }
7312   };
7313
7314
7315   /**
7316    * @ngdoc method
7317    * @name $compileProvider#imgSrcSanitizationWhitelist
7318    * @kind function
7319    *
7320    * @description
7321    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
7322    * urls during img[src] sanitization.
7323    *
7324    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
7325    *
7326    * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
7327    * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
7328    * regular expression. If a match is found, the original url is written into the dom. Otherwise,
7329    * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
7330    *
7331    * @param {RegExp=} regexp New regexp to whitelist urls with.
7332    * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
7333    *    chaining otherwise.
7334    */
7335   this.imgSrcSanitizationWhitelist = function(regexp) {
7336     if (isDefined(regexp)) {
7337       $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
7338       return this;
7339     } else {
7340       return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
7341     }
7342   };
7343
7344   /**
7345    * @ngdoc method
7346    * @name  $compileProvider#debugInfoEnabled
7347    *
7348    * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
7349    * current debugInfoEnabled state
7350    * @returns {*} current value if used as getter or itself (chaining) if used as setter
7351    *
7352    * @kind function
7353    *
7354    * @description
7355    * Call this method to enable/disable various debug runtime information in the compiler such as adding
7356    * binding information and a reference to the current scope on to DOM elements.
7357    * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
7358    * * `ng-binding` CSS class
7359    * * `$binding` data property containing an array of the binding expressions
7360    *
7361    * You may want to disable this in production for a significant performance boost. See
7362    * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
7363    *
7364    * The default value is true.
7365    */
7366   var debugInfoEnabled = true;
7367   this.debugInfoEnabled = function(enabled) {
7368     if (isDefined(enabled)) {
7369       debugInfoEnabled = enabled;
7370       return this;
7371     }
7372     return debugInfoEnabled;
7373   };
7374
7375   this.$get = [
7376             '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
7377             '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
7378     function($injector,   $interpolate,   $exceptionHandler,   $templateRequest,   $parse,
7379              $controller,   $rootScope,   $document,   $sce,   $animate,   $$sanitizeUri) {
7380
7381     var Attributes = function(element, attributesToCopy) {
7382       if (attributesToCopy) {
7383         var keys = Object.keys(attributesToCopy);
7384         var i, l, key;
7385
7386         for (i = 0, l = keys.length; i < l; i++) {
7387           key = keys[i];
7388           this[key] = attributesToCopy[key];
7389         }
7390       } else {
7391         this.$attr = {};
7392       }
7393
7394       this.$$element = element;
7395     };
7396
7397     Attributes.prototype = {
7398       /**
7399        * @ngdoc method
7400        * @name $compile.directive.Attributes#$normalize
7401        * @kind function
7402        *
7403        * @description
7404        * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
7405        * `data-`) to its normalized, camelCase form.
7406        *
7407        * Also there is special case for Moz prefix starting with upper case letter.
7408        *
7409        * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
7410        *
7411        * @param {string} name Name to normalize
7412        */
7413       $normalize: directiveNormalize,
7414
7415
7416       /**
7417        * @ngdoc method
7418        * @name $compile.directive.Attributes#$addClass
7419        * @kind function
7420        *
7421        * @description
7422        * Adds the CSS class value specified by the classVal parameter to the element. If animations
7423        * are enabled then an animation will be triggered for the class addition.
7424        *
7425        * @param {string} classVal The className value that will be added to the element
7426        */
7427       $addClass: function(classVal) {
7428         if (classVal && classVal.length > 0) {
7429           $animate.addClass(this.$$element, classVal);
7430         }
7431       },
7432
7433       /**
7434        * @ngdoc method
7435        * @name $compile.directive.Attributes#$removeClass
7436        * @kind function
7437        *
7438        * @description
7439        * Removes the CSS class value specified by the classVal parameter from the element. If
7440        * animations are enabled then an animation will be triggered for the class removal.
7441        *
7442        * @param {string} classVal The className value that will be removed from the element
7443        */
7444       $removeClass: function(classVal) {
7445         if (classVal && classVal.length > 0) {
7446           $animate.removeClass(this.$$element, classVal);
7447         }
7448       },
7449
7450       /**
7451        * @ngdoc method
7452        * @name $compile.directive.Attributes#$updateClass
7453        * @kind function
7454        *
7455        * @description
7456        * Adds and removes the appropriate CSS class values to the element based on the difference
7457        * between the new and old CSS class values (specified as newClasses and oldClasses).
7458        *
7459        * @param {string} newClasses The current CSS className value
7460        * @param {string} oldClasses The former CSS className value
7461        */
7462       $updateClass: function(newClasses, oldClasses) {
7463         var toAdd = tokenDifference(newClasses, oldClasses);
7464         if (toAdd && toAdd.length) {
7465           $animate.addClass(this.$$element, toAdd);
7466         }
7467
7468         var toRemove = tokenDifference(oldClasses, newClasses);
7469         if (toRemove && toRemove.length) {
7470           $animate.removeClass(this.$$element, toRemove);
7471         }
7472       },
7473
7474       /**
7475        * Set a normalized attribute on the element in a way such that all directives
7476        * can share the attribute. This function properly handles boolean attributes.
7477        * @param {string} key Normalized key. (ie ngAttribute)
7478        * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
7479        * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
7480        *     Defaults to true.
7481        * @param {string=} attrName Optional none normalized name. Defaults to key.
7482        */
7483       $set: function(key, value, writeAttr, attrName) {
7484         // TODO: decide whether or not to throw an error if "class"
7485         //is set through this function since it may cause $updateClass to
7486         //become unstable.
7487
7488         var node = this.$$element[0],
7489             booleanKey = getBooleanAttrName(node, key),
7490             aliasedKey = getAliasedAttrName(key),
7491             observer = key,
7492             nodeName;
7493
7494         if (booleanKey) {
7495           this.$$element.prop(key, value);
7496           attrName = booleanKey;
7497         } else if (aliasedKey) {
7498           this[aliasedKey] = value;
7499           observer = aliasedKey;
7500         }
7501
7502         this[key] = value;
7503
7504         // translate normalized key to actual key
7505         if (attrName) {
7506           this.$attr[key] = attrName;
7507         } else {
7508           attrName = this.$attr[key];
7509           if (!attrName) {
7510             this.$attr[key] = attrName = snake_case(key, '-');
7511           }
7512         }
7513
7514         nodeName = nodeName_(this.$$element);
7515
7516         if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
7517             (nodeName === 'img' && key === 'src')) {
7518           // sanitize a[href] and img[src] values
7519           this[key] = value = $$sanitizeUri(value, key === 'src');
7520         } else if (nodeName === 'img' && key === 'srcset') {
7521           // sanitize img[srcset] values
7522           var result = "";
7523
7524           // first check if there are spaces because it's not the same pattern
7525           var trimmedSrcset = trim(value);
7526           //                (   999x   ,|   999w   ,|   ,|,   )
7527           var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
7528           var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
7529
7530           // split srcset into tuple of uri and descriptor except for the last item
7531           var rawUris = trimmedSrcset.split(pattern);
7532
7533           // for each tuples
7534           var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
7535           for (var i = 0; i < nbrUrisWith2parts; i++) {
7536             var innerIdx = i * 2;
7537             // sanitize the uri
7538             result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
7539             // add the descriptor
7540             result += (" " + trim(rawUris[innerIdx + 1]));
7541           }
7542
7543           // split the last item into uri and descriptor
7544           var lastTuple = trim(rawUris[i * 2]).split(/\s/);
7545
7546           // sanitize the last uri
7547           result += $$sanitizeUri(trim(lastTuple[0]), true);
7548
7549           // and add the last descriptor if any
7550           if (lastTuple.length === 2) {
7551             result += (" " + trim(lastTuple[1]));
7552           }
7553           this[key] = value = result;
7554         }
7555
7556         if (writeAttr !== false) {
7557           if (value === null || isUndefined(value)) {
7558             this.$$element.removeAttr(attrName);
7559           } else {
7560             this.$$element.attr(attrName, value);
7561           }
7562         }
7563
7564         // fire observers
7565         var $$observers = this.$$observers;
7566         $$observers && forEach($$observers[observer], function(fn) {
7567           try {
7568             fn(value);
7569           } catch (e) {
7570             $exceptionHandler(e);
7571           }
7572         });
7573       },
7574
7575
7576       /**
7577        * @ngdoc method
7578        * @name $compile.directive.Attributes#$observe
7579        * @kind function
7580        *
7581        * @description
7582        * Observes an interpolated attribute.
7583        *
7584        * The observer function will be invoked once during the next `$digest` following
7585        * compilation. The observer is then invoked whenever the interpolated value
7586        * changes.
7587        *
7588        * @param {string} key Normalized key. (ie ngAttribute) .
7589        * @param {function(interpolatedValue)} fn Function that will be called whenever
7590                 the interpolated value of the attribute changes.
7591        *        See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
7592        * @returns {function()} Returns a deregistration function for this observer.
7593        */
7594       $observe: function(key, fn) {
7595         var attrs = this,
7596             $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
7597             listeners = ($$observers[key] || ($$observers[key] = []));
7598
7599         listeners.push(fn);
7600         $rootScope.$evalAsync(function() {
7601           if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
7602             // no one registered attribute interpolation function, so lets call it manually
7603             fn(attrs[key]);
7604           }
7605         });
7606
7607         return function() {
7608           arrayRemove(listeners, fn);
7609         };
7610       }
7611     };
7612
7613
7614     function safeAddClass($element, className) {
7615       try {
7616         $element.addClass(className);
7617       } catch (e) {
7618         // ignore, since it means that we are trying to set class on
7619         // SVG element, where class name is read-only.
7620       }
7621     }
7622
7623
7624     var startSymbol = $interpolate.startSymbol(),
7625         endSymbol = $interpolate.endSymbol(),
7626         denormalizeTemplate = (startSymbol == '{{' || endSymbol  == '}}')
7627             ? identity
7628             : function denormalizeTemplate(template) {
7629               return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
7630         },
7631         NG_ATTR_BINDING = /^ngAttr[A-Z]/;
7632     var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
7633
7634     compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
7635       var bindings = $element.data('$binding') || [];
7636
7637       if (isArray(binding)) {
7638         bindings = bindings.concat(binding);
7639       } else {
7640         bindings.push(binding);
7641       }
7642
7643       $element.data('$binding', bindings);
7644     } : noop;
7645
7646     compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
7647       safeAddClass($element, 'ng-binding');
7648     } : noop;
7649
7650     compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
7651       var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
7652       $element.data(dataName, scope);
7653     } : noop;
7654
7655     compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
7656       safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
7657     } : noop;
7658
7659     return compile;
7660
7661     //================================
7662
7663     function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
7664                         previousCompileContext) {
7665       if (!($compileNodes instanceof jqLite)) {
7666         // jquery always rewraps, whereas we need to preserve the original selector so that we can
7667         // modify it.
7668         $compileNodes = jqLite($compileNodes);
7669       }
7670       // We can not compile top level text elements since text nodes can be merged and we will
7671       // not be able to attach scope data to them, so we will wrap them in <span>
7672       forEach($compileNodes, function(node, index) {
7673         if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */) {
7674           $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
7675         }
7676       });
7677       var compositeLinkFn =
7678               compileNodes($compileNodes, transcludeFn, $compileNodes,
7679                            maxPriority, ignoreDirective, previousCompileContext);
7680       compile.$$addScopeClass($compileNodes);
7681       var namespace = null;
7682       return function publicLinkFn(scope, cloneConnectFn, options) {
7683         assertArg(scope, 'scope');
7684
7685         if (previousCompileContext && previousCompileContext.needsNewScope) {
7686           // A parent directive did a replace and a directive on this element asked
7687           // for transclusion, which caused us to lose a layer of element on which
7688           // we could hold the new transclusion scope, so we will create it manually
7689           // here.
7690           scope = scope.$parent.$new();
7691         }
7692
7693         options = options || {};
7694         var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
7695           transcludeControllers = options.transcludeControllers,
7696           futureParentElement = options.futureParentElement;
7697
7698         // When `parentBoundTranscludeFn` is passed, it is a
7699         // `controllersBoundTransclude` function (it was previously passed
7700         // as `transclude` to directive.link) so we must unwrap it to get
7701         // its `boundTranscludeFn`
7702         if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
7703           parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
7704         }
7705
7706         if (!namespace) {
7707           namespace = detectNamespaceForChildElements(futureParentElement);
7708         }
7709         var $linkNode;
7710         if (namespace !== 'html') {
7711           // When using a directive with replace:true and templateUrl the $compileNodes
7712           // (or a child element inside of them)
7713           // might change, so we need to recreate the namespace adapted compileNodes
7714           // for call to the link function.
7715           // Note: This will already clone the nodes...
7716           $linkNode = jqLite(
7717             wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
7718           );
7719         } else if (cloneConnectFn) {
7720           // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
7721           // and sometimes changes the structure of the DOM.
7722           $linkNode = JQLitePrototype.clone.call($compileNodes);
7723         } else {
7724           $linkNode = $compileNodes;
7725         }
7726
7727         if (transcludeControllers) {
7728           for (var controllerName in transcludeControllers) {
7729             $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
7730           }
7731         }
7732
7733         compile.$$addScopeInfo($linkNode, scope);
7734
7735         if (cloneConnectFn) cloneConnectFn($linkNode, scope);
7736         if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
7737         return $linkNode;
7738       };
7739     }
7740
7741     function detectNamespaceForChildElements(parentElement) {
7742       // TODO: Make this detect MathML as well...
7743       var node = parentElement && parentElement[0];
7744       if (!node) {
7745         return 'html';
7746       } else {
7747         return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
7748       }
7749     }
7750
7751     /**
7752      * Compile function matches each node in nodeList against the directives. Once all directives
7753      * for a particular node are collected their compile functions are executed. The compile
7754      * functions return values - the linking functions - are combined into a composite linking
7755      * function, which is the a linking function for the node.
7756      *
7757      * @param {NodeList} nodeList an array of nodes or NodeList to compile
7758      * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
7759      *        scope argument is auto-generated to the new child of the transcluded parent scope.
7760      * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
7761      *        the rootElement must be set the jqLite collection of the compile root. This is
7762      *        needed so that the jqLite collection items can be replaced with widgets.
7763      * @param {number=} maxPriority Max directive priority.
7764      * @returns {Function} A composite linking function of all of the matched directives or null.
7765      */
7766     function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
7767                             previousCompileContext) {
7768       var linkFns = [],
7769           attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
7770
7771       for (var i = 0; i < nodeList.length; i++) {
7772         attrs = new Attributes();
7773
7774         // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
7775         directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
7776                                         ignoreDirective);
7777
7778         nodeLinkFn = (directives.length)
7779             ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
7780                                       null, [], [], previousCompileContext)
7781             : null;
7782
7783         if (nodeLinkFn && nodeLinkFn.scope) {
7784           compile.$$addScopeClass(attrs.$$element);
7785         }
7786
7787         childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
7788                       !(childNodes = nodeList[i].childNodes) ||
7789                       !childNodes.length)
7790             ? null
7791             : compileNodes(childNodes,
7792                  nodeLinkFn ? (
7793                   (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
7794                      && nodeLinkFn.transclude) : transcludeFn);
7795
7796         if (nodeLinkFn || childLinkFn) {
7797           linkFns.push(i, nodeLinkFn, childLinkFn);
7798           linkFnFound = true;
7799           nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
7800         }
7801
7802         //use the previous context only for the first element in the virtual group
7803         previousCompileContext = null;
7804       }
7805
7806       // return a linking function if we have found anything, null otherwise
7807       return linkFnFound ? compositeLinkFn : null;
7808
7809       function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
7810         var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
7811         var stableNodeList;
7812
7813
7814         if (nodeLinkFnFound) {
7815           // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
7816           // offsets don't get screwed up
7817           var nodeListLength = nodeList.length;
7818           stableNodeList = new Array(nodeListLength);
7819
7820           // create a sparse array by only copying the elements which have a linkFn
7821           for (i = 0; i < linkFns.length; i+=3) {
7822             idx = linkFns[i];
7823             stableNodeList[idx] = nodeList[idx];
7824           }
7825         } else {
7826           stableNodeList = nodeList;
7827         }
7828
7829         for (i = 0, ii = linkFns.length; i < ii;) {
7830           node = stableNodeList[linkFns[i++]];
7831           nodeLinkFn = linkFns[i++];
7832           childLinkFn = linkFns[i++];
7833
7834           if (nodeLinkFn) {
7835             if (nodeLinkFn.scope) {
7836               childScope = scope.$new();
7837               compile.$$addScopeInfo(jqLite(node), childScope);
7838             } else {
7839               childScope = scope;
7840             }
7841
7842             if (nodeLinkFn.transcludeOnThisElement) {
7843               childBoundTranscludeFn = createBoundTranscludeFn(
7844                   scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
7845
7846             } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
7847               childBoundTranscludeFn = parentBoundTranscludeFn;
7848
7849             } else if (!parentBoundTranscludeFn && transcludeFn) {
7850               childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
7851
7852             } else {
7853               childBoundTranscludeFn = null;
7854             }
7855
7856             nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
7857
7858           } else if (childLinkFn) {
7859             childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
7860           }
7861         }
7862       }
7863     }
7864
7865     function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
7866
7867       var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
7868
7869         if (!transcludedScope) {
7870           transcludedScope = scope.$new(false, containingScope);
7871           transcludedScope.$$transcluded = true;
7872         }
7873
7874         return transcludeFn(transcludedScope, cloneFn, {
7875           parentBoundTranscludeFn: previousBoundTranscludeFn,
7876           transcludeControllers: controllers,
7877           futureParentElement: futureParentElement
7878         });
7879       };
7880
7881       // We need  to attach the transclusion slots onto the `boundTranscludeFn`
7882       // so that they are available inside the `controllersBoundTransclude` function
7883       var boundSlots = boundTranscludeFn.$$slots = createMap();
7884       for (var slotName in transcludeFn.$$slots) {
7885         boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
7886       }
7887
7888       return boundTranscludeFn;
7889     }
7890
7891     /**
7892      * Looks for directives on the given node and adds them to the directive collection which is
7893      * sorted.
7894      *
7895      * @param node Node to search.
7896      * @param directives An array to which the directives are added to. This array is sorted before
7897      *        the function returns.
7898      * @param attrs The shared attrs object which is used to populate the normalized attributes.
7899      * @param {number=} maxPriority Max directive priority.
7900      */
7901     function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
7902       var nodeType = node.nodeType,
7903           attrsMap = attrs.$attr,
7904           match,
7905           className;
7906
7907       switch (nodeType) {
7908         case NODE_TYPE_ELEMENT: /* Element */
7909           // use the node name: <directive>
7910           addDirective(directives,
7911               directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
7912
7913           // iterate over the attributes
7914           for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
7915                    j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
7916             var attrStartName = false;
7917             var attrEndName = false;
7918
7919             attr = nAttrs[j];
7920             name = attr.name;
7921             value = trim(attr.value);
7922
7923             // support ngAttr attribute binding
7924             ngAttrName = directiveNormalize(name);
7925             if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
7926               name = name.replace(PREFIX_REGEXP, '')
7927                 .substr(8).replace(/_(.)/g, function(match, letter) {
7928                   return letter.toUpperCase();
7929                 });
7930             }
7931
7932             var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
7933             if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
7934               attrStartName = name;
7935               attrEndName = name.substr(0, name.length - 5) + 'end';
7936               name = name.substr(0, name.length - 6);
7937             }
7938
7939             nName = directiveNormalize(name.toLowerCase());
7940             attrsMap[nName] = name;
7941             if (isNgAttr || !attrs.hasOwnProperty(nName)) {
7942                 attrs[nName] = value;
7943                 if (getBooleanAttrName(node, nName)) {
7944                   attrs[nName] = true; // presence means true
7945                 }
7946             }
7947             addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
7948             addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
7949                           attrEndName);
7950           }
7951
7952           // use class as directive
7953           className = node.className;
7954           if (isObject(className)) {
7955               // Maybe SVGAnimatedString
7956               className = className.animVal;
7957           }
7958           if (isString(className) && className !== '') {
7959             while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
7960               nName = directiveNormalize(match[2]);
7961               if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
7962                 attrs[nName] = trim(match[3]);
7963               }
7964               className = className.substr(match.index + match[0].length);
7965             }
7966           }
7967           break;
7968         case NODE_TYPE_TEXT: /* Text Node */
7969           if (msie === 11) {
7970             // Workaround for #11781
7971             while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
7972               node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
7973               node.parentNode.removeChild(node.nextSibling);
7974             }
7975           }
7976           addTextInterpolateDirective(directives, node.nodeValue);
7977           break;
7978         case NODE_TYPE_COMMENT: /* Comment */
7979           try {
7980             match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
7981             if (match) {
7982               nName = directiveNormalize(match[1]);
7983               if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
7984                 attrs[nName] = trim(match[2]);
7985               }
7986             }
7987           } catch (e) {
7988             // turns out that under some circumstances IE9 throws errors when one attempts to read
7989             // comment's node value.
7990             // Just ignore it and continue. (Can't seem to reproduce in test case.)
7991           }
7992           break;
7993       }
7994
7995       directives.sort(byPriority);
7996       return directives;
7997     }
7998
7999     /**
8000      * Given a node with an directive-start it collects all of the siblings until it finds
8001      * directive-end.
8002      * @param node
8003      * @param attrStart
8004      * @param attrEnd
8005      * @returns {*}
8006      */
8007     function groupScan(node, attrStart, attrEnd) {
8008       var nodes = [];
8009       var depth = 0;
8010       if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
8011         do {
8012           if (!node) {
8013             throw $compileMinErr('uterdir',
8014                       "Unterminated attribute, found '{0}' but no matching '{1}' found.",
8015                       attrStart, attrEnd);
8016           }
8017           if (node.nodeType == NODE_TYPE_ELEMENT) {
8018             if (node.hasAttribute(attrStart)) depth++;
8019             if (node.hasAttribute(attrEnd)) depth--;
8020           }
8021           nodes.push(node);
8022           node = node.nextSibling;
8023         } while (depth > 0);
8024       } else {
8025         nodes.push(node);
8026       }
8027
8028       return jqLite(nodes);
8029     }
8030
8031     /**
8032      * Wrapper for linking function which converts normal linking function into a grouped
8033      * linking function.
8034      * @param linkFn
8035      * @param attrStart
8036      * @param attrEnd
8037      * @returns {Function}
8038      */
8039     function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
8040       return function(scope, element, attrs, controllers, transcludeFn) {
8041         element = groupScan(element[0], attrStart, attrEnd);
8042         return linkFn(scope, element, attrs, controllers, transcludeFn);
8043       };
8044     }
8045
8046     /**
8047      * A function generator that is used to support both eager and lazy compilation
8048      * linking function.
8049      * @param eager
8050      * @param $compileNodes
8051      * @param transcludeFn
8052      * @param maxPriority
8053      * @param ignoreDirective
8054      * @param previousCompileContext
8055      * @returns {Function}
8056      */
8057     function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
8058         if (eager) {
8059             return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
8060         }
8061
8062         var compiled;
8063
8064         return function() {
8065             if (!compiled) {
8066                 compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
8067
8068                 // Null out all of these references in order to make them eligible for garbage collection
8069                 // since this is a potentially long lived closure
8070                 $compileNodes = transcludeFn = previousCompileContext = null;
8071             }
8072
8073             return compiled.apply(this, arguments);
8074         };
8075     }
8076
8077     /**
8078      * Once the directives have been collected, their compile functions are executed. This method
8079      * is responsible for inlining directive templates as well as terminating the application
8080      * of the directives if the terminal directive has been reached.
8081      *
8082      * @param {Array} directives Array of collected directives to execute their compile function.
8083      *        this needs to be pre-sorted by priority order.
8084      * @param {Node} compileNode The raw DOM node to apply the compile functions to
8085      * @param {Object} templateAttrs The shared attribute function
8086      * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
8087      *                                                  scope argument is auto-generated to the new
8088      *                                                  child of the transcluded parent scope.
8089      * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
8090      *                              argument has the root jqLite array so that we can replace nodes
8091      *                              on it.
8092      * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
8093      *                                           compiling the transclusion.
8094      * @param {Array.<Function>} preLinkFns
8095      * @param {Array.<Function>} postLinkFns
8096      * @param {Object} previousCompileContext Context used for previous compilation of the current
8097      *                                        node
8098      * @returns {Function} linkFn
8099      */
8100     function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
8101                                    jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
8102                                    previousCompileContext) {
8103       previousCompileContext = previousCompileContext || {};
8104
8105       var terminalPriority = -Number.MAX_VALUE,
8106           newScopeDirective = previousCompileContext.newScopeDirective,
8107           controllerDirectives = previousCompileContext.controllerDirectives,
8108           newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
8109           templateDirective = previousCompileContext.templateDirective,
8110           nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
8111           hasTranscludeDirective = false,
8112           hasTemplate = false,
8113           hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
8114           $compileNode = templateAttrs.$$element = jqLite(compileNode),
8115           directive,
8116           directiveName,
8117           $template,
8118           replaceDirective = originalReplaceDirective,
8119           childTranscludeFn = transcludeFn,
8120           linkFn,
8121           didScanForMultipleTransclusion = false,
8122           mightHaveMultipleTransclusionError = false,
8123           directiveValue;
8124
8125       // executes all directives on the current element
8126       for (var i = 0, ii = directives.length; i < ii; i++) {
8127         directive = directives[i];
8128         var attrStart = directive.$$start;
8129         var attrEnd = directive.$$end;
8130
8131         // collect multiblock sections
8132         if (attrStart) {
8133           $compileNode = groupScan(compileNode, attrStart, attrEnd);
8134         }
8135         $template = undefined;
8136
8137         if (terminalPriority > directive.priority) {
8138           break; // prevent further processing of directives
8139         }
8140
8141         if (directiveValue = directive.scope) {
8142
8143           // skip the check for directives with async templates, we'll check the derived sync
8144           // directive when the template arrives
8145           if (!directive.templateUrl) {
8146             if (isObject(directiveValue)) {
8147               // This directive is trying to add an isolated scope.
8148               // Check that there is no scope of any kind already
8149               assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
8150                                 directive, $compileNode);
8151               newIsolateScopeDirective = directive;
8152             } else {
8153               // This directive is trying to add a child scope.
8154               // Check that there is no isolated scope already
8155               assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
8156                                 $compileNode);
8157             }
8158           }
8159
8160           newScopeDirective = newScopeDirective || directive;
8161         }
8162
8163         directiveName = directive.name;
8164
8165         // If we encounter a condition that can result in transclusion on the directive,
8166         // then scan ahead in the remaining directives for others that may cause a multiple
8167         // transclusion error to be thrown during the compilation process.  If a matching directive
8168         // is found, then we know that when we encounter a transcluded directive, we need to eagerly
8169         // compile the `transclude` function rather than doing it lazily in order to throw
8170         // exceptions at the correct time
8171         if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
8172             || (directive.transclude && !directive.$$tlb))) {
8173                 var candidateDirective;
8174
8175                 for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
8176                     if ((candidateDirective.transclude && !candidateDirective.$$tlb)
8177                         || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
8178                         mightHaveMultipleTransclusionError = true;
8179                         break;
8180                     }
8181                 }
8182
8183                 didScanForMultipleTransclusion = true;
8184         }
8185
8186         if (!directive.templateUrl && directive.controller) {
8187           directiveValue = directive.controller;
8188           controllerDirectives = controllerDirectives || createMap();
8189           assertNoDuplicate("'" + directiveName + "' controller",
8190               controllerDirectives[directiveName], directive, $compileNode);
8191           controllerDirectives[directiveName] = directive;
8192         }
8193
8194         if (directiveValue = directive.transclude) {
8195           hasTranscludeDirective = true;
8196
8197           // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
8198           // This option should only be used by directives that know how to safely handle element transclusion,
8199           // where the transcluded nodes are added or replaced after linking.
8200           if (!directive.$$tlb) {
8201             assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
8202             nonTlbTranscludeDirective = directive;
8203           }
8204
8205           if (directiveValue == 'element') {
8206             hasElementTranscludeDirective = true;
8207             terminalPriority = directive.priority;
8208             $template = $compileNode;
8209             $compileNode = templateAttrs.$$element =
8210                 jqLite(document.createComment(' ' + directiveName + ': ' +
8211                                               templateAttrs[directiveName] + ' '));
8212             compileNode = $compileNode[0];
8213             replaceWith(jqCollection, sliceArgs($template), compileNode);
8214
8215             childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
8216                                         replaceDirective && replaceDirective.name, {
8217                                           // Don't pass in:
8218                                           // - controllerDirectives - otherwise we'll create duplicates controllers
8219                                           // - newIsolateScopeDirective or templateDirective - combining templates with
8220                                           //   element transclusion doesn't make sense.
8221                                           //
8222                                           // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
8223                                           // on the same element more than once.
8224                                           nonTlbTranscludeDirective: nonTlbTranscludeDirective
8225                                         });
8226           } else {
8227
8228             var slots = createMap();
8229             $template = jqLite(jqLiteClone(compileNode)).contents();
8230
8231             if (isObject(directiveValue)) {
8232
8233               // We have transclusion slots - collect them up and compile them and store their
8234               // transclusion functions
8235               $template = [];
8236               var slotNames = createMap();
8237               var filledSlots = createMap();
8238
8239               // Parse the slot names: if they start with a ? then they are optional
8240               forEach(directiveValue, function(slotName, key) {
8241                 var optional = (slotName.charAt(0) === '?');
8242                 slotName = optional ? slotName.substring(1) : slotName;
8243                 slotNames[key] = slotName;
8244                 slots[slotName] = [];
8245                 // filledSlots contains `true` for all slots that are either optional or have been
8246                 // filled. This is used to check that we have not missed any required slots
8247                 filledSlots[slotName] = optional;
8248               });
8249
8250               // Add the matching elements into their slot
8251               forEach($compileNode.children(), function(node) {
8252                 var slotName = slotNames[directiveNormalize(nodeName_(node))];
8253                 if (slotName) {
8254                   filledSlots[slotName] = true;
8255                   slots[slotName].push(node);
8256                 } else {
8257                   $template.push(node);
8258                 }
8259               });
8260
8261               // Check for required slots that were not filled
8262               forEach(filledSlots, function(filled, slotName) {
8263                 if (!filled) {
8264                   throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
8265                 }
8266               });
8267
8268               forEach(Object.keys(slots), function(slotName) {
8269                 slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
8270               });
8271             }
8272
8273             $compileNode.empty(); // clear contents
8274             childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
8275                 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
8276             childTranscludeFn.$$slots = slots;
8277           }
8278         }
8279
8280         if (directive.template) {
8281           hasTemplate = true;
8282           assertNoDuplicate('template', templateDirective, directive, $compileNode);
8283           templateDirective = directive;
8284
8285           directiveValue = (isFunction(directive.template))
8286               ? directive.template($compileNode, templateAttrs)
8287               : directive.template;
8288
8289           directiveValue = denormalizeTemplate(directiveValue);
8290
8291           if (directive.replace) {
8292             replaceDirective = directive;
8293             if (jqLiteIsTextNode(directiveValue)) {
8294               $template = [];
8295             } else {
8296               $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
8297             }
8298             compileNode = $template[0];
8299
8300             if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
8301               throw $compileMinErr('tplrt',
8302                   "Template for directive '{0}' must have exactly one root element. {1}",
8303                   directiveName, '');
8304             }
8305
8306             replaceWith(jqCollection, $compileNode, compileNode);
8307
8308             var newTemplateAttrs = {$attr: {}};
8309
8310             // combine directives from the original node and from the template:
8311             // - take the array of directives for this element
8312             // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
8313             // - collect directives from the template and sort them by priority
8314             // - combine directives as: processed + template + unprocessed
8315             var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
8316             var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
8317
8318             if (newIsolateScopeDirective || newScopeDirective) {
8319               // The original directive caused the current element to be replaced but this element
8320               // also needs to have a new scope, so we need to tell the template directives
8321               // that they would need to get their scope from further up, if they require transclusion
8322               markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
8323             }
8324             directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
8325             mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
8326
8327             ii = directives.length;
8328           } else {
8329             $compileNode.html(directiveValue);
8330           }
8331         }
8332
8333         if (directive.templateUrl) {
8334           hasTemplate = true;
8335           assertNoDuplicate('template', templateDirective, directive, $compileNode);
8336           templateDirective = directive;
8337
8338           if (directive.replace) {
8339             replaceDirective = directive;
8340           }
8341
8342           nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
8343               templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
8344                 controllerDirectives: controllerDirectives,
8345                 newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
8346                 newIsolateScopeDirective: newIsolateScopeDirective,
8347                 templateDirective: templateDirective,
8348                 nonTlbTranscludeDirective: nonTlbTranscludeDirective
8349               });
8350           ii = directives.length;
8351         } else if (directive.compile) {
8352           try {
8353             linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
8354             if (isFunction(linkFn)) {
8355               addLinkFns(null, linkFn, attrStart, attrEnd);
8356             } else if (linkFn) {
8357               addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
8358             }
8359           } catch (e) {
8360             $exceptionHandler(e, startingTag($compileNode));
8361           }
8362         }
8363
8364         if (directive.terminal) {
8365           nodeLinkFn.terminal = true;
8366           terminalPriority = Math.max(terminalPriority, directive.priority);
8367         }
8368
8369       }
8370
8371       nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
8372       nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
8373       nodeLinkFn.templateOnThisElement = hasTemplate;
8374       nodeLinkFn.transclude = childTranscludeFn;
8375
8376       previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
8377
8378       // might be normal or delayed nodeLinkFn depending on if templateUrl is present
8379       return nodeLinkFn;
8380
8381       ////////////////////
8382
8383       function addLinkFns(pre, post, attrStart, attrEnd) {
8384         if (pre) {
8385           if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
8386           pre.require = directive.require;
8387           pre.directiveName = directiveName;
8388           if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
8389             pre = cloneAndAnnotateFn(pre, {isolateScope: true});
8390           }
8391           preLinkFns.push(pre);
8392         }
8393         if (post) {
8394           if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
8395           post.require = directive.require;
8396           post.directiveName = directiveName;
8397           if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
8398             post = cloneAndAnnotateFn(post, {isolateScope: true});
8399           }
8400           postLinkFns.push(post);
8401         }
8402       }
8403
8404
8405       function getControllers(directiveName, require, $element, elementControllers) {
8406         var value;
8407
8408         if (isString(require)) {
8409           var match = require.match(REQUIRE_PREFIX_REGEXP);
8410           var name = require.substring(match[0].length);
8411           var inheritType = match[1] || match[3];
8412           var optional = match[2] === '?';
8413
8414           //If only parents then start at the parent element
8415           if (inheritType === '^^') {
8416             $element = $element.parent();
8417           //Otherwise attempt getting the controller from elementControllers in case
8418           //the element is transcluded (and has no data) and to avoid .data if possible
8419           } else {
8420             value = elementControllers && elementControllers[name];
8421             value = value && value.instance;
8422           }
8423
8424           if (!value) {
8425             var dataName = '$' + name + 'Controller';
8426             value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
8427           }
8428
8429           if (!value && !optional) {
8430             throw $compileMinErr('ctreq',
8431                 "Controller '{0}', required by directive '{1}', can't be found!",
8432                 name, directiveName);
8433           }
8434         } else if (isArray(require)) {
8435           value = [];
8436           for (var i = 0, ii = require.length; i < ii; i++) {
8437             value[i] = getControllers(directiveName, require[i], $element, elementControllers);
8438           }
8439         }
8440
8441         return value || null;
8442       }
8443
8444       function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
8445         var elementControllers = createMap();
8446         for (var controllerKey in controllerDirectives) {
8447           var directive = controllerDirectives[controllerKey];
8448           var locals = {
8449             $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
8450             $element: $element,
8451             $attrs: attrs,
8452             $transclude: transcludeFn
8453           };
8454
8455           var controller = directive.controller;
8456           if (controller == '@') {
8457             controller = attrs[directive.name];
8458           }
8459
8460           var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
8461
8462           // For directives with element transclusion the element is a comment,
8463           // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
8464           // clean up (http://bugs.jquery.com/ticket/8335).
8465           // Instead, we save the controllers for the element in a local hash and attach to .data
8466           // later, once we have the actual element.
8467           elementControllers[directive.name] = controllerInstance;
8468           if (!hasElementTranscludeDirective) {
8469             $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
8470           }
8471         }
8472         return elementControllers;
8473       }
8474
8475       function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
8476         var linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
8477             attrs, removeScopeBindingWatches, removeControllerBindingWatches;
8478
8479         if (compileNode === linkNode) {
8480           attrs = templateAttrs;
8481           $element = templateAttrs.$$element;
8482         } else {
8483           $element = jqLite(linkNode);
8484           attrs = new Attributes($element, templateAttrs);
8485         }
8486
8487         controllerScope = scope;
8488         if (newIsolateScopeDirective) {
8489           isolateScope = scope.$new(true);
8490         } else if (newScopeDirective) {
8491           controllerScope = scope.$parent;
8492         }
8493
8494         if (boundTranscludeFn) {
8495           // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
8496           // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
8497           transcludeFn = controllersBoundTransclude;
8498           transcludeFn.$$boundTransclude = boundTranscludeFn;
8499         }
8500
8501         if (controllerDirectives) {
8502           elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
8503         }
8504
8505         if (newIsolateScopeDirective) {
8506           // Initialize isolate scope bindings for new isolate scope directive.
8507           compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
8508               templateDirective === newIsolateScopeDirective.$$originalDirective)));
8509           compile.$$addScopeClass($element, true);
8510           isolateScope.$$isolateBindings =
8511               newIsolateScopeDirective.$$isolateBindings;
8512           removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
8513                                         isolateScope.$$isolateBindings,
8514                                         newIsolateScopeDirective);
8515           if (removeScopeBindingWatches) {
8516             isolateScope.$on('$destroy', removeScopeBindingWatches);
8517           }
8518         }
8519
8520         // Initialize bindToController bindings
8521         for (var name in elementControllers) {
8522           var controllerDirective = controllerDirectives[name];
8523           var controller = elementControllers[name];
8524           var bindings = controllerDirective.$$bindings.bindToController;
8525
8526           if (controller.identifier && bindings) {
8527             removeControllerBindingWatches =
8528               initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
8529           }
8530
8531           var controllerResult = controller();
8532           if (controllerResult !== controller.instance) {
8533             // If the controller constructor has a return value, overwrite the instance
8534             // from setupControllers
8535             controller.instance = controllerResult;
8536             $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
8537             removeControllerBindingWatches && removeControllerBindingWatches();
8538             removeControllerBindingWatches =
8539               initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
8540           }
8541         }
8542
8543         // PRELINKING
8544         for (i = 0, ii = preLinkFns.length; i < ii; i++) {
8545           linkFn = preLinkFns[i];
8546           invokeLinkFn(linkFn,
8547               linkFn.isolateScope ? isolateScope : scope,
8548               $element,
8549               attrs,
8550               linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
8551               transcludeFn
8552           );
8553         }
8554
8555         // RECURSION
8556         // We only pass the isolate scope, if the isolate directive has a template,
8557         // otherwise the child elements do not belong to the isolate directive.
8558         var scopeToChild = scope;
8559         if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
8560           scopeToChild = isolateScope;
8561         }
8562         childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
8563
8564         // POSTLINKING
8565         for (i = postLinkFns.length - 1; i >= 0; i--) {
8566           linkFn = postLinkFns[i];
8567           invokeLinkFn(linkFn,
8568               linkFn.isolateScope ? isolateScope : scope,
8569               $element,
8570               attrs,
8571               linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
8572               transcludeFn
8573           );
8574         }
8575
8576         // This is the function that is injected as `$transclude`.
8577         // Note: all arguments are optional!
8578         function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
8579           var transcludeControllers;
8580           // No scope passed in:
8581           if (!isScope(scope)) {
8582             slotName = futureParentElement;
8583             futureParentElement = cloneAttachFn;
8584             cloneAttachFn = scope;
8585             scope = undefined;
8586           }
8587
8588           if (hasElementTranscludeDirective) {
8589             transcludeControllers = elementControllers;
8590           }
8591           if (!futureParentElement) {
8592             futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
8593           }
8594           if (slotName) {
8595             var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
8596             if (!slotTranscludeFn) {
8597               throw $compileMinErr('noslot',
8598                'No parent directive that requires a transclusion with slot name "{0}". ' +
8599                'Element: {1}',
8600                slotName, startingTag($element));
8601             }
8602             return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
8603           }
8604           return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
8605         }
8606       }
8607     }
8608
8609     // Depending upon the context in which a directive finds itself it might need to have a new isolated
8610     // or child scope created. For instance:
8611     // * if the directive has been pulled into a template because another directive with a higher priority
8612     // asked for element transclusion
8613     // * if the directive itself asks for transclusion but it is at the root of a template and the original
8614     // element was replaced. See https://github.com/angular/angular.js/issues/12936
8615     function markDirectiveScope(directives, isolateScope, newScope) {
8616       for (var j = 0, jj = directives.length; j < jj; j++) {
8617         directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
8618       }
8619     }
8620
8621     /**
8622      * looks up the directive and decorates it with exception handling and proper parameters. We
8623      * call this the boundDirective.
8624      *
8625      * @param {string} name name of the directive to look up.
8626      * @param {string} location The directive must be found in specific format.
8627      *   String containing any of theses characters:
8628      *
8629      *   * `E`: element name
8630      *   * `A': attribute
8631      *   * `C`: class
8632      *   * `M`: comment
8633      * @returns {boolean} true if directive was added.
8634      */
8635     function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
8636                           endAttrName) {
8637       if (name === ignoreDirective) return null;
8638       var match = null;
8639       if (hasDirectives.hasOwnProperty(name)) {
8640         for (var directive, directives = $injector.get(name + Suffix),
8641             i = 0, ii = directives.length; i < ii; i++) {
8642           try {
8643             directive = directives[i];
8644             if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
8645                  directive.restrict.indexOf(location) != -1) {
8646               if (startAttrName) {
8647                 directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
8648               }
8649               tDirectives.push(directive);
8650               match = directive;
8651             }
8652           } catch (e) { $exceptionHandler(e); }
8653         }
8654       }
8655       return match;
8656     }
8657
8658
8659     /**
8660      * looks up the directive and returns true if it is a multi-element directive,
8661      * and therefore requires DOM nodes between -start and -end markers to be grouped
8662      * together.
8663      *
8664      * @param {string} name name of the directive to look up.
8665      * @returns true if directive was registered as multi-element.
8666      */
8667     function directiveIsMultiElement(name) {
8668       if (hasDirectives.hasOwnProperty(name)) {
8669         for (var directive, directives = $injector.get(name + Suffix),
8670             i = 0, ii = directives.length; i < ii; i++) {
8671           directive = directives[i];
8672           if (directive.multiElement) {
8673             return true;
8674           }
8675         }
8676       }
8677       return false;
8678     }
8679
8680     /**
8681      * When the element is replaced with HTML template then the new attributes
8682      * on the template need to be merged with the existing attributes in the DOM.
8683      * The desired effect is to have both of the attributes present.
8684      *
8685      * @param {object} dst destination attributes (original DOM)
8686      * @param {object} src source attributes (from the directive template)
8687      */
8688     function mergeTemplateAttributes(dst, src) {
8689       var srcAttr = src.$attr,
8690           dstAttr = dst.$attr,
8691           $element = dst.$$element;
8692
8693       // reapply the old attributes to the new element
8694       forEach(dst, function(value, key) {
8695         if (key.charAt(0) != '$') {
8696           if (src[key] && src[key] !== value) {
8697             value += (key === 'style' ? ';' : ' ') + src[key];
8698           }
8699           dst.$set(key, value, true, srcAttr[key]);
8700         }
8701       });
8702
8703       // copy the new attributes on the old attrs object
8704       forEach(src, function(value, key) {
8705         if (key == 'class') {
8706           safeAddClass($element, value);
8707           dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
8708         } else if (key == 'style') {
8709           $element.attr('style', $element.attr('style') + ';' + value);
8710           dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
8711           // `dst` will never contain hasOwnProperty as DOM parser won't let it.
8712           // You will get an "InvalidCharacterError: DOM Exception 5" error if you
8713           // have an attribute like "has-own-property" or "data-has-own-property", etc.
8714         } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
8715           dst[key] = value;
8716           dstAttr[key] = srcAttr[key];
8717         }
8718       });
8719     }
8720
8721
8722     function compileTemplateUrl(directives, $compileNode, tAttrs,
8723         $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
8724       var linkQueue = [],
8725           afterTemplateNodeLinkFn,
8726           afterTemplateChildLinkFn,
8727           beforeTemplateCompileNode = $compileNode[0],
8728           origAsyncDirective = directives.shift(),
8729           derivedSyncDirective = inherit(origAsyncDirective, {
8730             templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
8731           }),
8732           templateUrl = (isFunction(origAsyncDirective.templateUrl))
8733               ? origAsyncDirective.templateUrl($compileNode, tAttrs)
8734               : origAsyncDirective.templateUrl,
8735           templateNamespace = origAsyncDirective.templateNamespace;
8736
8737       $compileNode.empty();
8738
8739       $templateRequest(templateUrl)
8740         .then(function(content) {
8741           var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
8742
8743           content = denormalizeTemplate(content);
8744
8745           if (origAsyncDirective.replace) {
8746             if (jqLiteIsTextNode(content)) {
8747               $template = [];
8748             } else {
8749               $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
8750             }
8751             compileNode = $template[0];
8752
8753             if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
8754               throw $compileMinErr('tplrt',
8755                   "Template for directive '{0}' must have exactly one root element. {1}",
8756                   origAsyncDirective.name, templateUrl);
8757             }
8758
8759             tempTemplateAttrs = {$attr: {}};
8760             replaceWith($rootElement, $compileNode, compileNode);
8761             var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
8762
8763             if (isObject(origAsyncDirective.scope)) {
8764               // the original directive that caused the template to be loaded async required
8765               // an isolate scope
8766               markDirectiveScope(templateDirectives, true);
8767             }
8768             directives = templateDirectives.concat(directives);
8769             mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
8770           } else {
8771             compileNode = beforeTemplateCompileNode;
8772             $compileNode.html(content);
8773           }
8774
8775           directives.unshift(derivedSyncDirective);
8776
8777           afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
8778               childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
8779               previousCompileContext);
8780           forEach($rootElement, function(node, i) {
8781             if (node == compileNode) {
8782               $rootElement[i] = $compileNode[0];
8783             }
8784           });
8785           afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
8786
8787           while (linkQueue.length) {
8788             var scope = linkQueue.shift(),
8789                 beforeTemplateLinkNode = linkQueue.shift(),
8790                 linkRootElement = linkQueue.shift(),
8791                 boundTranscludeFn = linkQueue.shift(),
8792                 linkNode = $compileNode[0];
8793
8794             if (scope.$$destroyed) continue;
8795
8796             if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
8797               var oldClasses = beforeTemplateLinkNode.className;
8798
8799               if (!(previousCompileContext.hasElementTranscludeDirective &&
8800                   origAsyncDirective.replace)) {
8801                 // it was cloned therefore we have to clone as well.
8802                 linkNode = jqLiteClone(compileNode);
8803               }
8804               replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
8805
8806               // Copy in CSS classes from original node
8807               safeAddClass(jqLite(linkNode), oldClasses);
8808             }
8809             if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
8810               childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
8811             } else {
8812               childBoundTranscludeFn = boundTranscludeFn;
8813             }
8814             afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
8815               childBoundTranscludeFn);
8816           }
8817           linkQueue = null;
8818         });
8819
8820       return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
8821         var childBoundTranscludeFn = boundTranscludeFn;
8822         if (scope.$$destroyed) return;
8823         if (linkQueue) {
8824           linkQueue.push(scope,
8825                          node,
8826                          rootElement,
8827                          childBoundTranscludeFn);
8828         } else {
8829           if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
8830             childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
8831           }
8832           afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
8833         }
8834       };
8835     }
8836
8837
8838     /**
8839      * Sorting function for bound directives.
8840      */
8841     function byPriority(a, b) {
8842       var diff = b.priority - a.priority;
8843       if (diff !== 0) return diff;
8844       if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
8845       return a.index - b.index;
8846     }
8847
8848     function assertNoDuplicate(what, previousDirective, directive, element) {
8849
8850       function wrapModuleNameIfDefined(moduleName) {
8851         return moduleName ?
8852           (' (module: ' + moduleName + ')') :
8853           '';
8854       }
8855
8856       if (previousDirective) {
8857         throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
8858             previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
8859             directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
8860       }
8861     }
8862
8863
8864     function addTextInterpolateDirective(directives, text) {
8865       var interpolateFn = $interpolate(text, true);
8866       if (interpolateFn) {
8867         directives.push({
8868           priority: 0,
8869           compile: function textInterpolateCompileFn(templateNode) {
8870             var templateNodeParent = templateNode.parent(),
8871                 hasCompileParent = !!templateNodeParent.length;
8872
8873             // When transcluding a template that has bindings in the root
8874             // we don't have a parent and thus need to add the class during linking fn.
8875             if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
8876
8877             return function textInterpolateLinkFn(scope, node) {
8878               var parent = node.parent();
8879               if (!hasCompileParent) compile.$$addBindingClass(parent);
8880               compile.$$addBindingInfo(parent, interpolateFn.expressions);
8881               scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
8882                 node[0].nodeValue = value;
8883               });
8884             };
8885           }
8886         });
8887       }
8888     }
8889
8890
8891     function wrapTemplate(type, template) {
8892       type = lowercase(type || 'html');
8893       switch (type) {
8894       case 'svg':
8895       case 'math':
8896         var wrapper = document.createElement('div');
8897         wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
8898         return wrapper.childNodes[0].childNodes;
8899       default:
8900         return template;
8901       }
8902     }
8903
8904
8905     function getTrustedContext(node, attrNormalizedName) {
8906       if (attrNormalizedName == "srcdoc") {
8907         return $sce.HTML;
8908       }
8909       var tag = nodeName_(node);
8910       // maction[xlink:href] can source SVG.  It's not limited to <maction>.
8911       if (attrNormalizedName == "xlinkHref" ||
8912           (tag == "form" && attrNormalizedName == "action") ||
8913           (tag != "img" && (attrNormalizedName == "src" ||
8914                             attrNormalizedName == "ngSrc"))) {
8915         return $sce.RESOURCE_URL;
8916       }
8917     }
8918
8919
8920     function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
8921       var trustedContext = getTrustedContext(node, name);
8922       allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
8923
8924       var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
8925
8926       // no interpolation found -> ignore
8927       if (!interpolateFn) return;
8928
8929
8930       if (name === "multiple" && nodeName_(node) === "select") {
8931         throw $compileMinErr("selmulti",
8932             "Binding to the 'multiple' attribute is not supported. Element: {0}",
8933             startingTag(node));
8934       }
8935
8936       directives.push({
8937         priority: 100,
8938         compile: function() {
8939             return {
8940               pre: function attrInterpolatePreLinkFn(scope, element, attr) {
8941                 var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
8942
8943                 if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
8944                   throw $compileMinErr('nodomevents',
8945                       "Interpolations for HTML DOM event attributes are disallowed.  Please use the " +
8946                           "ng- versions (such as ng-click instead of onclick) instead.");
8947                 }
8948
8949                 // If the attribute has changed since last $interpolate()ed
8950                 var newValue = attr[name];
8951                 if (newValue !== value) {
8952                   // we need to interpolate again since the attribute value has been updated
8953                   // (e.g. by another directive's compile function)
8954                   // ensure unset/empty values make interpolateFn falsy
8955                   interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
8956                   value = newValue;
8957                 }
8958
8959                 // if attribute was updated so that there is no interpolation going on we don't want to
8960                 // register any observers
8961                 if (!interpolateFn) return;
8962
8963                 // initialize attr object so that it's ready in case we need the value for isolate
8964                 // scope initialization, otherwise the value would not be available from isolate
8965                 // directive's linking fn during linking phase
8966                 attr[name] = interpolateFn(scope);
8967
8968                 ($$observers[name] || ($$observers[name] = [])).$$inter = true;
8969                 (attr.$$observers && attr.$$observers[name].$$scope || scope).
8970                   $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
8971                     //special case for class attribute addition + removal
8972                     //so that class changes can tap into the animation
8973                     //hooks provided by the $animate service. Be sure to
8974                     //skip animations when the first digest occurs (when
8975                     //both the new and the old values are the same) since
8976                     //the CSS classes are the non-interpolated values
8977                     if (name === 'class' && newValue != oldValue) {
8978                       attr.$updateClass(newValue, oldValue);
8979                     } else {
8980                       attr.$set(name, newValue);
8981                     }
8982                   });
8983               }
8984             };
8985           }
8986       });
8987     }
8988
8989
8990     /**
8991      * This is a special jqLite.replaceWith, which can replace items which
8992      * have no parents, provided that the containing jqLite collection is provided.
8993      *
8994      * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
8995      *                               in the root of the tree.
8996      * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
8997      *                                  the shell, but replace its DOM node reference.
8998      * @param {Node} newNode The new DOM node.
8999      */
9000     function replaceWith($rootElement, elementsToRemove, newNode) {
9001       var firstElementToRemove = elementsToRemove[0],
9002           removeCount = elementsToRemove.length,
9003           parent = firstElementToRemove.parentNode,
9004           i, ii;
9005
9006       if ($rootElement) {
9007         for (i = 0, ii = $rootElement.length; i < ii; i++) {
9008           if ($rootElement[i] == firstElementToRemove) {
9009             $rootElement[i++] = newNode;
9010             for (var j = i, j2 = j + removeCount - 1,
9011                      jj = $rootElement.length;
9012                  j < jj; j++, j2++) {
9013               if (j2 < jj) {
9014                 $rootElement[j] = $rootElement[j2];
9015               } else {
9016                 delete $rootElement[j];
9017               }
9018             }
9019             $rootElement.length -= removeCount - 1;
9020
9021             // If the replaced element is also the jQuery .context then replace it
9022             // .context is a deprecated jQuery api, so we should set it only when jQuery set it
9023             // http://api.jquery.com/context/
9024             if ($rootElement.context === firstElementToRemove) {
9025               $rootElement.context = newNode;
9026             }
9027             break;
9028           }
9029         }
9030       }
9031
9032       if (parent) {
9033         parent.replaceChild(newNode, firstElementToRemove);
9034       }
9035
9036       // Append all the `elementsToRemove` to a fragment. This will...
9037       // - remove them from the DOM
9038       // - allow them to still be traversed with .nextSibling
9039       // - allow a single fragment.qSA to fetch all elements being removed
9040       var fragment = document.createDocumentFragment();
9041       for (i = 0; i < removeCount; i++) {
9042         fragment.appendChild(elementsToRemove[i]);
9043       }
9044
9045       if (jqLite.hasData(firstElementToRemove)) {
9046         // Copy over user data (that includes Angular's $scope etc.). Don't copy private
9047         // data here because there's no public interface in jQuery to do that and copying over
9048         // event listeners (which is the main use of private data) wouldn't work anyway.
9049         jqLite.data(newNode, jqLite.data(firstElementToRemove));
9050
9051         // Remove $destroy event listeners from `firstElementToRemove`
9052         jqLite(firstElementToRemove).off('$destroy');
9053       }
9054
9055       // Cleanup any data/listeners on the elements and children.
9056       // This includes invoking the $destroy event on any elements with listeners.
9057       jqLite.cleanData(fragment.querySelectorAll('*'));
9058
9059       // Update the jqLite collection to only contain the `newNode`
9060       for (i = 1; i < removeCount; i++) {
9061         delete elementsToRemove[i];
9062       }
9063       elementsToRemove[0] = newNode;
9064       elementsToRemove.length = 1;
9065     }
9066
9067
9068     function cloneAndAnnotateFn(fn, annotation) {
9069       return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
9070     }
9071
9072
9073     function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
9074       try {
9075         linkFn(scope, $element, attrs, controllers, transcludeFn);
9076       } catch (e) {
9077         $exceptionHandler(e, startingTag($element));
9078       }
9079     }
9080
9081
9082     // Set up $watches for isolate scope and controller bindings. This process
9083     // only occurs for isolate scopes and new scopes with controllerAs.
9084     function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
9085       var removeWatchCollection = [];
9086       forEach(bindings, function(definition, scopeName) {
9087         var attrName = definition.attrName,
9088         optional = definition.optional,
9089         mode = definition.mode, // @, =, or &
9090         lastValue,
9091         parentGet, parentSet, compare;
9092
9093         switch (mode) {
9094
9095           case '@':
9096             if (!optional && !hasOwnProperty.call(attrs, attrName)) {
9097               destination[scopeName] = attrs[attrName] = void 0;
9098             }
9099             attrs.$observe(attrName, function(value) {
9100               if (isString(value)) {
9101                 destination[scopeName] = value;
9102               }
9103             });
9104             attrs.$$observers[attrName].$$scope = scope;
9105             if (isString(attrs[attrName])) {
9106               // If the attribute has been provided then we trigger an interpolation to ensure
9107               // the value is there for use in the link fn
9108               destination[scopeName] = $interpolate(attrs[attrName])(scope);
9109             }
9110             break;
9111
9112           case '=':
9113             if (!hasOwnProperty.call(attrs, attrName)) {
9114               if (optional) break;
9115               attrs[attrName] = void 0;
9116             }
9117             if (optional && !attrs[attrName]) break;
9118
9119             parentGet = $parse(attrs[attrName]);
9120             if (parentGet.literal) {
9121               compare = equals;
9122             } else {
9123               compare = function(a, b) { return a === b || (a !== a && b !== b); };
9124             }
9125             parentSet = parentGet.assign || function() {
9126               // reset the change, or we will throw this exception on every $digest
9127               lastValue = destination[scopeName] = parentGet(scope);
9128               throw $compileMinErr('nonassign',
9129                   "Expression '{0}' used with directive '{1}' is non-assignable!",
9130                   attrs[attrName], directive.name);
9131             };
9132             lastValue = destination[scopeName] = parentGet(scope);
9133             var parentValueWatch = function parentValueWatch(parentValue) {
9134               if (!compare(parentValue, destination[scopeName])) {
9135                 // we are out of sync and need to copy
9136                 if (!compare(parentValue, lastValue)) {
9137                   // parent changed and it has precedence
9138                   destination[scopeName] = parentValue;
9139                 } else {
9140                   // if the parent can be assigned then do so
9141                   parentSet(scope, parentValue = destination[scopeName]);
9142                 }
9143               }
9144               return lastValue = parentValue;
9145             };
9146             parentValueWatch.$stateful = true;
9147             var removeWatch;
9148             if (definition.collection) {
9149               removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
9150             } else {
9151               removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
9152             }
9153             removeWatchCollection.push(removeWatch);
9154             break;
9155
9156           case '&':
9157             // Don't assign Object.prototype method to scope
9158             parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
9159
9160             // Don't assign noop to destination if expression is not valid
9161             if (parentGet === noop && optional) break;
9162
9163             destination[scopeName] = function(locals) {
9164               return parentGet(scope, locals);
9165             };
9166             break;
9167         }
9168       });
9169
9170       return removeWatchCollection.length && function removeWatches() {
9171         for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
9172           removeWatchCollection[i]();
9173         }
9174       };
9175     }
9176   }];
9177 }
9178
9179 var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
9180 /**
9181  * Converts all accepted directives format into proper directive name.
9182  * @param name Name to normalize
9183  */
9184 function directiveNormalize(name) {
9185   return camelCase(name.replace(PREFIX_REGEXP, ''));
9186 }
9187
9188 /**
9189  * @ngdoc type
9190  * @name $compile.directive.Attributes
9191  *
9192  * @description
9193  * A shared object between directive compile / linking functions which contains normalized DOM
9194  * element attributes. The values reflect current binding state `{{ }}`. The normalization is
9195  * needed since all of these are treated as equivalent in Angular:
9196  *
9197  * ```
9198  *    <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
9199  * ```
9200  */
9201
9202 /**
9203  * @ngdoc property
9204  * @name $compile.directive.Attributes#$attr
9205  *
9206  * @description
9207  * A map of DOM element attribute names to the normalized name. This is
9208  * needed to do reverse lookup from normalized name back to actual name.
9209  */
9210
9211
9212 /**
9213  * @ngdoc method
9214  * @name $compile.directive.Attributes#$set
9215  * @kind function
9216  *
9217  * @description
9218  * Set DOM element attribute value.
9219  *
9220  *
9221  * @param {string} name Normalized element attribute name of the property to modify. The name is
9222  *          reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
9223  *          property to the original name.
9224  * @param {string} value Value to set the attribute to. The value can be an interpolated string.
9225  */
9226
9227
9228
9229 /**
9230  * Closure compiler type information
9231  */
9232
9233 function nodesetLinkingFn(
9234   /* angular.Scope */ scope,
9235   /* NodeList */ nodeList,
9236   /* Element */ rootElement,
9237   /* function(Function) */ boundTranscludeFn
9238 ) {}
9239
9240 function directiveLinkingFn(
9241   /* nodesetLinkingFn */ nodesetLinkingFn,
9242   /* angular.Scope */ scope,
9243   /* Node */ node,
9244   /* Element */ rootElement,
9245   /* function(Function) */ boundTranscludeFn
9246 ) {}
9247
9248 function tokenDifference(str1, str2) {
9249   var values = '',
9250       tokens1 = str1.split(/\s+/),
9251       tokens2 = str2.split(/\s+/);
9252
9253   outer:
9254   for (var i = 0; i < tokens1.length; i++) {
9255     var token = tokens1[i];
9256     for (var j = 0; j < tokens2.length; j++) {
9257       if (token == tokens2[j]) continue outer;
9258     }
9259     values += (values.length > 0 ? ' ' : '') + token;
9260   }
9261   return values;
9262 }
9263
9264 function removeComments(jqNodes) {
9265   jqNodes = jqLite(jqNodes);
9266   var i = jqNodes.length;
9267
9268   if (i <= 1) {
9269     return jqNodes;
9270   }
9271
9272   while (i--) {
9273     var node = jqNodes[i];
9274     if (node.nodeType === NODE_TYPE_COMMENT) {
9275       splice.call(jqNodes, i, 1);
9276     }
9277   }
9278   return jqNodes;
9279 }
9280
9281 var $controllerMinErr = minErr('$controller');
9282
9283
9284 var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
9285 function identifierForController(controller, ident) {
9286   if (ident && isString(ident)) return ident;
9287   if (isString(controller)) {
9288     var match = CNTRL_REG.exec(controller);
9289     if (match) return match[3];
9290   }
9291 }
9292
9293
9294 /**
9295  * @ngdoc provider
9296  * @name $controllerProvider
9297  * @description
9298  * The {@link ng.$controller $controller service} is used by Angular to create new
9299  * controllers.
9300  *
9301  * This provider allows controller registration via the
9302  * {@link ng.$controllerProvider#register register} method.
9303  */
9304 function $ControllerProvider() {
9305   var controllers = {},
9306       globals = false;
9307
9308   /**
9309    * @ngdoc method
9310    * @name $controllerProvider#register
9311    * @param {string|Object} name Controller name, or an object map of controllers where the keys are
9312    *    the names and the values are the constructors.
9313    * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
9314    *    annotations in the array notation).
9315    */
9316   this.register = function(name, constructor) {
9317     assertNotHasOwnProperty(name, 'controller');
9318     if (isObject(name)) {
9319       extend(controllers, name);
9320     } else {
9321       controllers[name] = constructor;
9322     }
9323   };
9324
9325   /**
9326    * @ngdoc method
9327    * @name $controllerProvider#allowGlobals
9328    * @description If called, allows `$controller` to find controller constructors on `window`
9329    */
9330   this.allowGlobals = function() {
9331     globals = true;
9332   };
9333
9334
9335   this.$get = ['$injector', '$window', function($injector, $window) {
9336
9337     /**
9338      * @ngdoc service
9339      * @name $controller
9340      * @requires $injector
9341      *
9342      * @param {Function|string} constructor If called with a function then it's considered to be the
9343      *    controller constructor function. Otherwise it's considered to be a string which is used
9344      *    to retrieve the controller constructor using the following steps:
9345      *
9346      *    * check if a controller with given name is registered via `$controllerProvider`
9347      *    * check if evaluating the string on the current scope returns a constructor
9348      *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
9349      *      `window` object (not recommended)
9350      *
9351      *    The string can use the `controller as property` syntax, where the controller instance is published
9352      *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
9353      *    to work correctly.
9354      *
9355      * @param {Object} locals Injection locals for Controller.
9356      * @return {Object} Instance of given controller.
9357      *
9358      * @description
9359      * `$controller` service is responsible for instantiating controllers.
9360      *
9361      * It's just a simple call to {@link auto.$injector $injector}, but extracted into
9362      * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
9363      */
9364     return function(expression, locals, later, ident) {
9365       // PRIVATE API:
9366       //   param `later` --- indicates that the controller's constructor is invoked at a later time.
9367       //                     If true, $controller will allocate the object with the correct
9368       //                     prototype chain, but will not invoke the controller until a returned
9369       //                     callback is invoked.
9370       //   param `ident` --- An optional label which overrides the label parsed from the controller
9371       //                     expression, if any.
9372       var instance, match, constructor, identifier;
9373       later = later === true;
9374       if (ident && isString(ident)) {
9375         identifier = ident;
9376       }
9377
9378       if (isString(expression)) {
9379         match = expression.match(CNTRL_REG);
9380         if (!match) {
9381           throw $controllerMinErr('ctrlfmt',
9382             "Badly formed controller string '{0}'. " +
9383             "Must match `__name__ as __id__` or `__name__`.", expression);
9384         }
9385         constructor = match[1],
9386         identifier = identifier || match[3];
9387         expression = controllers.hasOwnProperty(constructor)
9388             ? controllers[constructor]
9389             : getter(locals.$scope, constructor, true) ||
9390                 (globals ? getter($window, constructor, true) : undefined);
9391
9392         assertArgFn(expression, constructor, true);
9393       }
9394
9395       if (later) {
9396         // Instantiate controller later:
9397         // This machinery is used to create an instance of the object before calling the
9398         // controller's constructor itself.
9399         //
9400         // This allows properties to be added to the controller before the constructor is
9401         // invoked. Primarily, this is used for isolate scope bindings in $compile.
9402         //
9403         // This feature is not intended for use by applications, and is thus not documented
9404         // publicly.
9405         // Object creation: http://jsperf.com/create-constructor/2
9406         var controllerPrototype = (isArray(expression) ?
9407           expression[expression.length - 1] : expression).prototype;
9408         instance = Object.create(controllerPrototype || null);
9409
9410         if (identifier) {
9411           addIdentifier(locals, identifier, instance, constructor || expression.name);
9412         }
9413
9414         var instantiate;
9415         return instantiate = extend(function() {
9416           var result = $injector.invoke(expression, instance, locals, constructor);
9417           if (result !== instance && (isObject(result) || isFunction(result))) {
9418             instance = result;
9419             if (identifier) {
9420               // If result changed, re-assign controllerAs value to scope.
9421               addIdentifier(locals, identifier, instance, constructor || expression.name);
9422             }
9423           }
9424           return instance;
9425         }, {
9426           instance: instance,
9427           identifier: identifier
9428         });
9429       }
9430
9431       instance = $injector.instantiate(expression, locals, constructor);
9432
9433       if (identifier) {
9434         addIdentifier(locals, identifier, instance, constructor || expression.name);
9435       }
9436
9437       return instance;
9438     };
9439
9440     function addIdentifier(locals, identifier, instance, name) {
9441       if (!(locals && isObject(locals.$scope))) {
9442         throw minErr('$controller')('noscp',
9443           "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
9444           name, identifier);
9445       }
9446
9447       locals.$scope[identifier] = instance;
9448     }
9449   }];
9450 }
9451
9452 /**
9453  * @ngdoc service
9454  * @name $document
9455  * @requires $window
9456  *
9457  * @description
9458  * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
9459  *
9460  * @example
9461    <example module="documentExample">
9462      <file name="index.html">
9463        <div ng-controller="ExampleController">
9464          <p>$document title: <b ng-bind="title"></b></p>
9465          <p>window.document title: <b ng-bind="windowTitle"></b></p>
9466        </div>
9467      </file>
9468      <file name="script.js">
9469        angular.module('documentExample', [])
9470          .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
9471            $scope.title = $document[0].title;
9472            $scope.windowTitle = angular.element(window.document)[0].title;
9473          }]);
9474      </file>
9475    </example>
9476  */
9477 function $DocumentProvider() {
9478   this.$get = ['$window', function(window) {
9479     return jqLite(window.document);
9480   }];
9481 }
9482
9483 /**
9484  * @ngdoc service
9485  * @name $exceptionHandler
9486  * @requires ng.$log
9487  *
9488  * @description
9489  * Any uncaught exception in angular expressions is delegated to this service.
9490  * The default implementation simply delegates to `$log.error` which logs it into
9491  * the browser console.
9492  *
9493  * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
9494  * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
9495  *
9496  * ## Example:
9497  *
9498  * ```js
9499  *   angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
9500  *     return function(exception, cause) {
9501  *       exception.message += ' (caused by "' + cause + '")';
9502  *       throw exception;
9503  *     };
9504  *   });
9505  * ```
9506  *
9507  * This example will override the normal action of `$exceptionHandler`, to make angular
9508  * exceptions fail hard when they happen, instead of just logging to the console.
9509  *
9510  * <hr />
9511  * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
9512  * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
9513  * (unless executed during a digest).
9514  *
9515  * If you wish, you can manually delegate exceptions, e.g.
9516  * `try { ... } catch(e) { $exceptionHandler(e); }`
9517  *
9518  * @param {Error} exception Exception associated with the error.
9519  * @param {string=} cause optional information about the context in which
9520  *       the error was thrown.
9521  *
9522  */
9523 function $ExceptionHandlerProvider() {
9524   this.$get = ['$log', function($log) {
9525     return function(exception, cause) {
9526       $log.error.apply($log, arguments);
9527     };
9528   }];
9529 }
9530
9531 var $$ForceReflowProvider = function() {
9532   this.$get = ['$document', function($document) {
9533     return function(domNode) {
9534       //the line below will force the browser to perform a repaint so
9535       //that all the animated elements within the animation frame will
9536       //be properly updated and drawn on screen. This is required to
9537       //ensure that the preparation animation is properly flushed so that
9538       //the active state picks up from there. DO NOT REMOVE THIS LINE.
9539       //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
9540       //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
9541       //WILL TAKE YEARS AWAY FROM YOUR LIFE.
9542       if (domNode) {
9543         if (!domNode.nodeType && domNode instanceof jqLite) {
9544           domNode = domNode[0];
9545         }
9546       } else {
9547         domNode = $document[0].body;
9548       }
9549       return domNode.offsetWidth + 1;
9550     };
9551   }];
9552 };
9553
9554 var APPLICATION_JSON = 'application/json';
9555 var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
9556 var JSON_START = /^\[|^\{(?!\{)/;
9557 var JSON_ENDS = {
9558   '[': /]$/,
9559   '{': /}$/
9560 };
9561 var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
9562 var $httpMinErr = minErr('$http');
9563 var $httpMinErrLegacyFn = function(method) {
9564   return function() {
9565     throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
9566   };
9567 };
9568
9569 function serializeValue(v) {
9570   if (isObject(v)) {
9571     return isDate(v) ? v.toISOString() : toJson(v);
9572   }
9573   return v;
9574 }
9575
9576
9577 function $HttpParamSerializerProvider() {
9578   /**
9579    * @ngdoc service
9580    * @name $httpParamSerializer
9581    * @description
9582    *
9583    * Default {@link $http `$http`} params serializer that converts objects to strings
9584    * according to the following rules:
9585    *
9586    * * `{'foo': 'bar'}` results in `foo=bar`
9587    * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
9588    * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
9589    * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
9590    *
9591    * Note that serializer will sort the request parameters alphabetically.
9592    * */
9593
9594   this.$get = function() {
9595     return function ngParamSerializer(params) {
9596       if (!params) return '';
9597       var parts = [];
9598       forEachSorted(params, function(value, key) {
9599         if (value === null || isUndefined(value)) return;
9600         if (isArray(value)) {
9601           forEach(value, function(v, k) {
9602             parts.push(encodeUriQuery(key)  + '=' + encodeUriQuery(serializeValue(v)));
9603           });
9604         } else {
9605           parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
9606         }
9607       });
9608
9609       return parts.join('&');
9610     };
9611   };
9612 }
9613
9614 function $HttpParamSerializerJQLikeProvider() {
9615   /**
9616    * @ngdoc service
9617    * @name $httpParamSerializerJQLike
9618    * @description
9619    *
9620    * Alternative {@link $http `$http`} params serializer that follows
9621    * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
9622    * The serializer will also sort the params alphabetically.
9623    *
9624    * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
9625    *
9626    * ```js
9627    * $http({
9628    *   url: myUrl,
9629    *   method: 'GET',
9630    *   params: myParams,
9631    *   paramSerializer: '$httpParamSerializerJQLike'
9632    * });
9633    * ```
9634    *
9635    * It is also possible to set it as the default `paramSerializer` in the
9636    * {@link $httpProvider#defaults `$httpProvider`}.
9637    *
9638    * Additionally, you can inject the serializer and use it explicitly, for example to serialize
9639    * form data for submission:
9640    *
9641    * ```js
9642    * .controller(function($http, $httpParamSerializerJQLike) {
9643    *   //...
9644    *
9645    *   $http({
9646    *     url: myUrl,
9647    *     method: 'POST',
9648    *     data: $httpParamSerializerJQLike(myData),
9649    *     headers: {
9650    *       'Content-Type': 'application/x-www-form-urlencoded'
9651    *     }
9652    *   });
9653    *
9654    * });
9655    * ```
9656    *
9657    * */
9658   this.$get = function() {
9659     return function jQueryLikeParamSerializer(params) {
9660       if (!params) return '';
9661       var parts = [];
9662       serialize(params, '', true);
9663       return parts.join('&');
9664
9665       function serialize(toSerialize, prefix, topLevel) {
9666         if (toSerialize === null || isUndefined(toSerialize)) return;
9667         if (isArray(toSerialize)) {
9668           forEach(toSerialize, function(value, index) {
9669             serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
9670           });
9671         } else if (isObject(toSerialize) && !isDate(toSerialize)) {
9672           forEachSorted(toSerialize, function(value, key) {
9673             serialize(value, prefix +
9674                 (topLevel ? '' : '[') +
9675                 key +
9676                 (topLevel ? '' : ']'));
9677           });
9678         } else {
9679           parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
9680         }
9681       }
9682     };
9683   };
9684 }
9685
9686 function defaultHttpResponseTransform(data, headers) {
9687   if (isString(data)) {
9688     // Strip json vulnerability protection prefix and trim whitespace
9689     var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
9690
9691     if (tempData) {
9692       var contentType = headers('Content-Type');
9693       if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
9694         data = fromJson(tempData);
9695       }
9696     }
9697   }
9698
9699   return data;
9700 }
9701
9702 function isJsonLike(str) {
9703     var jsonStart = str.match(JSON_START);
9704     return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
9705 }
9706
9707 /**
9708  * Parse headers into key value object
9709  *
9710  * @param {string} headers Raw headers as a string
9711  * @returns {Object} Parsed headers as key value object
9712  */
9713 function parseHeaders(headers) {
9714   var parsed = createMap(), i;
9715
9716   function fillInParsed(key, val) {
9717     if (key) {
9718       parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
9719     }
9720   }
9721
9722   if (isString(headers)) {
9723     forEach(headers.split('\n'), function(line) {
9724       i = line.indexOf(':');
9725       fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
9726     });
9727   } else if (isObject(headers)) {
9728     forEach(headers, function(headerVal, headerKey) {
9729       fillInParsed(lowercase(headerKey), trim(headerVal));
9730     });
9731   }
9732
9733   return parsed;
9734 }
9735
9736
9737 /**
9738  * Returns a function that provides access to parsed headers.
9739  *
9740  * Headers are lazy parsed when first requested.
9741  * @see parseHeaders
9742  *
9743  * @param {(string|Object)} headers Headers to provide access to.
9744  * @returns {function(string=)} Returns a getter function which if called with:
9745  *
9746  *   - if called with single an argument returns a single header value or null
9747  *   - if called with no arguments returns an object containing all headers.
9748  */
9749 function headersGetter(headers) {
9750   var headersObj;
9751
9752   return function(name) {
9753     if (!headersObj) headersObj =  parseHeaders(headers);
9754
9755     if (name) {
9756       var value = headersObj[lowercase(name)];
9757       if (value === void 0) {
9758         value = null;
9759       }
9760       return value;
9761     }
9762
9763     return headersObj;
9764   };
9765 }
9766
9767
9768 /**
9769  * Chain all given functions
9770  *
9771  * This function is used for both request and response transforming
9772  *
9773  * @param {*} data Data to transform.
9774  * @param {function(string=)} headers HTTP headers getter fn.
9775  * @param {number} status HTTP status code of the response.
9776  * @param {(Function|Array.<Function>)} fns Function or an array of functions.
9777  * @returns {*} Transformed data.
9778  */
9779 function transformData(data, headers, status, fns) {
9780   if (isFunction(fns)) {
9781     return fns(data, headers, status);
9782   }
9783
9784   forEach(fns, function(fn) {
9785     data = fn(data, headers, status);
9786   });
9787
9788   return data;
9789 }
9790
9791
9792 function isSuccess(status) {
9793   return 200 <= status && status < 300;
9794 }
9795
9796
9797 /**
9798  * @ngdoc provider
9799  * @name $httpProvider
9800  * @description
9801  * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
9802  * */
9803 function $HttpProvider() {
9804   /**
9805    * @ngdoc property
9806    * @name $httpProvider#defaults
9807    * @description
9808    *
9809    * Object containing default values for all {@link ng.$http $http} requests.
9810    *
9811    * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
9812    * that will provide the cache for all requests who set their `cache` property to `true`.
9813    * If you set the `defaults.cache = false` then only requests that specify their own custom
9814    * cache object will be cached. See {@link $http#caching $http Caching} for more information.
9815    *
9816    * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
9817    * Defaults value is `'XSRF-TOKEN'`.
9818    *
9819    * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
9820    * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
9821    *
9822    * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
9823    * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
9824    * setting default headers.
9825    *     - **`defaults.headers.common`**
9826    *     - **`defaults.headers.post`**
9827    *     - **`defaults.headers.put`**
9828    *     - **`defaults.headers.patch`**
9829    *
9830    *
9831    * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
9832    *  used to the prepare string representation of request parameters (specified as an object).
9833    *  If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
9834    *  Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
9835    *
9836    **/
9837   var defaults = this.defaults = {
9838     // transform incoming response data
9839     transformResponse: [defaultHttpResponseTransform],
9840
9841     // transform outgoing request data
9842     transformRequest: [function(d) {
9843       return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
9844     }],
9845
9846     // default headers
9847     headers: {
9848       common: {
9849         'Accept': 'application/json, text/plain, */*'
9850       },
9851       post:   shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
9852       put:    shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
9853       patch:  shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
9854     },
9855
9856     xsrfCookieName: 'XSRF-TOKEN',
9857     xsrfHeaderName: 'X-XSRF-TOKEN',
9858
9859     paramSerializer: '$httpParamSerializer'
9860   };
9861
9862   var useApplyAsync = false;
9863   /**
9864    * @ngdoc method
9865    * @name $httpProvider#useApplyAsync
9866    * @description
9867    *
9868    * Configure $http service to combine processing of multiple http responses received at around
9869    * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
9870    * significant performance improvement for bigger applications that make many HTTP requests
9871    * concurrently (common during application bootstrap).
9872    *
9873    * Defaults to false. If no value is specified, returns the current configured value.
9874    *
9875    * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
9876    *    "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
9877    *    to load and share the same digest cycle.
9878    *
9879    * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
9880    *    otherwise, returns the current configured value.
9881    **/
9882   this.useApplyAsync = function(value) {
9883     if (isDefined(value)) {
9884       useApplyAsync = !!value;
9885       return this;
9886     }
9887     return useApplyAsync;
9888   };
9889
9890   var useLegacyPromise = true;
9891   /**
9892    * @ngdoc method
9893    * @name $httpProvider#useLegacyPromiseExtensions
9894    * @description
9895    *
9896    * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
9897    * This should be used to make sure that applications work without these methods.
9898    *
9899    * Defaults to true. If no value is specified, returns the current configured value.
9900    *
9901    * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
9902    *
9903    * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
9904    *    otherwise, returns the current configured value.
9905    **/
9906   this.useLegacyPromiseExtensions = function(value) {
9907     if (isDefined(value)) {
9908       useLegacyPromise = !!value;
9909       return this;
9910     }
9911     return useLegacyPromise;
9912   };
9913
9914   /**
9915    * @ngdoc property
9916    * @name $httpProvider#interceptors
9917    * @description
9918    *
9919    * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
9920    * pre-processing of request or postprocessing of responses.
9921    *
9922    * These service factories are ordered by request, i.e. they are applied in the same order as the
9923    * array, on request, but reverse order, on response.
9924    *
9925    * {@link ng.$http#interceptors Interceptors detailed info}
9926    **/
9927   var interceptorFactories = this.interceptors = [];
9928
9929   this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
9930       function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
9931
9932     var defaultCache = $cacheFactory('$http');
9933
9934     /**
9935      * Make sure that default param serializer is exposed as a function
9936      */
9937     defaults.paramSerializer = isString(defaults.paramSerializer) ?
9938       $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
9939
9940     /**
9941      * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
9942      * The reversal is needed so that we can build up the interception chain around the
9943      * server request.
9944      */
9945     var reversedInterceptors = [];
9946
9947     forEach(interceptorFactories, function(interceptorFactory) {
9948       reversedInterceptors.unshift(isString(interceptorFactory)
9949           ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
9950     });
9951
9952     /**
9953      * @ngdoc service
9954      * @kind function
9955      * @name $http
9956      * @requires ng.$httpBackend
9957      * @requires $cacheFactory
9958      * @requires $rootScope
9959      * @requires $q
9960      * @requires $injector
9961      *
9962      * @description
9963      * The `$http` service is a core Angular service that facilitates communication with the remote
9964      * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
9965      * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
9966      *
9967      * For unit testing applications that use `$http` service, see
9968      * {@link ngMock.$httpBackend $httpBackend mock}.
9969      *
9970      * For a higher level of abstraction, please check out the {@link ngResource.$resource
9971      * $resource} service.
9972      *
9973      * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
9974      * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
9975      * it is important to familiarize yourself with these APIs and the guarantees they provide.
9976      *
9977      *
9978      * ## General usage
9979      * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
9980      * that is used to generate an HTTP request and returns  a {@link ng.$q promise}.
9981      *
9982      * ```js
9983      *   // Simple GET request example:
9984      *   $http({
9985      *     method: 'GET',
9986      *     url: '/someUrl'
9987      *   }).then(function successCallback(response) {
9988      *       // this callback will be called asynchronously
9989      *       // when the response is available
9990      *     }, function errorCallback(response) {
9991      *       // called asynchronously if an error occurs
9992      *       // or server returns response with an error status.
9993      *     });
9994      * ```
9995      *
9996      * The response object has these properties:
9997      *
9998      *   - **data** – `{string|Object}` – The response body transformed with the transform
9999      *     functions.
10000      *   - **status** – `{number}` – HTTP status code of the response.
10001      *   - **headers** – `{function([headerName])}` – Header getter function.
10002      *   - **config** – `{Object}` – The configuration object that was used to generate the request.
10003      *   - **statusText** – `{string}` – HTTP status text of the response.
10004      *
10005      * A response status code between 200 and 299 is considered a success status and
10006      * will result in the success callback being called. Note that if the response is a redirect,
10007      * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
10008      * called for such responses.
10009      *
10010      *
10011      * ## Shortcut methods
10012      *
10013      * Shortcut methods are also available. All shortcut methods require passing in the URL, and
10014      * request data must be passed in for POST/PUT requests. An optional config can be passed as the
10015      * last argument.
10016      *
10017      * ```js
10018      *   $http.get('/someUrl', config).then(successCallback, errorCallback);
10019      *   $http.post('/someUrl', data, config).then(successCallback, errorCallback);
10020      * ```
10021      *
10022      * Complete list of shortcut methods:
10023      *
10024      * - {@link ng.$http#get $http.get}
10025      * - {@link ng.$http#head $http.head}
10026      * - {@link ng.$http#post $http.post}
10027      * - {@link ng.$http#put $http.put}
10028      * - {@link ng.$http#delete $http.delete}
10029      * - {@link ng.$http#jsonp $http.jsonp}
10030      * - {@link ng.$http#patch $http.patch}
10031      *
10032      *
10033      * ## Writing Unit Tests that use $http
10034      * When unit testing (using {@link ngMock ngMock}), it is necessary to call
10035      * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
10036      * request using trained responses.
10037      *
10038      * ```
10039      * $httpBackend.expectGET(...);
10040      * $http.get(...);
10041      * $httpBackend.flush();
10042      * ```
10043      *
10044      * ## Deprecation Notice
10045      * <div class="alert alert-danger">
10046      *   The `$http` legacy promise methods `success` and `error` have been deprecated.
10047      *   Use the standard `then` method instead.
10048      *   If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
10049      *   `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
10050      * </div>
10051      *
10052      * ## Setting HTTP Headers
10053      *
10054      * The $http service will automatically add certain HTTP headers to all requests. These defaults
10055      * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
10056      * object, which currently contains this default configuration:
10057      *
10058      * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
10059      *   - `Accept: application/json, text/plain, * / *`
10060      * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
10061      *   - `Content-Type: application/json`
10062      * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
10063      *   - `Content-Type: application/json`
10064      *
10065      * To add or overwrite these defaults, simply add or remove a property from these configuration
10066      * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
10067      * with the lowercased HTTP method name as the key, e.g.
10068      * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
10069      *
10070      * The defaults can also be set at runtime via the `$http.defaults` object in the same
10071      * fashion. For example:
10072      *
10073      * ```
10074      * module.run(function($http) {
10075      *   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
10076      * });
10077      * ```
10078      *
10079      * In addition, you can supply a `headers` property in the config object passed when
10080      * calling `$http(config)`, which overrides the defaults without changing them globally.
10081      *
10082      * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
10083      * Use the `headers` property, setting the desired header to `undefined`. For example:
10084      *
10085      * ```js
10086      * var req = {
10087      *  method: 'POST',
10088      *  url: 'http://example.com',
10089      *  headers: {
10090      *    'Content-Type': undefined
10091      *  },
10092      *  data: { test: 'test' }
10093      * }
10094      *
10095      * $http(req).then(function(){...}, function(){...});
10096      * ```
10097      *
10098      * ## Transforming Requests and Responses
10099      *
10100      * Both requests and responses can be transformed using transformation functions: `transformRequest`
10101      * and `transformResponse`. These properties can be a single function that returns
10102      * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
10103      * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
10104      *
10105      * ### Default Transformations
10106      *
10107      * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
10108      * `defaults.transformResponse` properties. If a request does not provide its own transformations
10109      * then these will be applied.
10110      *
10111      * You can augment or replace the default transformations by modifying these properties by adding to or
10112      * replacing the array.
10113      *
10114      * Angular provides the following default transformations:
10115      *
10116      * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
10117      *
10118      * - If the `data` property of the request configuration object contains an object, serialize it
10119      *   into JSON format.
10120      *
10121      * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
10122      *
10123      *  - If XSRF prefix is detected, strip it (see Security Considerations section below).
10124      *  - If JSON response is detected, deserialize it using a JSON parser.
10125      *
10126      *
10127      * ### Overriding the Default Transformations Per Request
10128      *
10129      * If you wish override the request/response transformations only for a single request then provide
10130      * `transformRequest` and/or `transformResponse` properties on the configuration object passed
10131      * into `$http`.
10132      *
10133      * Note that if you provide these properties on the config object the default transformations will be
10134      * overwritten. If you wish to augment the default transformations then you must include them in your
10135      * local transformation array.
10136      *
10137      * The following code demonstrates adding a new response transformation to be run after the default response
10138      * transformations have been run.
10139      *
10140      * ```js
10141      * function appendTransform(defaults, transform) {
10142      *
10143      *   // We can't guarantee that the default transformation is an array
10144      *   defaults = angular.isArray(defaults) ? defaults : [defaults];
10145      *
10146      *   // Append the new transformation to the defaults
10147      *   return defaults.concat(transform);
10148      * }
10149      *
10150      * $http({
10151      *   url: '...',
10152      *   method: 'GET',
10153      *   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
10154      *     return doTransform(value);
10155      *   })
10156      * });
10157      * ```
10158      *
10159      *
10160      * ## Caching
10161      *
10162      * To enable caching, set the request configuration `cache` property to `true` (to use default
10163      * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
10164      * When the cache is enabled, `$http` stores the response from the server in the specified
10165      * cache. The next time the same request is made, the response is served from the cache without
10166      * sending a request to the server.
10167      *
10168      * Note that even if the response is served from cache, delivery of the data is asynchronous in
10169      * the same way that real requests are.
10170      *
10171      * If there are multiple GET requests for the same URL that should be cached using the same
10172      * cache, but the cache is not populated yet, only one request to the server will be made and
10173      * the remaining requests will be fulfilled using the response from the first request.
10174      *
10175      * You can change the default cache to a new object (built with
10176      * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
10177      * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
10178      * their `cache` property to `true` will now use this cache object.
10179      *
10180      * If you set the default cache to `false` then only requests that specify their own custom
10181      * cache object will be cached.
10182      *
10183      * ## Interceptors
10184      *
10185      * Before you start creating interceptors, be sure to understand the
10186      * {@link ng.$q $q and deferred/promise APIs}.
10187      *
10188      * For purposes of global error handling, authentication, or any kind of synchronous or
10189      * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
10190      * able to intercept requests before they are handed to the server and
10191      * responses before they are handed over to the application code that
10192      * initiated these requests. The interceptors leverage the {@link ng.$q
10193      * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
10194      *
10195      * The interceptors are service factories that are registered with the `$httpProvider` by
10196      * adding them to the `$httpProvider.interceptors` array. The factory is called and
10197      * injected with dependencies (if specified) and returns the interceptor.
10198      *
10199      * There are two kinds of interceptors (and two kinds of rejection interceptors):
10200      *
10201      *   * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
10202      *     modify the `config` object or create a new one. The function needs to return the `config`
10203      *     object directly, or a promise containing the `config` or a new `config` object.
10204      *   * `requestError`: interceptor gets called when a previous interceptor threw an error or
10205      *     resolved with a rejection.
10206      *   * `response`: interceptors get called with http `response` object. The function is free to
10207      *     modify the `response` object or create a new one. The function needs to return the `response`
10208      *     object directly, or as a promise containing the `response` or a new `response` object.
10209      *   * `responseError`: interceptor gets called when a previous interceptor threw an error or
10210      *     resolved with a rejection.
10211      *
10212      *
10213      * ```js
10214      *   // register the interceptor as a service
10215      *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
10216      *     return {
10217      *       // optional method
10218      *       'request': function(config) {
10219      *         // do something on success
10220      *         return config;
10221      *       },
10222      *
10223      *       // optional method
10224      *      'requestError': function(rejection) {
10225      *         // do something on error
10226      *         if (canRecover(rejection)) {
10227      *           return responseOrNewPromise
10228      *         }
10229      *         return $q.reject(rejection);
10230      *       },
10231      *
10232      *
10233      *
10234      *       // optional method
10235      *       'response': function(response) {
10236      *         // do something on success
10237      *         return response;
10238      *       },
10239      *
10240      *       // optional method
10241      *      'responseError': function(rejection) {
10242      *         // do something on error
10243      *         if (canRecover(rejection)) {
10244      *           return responseOrNewPromise
10245      *         }
10246      *         return $q.reject(rejection);
10247      *       }
10248      *     };
10249      *   });
10250      *
10251      *   $httpProvider.interceptors.push('myHttpInterceptor');
10252      *
10253      *
10254      *   // alternatively, register the interceptor via an anonymous factory
10255      *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
10256      *     return {
10257      *      'request': function(config) {
10258      *          // same as above
10259      *       },
10260      *
10261      *       'response': function(response) {
10262      *          // same as above
10263      *       }
10264      *     };
10265      *   });
10266      * ```
10267      *
10268      * ## Security Considerations
10269      *
10270      * When designing web applications, consider security threats from:
10271      *
10272      * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
10273      * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
10274      *
10275      * Both server and the client must cooperate in order to eliminate these threats. Angular comes
10276      * pre-configured with strategies that address these issues, but for this to work backend server
10277      * cooperation is required.
10278      *
10279      * ### JSON Vulnerability Protection
10280      *
10281      * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
10282      * allows third party website to turn your JSON resource URL into
10283      * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
10284      * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
10285      * Angular will automatically strip the prefix before processing it as JSON.
10286      *
10287      * For example if your server needs to return:
10288      * ```js
10289      * ['one','two']
10290      * ```
10291      *
10292      * which is vulnerable to attack, your server can return:
10293      * ```js
10294      * )]}',
10295      * ['one','two']
10296      * ```
10297      *
10298      * Angular will strip the prefix, before processing the JSON.
10299      *
10300      *
10301      * ### Cross Site Request Forgery (XSRF) Protection
10302      *
10303      * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
10304      * an unauthorized site can gain your user's private data. Angular provides a mechanism
10305      * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
10306      * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
10307      * JavaScript that runs on your domain could read the cookie, your server can be assured that
10308      * the XHR came from JavaScript running on your domain. The header will not be set for
10309      * cross-domain requests.
10310      *
10311      * To take advantage of this, your server needs to set a token in a JavaScript readable session
10312      * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
10313      * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
10314      * that only JavaScript running on your domain could have sent the request. The token must be
10315      * unique for each user and must be verifiable by the server (to prevent the JavaScript from
10316      * making up its own tokens). We recommend that the token is a digest of your site's
10317      * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
10318      * for added security.
10319      *
10320      * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
10321      * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
10322      * or the per-request config object.
10323      *
10324      * In order to prevent collisions in environments where multiple Angular apps share the
10325      * same domain or subdomain, we recommend that each application uses unique cookie name.
10326      *
10327      * @param {object} config Object describing the request to be made and how it should be
10328      *    processed. The object has following properties:
10329      *
10330      *    - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
10331      *    - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
10332      *    - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
10333      *      with the `paramSerializer` and appended as GET parameters.
10334      *    - **data** – `{string|Object}` – Data to be sent as the request message data.
10335      *    - **headers** – `{Object}` – Map of strings or functions which return strings representing
10336      *      HTTP headers to send to the server. If the return value of a function is null, the
10337      *      header will not be sent. Functions accept a config object as an argument.
10338      *    - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
10339      *    - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
10340      *    - **transformRequest** –
10341      *      `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
10342      *      transform function or an array of such functions. The transform function takes the http
10343      *      request body and headers and returns its transformed (typically serialized) version.
10344      *      See {@link ng.$http#overriding-the-default-transformations-per-request
10345      *      Overriding the Default Transformations}
10346      *    - **transformResponse** –
10347      *      `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
10348      *      transform function or an array of such functions. The transform function takes the http
10349      *      response body, headers and status and returns its transformed (typically deserialized) version.
10350      *      See {@link ng.$http#overriding-the-default-transformations-per-request
10351      *      Overriding the Default TransformationjqLiks}
10352      *    - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
10353      *      prepare the string representation of request parameters (specified as an object).
10354      *      If specified as string, it is interpreted as function registered with the
10355      *      {@link $injector $injector}, which means you can create your own serializer
10356      *      by registering it as a {@link auto.$provide#service service}.
10357      *      The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
10358      *      alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
10359      *    - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
10360      *      GET request, otherwise if a cache instance built with
10361      *      {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
10362      *      caching.
10363      *    - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
10364      *      that should abort the request when resolved.
10365      *    - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
10366      *      XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
10367      *      for more information.
10368      *    - **responseType** - `{string}` - see
10369      *      [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
10370      *
10371      * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
10372      *                        when the request succeeds or fails.
10373      *
10374      *
10375      * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
10376      *   requests. This is primarily meant to be used for debugging purposes.
10377      *
10378      *
10379      * @example
10380 <example module="httpExample">
10381 <file name="index.html">
10382   <div ng-controller="FetchController">
10383     <select ng-model="method" aria-label="Request method">
10384       <option>GET</option>
10385       <option>JSONP</option>
10386     </select>
10387     <input type="text" ng-model="url" size="80" aria-label="URL" />
10388     <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
10389     <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
10390     <button id="samplejsonpbtn"
10391       ng-click="updateModel('JSONP',
10392                     'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
10393       Sample JSONP
10394     </button>
10395     <button id="invalidjsonpbtn"
10396       ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
10397         Invalid JSONP
10398       </button>
10399     <pre>http status code: {{status}}</pre>
10400     <pre>http response data: {{data}}</pre>
10401   </div>
10402 </file>
10403 <file name="script.js">
10404   angular.module('httpExample', [])
10405     .controller('FetchController', ['$scope', '$http', '$templateCache',
10406       function($scope, $http, $templateCache) {
10407         $scope.method = 'GET';
10408         $scope.url = 'http-hello.html';
10409
10410         $scope.fetch = function() {
10411           $scope.code = null;
10412           $scope.response = null;
10413
10414           $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
10415             then(function(response) {
10416               $scope.status = response.status;
10417               $scope.data = response.data;
10418             }, function(response) {
10419               $scope.data = response.data || "Request failed";
10420               $scope.status = response.status;
10421           });
10422         };
10423
10424         $scope.updateModel = function(method, url) {
10425           $scope.method = method;
10426           $scope.url = url;
10427         };
10428       }]);
10429 </file>
10430 <file name="http-hello.html">
10431   Hello, $http!
10432 </file>
10433 <file name="protractor.js" type="protractor">
10434   var status = element(by.binding('status'));
10435   var data = element(by.binding('data'));
10436   var fetchBtn = element(by.id('fetchbtn'));
10437   var sampleGetBtn = element(by.id('samplegetbtn'));
10438   var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
10439   var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
10440
10441   it('should make an xhr GET request', function() {
10442     sampleGetBtn.click();
10443     fetchBtn.click();
10444     expect(status.getText()).toMatch('200');
10445     expect(data.getText()).toMatch(/Hello, \$http!/);
10446   });
10447
10448 // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
10449 // it('should make a JSONP request to angularjs.org', function() {
10450 //   sampleJsonpBtn.click();
10451 //   fetchBtn.click();
10452 //   expect(status.getText()).toMatch('200');
10453 //   expect(data.getText()).toMatch(/Super Hero!/);
10454 // });
10455
10456   it('should make JSONP request to invalid URL and invoke the error handler',
10457       function() {
10458     invalidJsonpBtn.click();
10459     fetchBtn.click();
10460     expect(status.getText()).toMatch('0');
10461     expect(data.getText()).toMatch('Request failed');
10462   });
10463 </file>
10464 </example>
10465      */
10466     function $http(requestConfig) {
10467
10468       if (!isObject(requestConfig)) {
10469         throw minErr('$http')('badreq', 'Http request configuration must be an object.  Received: {0}', requestConfig);
10470       }
10471
10472       var config = extend({
10473         method: 'get',
10474         transformRequest: defaults.transformRequest,
10475         transformResponse: defaults.transformResponse,
10476         paramSerializer: defaults.paramSerializer
10477       }, requestConfig);
10478
10479       config.headers = mergeHeaders(requestConfig);
10480       config.method = uppercase(config.method);
10481       config.paramSerializer = isString(config.paramSerializer) ?
10482         $injector.get(config.paramSerializer) : config.paramSerializer;
10483
10484       var serverRequest = function(config) {
10485         var headers = config.headers;
10486         var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
10487
10488         // strip content-type if data is undefined
10489         if (isUndefined(reqData)) {
10490           forEach(headers, function(value, header) {
10491             if (lowercase(header) === 'content-type') {
10492                 delete headers[header];
10493             }
10494           });
10495         }
10496
10497         if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
10498           config.withCredentials = defaults.withCredentials;
10499         }
10500
10501         // send request
10502         return sendReq(config, reqData).then(transformResponse, transformResponse);
10503       };
10504
10505       var chain = [serverRequest, undefined];
10506       var promise = $q.when(config);
10507
10508       // apply interceptors
10509       forEach(reversedInterceptors, function(interceptor) {
10510         if (interceptor.request || interceptor.requestError) {
10511           chain.unshift(interceptor.request, interceptor.requestError);
10512         }
10513         if (interceptor.response || interceptor.responseError) {
10514           chain.push(interceptor.response, interceptor.responseError);
10515         }
10516       });
10517
10518       while (chain.length) {
10519         var thenFn = chain.shift();
10520         var rejectFn = chain.shift();
10521
10522         promise = promise.then(thenFn, rejectFn);
10523       }
10524
10525       if (useLegacyPromise) {
10526         promise.success = function(fn) {
10527           assertArgFn(fn, 'fn');
10528
10529           promise.then(function(response) {
10530             fn(response.data, response.status, response.headers, config);
10531           });
10532           return promise;
10533         };
10534
10535         promise.error = function(fn) {
10536           assertArgFn(fn, 'fn');
10537
10538           promise.then(null, function(response) {
10539             fn(response.data, response.status, response.headers, config);
10540           });
10541           return promise;
10542         };
10543       } else {
10544         promise.success = $httpMinErrLegacyFn('success');
10545         promise.error = $httpMinErrLegacyFn('error');
10546       }
10547
10548       return promise;
10549
10550       function transformResponse(response) {
10551         // make a copy since the response must be cacheable
10552         var resp = extend({}, response);
10553         resp.data = transformData(response.data, response.headers, response.status,
10554                                   config.transformResponse);
10555         return (isSuccess(response.status))
10556           ? resp
10557           : $q.reject(resp);
10558       }
10559
10560       function executeHeaderFns(headers, config) {
10561         var headerContent, processedHeaders = {};
10562
10563         forEach(headers, function(headerFn, header) {
10564           if (isFunction(headerFn)) {
10565             headerContent = headerFn(config);
10566             if (headerContent != null) {
10567               processedHeaders[header] = headerContent;
10568             }
10569           } else {
10570             processedHeaders[header] = headerFn;
10571           }
10572         });
10573
10574         return processedHeaders;
10575       }
10576
10577       function mergeHeaders(config) {
10578         var defHeaders = defaults.headers,
10579             reqHeaders = extend({}, config.headers),
10580             defHeaderName, lowercaseDefHeaderName, reqHeaderName;
10581
10582         defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
10583
10584         // using for-in instead of forEach to avoid unecessary iteration after header has been found
10585         defaultHeadersIteration:
10586         for (defHeaderName in defHeaders) {
10587           lowercaseDefHeaderName = lowercase(defHeaderName);
10588
10589           for (reqHeaderName in reqHeaders) {
10590             if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
10591               continue defaultHeadersIteration;
10592             }
10593           }
10594
10595           reqHeaders[defHeaderName] = defHeaders[defHeaderName];
10596         }
10597
10598         // execute if header value is a function for merged headers
10599         return executeHeaderFns(reqHeaders, shallowCopy(config));
10600       }
10601     }
10602
10603     $http.pendingRequests = [];
10604
10605     /**
10606      * @ngdoc method
10607      * @name $http#get
10608      *
10609      * @description
10610      * Shortcut method to perform `GET` request.
10611      *
10612      * @param {string} url Relative or absolute URL specifying the destination of the request
10613      * @param {Object=} config Optional configuration object
10614      * @returns {HttpPromise} Future object
10615      */
10616
10617     /**
10618      * @ngdoc method
10619      * @name $http#delete
10620      *
10621      * @description
10622      * Shortcut method to perform `DELETE` request.
10623      *
10624      * @param {string} url Relative or absolute URL specifying the destination of the request
10625      * @param {Object=} config Optional configuration object
10626      * @returns {HttpPromise} Future object
10627      */
10628
10629     /**
10630      * @ngdoc method
10631      * @name $http#head
10632      *
10633      * @description
10634      * Shortcut method to perform `HEAD` request.
10635      *
10636      * @param {string} url Relative or absolute URL specifying the destination of the request
10637      * @param {Object=} config Optional configuration object
10638      * @returns {HttpPromise} Future object
10639      */
10640
10641     /**
10642      * @ngdoc method
10643      * @name $http#jsonp
10644      *
10645      * @description
10646      * Shortcut method to perform `JSONP` request.
10647      *
10648      * @param {string} url Relative or absolute URL specifying the destination of the request.
10649      *                     The name of the callback should be the string `JSON_CALLBACK`.
10650      * @param {Object=} config Optional configuration object
10651      * @returns {HttpPromise} Future object
10652      */
10653     createShortMethods('get', 'delete', 'head', 'jsonp');
10654
10655     /**
10656      * @ngdoc method
10657      * @name $http#post
10658      *
10659      * @description
10660      * Shortcut method to perform `POST` request.
10661      *
10662      * @param {string} url Relative or absolute URL specifying the destination of the request
10663      * @param {*} data Request content
10664      * @param {Object=} config Optional configuration object
10665      * @returns {HttpPromise} Future object
10666      */
10667
10668     /**
10669      * @ngdoc method
10670      * @name $http#put
10671      *
10672      * @description
10673      * Shortcut method to perform `PUT` request.
10674      *
10675      * @param {string} url Relative or absolute URL specifying the destination of the request
10676      * @param {*} data Request content
10677      * @param {Object=} config Optional configuration object
10678      * @returns {HttpPromise} Future object
10679      */
10680
10681      /**
10682       * @ngdoc method
10683       * @name $http#patch
10684       *
10685       * @description
10686       * Shortcut method to perform `PATCH` request.
10687       *
10688       * @param {string} url Relative or absolute URL specifying the destination of the request
10689       * @param {*} data Request content
10690       * @param {Object=} config Optional configuration object
10691       * @returns {HttpPromise} Future object
10692       */
10693     createShortMethodsWithData('post', 'put', 'patch');
10694
10695         /**
10696          * @ngdoc property
10697          * @name $http#defaults
10698          *
10699          * @description
10700          * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
10701          * default headers, withCredentials as well as request and response transformations.
10702          *
10703          * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
10704          */
10705     $http.defaults = defaults;
10706
10707
10708     return $http;
10709
10710
10711     function createShortMethods(names) {
10712       forEach(arguments, function(name) {
10713         $http[name] = function(url, config) {
10714           return $http(extend({}, config || {}, {
10715             method: name,
10716             url: url
10717           }));
10718         };
10719       });
10720     }
10721
10722
10723     function createShortMethodsWithData(name) {
10724       forEach(arguments, function(name) {
10725         $http[name] = function(url, data, config) {
10726           return $http(extend({}, config || {}, {
10727             method: name,
10728             url: url,
10729             data: data
10730           }));
10731         };
10732       });
10733     }
10734
10735
10736     /**
10737      * Makes the request.
10738      *
10739      * !!! ACCESSES CLOSURE VARS:
10740      * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
10741      */
10742     function sendReq(config, reqData) {
10743       var deferred = $q.defer(),
10744           promise = deferred.promise,
10745           cache,
10746           cachedResp,
10747           reqHeaders = config.headers,
10748           url = buildUrl(config.url, config.paramSerializer(config.params));
10749
10750       $http.pendingRequests.push(config);
10751       promise.then(removePendingReq, removePendingReq);
10752
10753
10754       if ((config.cache || defaults.cache) && config.cache !== false &&
10755           (config.method === 'GET' || config.method === 'JSONP')) {
10756         cache = isObject(config.cache) ? config.cache
10757               : isObject(defaults.cache) ? defaults.cache
10758               : defaultCache;
10759       }
10760
10761       if (cache) {
10762         cachedResp = cache.get(url);
10763         if (isDefined(cachedResp)) {
10764           if (isPromiseLike(cachedResp)) {
10765             // cached request has already been sent, but there is no response yet
10766             cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
10767           } else {
10768             // serving from cache
10769             if (isArray(cachedResp)) {
10770               resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
10771             } else {
10772               resolvePromise(cachedResp, 200, {}, 'OK');
10773             }
10774           }
10775         } else {
10776           // put the promise for the non-transformed response into cache as a placeholder
10777           cache.put(url, promise);
10778         }
10779       }
10780
10781
10782       // if we won't have the response in cache, set the xsrf headers and
10783       // send the request to the backend
10784       if (isUndefined(cachedResp)) {
10785         var xsrfValue = urlIsSameOrigin(config.url)
10786             ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
10787             : undefined;
10788         if (xsrfValue) {
10789           reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
10790         }
10791
10792         $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
10793             config.withCredentials, config.responseType);
10794       }
10795
10796       return promise;
10797
10798
10799       /**
10800        * Callback registered to $httpBackend():
10801        *  - caches the response if desired
10802        *  - resolves the raw $http promise
10803        *  - calls $apply
10804        */
10805       function done(status, response, headersString, statusText) {
10806         if (cache) {
10807           if (isSuccess(status)) {
10808             cache.put(url, [status, response, parseHeaders(headersString), statusText]);
10809           } else {
10810             // remove promise from the cache
10811             cache.remove(url);
10812           }
10813         }
10814
10815         function resolveHttpPromise() {
10816           resolvePromise(response, status, headersString, statusText);
10817         }
10818
10819         if (useApplyAsync) {
10820           $rootScope.$applyAsync(resolveHttpPromise);
10821         } else {
10822           resolveHttpPromise();
10823           if (!$rootScope.$$phase) $rootScope.$apply();
10824         }
10825       }
10826
10827
10828       /**
10829        * Resolves the raw $http promise.
10830        */
10831       function resolvePromise(response, status, headers, statusText) {
10832         //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
10833         status = status >= -1 ? status : 0;
10834
10835         (isSuccess(status) ? deferred.resolve : deferred.reject)({
10836           data: response,
10837           status: status,
10838           headers: headersGetter(headers),
10839           config: config,
10840           statusText: statusText
10841         });
10842       }
10843
10844       function resolvePromiseWithResult(result) {
10845         resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
10846       }
10847
10848       function removePendingReq() {
10849         var idx = $http.pendingRequests.indexOf(config);
10850         if (idx !== -1) $http.pendingRequests.splice(idx, 1);
10851       }
10852     }
10853
10854
10855     function buildUrl(url, serializedParams) {
10856       if (serializedParams.length > 0) {
10857         url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
10858       }
10859       return url;
10860     }
10861   }];
10862 }
10863
10864 /**
10865  * @ngdoc service
10866  * @name $xhrFactory
10867  *
10868  * @description
10869  * Factory function used to create XMLHttpRequest objects.
10870  *
10871  * Replace or decorate this service to create your own custom XMLHttpRequest objects.
10872  *
10873  * ```
10874  * angular.module('myApp', [])
10875  * .factory('$xhrFactory', function() {
10876  *   return function createXhr(method, url) {
10877  *     return new window.XMLHttpRequest({mozSystem: true});
10878  *   };
10879  * });
10880  * ```
10881  *
10882  * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
10883  * @param {string} url URL of the request.
10884  */
10885 function $xhrFactoryProvider() {
10886   this.$get = function() {
10887     return function createXhr() {
10888       return new window.XMLHttpRequest();
10889     };
10890   };
10891 }
10892
10893 /**
10894  * @ngdoc service
10895  * @name $httpBackend
10896  * @requires $window
10897  * @requires $document
10898  * @requires $xhrFactory
10899  *
10900  * @description
10901  * HTTP backend used by the {@link ng.$http service} that delegates to
10902  * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
10903  *
10904  * You should never need to use this service directly, instead use the higher-level abstractions:
10905  * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
10906  *
10907  * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
10908  * $httpBackend} which can be trained with responses.
10909  */
10910 function $HttpBackendProvider() {
10911   this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
10912     return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
10913   }];
10914 }
10915
10916 function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
10917   // TODO(vojta): fix the signature
10918   return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
10919     $browser.$$incOutstandingRequestCount();
10920     url = url || $browser.url();
10921
10922     if (lowercase(method) == 'jsonp') {
10923       var callbackId = '_' + (callbacks.counter++).toString(36);
10924       callbacks[callbackId] = function(data) {
10925         callbacks[callbackId].data = data;
10926         callbacks[callbackId].called = true;
10927       };
10928
10929       var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
10930           callbackId, function(status, text) {
10931         completeRequest(callback, status, callbacks[callbackId].data, "", text);
10932         callbacks[callbackId] = noop;
10933       });
10934     } else {
10935
10936       var xhr = createXhr(method, url);
10937
10938       xhr.open(method, url, true);
10939       forEach(headers, function(value, key) {
10940         if (isDefined(value)) {
10941             xhr.setRequestHeader(key, value);
10942         }
10943       });
10944
10945       xhr.onload = function requestLoaded() {
10946         var statusText = xhr.statusText || '';
10947
10948         // responseText is the old-school way of retrieving response (supported by IE9)
10949         // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
10950         var response = ('response' in xhr) ? xhr.response : xhr.responseText;
10951
10952         // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
10953         var status = xhr.status === 1223 ? 204 : xhr.status;
10954
10955         // fix status code when it is 0 (0 status is undocumented).
10956         // Occurs when accessing file resources or on Android 4.1 stock browser
10957         // while retrieving files from application cache.
10958         if (status === 0) {
10959           status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
10960         }
10961
10962         completeRequest(callback,
10963             status,
10964             response,
10965             xhr.getAllResponseHeaders(),
10966             statusText);
10967       };
10968
10969       var requestError = function() {
10970         // The response is always empty
10971         // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
10972         completeRequest(callback, -1, null, null, '');
10973       };
10974
10975       xhr.onerror = requestError;
10976       xhr.onabort = requestError;
10977
10978       if (withCredentials) {
10979         xhr.withCredentials = true;
10980       }
10981
10982       if (responseType) {
10983         try {
10984           xhr.responseType = responseType;
10985         } catch (e) {
10986           // WebKit added support for the json responseType value on 09/03/2013
10987           // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
10988           // known to throw when setting the value "json" as the response type. Other older
10989           // browsers implementing the responseType
10990           //
10991           // The json response type can be ignored if not supported, because JSON payloads are
10992           // parsed on the client-side regardless.
10993           if (responseType !== 'json') {
10994             throw e;
10995           }
10996         }
10997       }
10998
10999       xhr.send(isUndefined(post) ? null : post);
11000     }
11001
11002     if (timeout > 0) {
11003       var timeoutId = $browserDefer(timeoutRequest, timeout);
11004     } else if (isPromiseLike(timeout)) {
11005       timeout.then(timeoutRequest);
11006     }
11007
11008
11009     function timeoutRequest() {
11010       jsonpDone && jsonpDone();
11011       xhr && xhr.abort();
11012     }
11013
11014     function completeRequest(callback, status, response, headersString, statusText) {
11015       // cancel timeout and subsequent timeout promise resolution
11016       if (isDefined(timeoutId)) {
11017         $browserDefer.cancel(timeoutId);
11018       }
11019       jsonpDone = xhr = null;
11020
11021       callback(status, response, headersString, statusText);
11022       $browser.$$completeOutstandingRequest(noop);
11023     }
11024   };
11025
11026   function jsonpReq(url, callbackId, done) {
11027     // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
11028     // - fetches local scripts via XHR and evals them
11029     // - adds and immediately removes script elements from the document
11030     var script = rawDocument.createElement('script'), callback = null;
11031     script.type = "text/javascript";
11032     script.src = url;
11033     script.async = true;
11034
11035     callback = function(event) {
11036       removeEventListenerFn(script, "load", callback);
11037       removeEventListenerFn(script, "error", callback);
11038       rawDocument.body.removeChild(script);
11039       script = null;
11040       var status = -1;
11041       var text = "unknown";
11042
11043       if (event) {
11044         if (event.type === "load" && !callbacks[callbackId].called) {
11045           event = { type: "error" };
11046         }
11047         text = event.type;
11048         status = event.type === "error" ? 404 : 200;
11049       }
11050
11051       if (done) {
11052         done(status, text);
11053       }
11054     };
11055
11056     addEventListenerFn(script, "load", callback);
11057     addEventListenerFn(script, "error", callback);
11058     rawDocument.body.appendChild(script);
11059     return callback;
11060   }
11061 }
11062
11063 var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
11064 $interpolateMinErr.throwNoconcat = function(text) {
11065   throw $interpolateMinErr('noconcat',
11066       "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
11067       "interpolations that concatenate multiple expressions when a trusted value is " +
11068       "required.  See http://docs.angularjs.org/api/ng.$sce", text);
11069 };
11070
11071 $interpolateMinErr.interr = function(text, err) {
11072   return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
11073 };
11074
11075 /**
11076  * @ngdoc provider
11077  * @name $interpolateProvider
11078  *
11079  * @description
11080  *
11081  * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
11082  *
11083  * <div class="alert alert-danger">
11084  * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
11085  * template within a Python Jinja template (or any other template language). Mixing templating
11086  * languages is **very dangerous**. The embedding template language will not safely escape Angular
11087  * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
11088  * security bugs!
11089  * </div>
11090  *
11091  * @example
11092 <example module="customInterpolationApp">
11093 <file name="index.html">
11094 <script>
11095   var customInterpolationApp = angular.module('customInterpolationApp', []);
11096
11097   customInterpolationApp.config(function($interpolateProvider) {
11098     $interpolateProvider.startSymbol('//');
11099     $interpolateProvider.endSymbol('//');
11100   });
11101
11102
11103   customInterpolationApp.controller('DemoController', function() {
11104       this.label = "This binding is brought you by // interpolation symbols.";
11105   });
11106 </script>
11107 <div ng-app="App" ng-controller="DemoController as demo">
11108     //demo.label//
11109 </div>
11110 </file>
11111 <file name="protractor.js" type="protractor">
11112   it('should interpolate binding with custom symbols', function() {
11113     expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
11114   });
11115 </file>
11116 </example>
11117  */
11118 function $InterpolateProvider() {
11119   var startSymbol = '{{';
11120   var endSymbol = '}}';
11121
11122   /**
11123    * @ngdoc method
11124    * @name $interpolateProvider#startSymbol
11125    * @description
11126    * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
11127    *
11128    * @param {string=} value new value to set the starting symbol to.
11129    * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
11130    */
11131   this.startSymbol = function(value) {
11132     if (value) {
11133       startSymbol = value;
11134       return this;
11135     } else {
11136       return startSymbol;
11137     }
11138   };
11139
11140   /**
11141    * @ngdoc method
11142    * @name $interpolateProvider#endSymbol
11143    * @description
11144    * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
11145    *
11146    * @param {string=} value new value to set the ending symbol to.
11147    * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
11148    */
11149   this.endSymbol = function(value) {
11150     if (value) {
11151       endSymbol = value;
11152       return this;
11153     } else {
11154       return endSymbol;
11155     }
11156   };
11157
11158
11159   this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
11160     var startSymbolLength = startSymbol.length,
11161         endSymbolLength = endSymbol.length,
11162         escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
11163         escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
11164
11165     function escape(ch) {
11166       return '\\\\\\' + ch;
11167     }
11168
11169     function unescapeText(text) {
11170       return text.replace(escapedStartRegexp, startSymbol).
11171         replace(escapedEndRegexp, endSymbol);
11172     }
11173
11174     function stringify(value) {
11175       if (value == null) { // null || undefined
11176         return '';
11177       }
11178       switch (typeof value) {
11179         case 'string':
11180           break;
11181         case 'number':
11182           value = '' + value;
11183           break;
11184         default:
11185           value = toJson(value);
11186       }
11187
11188       return value;
11189     }
11190
11191     //TODO: this is the same as the constantWatchDelegate in parse.js
11192     function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
11193       var unwatch;
11194       return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
11195         unwatch();
11196         return constantInterp(scope);
11197       }, listener, objectEquality);
11198     }
11199
11200     /**
11201      * @ngdoc service
11202      * @name $interpolate
11203      * @kind function
11204      *
11205      * @requires $parse
11206      * @requires $sce
11207      *
11208      * @description
11209      *
11210      * Compiles a string with markup into an interpolation function. This service is used by the
11211      * HTML {@link ng.$compile $compile} service for data binding. See
11212      * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
11213      * interpolation markup.
11214      *
11215      *
11216      * ```js
11217      *   var $interpolate = ...; // injected
11218      *   var exp = $interpolate('Hello {{name | uppercase}}!');
11219      *   expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
11220      * ```
11221      *
11222      * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
11223      * `true`, the interpolation function will return `undefined` unless all embedded expressions
11224      * evaluate to a value other than `undefined`.
11225      *
11226      * ```js
11227      *   var $interpolate = ...; // injected
11228      *   var context = {greeting: 'Hello', name: undefined };
11229      *
11230      *   // default "forgiving" mode
11231      *   var exp = $interpolate('{{greeting}} {{name}}!');
11232      *   expect(exp(context)).toEqual('Hello !');
11233      *
11234      *   // "allOrNothing" mode
11235      *   exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
11236      *   expect(exp(context)).toBeUndefined();
11237      *   context.name = 'Angular';
11238      *   expect(exp(context)).toEqual('Hello Angular!');
11239      * ```
11240      *
11241      * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
11242      *
11243      * ####Escaped Interpolation
11244      * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
11245      * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
11246      * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
11247      * or binding.
11248      *
11249      * This enables web-servers to prevent script injection attacks and defacing attacks, to some
11250      * degree, while also enabling code examples to work without relying on the
11251      * {@link ng.directive:ngNonBindable ngNonBindable} directive.
11252      *
11253      * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
11254      * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
11255      * interpolation start/end markers with their escaped counterparts.**
11256      *
11257      * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
11258      * output when the $interpolate service processes the text. So, for HTML elements interpolated
11259      * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
11260      * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
11261      * this is typically useful only when user-data is used in rendering a template from the server, or
11262      * when otherwise untrusted data is used by a directive.
11263      *
11264      * <example>
11265      *  <file name="index.html">
11266      *    <div ng-init="username='A user'">
11267      *      <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
11268      *        </p>
11269      *      <p><strong>{{username}}</strong> attempts to inject code which will deface the
11270      *        application, but fails to accomplish their task, because the server has correctly
11271      *        escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
11272      *        characters.</p>
11273      *      <p>Instead, the result of the attempted script injection is visible, and can be removed
11274      *        from the database by an administrator.</p>
11275      *    </div>
11276      *  </file>
11277      * </example>
11278      *
11279      * @param {string} text The text with markup to interpolate.
11280      * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
11281      *    embedded expression in order to return an interpolation function. Strings with no
11282      *    embedded expression will return null for the interpolation function.
11283      * @param {string=} trustedContext when provided, the returned function passes the interpolated
11284      *    result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
11285      *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that
11286      *    provides Strict Contextual Escaping for details.
11287      * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
11288      *    unless all embedded expressions evaluate to a value other than `undefined`.
11289      * @returns {function(context)} an interpolation function which is used to compute the
11290      *    interpolated string. The function has these parameters:
11291      *
11292      * - `context`: evaluation context for all expressions embedded in the interpolated text
11293      */
11294     function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
11295       // Provide a quick exit and simplified result function for text with no interpolation
11296       if (!text.length || text.indexOf(startSymbol) === -1) {
11297         var constantInterp;
11298         if (!mustHaveExpression) {
11299           var unescapedText = unescapeText(text);
11300           constantInterp = valueFn(unescapedText);
11301           constantInterp.exp = text;
11302           constantInterp.expressions = [];
11303           constantInterp.$$watchDelegate = constantWatchDelegate;
11304         }
11305         return constantInterp;
11306       }
11307
11308       allOrNothing = !!allOrNothing;
11309       var startIndex,
11310           endIndex,
11311           index = 0,
11312           expressions = [],
11313           parseFns = [],
11314           textLength = text.length,
11315           exp,
11316           concat = [],
11317           expressionPositions = [];
11318
11319       while (index < textLength) {
11320         if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
11321              ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
11322           if (index !== startIndex) {
11323             concat.push(unescapeText(text.substring(index, startIndex)));
11324           }
11325           exp = text.substring(startIndex + startSymbolLength, endIndex);
11326           expressions.push(exp);
11327           parseFns.push($parse(exp, parseStringifyInterceptor));
11328           index = endIndex + endSymbolLength;
11329           expressionPositions.push(concat.length);
11330           concat.push('');
11331         } else {
11332           // we did not find an interpolation, so we have to add the remainder to the separators array
11333           if (index !== textLength) {
11334             concat.push(unescapeText(text.substring(index)));
11335           }
11336           break;
11337         }
11338       }
11339
11340       // Concatenating expressions makes it hard to reason about whether some combination of
11341       // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a
11342       // single expression be used for iframe[src], object[src], etc., we ensure that the value
11343       // that's used is assigned or constructed by some JS code somewhere that is more testable or
11344       // make it obvious that you bound the value to some user controlled value.  This helps reduce
11345       // the load when auditing for XSS issues.
11346       if (trustedContext && concat.length > 1) {
11347           $interpolateMinErr.throwNoconcat(text);
11348       }
11349
11350       if (!mustHaveExpression || expressions.length) {
11351         var compute = function(values) {
11352           for (var i = 0, ii = expressions.length; i < ii; i++) {
11353             if (allOrNothing && isUndefined(values[i])) return;
11354             concat[expressionPositions[i]] = values[i];
11355           }
11356           return concat.join('');
11357         };
11358
11359         var getValue = function(value) {
11360           return trustedContext ?
11361             $sce.getTrusted(trustedContext, value) :
11362             $sce.valueOf(value);
11363         };
11364
11365         return extend(function interpolationFn(context) {
11366             var i = 0;
11367             var ii = expressions.length;
11368             var values = new Array(ii);
11369
11370             try {
11371               for (; i < ii; i++) {
11372                 values[i] = parseFns[i](context);
11373               }
11374
11375               return compute(values);
11376             } catch (err) {
11377               $exceptionHandler($interpolateMinErr.interr(text, err));
11378             }
11379
11380           }, {
11381           // all of these properties are undocumented for now
11382           exp: text, //just for compatibility with regular watchers created via $watch
11383           expressions: expressions,
11384           $$watchDelegate: function(scope, listener) {
11385             var lastValue;
11386             return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
11387               var currValue = compute(values);
11388               if (isFunction(listener)) {
11389                 listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
11390               }
11391               lastValue = currValue;
11392             });
11393           }
11394         });
11395       }
11396
11397       function parseStringifyInterceptor(value) {
11398         try {
11399           value = getValue(value);
11400           return allOrNothing && !isDefined(value) ? value : stringify(value);
11401         } catch (err) {
11402           $exceptionHandler($interpolateMinErr.interr(text, err));
11403         }
11404       }
11405     }
11406
11407
11408     /**
11409      * @ngdoc method
11410      * @name $interpolate#startSymbol
11411      * @description
11412      * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
11413      *
11414      * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
11415      * the symbol.
11416      *
11417      * @returns {string} start symbol.
11418      */
11419     $interpolate.startSymbol = function() {
11420       return startSymbol;
11421     };
11422
11423
11424     /**
11425      * @ngdoc method
11426      * @name $interpolate#endSymbol
11427      * @description
11428      * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
11429      *
11430      * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
11431      * the symbol.
11432      *
11433      * @returns {string} end symbol.
11434      */
11435     $interpolate.endSymbol = function() {
11436       return endSymbol;
11437     };
11438
11439     return $interpolate;
11440   }];
11441 }
11442
11443 function $IntervalProvider() {
11444   this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
11445        function($rootScope,   $window,   $q,   $$q,   $browser) {
11446     var intervals = {};
11447
11448
11449      /**
11450       * @ngdoc service
11451       * @name $interval
11452       *
11453       * @description
11454       * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
11455       * milliseconds.
11456       *
11457       * The return value of registering an interval function is a promise. This promise will be
11458       * notified upon each tick of the interval, and will be resolved after `count` iterations, or
11459       * run indefinitely if `count` is not defined. The value of the notification will be the
11460       * number of iterations that have run.
11461       * To cancel an interval, call `$interval.cancel(promise)`.
11462       *
11463       * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
11464       * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
11465       * time.
11466       *
11467       * <div class="alert alert-warning">
11468       * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
11469       * with them.  In particular they are not automatically destroyed when a controller's scope or a
11470       * directive's element are destroyed.
11471       * You should take this into consideration and make sure to always cancel the interval at the
11472       * appropriate moment.  See the example below for more details on how and when to do this.
11473       * </div>
11474       *
11475       * @param {function()} fn A function that should be called repeatedly.
11476       * @param {number} delay Number of milliseconds between each function call.
11477       * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
11478       *   indefinitely.
11479       * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
11480       *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
11481       * @param {...*=} Pass additional parameters to the executed function.
11482       * @returns {promise} A promise which will be notified on each iteration.
11483       *
11484       * @example
11485       * <example module="intervalExample">
11486       * <file name="index.html">
11487       *   <script>
11488       *     angular.module('intervalExample', [])
11489       *       .controller('ExampleController', ['$scope', '$interval',
11490       *         function($scope, $interval) {
11491       *           $scope.format = 'M/d/yy h:mm:ss a';
11492       *           $scope.blood_1 = 100;
11493       *           $scope.blood_2 = 120;
11494       *
11495       *           var stop;
11496       *           $scope.fight = function() {
11497       *             // Don't start a new fight if we are already fighting
11498       *             if ( angular.isDefined(stop) ) return;
11499       *
11500       *             stop = $interval(function() {
11501       *               if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
11502       *                 $scope.blood_1 = $scope.blood_1 - 3;
11503       *                 $scope.blood_2 = $scope.blood_2 - 4;
11504       *               } else {
11505       *                 $scope.stopFight();
11506       *               }
11507       *             }, 100);
11508       *           };
11509       *
11510       *           $scope.stopFight = function() {
11511       *             if (angular.isDefined(stop)) {
11512       *               $interval.cancel(stop);
11513       *               stop = undefined;
11514       *             }
11515       *           };
11516       *
11517       *           $scope.resetFight = function() {
11518       *             $scope.blood_1 = 100;
11519       *             $scope.blood_2 = 120;
11520       *           };
11521       *
11522       *           $scope.$on('$destroy', function() {
11523       *             // Make sure that the interval is destroyed too
11524       *             $scope.stopFight();
11525       *           });
11526       *         }])
11527       *       // Register the 'myCurrentTime' directive factory method.
11528       *       // We inject $interval and dateFilter service since the factory method is DI.
11529       *       .directive('myCurrentTime', ['$interval', 'dateFilter',
11530       *         function($interval, dateFilter) {
11531       *           // return the directive link function. (compile function not needed)
11532       *           return function(scope, element, attrs) {
11533       *             var format,  // date format
11534       *                 stopTime; // so that we can cancel the time updates
11535       *
11536       *             // used to update the UI
11537       *             function updateTime() {
11538       *               element.text(dateFilter(new Date(), format));
11539       *             }
11540       *
11541       *             // watch the expression, and update the UI on change.
11542       *             scope.$watch(attrs.myCurrentTime, function(value) {
11543       *               format = value;
11544       *               updateTime();
11545       *             });
11546       *
11547       *             stopTime = $interval(updateTime, 1000);
11548       *
11549       *             // listen on DOM destroy (removal) event, and cancel the next UI update
11550       *             // to prevent updating time after the DOM element was removed.
11551       *             element.on('$destroy', function() {
11552       *               $interval.cancel(stopTime);
11553       *             });
11554       *           }
11555       *         }]);
11556       *   </script>
11557       *
11558       *   <div>
11559       *     <div ng-controller="ExampleController">
11560       *       <label>Date format: <input ng-model="format"></label> <hr/>
11561       *       Current time is: <span my-current-time="format"></span>
11562       *       <hr/>
11563       *       Blood 1 : <font color='red'>{{blood_1}}</font>
11564       *       Blood 2 : <font color='red'>{{blood_2}}</font>
11565       *       <button type="button" data-ng-click="fight()">Fight</button>
11566       *       <button type="button" data-ng-click="stopFight()">StopFight</button>
11567       *       <button type="button" data-ng-click="resetFight()">resetFight</button>
11568       *     </div>
11569       *   </div>
11570       *
11571       * </file>
11572       * </example>
11573       */
11574     function interval(fn, delay, count, invokeApply) {
11575       var hasParams = arguments.length > 4,
11576           args = hasParams ? sliceArgs(arguments, 4) : [],
11577           setInterval = $window.setInterval,
11578           clearInterval = $window.clearInterval,
11579           iteration = 0,
11580           skipApply = (isDefined(invokeApply) && !invokeApply),
11581           deferred = (skipApply ? $$q : $q).defer(),
11582           promise = deferred.promise;
11583
11584       count = isDefined(count) ? count : 0;
11585
11586       promise.$$intervalId = setInterval(function tick() {
11587         if (skipApply) {
11588           $browser.defer(callback);
11589         } else {
11590           $rootScope.$evalAsync(callback);
11591         }
11592         deferred.notify(iteration++);
11593
11594         if (count > 0 && iteration >= count) {
11595           deferred.resolve(iteration);
11596           clearInterval(promise.$$intervalId);
11597           delete intervals[promise.$$intervalId];
11598         }
11599
11600         if (!skipApply) $rootScope.$apply();
11601
11602       }, delay);
11603
11604       intervals[promise.$$intervalId] = deferred;
11605
11606       return promise;
11607
11608       function callback() {
11609         if (!hasParams) {
11610           fn(iteration);
11611         } else {
11612           fn.apply(null, args);
11613         }
11614       }
11615     }
11616
11617
11618      /**
11619       * @ngdoc method
11620       * @name $interval#cancel
11621       *
11622       * @description
11623       * Cancels a task associated with the `promise`.
11624       *
11625       * @param {Promise=} promise returned by the `$interval` function.
11626       * @returns {boolean} Returns `true` if the task was successfully canceled.
11627       */
11628     interval.cancel = function(promise) {
11629       if (promise && promise.$$intervalId in intervals) {
11630         intervals[promise.$$intervalId].reject('canceled');
11631         $window.clearInterval(promise.$$intervalId);
11632         delete intervals[promise.$$intervalId];
11633         return true;
11634       }
11635       return false;
11636     };
11637
11638     return interval;
11639   }];
11640 }
11641
11642 /**
11643  * @ngdoc service
11644  * @name $locale
11645  *
11646  * @description
11647  * $locale service provides localization rules for various Angular components. As of right now the
11648  * only public api is:
11649  *
11650  * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
11651  */
11652
11653 var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
11654     DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
11655 var $locationMinErr = minErr('$location');
11656
11657
11658 /**
11659  * Encode path using encodeUriSegment, ignoring forward slashes
11660  *
11661  * @param {string} path Path to encode
11662  * @returns {string}
11663  */
11664 function encodePath(path) {
11665   var segments = path.split('/'),
11666       i = segments.length;
11667
11668   while (i--) {
11669     segments[i] = encodeUriSegment(segments[i]);
11670   }
11671
11672   return segments.join('/');
11673 }
11674
11675 function parseAbsoluteUrl(absoluteUrl, locationObj) {
11676   var parsedUrl = urlResolve(absoluteUrl);
11677
11678   locationObj.$$protocol = parsedUrl.protocol;
11679   locationObj.$$host = parsedUrl.hostname;
11680   locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
11681 }
11682
11683
11684 function parseAppUrl(relativeUrl, locationObj) {
11685   var prefixed = (relativeUrl.charAt(0) !== '/');
11686   if (prefixed) {
11687     relativeUrl = '/' + relativeUrl;
11688   }
11689   var match = urlResolve(relativeUrl);
11690   locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
11691       match.pathname.substring(1) : match.pathname);
11692   locationObj.$$search = parseKeyValue(match.search);
11693   locationObj.$$hash = decodeURIComponent(match.hash);
11694
11695   // make sure path starts with '/';
11696   if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
11697     locationObj.$$path = '/' + locationObj.$$path;
11698   }
11699 }
11700
11701
11702 /**
11703  *
11704  * @param {string} begin
11705  * @param {string} whole
11706  * @returns {string} returns text from whole after begin or undefined if it does not begin with
11707  *                   expected string.
11708  */
11709 function beginsWith(begin, whole) {
11710   if (whole.indexOf(begin) === 0) {
11711     return whole.substr(begin.length);
11712   }
11713 }
11714
11715
11716 function stripHash(url) {
11717   var index = url.indexOf('#');
11718   return index == -1 ? url : url.substr(0, index);
11719 }
11720
11721 function trimEmptyHash(url) {
11722   return url.replace(/(#.+)|#$/, '$1');
11723 }
11724
11725
11726 function stripFile(url) {
11727   return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
11728 }
11729
11730 /* return the server only (scheme://host:port) */
11731 function serverBase(url) {
11732   return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
11733 }
11734
11735
11736 /**
11737  * LocationHtml5Url represents an url
11738  * This object is exposed as $location service when HTML5 mode is enabled and supported
11739  *
11740  * @constructor
11741  * @param {string} appBase application base URL
11742  * @param {string} appBaseNoFile application base URL stripped of any filename
11743  * @param {string} basePrefix url path prefix
11744  */
11745 function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
11746   this.$$html5 = true;
11747   basePrefix = basePrefix || '';
11748   parseAbsoluteUrl(appBase, this);
11749
11750
11751   /**
11752    * Parse given html5 (regular) url string into properties
11753    * @param {string} url HTML5 url
11754    * @private
11755    */
11756   this.$$parse = function(url) {
11757     var pathUrl = beginsWith(appBaseNoFile, url);
11758     if (!isString(pathUrl)) {
11759       throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
11760           appBaseNoFile);
11761     }
11762
11763     parseAppUrl(pathUrl, this);
11764
11765     if (!this.$$path) {
11766       this.$$path = '/';
11767     }
11768
11769     this.$$compose();
11770   };
11771
11772   /**
11773    * Compose url and update `absUrl` property
11774    * @private
11775    */
11776   this.$$compose = function() {
11777     var search = toKeyValue(this.$$search),
11778         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
11779
11780     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
11781     this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
11782   };
11783
11784   this.$$parseLinkUrl = function(url, relHref) {
11785     if (relHref && relHref[0] === '#') {
11786       // special case for links to hash fragments:
11787       // keep the old url and only replace the hash fragment
11788       this.hash(relHref.slice(1));
11789       return true;
11790     }
11791     var appUrl, prevAppUrl;
11792     var rewrittenUrl;
11793
11794     if (isDefined(appUrl = beginsWith(appBase, url))) {
11795       prevAppUrl = appUrl;
11796       if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
11797         rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
11798       } else {
11799         rewrittenUrl = appBase + prevAppUrl;
11800       }
11801     } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
11802       rewrittenUrl = appBaseNoFile + appUrl;
11803     } else if (appBaseNoFile == url + '/') {
11804       rewrittenUrl = appBaseNoFile;
11805     }
11806     if (rewrittenUrl) {
11807       this.$$parse(rewrittenUrl);
11808     }
11809     return !!rewrittenUrl;
11810   };
11811 }
11812
11813
11814 /**
11815  * LocationHashbangUrl represents url
11816  * This object is exposed as $location service when developer doesn't opt into html5 mode.
11817  * It also serves as the base class for html5 mode fallback on legacy browsers.
11818  *
11819  * @constructor
11820  * @param {string} appBase application base URL
11821  * @param {string} appBaseNoFile application base URL stripped of any filename
11822  * @param {string} hashPrefix hashbang prefix
11823  */
11824 function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
11825
11826   parseAbsoluteUrl(appBase, this);
11827
11828
11829   /**
11830    * Parse given hashbang url into properties
11831    * @param {string} url Hashbang url
11832    * @private
11833    */
11834   this.$$parse = function(url) {
11835     var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
11836     var withoutHashUrl;
11837
11838     if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
11839
11840       // The rest of the url starts with a hash so we have
11841       // got either a hashbang path or a plain hash fragment
11842       withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
11843       if (isUndefined(withoutHashUrl)) {
11844         // There was no hashbang prefix so we just have a hash fragment
11845         withoutHashUrl = withoutBaseUrl;
11846       }
11847
11848     } else {
11849       // There was no hashbang path nor hash fragment:
11850       // If we are in HTML5 mode we use what is left as the path;
11851       // Otherwise we ignore what is left
11852       if (this.$$html5) {
11853         withoutHashUrl = withoutBaseUrl;
11854       } else {
11855         withoutHashUrl = '';
11856         if (isUndefined(withoutBaseUrl)) {
11857           appBase = url;
11858           this.replace();
11859         }
11860       }
11861     }
11862
11863     parseAppUrl(withoutHashUrl, this);
11864
11865     this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
11866
11867     this.$$compose();
11868
11869     /*
11870      * In Windows, on an anchor node on documents loaded from
11871      * the filesystem, the browser will return a pathname
11872      * prefixed with the drive name ('/C:/path') when a
11873      * pathname without a drive is set:
11874      *  * a.setAttribute('href', '/foo')
11875      *   * a.pathname === '/C:/foo' //true
11876      *
11877      * Inside of Angular, we're always using pathnames that
11878      * do not include drive names for routing.
11879      */
11880     function removeWindowsDriveName(path, url, base) {
11881       /*
11882       Matches paths for file protocol on windows,
11883       such as /C:/foo/bar, and captures only /foo/bar.
11884       */
11885       var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
11886
11887       var firstPathSegmentMatch;
11888
11889       //Get the relative path from the input URL.
11890       if (url.indexOf(base) === 0) {
11891         url = url.replace(base, '');
11892       }
11893
11894       // The input URL intentionally contains a first path segment that ends with a colon.
11895       if (windowsFilePathExp.exec(url)) {
11896         return path;
11897       }
11898
11899       firstPathSegmentMatch = windowsFilePathExp.exec(path);
11900       return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
11901     }
11902   };
11903
11904   /**
11905    * Compose hashbang url and update `absUrl` property
11906    * @private
11907    */
11908   this.$$compose = function() {
11909     var search = toKeyValue(this.$$search),
11910         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
11911
11912     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
11913     this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
11914   };
11915
11916   this.$$parseLinkUrl = function(url, relHref) {
11917     if (stripHash(appBase) == stripHash(url)) {
11918       this.$$parse(url);
11919       return true;
11920     }
11921     return false;
11922   };
11923 }
11924
11925
11926 /**
11927  * LocationHashbangUrl represents url
11928  * This object is exposed as $location service when html5 history api is enabled but the browser
11929  * does not support it.
11930  *
11931  * @constructor
11932  * @param {string} appBase application base URL
11933  * @param {string} appBaseNoFile application base URL stripped of any filename
11934  * @param {string} hashPrefix hashbang prefix
11935  */
11936 function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
11937   this.$$html5 = true;
11938   LocationHashbangUrl.apply(this, arguments);
11939
11940   this.$$parseLinkUrl = function(url, relHref) {
11941     if (relHref && relHref[0] === '#') {
11942       // special case for links to hash fragments:
11943       // keep the old url and only replace the hash fragment
11944       this.hash(relHref.slice(1));
11945       return true;
11946     }
11947
11948     var rewrittenUrl;
11949     var appUrl;
11950
11951     if (appBase == stripHash(url)) {
11952       rewrittenUrl = url;
11953     } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
11954       rewrittenUrl = appBase + hashPrefix + appUrl;
11955     } else if (appBaseNoFile === url + '/') {
11956       rewrittenUrl = appBaseNoFile;
11957     }
11958     if (rewrittenUrl) {
11959       this.$$parse(rewrittenUrl);
11960     }
11961     return !!rewrittenUrl;
11962   };
11963
11964   this.$$compose = function() {
11965     var search = toKeyValue(this.$$search),
11966         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
11967
11968     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
11969     // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
11970     this.$$absUrl = appBase + hashPrefix + this.$$url;
11971   };
11972
11973 }
11974
11975
11976 var locationPrototype = {
11977
11978   /**
11979    * Are we in html5 mode?
11980    * @private
11981    */
11982   $$html5: false,
11983
11984   /**
11985    * Has any change been replacing?
11986    * @private
11987    */
11988   $$replace: false,
11989
11990   /**
11991    * @ngdoc method
11992    * @name $location#absUrl
11993    *
11994    * @description
11995    * This method is getter only.
11996    *
11997    * Return full url representation with all segments encoded according to rules specified in
11998    * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
11999    *
12000    *
12001    * ```js
12002    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12003    * var absUrl = $location.absUrl();
12004    * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
12005    * ```
12006    *
12007    * @return {string} full url
12008    */
12009   absUrl: locationGetter('$$absUrl'),
12010
12011   /**
12012    * @ngdoc method
12013    * @name $location#url
12014    *
12015    * @description
12016    * This method is getter / setter.
12017    *
12018    * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
12019    *
12020    * Change path, search and hash, when called with parameter and return `$location`.
12021    *
12022    *
12023    * ```js
12024    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12025    * var url = $location.url();
12026    * // => "/some/path?foo=bar&baz=xoxo"
12027    * ```
12028    *
12029    * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
12030    * @return {string} url
12031    */
12032   url: function(url) {
12033     if (isUndefined(url)) {
12034       return this.$$url;
12035     }
12036
12037     var match = PATH_MATCH.exec(url);
12038     if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
12039     if (match[2] || match[1] || url === '') this.search(match[3] || '');
12040     this.hash(match[5] || '');
12041
12042     return this;
12043   },
12044
12045   /**
12046    * @ngdoc method
12047    * @name $location#protocol
12048    *
12049    * @description
12050    * This method is getter only.
12051    *
12052    * Return protocol of current url.
12053    *
12054    *
12055    * ```js
12056    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12057    * var protocol = $location.protocol();
12058    * // => "http"
12059    * ```
12060    *
12061    * @return {string} protocol of current url
12062    */
12063   protocol: locationGetter('$$protocol'),
12064
12065   /**
12066    * @ngdoc method
12067    * @name $location#host
12068    *
12069    * @description
12070    * This method is getter only.
12071    *
12072    * Return host of current url.
12073    *
12074    * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
12075    *
12076    *
12077    * ```js
12078    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12079    * var host = $location.host();
12080    * // => "example.com"
12081    *
12082    * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
12083    * host = $location.host();
12084    * // => "example.com"
12085    * host = location.host;
12086    * // => "example.com:8080"
12087    * ```
12088    *
12089    * @return {string} host of current url.
12090    */
12091   host: locationGetter('$$host'),
12092
12093   /**
12094    * @ngdoc method
12095    * @name $location#port
12096    *
12097    * @description
12098    * This method is getter only.
12099    *
12100    * Return port of current url.
12101    *
12102    *
12103    * ```js
12104    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12105    * var port = $location.port();
12106    * // => 80
12107    * ```
12108    *
12109    * @return {Number} port
12110    */
12111   port: locationGetter('$$port'),
12112
12113   /**
12114    * @ngdoc method
12115    * @name $location#path
12116    *
12117    * @description
12118    * This method is getter / setter.
12119    *
12120    * Return path of current url when called without any parameter.
12121    *
12122    * Change path when called with parameter and return `$location`.
12123    *
12124    * Note: Path should always begin with forward slash (/), this method will add the forward slash
12125    * if it is missing.
12126    *
12127    *
12128    * ```js
12129    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12130    * var path = $location.path();
12131    * // => "/some/path"
12132    * ```
12133    *
12134    * @param {(string|number)=} path New path
12135    * @return {string} path
12136    */
12137   path: locationGetterSetter('$$path', function(path) {
12138     path = path !== null ? path.toString() : '';
12139     return path.charAt(0) == '/' ? path : '/' + path;
12140   }),
12141
12142   /**
12143    * @ngdoc method
12144    * @name $location#search
12145    *
12146    * @description
12147    * This method is getter / setter.
12148    *
12149    * Return search part (as object) of current url when called without any parameter.
12150    *
12151    * Change search part when called with parameter and return `$location`.
12152    *
12153    *
12154    * ```js
12155    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12156    * var searchObject = $location.search();
12157    * // => {foo: 'bar', baz: 'xoxo'}
12158    *
12159    * // set foo to 'yipee'
12160    * $location.search('foo', 'yipee');
12161    * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
12162    * ```
12163    *
12164    * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
12165    * hash object.
12166    *
12167    * When called with a single argument the method acts as a setter, setting the `search` component
12168    * of `$location` to the specified value.
12169    *
12170    * If the argument is a hash object containing an array of values, these values will be encoded
12171    * as duplicate search parameters in the url.
12172    *
12173    * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
12174    * will override only a single search property.
12175    *
12176    * If `paramValue` is an array, it will override the property of the `search` component of
12177    * `$location` specified via the first argument.
12178    *
12179    * If `paramValue` is `null`, the property specified via the first argument will be deleted.
12180    *
12181    * If `paramValue` is `true`, the property specified via the first argument will be added with no
12182    * value nor trailing equal sign.
12183    *
12184    * @return {Object} If called with no arguments returns the parsed `search` object. If called with
12185    * one or more arguments returns `$location` object itself.
12186    */
12187   search: function(search, paramValue) {
12188     switch (arguments.length) {
12189       case 0:
12190         return this.$$search;
12191       case 1:
12192         if (isString(search) || isNumber(search)) {
12193           search = search.toString();
12194           this.$$search = parseKeyValue(search);
12195         } else if (isObject(search)) {
12196           search = copy(search, {});
12197           // remove object undefined or null properties
12198           forEach(search, function(value, key) {
12199             if (value == null) delete search[key];
12200           });
12201
12202           this.$$search = search;
12203         } else {
12204           throw $locationMinErr('isrcharg',
12205               'The first argument of the `$location#search()` call must be a string or an object.');
12206         }
12207         break;
12208       default:
12209         if (isUndefined(paramValue) || paramValue === null) {
12210           delete this.$$search[search];
12211         } else {
12212           this.$$search[search] = paramValue;
12213         }
12214     }
12215
12216     this.$$compose();
12217     return this;
12218   },
12219
12220   /**
12221    * @ngdoc method
12222    * @name $location#hash
12223    *
12224    * @description
12225    * This method is getter / setter.
12226    *
12227    * Returns the hash fragment when called without any parameters.
12228    *
12229    * Changes the hash fragment when called with a parameter and returns `$location`.
12230    *
12231    *
12232    * ```js
12233    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
12234    * var hash = $location.hash();
12235    * // => "hashValue"
12236    * ```
12237    *
12238    * @param {(string|number)=} hash New hash fragment
12239    * @return {string} hash
12240    */
12241   hash: locationGetterSetter('$$hash', function(hash) {
12242     return hash !== null ? hash.toString() : '';
12243   }),
12244
12245   /**
12246    * @ngdoc method
12247    * @name $location#replace
12248    *
12249    * @description
12250    * If called, all changes to $location during the current `$digest` will replace the current history
12251    * record, instead of adding a new one.
12252    */
12253   replace: function() {
12254     this.$$replace = true;
12255     return this;
12256   }
12257 };
12258
12259 forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
12260   Location.prototype = Object.create(locationPrototype);
12261
12262   /**
12263    * @ngdoc method
12264    * @name $location#state
12265    *
12266    * @description
12267    * This method is getter / setter.
12268    *
12269    * Return the history state object when called without any parameter.
12270    *
12271    * Change the history state object when called with one parameter and return `$location`.
12272    * The state object is later passed to `pushState` or `replaceState`.
12273    *
12274    * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
12275    * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
12276    * older browsers (like IE9 or Android < 4.0), don't use this method.
12277    *
12278    * @param {object=} state State object for pushState or replaceState
12279    * @return {object} state
12280    */
12281   Location.prototype.state = function(state) {
12282     if (!arguments.length) {
12283       return this.$$state;
12284     }
12285
12286     if (Location !== LocationHtml5Url || !this.$$html5) {
12287       throw $locationMinErr('nostate', 'History API state support is available only ' +
12288         'in HTML5 mode and only in browsers supporting HTML5 History API');
12289     }
12290     // The user might modify `stateObject` after invoking `$location.state(stateObject)`
12291     // but we're changing the $$state reference to $browser.state() during the $digest
12292     // so the modification window is narrow.
12293     this.$$state = isUndefined(state) ? null : state;
12294
12295     return this;
12296   };
12297 });
12298
12299
12300 function locationGetter(property) {
12301   return function() {
12302     return this[property];
12303   };
12304 }
12305
12306
12307 function locationGetterSetter(property, preprocess) {
12308   return function(value) {
12309     if (isUndefined(value)) {
12310       return this[property];
12311     }
12312
12313     this[property] = preprocess(value);
12314     this.$$compose();
12315
12316     return this;
12317   };
12318 }
12319
12320
12321 /**
12322  * @ngdoc service
12323  * @name $location
12324  *
12325  * @requires $rootElement
12326  *
12327  * @description
12328  * The $location service parses the URL in the browser address bar (based on the
12329  * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
12330  * available to your application. Changes to the URL in the address bar are reflected into
12331  * $location service and changes to $location are reflected into the browser address bar.
12332  *
12333  * **The $location service:**
12334  *
12335  * - Exposes the current URL in the browser address bar, so you can
12336  *   - Watch and observe the URL.
12337  *   - Change the URL.
12338  * - Synchronizes the URL with the browser when the user
12339  *   - Changes the address bar.
12340  *   - Clicks the back or forward button (or clicks a History link).
12341  *   - Clicks on a link.
12342  * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
12343  *
12344  * For more information see {@link guide/$location Developer Guide: Using $location}
12345  */
12346
12347 /**
12348  * @ngdoc provider
12349  * @name $locationProvider
12350  * @description
12351  * Use the `$locationProvider` to configure how the application deep linking paths are stored.
12352  */
12353 function $LocationProvider() {
12354   var hashPrefix = '',
12355       html5Mode = {
12356         enabled: false,
12357         requireBase: true,
12358         rewriteLinks: true
12359       };
12360
12361   /**
12362    * @ngdoc method
12363    * @name $locationProvider#hashPrefix
12364    * @description
12365    * @param {string=} prefix Prefix for hash part (containing path and search)
12366    * @returns {*} current value if used as getter or itself (chaining) if used as setter
12367    */
12368   this.hashPrefix = function(prefix) {
12369     if (isDefined(prefix)) {
12370       hashPrefix = prefix;
12371       return this;
12372     } else {
12373       return hashPrefix;
12374     }
12375   };
12376
12377   /**
12378    * @ngdoc method
12379    * @name $locationProvider#html5Mode
12380    * @description
12381    * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
12382    *   If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
12383    *   properties:
12384    *   - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
12385    *     change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
12386    *     support `pushState`.
12387    *   - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
12388    *     whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
12389    *     true, and a base tag is not present, an error will be thrown when `$location` is injected.
12390    *     See the {@link guide/$location $location guide for more information}
12391    *   - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
12392    *     enables/disables url rewriting for relative links.
12393    *
12394    * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
12395    */
12396   this.html5Mode = function(mode) {
12397     if (isBoolean(mode)) {
12398       html5Mode.enabled = mode;
12399       return this;
12400     } else if (isObject(mode)) {
12401
12402       if (isBoolean(mode.enabled)) {
12403         html5Mode.enabled = mode.enabled;
12404       }
12405
12406       if (isBoolean(mode.requireBase)) {
12407         html5Mode.requireBase = mode.requireBase;
12408       }
12409
12410       if (isBoolean(mode.rewriteLinks)) {
12411         html5Mode.rewriteLinks = mode.rewriteLinks;
12412       }
12413
12414       return this;
12415     } else {
12416       return html5Mode;
12417     }
12418   };
12419
12420   /**
12421    * @ngdoc event
12422    * @name $location#$locationChangeStart
12423    * @eventType broadcast on root scope
12424    * @description
12425    * Broadcasted before a URL will change.
12426    *
12427    * This change can be prevented by calling
12428    * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
12429    * details about event object. Upon successful change
12430    * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
12431    *
12432    * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
12433    * the browser supports the HTML5 History API.
12434    *
12435    * @param {Object} angularEvent Synthetic event object.
12436    * @param {string} newUrl New URL
12437    * @param {string=} oldUrl URL that was before it was changed.
12438    * @param {string=} newState New history state object
12439    * @param {string=} oldState History state object that was before it was changed.
12440    */
12441
12442   /**
12443    * @ngdoc event
12444    * @name $location#$locationChangeSuccess
12445    * @eventType broadcast on root scope
12446    * @description
12447    * Broadcasted after a URL was changed.
12448    *
12449    * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
12450    * the browser supports the HTML5 History API.
12451    *
12452    * @param {Object} angularEvent Synthetic event object.
12453    * @param {string} newUrl New URL
12454    * @param {string=} oldUrl URL that was before it was changed.
12455    * @param {string=} newState New history state object
12456    * @param {string=} oldState History state object that was before it was changed.
12457    */
12458
12459   this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
12460       function($rootScope, $browser, $sniffer, $rootElement, $window) {
12461     var $location,
12462         LocationMode,
12463         baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
12464         initialUrl = $browser.url(),
12465         appBase;
12466
12467     if (html5Mode.enabled) {
12468       if (!baseHref && html5Mode.requireBase) {
12469         throw $locationMinErr('nobase',
12470           "$location in HTML5 mode requires a <base> tag to be present!");
12471       }
12472       appBase = serverBase(initialUrl) + (baseHref || '/');
12473       LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
12474     } else {
12475       appBase = stripHash(initialUrl);
12476       LocationMode = LocationHashbangUrl;
12477     }
12478     var appBaseNoFile = stripFile(appBase);
12479
12480     $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
12481     $location.$$parseLinkUrl(initialUrl, initialUrl);
12482
12483     $location.$$state = $browser.state();
12484
12485     var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
12486
12487     function setBrowserUrlWithFallback(url, replace, state) {
12488       var oldUrl = $location.url();
12489       var oldState = $location.$$state;
12490       try {
12491         $browser.url(url, replace, state);
12492
12493         // Make sure $location.state() returns referentially identical (not just deeply equal)
12494         // state object; this makes possible quick checking if the state changed in the digest
12495         // loop. Checking deep equality would be too expensive.
12496         $location.$$state = $browser.state();
12497       } catch (e) {
12498         // Restore old values if pushState fails
12499         $location.url(oldUrl);
12500         $location.$$state = oldState;
12501
12502         throw e;
12503       }
12504     }
12505
12506     $rootElement.on('click', function(event) {
12507       // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
12508       // currently we open nice url link and redirect then
12509
12510       if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
12511
12512       var elm = jqLite(event.target);
12513
12514       // traverse the DOM up to find first A tag
12515       while (nodeName_(elm[0]) !== 'a') {
12516         // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
12517         if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
12518       }
12519
12520       var absHref = elm.prop('href');
12521       // get the actual href attribute - see
12522       // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
12523       var relHref = elm.attr('href') || elm.attr('xlink:href');
12524
12525       if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
12526         // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
12527         // an animation.
12528         absHref = urlResolve(absHref.animVal).href;
12529       }
12530
12531       // Ignore when url is started with javascript: or mailto:
12532       if (IGNORE_URI_REGEXP.test(absHref)) return;
12533
12534       if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
12535         if ($location.$$parseLinkUrl(absHref, relHref)) {
12536           // We do a preventDefault for all urls that are part of the angular application,
12537           // in html5mode and also without, so that we are able to abort navigation without
12538           // getting double entries in the location history.
12539           event.preventDefault();
12540           // update location manually
12541           if ($location.absUrl() != $browser.url()) {
12542             $rootScope.$apply();
12543             // hack to work around FF6 bug 684208 when scenario runner clicks on links
12544             $window.angular['ff-684208-preventDefault'] = true;
12545           }
12546         }
12547       }
12548     });
12549
12550
12551     // rewrite hashbang url <> html5 url
12552     if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
12553       $browser.url($location.absUrl(), true);
12554     }
12555
12556     var initializing = true;
12557
12558     // update $location when $browser url changes
12559     $browser.onUrlChange(function(newUrl, newState) {
12560
12561       if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
12562         // If we are navigating outside of the app then force a reload
12563         $window.location.href = newUrl;
12564         return;
12565       }
12566
12567       $rootScope.$evalAsync(function() {
12568         var oldUrl = $location.absUrl();
12569         var oldState = $location.$$state;
12570         var defaultPrevented;
12571         newUrl = trimEmptyHash(newUrl);
12572         $location.$$parse(newUrl);
12573         $location.$$state = newState;
12574
12575         defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
12576             newState, oldState).defaultPrevented;
12577
12578         // if the location was changed by a `$locationChangeStart` handler then stop
12579         // processing this location change
12580         if ($location.absUrl() !== newUrl) return;
12581
12582         if (defaultPrevented) {
12583           $location.$$parse(oldUrl);
12584           $location.$$state = oldState;
12585           setBrowserUrlWithFallback(oldUrl, false, oldState);
12586         } else {
12587           initializing = false;
12588           afterLocationChange(oldUrl, oldState);
12589         }
12590       });
12591       if (!$rootScope.$$phase) $rootScope.$digest();
12592     });
12593
12594     // update browser
12595     $rootScope.$watch(function $locationWatch() {
12596       var oldUrl = trimEmptyHash($browser.url());
12597       var newUrl = trimEmptyHash($location.absUrl());
12598       var oldState = $browser.state();
12599       var currentReplace = $location.$$replace;
12600       var urlOrStateChanged = oldUrl !== newUrl ||
12601         ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
12602
12603       if (initializing || urlOrStateChanged) {
12604         initializing = false;
12605
12606         $rootScope.$evalAsync(function() {
12607           var newUrl = $location.absUrl();
12608           var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
12609               $location.$$state, oldState).defaultPrevented;
12610
12611           // if the location was changed by a `$locationChangeStart` handler then stop
12612           // processing this location change
12613           if ($location.absUrl() !== newUrl) return;
12614
12615           if (defaultPrevented) {
12616             $location.$$parse(oldUrl);
12617             $location.$$state = oldState;
12618           } else {
12619             if (urlOrStateChanged) {
12620               setBrowserUrlWithFallback(newUrl, currentReplace,
12621                                         oldState === $location.$$state ? null : $location.$$state);
12622             }
12623             afterLocationChange(oldUrl, oldState);
12624           }
12625         });
12626       }
12627
12628       $location.$$replace = false;
12629
12630       // we don't need to return anything because $evalAsync will make the digest loop dirty when
12631       // there is a change
12632     });
12633
12634     return $location;
12635
12636     function afterLocationChange(oldUrl, oldState) {
12637       $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
12638         $location.$$state, oldState);
12639     }
12640 }];
12641 }
12642
12643 /**
12644  * @ngdoc service
12645  * @name $log
12646  * @requires $window
12647  *
12648  * @description
12649  * Simple service for logging. Default implementation safely writes the message
12650  * into the browser's console (if present).
12651  *
12652  * The main purpose of this service is to simplify debugging and troubleshooting.
12653  *
12654  * The default is to log `debug` messages. You can use
12655  * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
12656  *
12657  * @example
12658    <example module="logExample">
12659      <file name="script.js">
12660        angular.module('logExample', [])
12661          .controller('LogController', ['$scope', '$log', function($scope, $log) {
12662            $scope.$log = $log;
12663            $scope.message = 'Hello World!';
12664          }]);
12665      </file>
12666      <file name="index.html">
12667        <div ng-controller="LogController">
12668          <p>Reload this page with open console, enter text and hit the log button...</p>
12669          <label>Message:
12670          <input type="text" ng-model="message" /></label>
12671          <button ng-click="$log.log(message)">log</button>
12672          <button ng-click="$log.warn(message)">warn</button>
12673          <button ng-click="$log.info(message)">info</button>
12674          <button ng-click="$log.error(message)">error</button>
12675          <button ng-click="$log.debug(message)">debug</button>
12676        </div>
12677      </file>
12678    </example>
12679  */
12680
12681 /**
12682  * @ngdoc provider
12683  * @name $logProvider
12684  * @description
12685  * Use the `$logProvider` to configure how the application logs messages
12686  */
12687 function $LogProvider() {
12688   var debug = true,
12689       self = this;
12690
12691   /**
12692    * @ngdoc method
12693    * @name $logProvider#debugEnabled
12694    * @description
12695    * @param {boolean=} flag enable or disable debug level messages
12696    * @returns {*} current value if used as getter or itself (chaining) if used as setter
12697    */
12698   this.debugEnabled = function(flag) {
12699     if (isDefined(flag)) {
12700       debug = flag;
12701     return this;
12702     } else {
12703       return debug;
12704     }
12705   };
12706
12707   this.$get = ['$window', function($window) {
12708     return {
12709       /**
12710        * @ngdoc method
12711        * @name $log#log
12712        *
12713        * @description
12714        * Write a log message
12715        */
12716       log: consoleLog('log'),
12717
12718       /**
12719        * @ngdoc method
12720        * @name $log#info
12721        *
12722        * @description
12723        * Write an information message
12724        */
12725       info: consoleLog('info'),
12726
12727       /**
12728        * @ngdoc method
12729        * @name $log#warn
12730        *
12731        * @description
12732        * Write a warning message
12733        */
12734       warn: consoleLog('warn'),
12735
12736       /**
12737        * @ngdoc method
12738        * @name $log#error
12739        *
12740        * @description
12741        * Write an error message
12742        */
12743       error: consoleLog('error'),
12744
12745       /**
12746        * @ngdoc method
12747        * @name $log#debug
12748        *
12749        * @description
12750        * Write a debug message
12751        */
12752       debug: (function() {
12753         var fn = consoleLog('debug');
12754
12755         return function() {
12756           if (debug) {
12757             fn.apply(self, arguments);
12758           }
12759         };
12760       }())
12761     };
12762
12763     function formatError(arg) {
12764       if (arg instanceof Error) {
12765         if (arg.stack) {
12766           arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
12767               ? 'Error: ' + arg.message + '\n' + arg.stack
12768               : arg.stack;
12769         } else if (arg.sourceURL) {
12770           arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
12771         }
12772       }
12773       return arg;
12774     }
12775
12776     function consoleLog(type) {
12777       var console = $window.console || {},
12778           logFn = console[type] || console.log || noop,
12779           hasApply = false;
12780
12781       // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
12782       // The reason behind this is that console.log has type "object" in IE8...
12783       try {
12784         hasApply = !!logFn.apply;
12785       } catch (e) {}
12786
12787       if (hasApply) {
12788         return function() {
12789           var args = [];
12790           forEach(arguments, function(arg) {
12791             args.push(formatError(arg));
12792           });
12793           return logFn.apply(console, args);
12794         };
12795       }
12796
12797       // we are IE which either doesn't have window.console => this is noop and we do nothing,
12798       // or we are IE where console.log doesn't have apply so we log at least first 2 args
12799       return function(arg1, arg2) {
12800         logFn(arg1, arg2 == null ? '' : arg2);
12801       };
12802     }
12803   }];
12804 }
12805
12806 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
12807  *     Any commits to this file should be reviewed with security in mind.  *
12808  *   Changes to this file can potentially create security vulnerabilities. *
12809  *          An approval from 2 Core members with history of modifying      *
12810  *                         this file is required.                          *
12811  *                                                                         *
12812  *  Does the change somehow allow for arbitrary javascript to be executed? *
12813  *    Or allows for someone to change the prototype of built-in objects?   *
12814  *     Or gives undesired access to variables likes document or window?    *
12815  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12816
12817 var $parseMinErr = minErr('$parse');
12818
12819 // Sandboxing Angular Expressions
12820 // ------------------------------
12821 // Angular expressions are generally considered safe because these expressions only have direct
12822 // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
12823 // obtaining a reference to native JS functions such as the Function constructor.
12824 //
12825 // As an example, consider the following Angular expression:
12826 //
12827 //   {}.toString.constructor('alert("evil JS code")')
12828 //
12829 // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
12830 // against the expression language, but not to prevent exploits that were enabled by exposing
12831 // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
12832 // practice and therefore we are not even trying to protect against interaction with an object
12833 // explicitly exposed in this way.
12834 //
12835 // In general, it is not possible to access a Window object from an angular expression unless a
12836 // window or some DOM object that has a reference to window is published onto a Scope.
12837 // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
12838 // native objects.
12839 //
12840 // See https://docs.angularjs.org/guide/security
12841
12842
12843 function ensureSafeMemberName(name, fullExpression) {
12844   if (name === "__defineGetter__" || name === "__defineSetter__"
12845       || name === "__lookupGetter__" || name === "__lookupSetter__"
12846       || name === "__proto__") {
12847     throw $parseMinErr('isecfld',
12848         'Attempting to access a disallowed field in Angular expressions! '
12849         + 'Expression: {0}', fullExpression);
12850   }
12851   return name;
12852 }
12853
12854 function getStringValue(name, fullExpression) {
12855   // From the JavaScript docs:
12856   // Property names must be strings. This means that non-string objects cannot be used
12857   // as keys in an object. Any non-string object, including a number, is typecasted
12858   // into a string via the toString method.
12859   //
12860   // So, to ensure that we are checking the same `name` that JavaScript would use,
12861   // we cast it to a string, if possible.
12862   // Doing `name + ''` can cause a repl error if the result to `toString` is not a string,
12863   // this is, this will handle objects that misbehave.
12864   name = name + '';
12865   if (!isString(name)) {
12866     throw $parseMinErr('iseccst',
12867         'Cannot convert object to primitive value! '
12868         + 'Expression: {0}', fullExpression);
12869   }
12870   return name;
12871 }
12872
12873 function ensureSafeObject(obj, fullExpression) {
12874   // nifty check if obj is Function that is fast and works across iframes and other contexts
12875   if (obj) {
12876     if (obj.constructor === obj) {
12877       throw $parseMinErr('isecfn',
12878           'Referencing Function in Angular expressions is disallowed! Expression: {0}',
12879           fullExpression);
12880     } else if (// isWindow(obj)
12881         obj.window === obj) {
12882       throw $parseMinErr('isecwindow',
12883           'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
12884           fullExpression);
12885     } else if (// isElement(obj)
12886         obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
12887       throw $parseMinErr('isecdom',
12888           'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
12889           fullExpression);
12890     } else if (// block Object so that we can't get hold of dangerous Object.* methods
12891         obj === Object) {
12892       throw $parseMinErr('isecobj',
12893           'Referencing Object in Angular expressions is disallowed! Expression: {0}',
12894           fullExpression);
12895     }
12896   }
12897   return obj;
12898 }
12899
12900 var CALL = Function.prototype.call;
12901 var APPLY = Function.prototype.apply;
12902 var BIND = Function.prototype.bind;
12903
12904 function ensureSafeFunction(obj, fullExpression) {
12905   if (obj) {
12906     if (obj.constructor === obj) {
12907       throw $parseMinErr('isecfn',
12908         'Referencing Function in Angular expressions is disallowed! Expression: {0}',
12909         fullExpression);
12910     } else if (obj === CALL || obj === APPLY || obj === BIND) {
12911       throw $parseMinErr('isecff',
12912         'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
12913         fullExpression);
12914     }
12915   }
12916 }
12917
12918 function ensureSafeAssignContext(obj, fullExpression) {
12919   if (obj) {
12920     if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
12921         obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
12922       throw $parseMinErr('isecaf',
12923         'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
12924     }
12925   }
12926 }
12927
12928 var OPERATORS = createMap();
12929 forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
12930 var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
12931
12932
12933 /////////////////////////////////////////
12934
12935
12936 /**
12937  * @constructor
12938  */
12939 var Lexer = function(options) {
12940   this.options = options;
12941 };
12942
12943 Lexer.prototype = {
12944   constructor: Lexer,
12945
12946   lex: function(text) {
12947     this.text = text;
12948     this.index = 0;
12949     this.tokens = [];
12950
12951     while (this.index < this.text.length) {
12952       var ch = this.text.charAt(this.index);
12953       if (ch === '"' || ch === "'") {
12954         this.readString(ch);
12955       } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
12956         this.readNumber();
12957       } else if (this.isIdent(ch)) {
12958         this.readIdent();
12959       } else if (this.is(ch, '(){}[].,;:?')) {
12960         this.tokens.push({index: this.index, text: ch});
12961         this.index++;
12962       } else if (this.isWhitespace(ch)) {
12963         this.index++;
12964       } else {
12965         var ch2 = ch + this.peek();
12966         var ch3 = ch2 + this.peek(2);
12967         var op1 = OPERATORS[ch];
12968         var op2 = OPERATORS[ch2];
12969         var op3 = OPERATORS[ch3];
12970         if (op1 || op2 || op3) {
12971           var token = op3 ? ch3 : (op2 ? ch2 : ch);
12972           this.tokens.push({index: this.index, text: token, operator: true});
12973           this.index += token.length;
12974         } else {
12975           this.throwError('Unexpected next character ', this.index, this.index + 1);
12976         }
12977       }
12978     }
12979     return this.tokens;
12980   },
12981
12982   is: function(ch, chars) {
12983     return chars.indexOf(ch) !== -1;
12984   },
12985
12986   peek: function(i) {
12987     var num = i || 1;
12988     return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
12989   },
12990
12991   isNumber: function(ch) {
12992     return ('0' <= ch && ch <= '9') && typeof ch === "string";
12993   },
12994
12995   isWhitespace: function(ch) {
12996     // IE treats non-breaking space as \u00A0
12997     return (ch === ' ' || ch === '\r' || ch === '\t' ||
12998             ch === '\n' || ch === '\v' || ch === '\u00A0');
12999   },
13000
13001   isIdent: function(ch) {
13002     return ('a' <= ch && ch <= 'z' ||
13003             'A' <= ch && ch <= 'Z' ||
13004             '_' === ch || ch === '$');
13005   },
13006
13007   isExpOperator: function(ch) {
13008     return (ch === '-' || ch === '+' || this.isNumber(ch));
13009   },
13010
13011   throwError: function(error, start, end) {
13012     end = end || this.index;
13013     var colStr = (isDefined(start)
13014             ? 's ' + start +  '-' + this.index + ' [' + this.text.substring(start, end) + ']'
13015             : ' ' + end);
13016     throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
13017         error, colStr, this.text);
13018   },
13019
13020   readNumber: function() {
13021     var number = '';
13022     var start = this.index;
13023     while (this.index < this.text.length) {
13024       var ch = lowercase(this.text.charAt(this.index));
13025       if (ch == '.' || this.isNumber(ch)) {
13026         number += ch;
13027       } else {
13028         var peekCh = this.peek();
13029         if (ch == 'e' && this.isExpOperator(peekCh)) {
13030           number += ch;
13031         } else if (this.isExpOperator(ch) &&
13032             peekCh && this.isNumber(peekCh) &&
13033             number.charAt(number.length - 1) == 'e') {
13034           number += ch;
13035         } else if (this.isExpOperator(ch) &&
13036             (!peekCh || !this.isNumber(peekCh)) &&
13037             number.charAt(number.length - 1) == 'e') {
13038           this.throwError('Invalid exponent');
13039         } else {
13040           break;
13041         }
13042       }
13043       this.index++;
13044     }
13045     this.tokens.push({
13046       index: start,
13047       text: number,
13048       constant: true,
13049       value: Number(number)
13050     });
13051   },
13052
13053   readIdent: function() {
13054     var start = this.index;
13055     while (this.index < this.text.length) {
13056       var ch = this.text.charAt(this.index);
13057       if (!(this.isIdent(ch) || this.isNumber(ch))) {
13058         break;
13059       }
13060       this.index++;
13061     }
13062     this.tokens.push({
13063       index: start,
13064       text: this.text.slice(start, this.index),
13065       identifier: true
13066     });
13067   },
13068
13069   readString: function(quote) {
13070     var start = this.index;
13071     this.index++;
13072     var string = '';
13073     var rawString = quote;
13074     var escape = false;
13075     while (this.index < this.text.length) {
13076       var ch = this.text.charAt(this.index);
13077       rawString += ch;
13078       if (escape) {
13079         if (ch === 'u') {
13080           var hex = this.text.substring(this.index + 1, this.index + 5);
13081           if (!hex.match(/[\da-f]{4}/i)) {
13082             this.throwError('Invalid unicode escape [\\u' + hex + ']');
13083           }
13084           this.index += 4;
13085           string += String.fromCharCode(parseInt(hex, 16));
13086         } else {
13087           var rep = ESCAPE[ch];
13088           string = string + (rep || ch);
13089         }
13090         escape = false;
13091       } else if (ch === '\\') {
13092         escape = true;
13093       } else if (ch === quote) {
13094         this.index++;
13095         this.tokens.push({
13096           index: start,
13097           text: rawString,
13098           constant: true,
13099           value: string
13100         });
13101         return;
13102       } else {
13103         string += ch;
13104       }
13105       this.index++;
13106     }
13107     this.throwError('Unterminated quote', start);
13108   }
13109 };
13110
13111 var AST = function(lexer, options) {
13112   this.lexer = lexer;
13113   this.options = options;
13114 };
13115
13116 AST.Program = 'Program';
13117 AST.ExpressionStatement = 'ExpressionStatement';
13118 AST.AssignmentExpression = 'AssignmentExpression';
13119 AST.ConditionalExpression = 'ConditionalExpression';
13120 AST.LogicalExpression = 'LogicalExpression';
13121 AST.BinaryExpression = 'BinaryExpression';
13122 AST.UnaryExpression = 'UnaryExpression';
13123 AST.CallExpression = 'CallExpression';
13124 AST.MemberExpression = 'MemberExpression';
13125 AST.Identifier = 'Identifier';
13126 AST.Literal = 'Literal';
13127 AST.ArrayExpression = 'ArrayExpression';
13128 AST.Property = 'Property';
13129 AST.ObjectExpression = 'ObjectExpression';
13130 AST.ThisExpression = 'ThisExpression';
13131
13132 // Internal use only
13133 AST.NGValueParameter = 'NGValueParameter';
13134
13135 AST.prototype = {
13136   ast: function(text) {
13137     this.text = text;
13138     this.tokens = this.lexer.lex(text);
13139
13140     var value = this.program();
13141
13142     if (this.tokens.length !== 0) {
13143       this.throwError('is an unexpected token', this.tokens[0]);
13144     }
13145
13146     return value;
13147   },
13148
13149   program: function() {
13150     var body = [];
13151     while (true) {
13152       if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
13153         body.push(this.expressionStatement());
13154       if (!this.expect(';')) {
13155         return { type: AST.Program, body: body};
13156       }
13157     }
13158   },
13159
13160   expressionStatement: function() {
13161     return { type: AST.ExpressionStatement, expression: this.filterChain() };
13162   },
13163
13164   filterChain: function() {
13165     var left = this.expression();
13166     var token;
13167     while ((token = this.expect('|'))) {
13168       left = this.filter(left);
13169     }
13170     return left;
13171   },
13172
13173   expression: function() {
13174     return this.assignment();
13175   },
13176
13177   assignment: function() {
13178     var result = this.ternary();
13179     if (this.expect('=')) {
13180       result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
13181     }
13182     return result;
13183   },
13184
13185   ternary: function() {
13186     var test = this.logicalOR();
13187     var alternate;
13188     var consequent;
13189     if (this.expect('?')) {
13190       alternate = this.expression();
13191       if (this.consume(':')) {
13192         consequent = this.expression();
13193         return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
13194       }
13195     }
13196     return test;
13197   },
13198
13199   logicalOR: function() {
13200     var left = this.logicalAND();
13201     while (this.expect('||')) {
13202       left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
13203     }
13204     return left;
13205   },
13206
13207   logicalAND: function() {
13208     var left = this.equality();
13209     while (this.expect('&&')) {
13210       left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
13211     }
13212     return left;
13213   },
13214
13215   equality: function() {
13216     var left = this.relational();
13217     var token;
13218     while ((token = this.expect('==','!=','===','!=='))) {
13219       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
13220     }
13221     return left;
13222   },
13223
13224   relational: function() {
13225     var left = this.additive();
13226     var token;
13227     while ((token = this.expect('<', '>', '<=', '>='))) {
13228       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
13229     }
13230     return left;
13231   },
13232
13233   additive: function() {
13234     var left = this.multiplicative();
13235     var token;
13236     while ((token = this.expect('+','-'))) {
13237       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
13238     }
13239     return left;
13240   },
13241
13242   multiplicative: function() {
13243     var left = this.unary();
13244     var token;
13245     while ((token = this.expect('*','/','%'))) {
13246       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
13247     }
13248     return left;
13249   },
13250
13251   unary: function() {
13252     var token;
13253     if ((token = this.expect('+', '-', '!'))) {
13254       return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
13255     } else {
13256       return this.primary();
13257     }
13258   },
13259
13260   primary: function() {
13261     var primary;
13262     if (this.expect('(')) {
13263       primary = this.filterChain();
13264       this.consume(')');
13265     } else if (this.expect('[')) {
13266       primary = this.arrayDeclaration();
13267     } else if (this.expect('{')) {
13268       primary = this.object();
13269     } else if (this.constants.hasOwnProperty(this.peek().text)) {
13270       primary = copy(this.constants[this.consume().text]);
13271     } else if (this.peek().identifier) {
13272       primary = this.identifier();
13273     } else if (this.peek().constant) {
13274       primary = this.constant();
13275     } else {
13276       this.throwError('not a primary expression', this.peek());
13277     }
13278
13279     var next;
13280     while ((next = this.expect('(', '[', '.'))) {
13281       if (next.text === '(') {
13282         primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
13283         this.consume(')');
13284       } else if (next.text === '[') {
13285         primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
13286         this.consume(']');
13287       } else if (next.text === '.') {
13288         primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
13289       } else {
13290         this.throwError('IMPOSSIBLE');
13291       }
13292     }
13293     return primary;
13294   },
13295
13296   filter: function(baseExpression) {
13297     var args = [baseExpression];
13298     var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
13299
13300     while (this.expect(':')) {
13301       args.push(this.expression());
13302     }
13303
13304     return result;
13305   },
13306
13307   parseArguments: function() {
13308     var args = [];
13309     if (this.peekToken().text !== ')') {
13310       do {
13311         args.push(this.expression());
13312       } while (this.expect(','));
13313     }
13314     return args;
13315   },
13316
13317   identifier: function() {
13318     var token = this.consume();
13319     if (!token.identifier) {
13320       this.throwError('is not a valid identifier', token);
13321     }
13322     return { type: AST.Identifier, name: token.text };
13323   },
13324
13325   constant: function() {
13326     // TODO check that it is a constant
13327     return { type: AST.Literal, value: this.consume().value };
13328   },
13329
13330   arrayDeclaration: function() {
13331     var elements = [];
13332     if (this.peekToken().text !== ']') {
13333       do {
13334         if (this.peek(']')) {
13335           // Support trailing commas per ES5.1.
13336           break;
13337         }
13338         elements.push(this.expression());
13339       } while (this.expect(','));
13340     }
13341     this.consume(']');
13342
13343     return { type: AST.ArrayExpression, elements: elements };
13344   },
13345
13346   object: function() {
13347     var properties = [], property;
13348     if (this.peekToken().text !== '}') {
13349       do {
13350         if (this.peek('}')) {
13351           // Support trailing commas per ES5.1.
13352           break;
13353         }
13354         property = {type: AST.Property, kind: 'init'};
13355         if (this.peek().constant) {
13356           property.key = this.constant();
13357         } else if (this.peek().identifier) {
13358           property.key = this.identifier();
13359         } else {
13360           this.throwError("invalid key", this.peek());
13361         }
13362         this.consume(':');
13363         property.value = this.expression();
13364         properties.push(property);
13365       } while (this.expect(','));
13366     }
13367     this.consume('}');
13368
13369     return {type: AST.ObjectExpression, properties: properties };
13370   },
13371
13372   throwError: function(msg, token) {
13373     throw $parseMinErr('syntax',
13374         'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
13375           token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
13376   },
13377
13378   consume: function(e1) {
13379     if (this.tokens.length === 0) {
13380       throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
13381     }
13382
13383     var token = this.expect(e1);
13384     if (!token) {
13385       this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
13386     }
13387     return token;
13388   },
13389
13390   peekToken: function() {
13391     if (this.tokens.length === 0) {
13392       throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
13393     }
13394     return this.tokens[0];
13395   },
13396
13397   peek: function(e1, e2, e3, e4) {
13398     return this.peekAhead(0, e1, e2, e3, e4);
13399   },
13400
13401   peekAhead: function(i, e1, e2, e3, e4) {
13402     if (this.tokens.length > i) {
13403       var token = this.tokens[i];
13404       var t = token.text;
13405       if (t === e1 || t === e2 || t === e3 || t === e4 ||
13406           (!e1 && !e2 && !e3 && !e4)) {
13407         return token;
13408       }
13409     }
13410     return false;
13411   },
13412
13413   expect: function(e1, e2, e3, e4) {
13414     var token = this.peek(e1, e2, e3, e4);
13415     if (token) {
13416       this.tokens.shift();
13417       return token;
13418     }
13419     return false;
13420   },
13421
13422
13423   /* `undefined` is not a constant, it is an identifier,
13424    * but using it as an identifier is not supported
13425    */
13426   constants: {
13427     'true': { type: AST.Literal, value: true },
13428     'false': { type: AST.Literal, value: false },
13429     'null': { type: AST.Literal, value: null },
13430     'undefined': {type: AST.Literal, value: undefined },
13431     'this': {type: AST.ThisExpression }
13432   }
13433 };
13434
13435 function ifDefined(v, d) {
13436   return typeof v !== 'undefined' ? v : d;
13437 }
13438
13439 function plusFn(l, r) {
13440   if (typeof l === 'undefined') return r;
13441   if (typeof r === 'undefined') return l;
13442   return l + r;
13443 }
13444
13445 function isStateless($filter, filterName) {
13446   var fn = $filter(filterName);
13447   return !fn.$stateful;
13448 }
13449
13450 function findConstantAndWatchExpressions(ast, $filter) {
13451   var allConstants;
13452   var argsToWatch;
13453   switch (ast.type) {
13454   case AST.Program:
13455     allConstants = true;
13456     forEach(ast.body, function(expr) {
13457       findConstantAndWatchExpressions(expr.expression, $filter);
13458       allConstants = allConstants && expr.expression.constant;
13459     });
13460     ast.constant = allConstants;
13461     break;
13462   case AST.Literal:
13463     ast.constant = true;
13464     ast.toWatch = [];
13465     break;
13466   case AST.UnaryExpression:
13467     findConstantAndWatchExpressions(ast.argument, $filter);
13468     ast.constant = ast.argument.constant;
13469     ast.toWatch = ast.argument.toWatch;
13470     break;
13471   case AST.BinaryExpression:
13472     findConstantAndWatchExpressions(ast.left, $filter);
13473     findConstantAndWatchExpressions(ast.right, $filter);
13474     ast.constant = ast.left.constant && ast.right.constant;
13475     ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
13476     break;
13477   case AST.LogicalExpression:
13478     findConstantAndWatchExpressions(ast.left, $filter);
13479     findConstantAndWatchExpressions(ast.right, $filter);
13480     ast.constant = ast.left.constant && ast.right.constant;
13481     ast.toWatch = ast.constant ? [] : [ast];
13482     break;
13483   case AST.ConditionalExpression:
13484     findConstantAndWatchExpressions(ast.test, $filter);
13485     findConstantAndWatchExpressions(ast.alternate, $filter);
13486     findConstantAndWatchExpressions(ast.consequent, $filter);
13487     ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
13488     ast.toWatch = ast.constant ? [] : [ast];
13489     break;
13490   case AST.Identifier:
13491     ast.constant = false;
13492     ast.toWatch = [ast];
13493     break;
13494   case AST.MemberExpression:
13495     findConstantAndWatchExpressions(ast.object, $filter);
13496     if (ast.computed) {
13497       findConstantAndWatchExpressions(ast.property, $filter);
13498     }
13499     ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
13500     ast.toWatch = [ast];
13501     break;
13502   case AST.CallExpression:
13503     allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
13504     argsToWatch = [];
13505     forEach(ast.arguments, function(expr) {
13506       findConstantAndWatchExpressions(expr, $filter);
13507       allConstants = allConstants && expr.constant;
13508       if (!expr.constant) {
13509         argsToWatch.push.apply(argsToWatch, expr.toWatch);
13510       }
13511     });
13512     ast.constant = allConstants;
13513     ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
13514     break;
13515   case AST.AssignmentExpression:
13516     findConstantAndWatchExpressions(ast.left, $filter);
13517     findConstantAndWatchExpressions(ast.right, $filter);
13518     ast.constant = ast.left.constant && ast.right.constant;
13519     ast.toWatch = [ast];
13520     break;
13521   case AST.ArrayExpression:
13522     allConstants = true;
13523     argsToWatch = [];
13524     forEach(ast.elements, function(expr) {
13525       findConstantAndWatchExpressions(expr, $filter);
13526       allConstants = allConstants && expr.constant;
13527       if (!expr.constant) {
13528         argsToWatch.push.apply(argsToWatch, expr.toWatch);
13529       }
13530     });
13531     ast.constant = allConstants;
13532     ast.toWatch = argsToWatch;
13533     break;
13534   case AST.ObjectExpression:
13535     allConstants = true;
13536     argsToWatch = [];
13537     forEach(ast.properties, function(property) {
13538       findConstantAndWatchExpressions(property.value, $filter);
13539       allConstants = allConstants && property.value.constant;
13540       if (!property.value.constant) {
13541         argsToWatch.push.apply(argsToWatch, property.value.toWatch);
13542       }
13543     });
13544     ast.constant = allConstants;
13545     ast.toWatch = argsToWatch;
13546     break;
13547   case AST.ThisExpression:
13548     ast.constant = false;
13549     ast.toWatch = [];
13550     break;
13551   }
13552 }
13553
13554 function getInputs(body) {
13555   if (body.length != 1) return;
13556   var lastExpression = body[0].expression;
13557   var candidate = lastExpression.toWatch;
13558   if (candidate.length !== 1) return candidate;
13559   return candidate[0] !== lastExpression ? candidate : undefined;
13560 }
13561
13562 function isAssignable(ast) {
13563   return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
13564 }
13565
13566 function assignableAST(ast) {
13567   if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
13568     return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
13569   }
13570 }
13571
13572 function isLiteral(ast) {
13573   return ast.body.length === 0 ||
13574       ast.body.length === 1 && (
13575       ast.body[0].expression.type === AST.Literal ||
13576       ast.body[0].expression.type === AST.ArrayExpression ||
13577       ast.body[0].expression.type === AST.ObjectExpression);
13578 }
13579
13580 function isConstant(ast) {
13581   return ast.constant;
13582 }
13583
13584 function ASTCompiler(astBuilder, $filter) {
13585   this.astBuilder = astBuilder;
13586   this.$filter = $filter;
13587 }
13588
13589 ASTCompiler.prototype = {
13590   compile: function(expression, expensiveChecks) {
13591     var self = this;
13592     var ast = this.astBuilder.ast(expression);
13593     this.state = {
13594       nextId: 0,
13595       filters: {},
13596       expensiveChecks: expensiveChecks,
13597       fn: {vars: [], body: [], own: {}},
13598       assign: {vars: [], body: [], own: {}},
13599       inputs: []
13600     };
13601     findConstantAndWatchExpressions(ast, self.$filter);
13602     var extra = '';
13603     var assignable;
13604     this.stage = 'assign';
13605     if ((assignable = assignableAST(ast))) {
13606       this.state.computing = 'assign';
13607       var result = this.nextId();
13608       this.recurse(assignable, result);
13609       this.return_(result);
13610       extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
13611     }
13612     var toWatch = getInputs(ast.body);
13613     self.stage = 'inputs';
13614     forEach(toWatch, function(watch, key) {
13615       var fnKey = 'fn' + key;
13616       self.state[fnKey] = {vars: [], body: [], own: {}};
13617       self.state.computing = fnKey;
13618       var intoId = self.nextId();
13619       self.recurse(watch, intoId);
13620       self.return_(intoId);
13621       self.state.inputs.push(fnKey);
13622       watch.watchId = key;
13623     });
13624     this.state.computing = 'fn';
13625     this.stage = 'main';
13626     this.recurse(ast);
13627     var fnString =
13628       // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
13629       // This is a workaround for this until we do a better job at only removing the prefix only when we should.
13630       '"' + this.USE + ' ' + this.STRICT + '";\n' +
13631       this.filterPrefix() +
13632       'var fn=' + this.generateFunction('fn', 's,l,a,i') +
13633       extra +
13634       this.watchFns() +
13635       'return fn;';
13636
13637     /* jshint -W054 */
13638     var fn = (new Function('$filter',
13639         'ensureSafeMemberName',
13640         'ensureSafeObject',
13641         'ensureSafeFunction',
13642         'getStringValue',
13643         'ensureSafeAssignContext',
13644         'ifDefined',
13645         'plus',
13646         'text',
13647         fnString))(
13648           this.$filter,
13649           ensureSafeMemberName,
13650           ensureSafeObject,
13651           ensureSafeFunction,
13652           getStringValue,
13653           ensureSafeAssignContext,
13654           ifDefined,
13655           plusFn,
13656           expression);
13657     /* jshint +W054 */
13658     this.state = this.stage = undefined;
13659     fn.literal = isLiteral(ast);
13660     fn.constant = isConstant(ast);
13661     return fn;
13662   },
13663
13664   USE: 'use',
13665
13666   STRICT: 'strict',
13667
13668   watchFns: function() {
13669     var result = [];
13670     var fns = this.state.inputs;
13671     var self = this;
13672     forEach(fns, function(name) {
13673       result.push('var ' + name + '=' + self.generateFunction(name, 's'));
13674     });
13675     if (fns.length) {
13676       result.push('fn.inputs=[' + fns.join(',') + '];');
13677     }
13678     return result.join('');
13679   },
13680
13681   generateFunction: function(name, params) {
13682     return 'function(' + params + '){' +
13683         this.varsPrefix(name) +
13684         this.body(name) +
13685         '};';
13686   },
13687
13688   filterPrefix: function() {
13689     var parts = [];
13690     var self = this;
13691     forEach(this.state.filters, function(id, filter) {
13692       parts.push(id + '=$filter(' + self.escape(filter) + ')');
13693     });
13694     if (parts.length) return 'var ' + parts.join(',') + ';';
13695     return '';
13696   },
13697
13698   varsPrefix: function(section) {
13699     return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
13700   },
13701
13702   body: function(section) {
13703     return this.state[section].body.join('');
13704   },
13705
13706   recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
13707     var left, right, self = this, args, expression;
13708     recursionFn = recursionFn || noop;
13709     if (!skipWatchIdCheck && isDefined(ast.watchId)) {
13710       intoId = intoId || this.nextId();
13711       this.if_('i',
13712         this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
13713         this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
13714       );
13715       return;
13716     }
13717     switch (ast.type) {
13718     case AST.Program:
13719       forEach(ast.body, function(expression, pos) {
13720         self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
13721         if (pos !== ast.body.length - 1) {
13722           self.current().body.push(right, ';');
13723         } else {
13724           self.return_(right);
13725         }
13726       });
13727       break;
13728     case AST.Literal:
13729       expression = this.escape(ast.value);
13730       this.assign(intoId, expression);
13731       recursionFn(expression);
13732       break;
13733     case AST.UnaryExpression:
13734       this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
13735       expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
13736       this.assign(intoId, expression);
13737       recursionFn(expression);
13738       break;
13739     case AST.BinaryExpression:
13740       this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
13741       this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
13742       if (ast.operator === '+') {
13743         expression = this.plus(left, right);
13744       } else if (ast.operator === '-') {
13745         expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
13746       } else {
13747         expression = '(' + left + ')' + ast.operator + '(' + right + ')';
13748       }
13749       this.assign(intoId, expression);
13750       recursionFn(expression);
13751       break;
13752     case AST.LogicalExpression:
13753       intoId = intoId || this.nextId();
13754       self.recurse(ast.left, intoId);
13755       self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
13756       recursionFn(intoId);
13757       break;
13758     case AST.ConditionalExpression:
13759       intoId = intoId || this.nextId();
13760       self.recurse(ast.test, intoId);
13761       self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
13762       recursionFn(intoId);
13763       break;
13764     case AST.Identifier:
13765       intoId = intoId || this.nextId();
13766       if (nameId) {
13767         nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
13768         nameId.computed = false;
13769         nameId.name = ast.name;
13770       }
13771       ensureSafeMemberName(ast.name);
13772       self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
13773         function() {
13774           self.if_(self.stage === 'inputs' || 's', function() {
13775             if (create && create !== 1) {
13776               self.if_(
13777                 self.not(self.nonComputedMember('s', ast.name)),
13778                 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
13779             }
13780             self.assign(intoId, self.nonComputedMember('s', ast.name));
13781           });
13782         }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
13783         );
13784       if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
13785         self.addEnsureSafeObject(intoId);
13786       }
13787       recursionFn(intoId);
13788       break;
13789     case AST.MemberExpression:
13790       left = nameId && (nameId.context = this.nextId()) || this.nextId();
13791       intoId = intoId || this.nextId();
13792       self.recurse(ast.object, left, undefined, function() {
13793         self.if_(self.notNull(left), function() {
13794           if (ast.computed) {
13795             right = self.nextId();
13796             self.recurse(ast.property, right);
13797             self.getStringValue(right);
13798             self.addEnsureSafeMemberName(right);
13799             if (create && create !== 1) {
13800               self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
13801             }
13802             expression = self.ensureSafeObject(self.computedMember(left, right));
13803             self.assign(intoId, expression);
13804             if (nameId) {
13805               nameId.computed = true;
13806               nameId.name = right;
13807             }
13808           } else {
13809             ensureSafeMemberName(ast.property.name);
13810             if (create && create !== 1) {
13811               self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
13812             }
13813             expression = self.nonComputedMember(left, ast.property.name);
13814             if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
13815               expression = self.ensureSafeObject(expression);
13816             }
13817             self.assign(intoId, expression);
13818             if (nameId) {
13819               nameId.computed = false;
13820               nameId.name = ast.property.name;
13821             }
13822           }
13823         }, function() {
13824           self.assign(intoId, 'undefined');
13825         });
13826         recursionFn(intoId);
13827       }, !!create);
13828       break;
13829     case AST.CallExpression:
13830       intoId = intoId || this.nextId();
13831       if (ast.filter) {
13832         right = self.filter(ast.callee.name);
13833         args = [];
13834         forEach(ast.arguments, function(expr) {
13835           var argument = self.nextId();
13836           self.recurse(expr, argument);
13837           args.push(argument);
13838         });
13839         expression = right + '(' + args.join(',') + ')';
13840         self.assign(intoId, expression);
13841         recursionFn(intoId);
13842       } else {
13843         right = self.nextId();
13844         left = {};
13845         args = [];
13846         self.recurse(ast.callee, right, left, function() {
13847           self.if_(self.notNull(right), function() {
13848             self.addEnsureSafeFunction(right);
13849             forEach(ast.arguments, function(expr) {
13850               self.recurse(expr, self.nextId(), undefined, function(argument) {
13851                 args.push(self.ensureSafeObject(argument));
13852               });
13853             });
13854             if (left.name) {
13855               if (!self.state.expensiveChecks) {
13856                 self.addEnsureSafeObject(left.context);
13857               }
13858               expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
13859             } else {
13860               expression = right + '(' + args.join(',') + ')';
13861             }
13862             expression = self.ensureSafeObject(expression);
13863             self.assign(intoId, expression);
13864           }, function() {
13865             self.assign(intoId, 'undefined');
13866           });
13867           recursionFn(intoId);
13868         });
13869       }
13870       break;
13871     case AST.AssignmentExpression:
13872       right = this.nextId();
13873       left = {};
13874       if (!isAssignable(ast.left)) {
13875         throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
13876       }
13877       this.recurse(ast.left, undefined, left, function() {
13878         self.if_(self.notNull(left.context), function() {
13879           self.recurse(ast.right, right);
13880           self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
13881           self.addEnsureSafeAssignContext(left.context);
13882           expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
13883           self.assign(intoId, expression);
13884           recursionFn(intoId || expression);
13885         });
13886       }, 1);
13887       break;
13888     case AST.ArrayExpression:
13889       args = [];
13890       forEach(ast.elements, function(expr) {
13891         self.recurse(expr, self.nextId(), undefined, function(argument) {
13892           args.push(argument);
13893         });
13894       });
13895       expression = '[' + args.join(',') + ']';
13896       this.assign(intoId, expression);
13897       recursionFn(expression);
13898       break;
13899     case AST.ObjectExpression:
13900       args = [];
13901       forEach(ast.properties, function(property) {
13902         self.recurse(property.value, self.nextId(), undefined, function(expr) {
13903           args.push(self.escape(
13904               property.key.type === AST.Identifier ? property.key.name :
13905                 ('' + property.key.value)) +
13906               ':' + expr);
13907         });
13908       });
13909       expression = '{' + args.join(',') + '}';
13910       this.assign(intoId, expression);
13911       recursionFn(expression);
13912       break;
13913     case AST.ThisExpression:
13914       this.assign(intoId, 's');
13915       recursionFn('s');
13916       break;
13917     case AST.NGValueParameter:
13918       this.assign(intoId, 'v');
13919       recursionFn('v');
13920       break;
13921     }
13922   },
13923
13924   getHasOwnProperty: function(element, property) {
13925     var key = element + '.' + property;
13926     var own = this.current().own;
13927     if (!own.hasOwnProperty(key)) {
13928       own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
13929     }
13930     return own[key];
13931   },
13932
13933   assign: function(id, value) {
13934     if (!id) return;
13935     this.current().body.push(id, '=', value, ';');
13936     return id;
13937   },
13938
13939   filter: function(filterName) {
13940     if (!this.state.filters.hasOwnProperty(filterName)) {
13941       this.state.filters[filterName] = this.nextId(true);
13942     }
13943     return this.state.filters[filterName];
13944   },
13945
13946   ifDefined: function(id, defaultValue) {
13947     return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
13948   },
13949
13950   plus: function(left, right) {
13951     return 'plus(' + left + ',' + right + ')';
13952   },
13953
13954   return_: function(id) {
13955     this.current().body.push('return ', id, ';');
13956   },
13957
13958   if_: function(test, alternate, consequent) {
13959     if (test === true) {
13960       alternate();
13961     } else {
13962       var body = this.current().body;
13963       body.push('if(', test, '){');
13964       alternate();
13965       body.push('}');
13966       if (consequent) {
13967         body.push('else{');
13968         consequent();
13969         body.push('}');
13970       }
13971     }
13972   },
13973
13974   not: function(expression) {
13975     return '!(' + expression + ')';
13976   },
13977
13978   notNull: function(expression) {
13979     return expression + '!=null';
13980   },
13981
13982   nonComputedMember: function(left, right) {
13983     return left + '.' + right;
13984   },
13985
13986   computedMember: function(left, right) {
13987     return left + '[' + right + ']';
13988   },
13989
13990   member: function(left, right, computed) {
13991     if (computed) return this.computedMember(left, right);
13992     return this.nonComputedMember(left, right);
13993   },
13994
13995   addEnsureSafeObject: function(item) {
13996     this.current().body.push(this.ensureSafeObject(item), ';');
13997   },
13998
13999   addEnsureSafeMemberName: function(item) {
14000     this.current().body.push(this.ensureSafeMemberName(item), ';');
14001   },
14002
14003   addEnsureSafeFunction: function(item) {
14004     this.current().body.push(this.ensureSafeFunction(item), ';');
14005   },
14006
14007   addEnsureSafeAssignContext: function(item) {
14008     this.current().body.push(this.ensureSafeAssignContext(item), ';');
14009   },
14010
14011   ensureSafeObject: function(item) {
14012     return 'ensureSafeObject(' + item + ',text)';
14013   },
14014
14015   ensureSafeMemberName: function(item) {
14016     return 'ensureSafeMemberName(' + item + ',text)';
14017   },
14018
14019   ensureSafeFunction: function(item) {
14020     return 'ensureSafeFunction(' + item + ',text)';
14021   },
14022
14023   getStringValue: function(item) {
14024     this.assign(item, 'getStringValue(' + item + ',text)');
14025   },
14026
14027   ensureSafeAssignContext: function(item) {
14028     return 'ensureSafeAssignContext(' + item + ',text)';
14029   },
14030
14031   lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
14032     var self = this;
14033     return function() {
14034       self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
14035     };
14036   },
14037
14038   lazyAssign: function(id, value) {
14039     var self = this;
14040     return function() {
14041       self.assign(id, value);
14042     };
14043   },
14044
14045   stringEscapeRegex: /[^ a-zA-Z0-9]/g,
14046
14047   stringEscapeFn: function(c) {
14048     return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
14049   },
14050
14051   escape: function(value) {
14052     if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
14053     if (isNumber(value)) return value.toString();
14054     if (value === true) return 'true';
14055     if (value === false) return 'false';
14056     if (value === null) return 'null';
14057     if (typeof value === 'undefined') return 'undefined';
14058
14059     throw $parseMinErr('esc', 'IMPOSSIBLE');
14060   },
14061
14062   nextId: function(skip, init) {
14063     var id = 'v' + (this.state.nextId++);
14064     if (!skip) {
14065       this.current().vars.push(id + (init ? '=' + init : ''));
14066     }
14067     return id;
14068   },
14069
14070   current: function() {
14071     return this.state[this.state.computing];
14072   }
14073 };
14074
14075
14076 function ASTInterpreter(astBuilder, $filter) {
14077   this.astBuilder = astBuilder;
14078   this.$filter = $filter;
14079 }
14080
14081 ASTInterpreter.prototype = {
14082   compile: function(expression, expensiveChecks) {
14083     var self = this;
14084     var ast = this.astBuilder.ast(expression);
14085     this.expression = expression;
14086     this.expensiveChecks = expensiveChecks;
14087     findConstantAndWatchExpressions(ast, self.$filter);
14088     var assignable;
14089     var assign;
14090     if ((assignable = assignableAST(ast))) {
14091       assign = this.recurse(assignable);
14092     }
14093     var toWatch = getInputs(ast.body);
14094     var inputs;
14095     if (toWatch) {
14096       inputs = [];
14097       forEach(toWatch, function(watch, key) {
14098         var input = self.recurse(watch);
14099         watch.input = input;
14100         inputs.push(input);
14101         watch.watchId = key;
14102       });
14103     }
14104     var expressions = [];
14105     forEach(ast.body, function(expression) {
14106       expressions.push(self.recurse(expression.expression));
14107     });
14108     var fn = ast.body.length === 0 ? function() {} :
14109              ast.body.length === 1 ? expressions[0] :
14110              function(scope, locals) {
14111                var lastValue;
14112                forEach(expressions, function(exp) {
14113                  lastValue = exp(scope, locals);
14114                });
14115                return lastValue;
14116              };
14117     if (assign) {
14118       fn.assign = function(scope, value, locals) {
14119         return assign(scope, locals, value);
14120       };
14121     }
14122     if (inputs) {
14123       fn.inputs = inputs;
14124     }
14125     fn.literal = isLiteral(ast);
14126     fn.constant = isConstant(ast);
14127     return fn;
14128   },
14129
14130   recurse: function(ast, context, create) {
14131     var left, right, self = this, args, expression;
14132     if (ast.input) {
14133       return this.inputs(ast.input, ast.watchId);
14134     }
14135     switch (ast.type) {
14136     case AST.Literal:
14137       return this.value(ast.value, context);
14138     case AST.UnaryExpression:
14139       right = this.recurse(ast.argument);
14140       return this['unary' + ast.operator](right, context);
14141     case AST.BinaryExpression:
14142       left = this.recurse(ast.left);
14143       right = this.recurse(ast.right);
14144       return this['binary' + ast.operator](left, right, context);
14145     case AST.LogicalExpression:
14146       left = this.recurse(ast.left);
14147       right = this.recurse(ast.right);
14148       return this['binary' + ast.operator](left, right, context);
14149     case AST.ConditionalExpression:
14150       return this['ternary?:'](
14151         this.recurse(ast.test),
14152         this.recurse(ast.alternate),
14153         this.recurse(ast.consequent),
14154         context
14155       );
14156     case AST.Identifier:
14157       ensureSafeMemberName(ast.name, self.expression);
14158       return self.identifier(ast.name,
14159                              self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
14160                              context, create, self.expression);
14161     case AST.MemberExpression:
14162       left = this.recurse(ast.object, false, !!create);
14163       if (!ast.computed) {
14164         ensureSafeMemberName(ast.property.name, self.expression);
14165         right = ast.property.name;
14166       }
14167       if (ast.computed) right = this.recurse(ast.property);
14168       return ast.computed ?
14169         this.computedMember(left, right, context, create, self.expression) :
14170         this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
14171     case AST.CallExpression:
14172       args = [];
14173       forEach(ast.arguments, function(expr) {
14174         args.push(self.recurse(expr));
14175       });
14176       if (ast.filter) right = this.$filter(ast.callee.name);
14177       if (!ast.filter) right = this.recurse(ast.callee, true);
14178       return ast.filter ?
14179         function(scope, locals, assign, inputs) {
14180           var values = [];
14181           for (var i = 0; i < args.length; ++i) {
14182             values.push(args[i](scope, locals, assign, inputs));
14183           }
14184           var value = right.apply(undefined, values, inputs);
14185           return context ? {context: undefined, name: undefined, value: value} : value;
14186         } :
14187         function(scope, locals, assign, inputs) {
14188           var rhs = right(scope, locals, assign, inputs);
14189           var value;
14190           if (rhs.value != null) {
14191             ensureSafeObject(rhs.context, self.expression);
14192             ensureSafeFunction(rhs.value, self.expression);
14193             var values = [];
14194             for (var i = 0; i < args.length; ++i) {
14195               values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
14196             }
14197             value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
14198           }
14199           return context ? {value: value} : value;
14200         };
14201     case AST.AssignmentExpression:
14202       left = this.recurse(ast.left, true, 1);
14203       right = this.recurse(ast.right);
14204       return function(scope, locals, assign, inputs) {
14205         var lhs = left(scope, locals, assign, inputs);
14206         var rhs = right(scope, locals, assign, inputs);
14207         ensureSafeObject(lhs.value, self.expression);
14208         ensureSafeAssignContext(lhs.context);
14209         lhs.context[lhs.name] = rhs;
14210         return context ? {value: rhs} : rhs;
14211       };
14212     case AST.ArrayExpression:
14213       args = [];
14214       forEach(ast.elements, function(expr) {
14215         args.push(self.recurse(expr));
14216       });
14217       return function(scope, locals, assign, inputs) {
14218         var value = [];
14219         for (var i = 0; i < args.length; ++i) {
14220           value.push(args[i](scope, locals, assign, inputs));
14221         }
14222         return context ? {value: value} : value;
14223       };
14224     case AST.ObjectExpression:
14225       args = [];
14226       forEach(ast.properties, function(property) {
14227         args.push({key: property.key.type === AST.Identifier ?
14228                         property.key.name :
14229                         ('' + property.key.value),
14230                    value: self.recurse(property.value)
14231         });
14232       });
14233       return function(scope, locals, assign, inputs) {
14234         var value = {};
14235         for (var i = 0; i < args.length; ++i) {
14236           value[args[i].key] = args[i].value(scope, locals, assign, inputs);
14237         }
14238         return context ? {value: value} : value;
14239       };
14240     case AST.ThisExpression:
14241       return function(scope) {
14242         return context ? {value: scope} : scope;
14243       };
14244     case AST.NGValueParameter:
14245       return function(scope, locals, assign, inputs) {
14246         return context ? {value: assign} : assign;
14247       };
14248     }
14249   },
14250
14251   'unary+': function(argument, context) {
14252     return function(scope, locals, assign, inputs) {
14253       var arg = argument(scope, locals, assign, inputs);
14254       if (isDefined(arg)) {
14255         arg = +arg;
14256       } else {
14257         arg = 0;
14258       }
14259       return context ? {value: arg} : arg;
14260     };
14261   },
14262   'unary-': function(argument, context) {
14263     return function(scope, locals, assign, inputs) {
14264       var arg = argument(scope, locals, assign, inputs);
14265       if (isDefined(arg)) {
14266         arg = -arg;
14267       } else {
14268         arg = 0;
14269       }
14270       return context ? {value: arg} : arg;
14271     };
14272   },
14273   'unary!': function(argument, context) {
14274     return function(scope, locals, assign, inputs) {
14275       var arg = !argument(scope, locals, assign, inputs);
14276       return context ? {value: arg} : arg;
14277     };
14278   },
14279   'binary+': function(left, right, context) {
14280     return function(scope, locals, assign, inputs) {
14281       var lhs = left(scope, locals, assign, inputs);
14282       var rhs = right(scope, locals, assign, inputs);
14283       var arg = plusFn(lhs, rhs);
14284       return context ? {value: arg} : arg;
14285     };
14286   },
14287   'binary-': function(left, right, context) {
14288     return function(scope, locals, assign, inputs) {
14289       var lhs = left(scope, locals, assign, inputs);
14290       var rhs = right(scope, locals, assign, inputs);
14291       var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
14292       return context ? {value: arg} : arg;
14293     };
14294   },
14295   'binary*': function(left, right, context) {
14296     return function(scope, locals, assign, inputs) {
14297       var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
14298       return context ? {value: arg} : arg;
14299     };
14300   },
14301   'binary/': function(left, right, context) {
14302     return function(scope, locals, assign, inputs) {
14303       var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
14304       return context ? {value: arg} : arg;
14305     };
14306   },
14307   'binary%': function(left, right, context) {
14308     return function(scope, locals, assign, inputs) {
14309       var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
14310       return context ? {value: arg} : arg;
14311     };
14312   },
14313   'binary===': function(left, right, context) {
14314     return function(scope, locals, assign, inputs) {
14315       var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
14316       return context ? {value: arg} : arg;
14317     };
14318   },
14319   'binary!==': function(left, right, context) {
14320     return function(scope, locals, assign, inputs) {
14321       var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
14322       return context ? {value: arg} : arg;
14323     };
14324   },
14325   'binary==': function(left, right, context) {
14326     return function(scope, locals, assign, inputs) {
14327       var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
14328       return context ? {value: arg} : arg;
14329     };
14330   },
14331   'binary!=': function(left, right, context) {
14332     return function(scope, locals, assign, inputs) {
14333       var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
14334       return context ? {value: arg} : arg;
14335     };
14336   },
14337   'binary<': function(left, right, context) {
14338     return function(scope, locals, assign, inputs) {
14339       var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
14340       return context ? {value: arg} : arg;
14341     };
14342   },
14343   'binary>': function(left, right, context) {
14344     return function(scope, locals, assign, inputs) {
14345       var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
14346       return context ? {value: arg} : arg;
14347     };
14348   },
14349   'binary<=': function(left, right, context) {
14350     return function(scope, locals, assign, inputs) {
14351       var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
14352       return context ? {value: arg} : arg;
14353     };
14354   },
14355   'binary>=': function(left, right, context) {
14356     return function(scope, locals, assign, inputs) {
14357       var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
14358       return context ? {value: arg} : arg;
14359     };
14360   },
14361   'binary&&': function(left, right, context) {
14362     return function(scope, locals, assign, inputs) {
14363       var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
14364       return context ? {value: arg} : arg;
14365     };
14366   },
14367   'binary||': function(left, right, context) {
14368     return function(scope, locals, assign, inputs) {
14369       var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
14370       return context ? {value: arg} : arg;
14371     };
14372   },
14373   'ternary?:': function(test, alternate, consequent, context) {
14374     return function(scope, locals, assign, inputs) {
14375       var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
14376       return context ? {value: arg} : arg;
14377     };
14378   },
14379   value: function(value, context) {
14380     return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
14381   },
14382   identifier: function(name, expensiveChecks, context, create, expression) {
14383     return function(scope, locals, assign, inputs) {
14384       var base = locals && (name in locals) ? locals : scope;
14385       if (create && create !== 1 && base && !(base[name])) {
14386         base[name] = {};
14387       }
14388       var value = base ? base[name] : undefined;
14389       if (expensiveChecks) {
14390         ensureSafeObject(value, expression);
14391       }
14392       if (context) {
14393         return {context: base, name: name, value: value};
14394       } else {
14395         return value;
14396       }
14397     };
14398   },
14399   computedMember: function(left, right, context, create, expression) {
14400     return function(scope, locals, assign, inputs) {
14401       var lhs = left(scope, locals, assign, inputs);
14402       var rhs;
14403       var value;
14404       if (lhs != null) {
14405         rhs = right(scope, locals, assign, inputs);
14406         rhs = getStringValue(rhs);
14407         ensureSafeMemberName(rhs, expression);
14408         if (create && create !== 1 && lhs && !(lhs[rhs])) {
14409           lhs[rhs] = {};
14410         }
14411         value = lhs[rhs];
14412         ensureSafeObject(value, expression);
14413       }
14414       if (context) {
14415         return {context: lhs, name: rhs, value: value};
14416       } else {
14417         return value;
14418       }
14419     };
14420   },
14421   nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
14422     return function(scope, locals, assign, inputs) {
14423       var lhs = left(scope, locals, assign, inputs);
14424       if (create && create !== 1 && lhs && !(lhs[right])) {
14425         lhs[right] = {};
14426       }
14427       var value = lhs != null ? lhs[right] : undefined;
14428       if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
14429         ensureSafeObject(value, expression);
14430       }
14431       if (context) {
14432         return {context: lhs, name: right, value: value};
14433       } else {
14434         return value;
14435       }
14436     };
14437   },
14438   inputs: function(input, watchId) {
14439     return function(scope, value, locals, inputs) {
14440       if (inputs) return inputs[watchId];
14441       return input(scope, value, locals);
14442     };
14443   }
14444 };
14445
14446 /**
14447  * @constructor
14448  */
14449 var Parser = function(lexer, $filter, options) {
14450   this.lexer = lexer;
14451   this.$filter = $filter;
14452   this.options = options;
14453   this.ast = new AST(this.lexer);
14454   this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
14455                                    new ASTCompiler(this.ast, $filter);
14456 };
14457
14458 Parser.prototype = {
14459   constructor: Parser,
14460
14461   parse: function(text) {
14462     return this.astCompiler.compile(text, this.options.expensiveChecks);
14463   }
14464 };
14465
14466 var getterFnCacheDefault = createMap();
14467 var getterFnCacheExpensive = createMap();
14468
14469 function isPossiblyDangerousMemberName(name) {
14470   return name == 'constructor';
14471 }
14472
14473 var objectValueOf = Object.prototype.valueOf;
14474
14475 function getValueOf(value) {
14476   return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
14477 }
14478
14479 ///////////////////////////////////
14480
14481 /**
14482  * @ngdoc service
14483  * @name $parse
14484  * @kind function
14485  *
14486  * @description
14487  *
14488  * Converts Angular {@link guide/expression expression} into a function.
14489  *
14490  * ```js
14491  *   var getter = $parse('user.name');
14492  *   var setter = getter.assign;
14493  *   var context = {user:{name:'angular'}};
14494  *   var locals = {user:{name:'local'}};
14495  *
14496  *   expect(getter(context)).toEqual('angular');
14497  *   setter(context, 'newValue');
14498  *   expect(context.user.name).toEqual('newValue');
14499  *   expect(getter(context, locals)).toEqual('local');
14500  * ```
14501  *
14502  *
14503  * @param {string} expression String expression to compile.
14504  * @returns {function(context, locals)} a function which represents the compiled expression:
14505  *
14506  *    * `context` – `{object}` – an object against which any expressions embedded in the strings
14507  *      are evaluated against (typically a scope object).
14508  *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
14509  *      `context`.
14510  *
14511  *    The returned function also has the following properties:
14512  *      * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
14513  *        literal.
14514  *      * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
14515  *        constant literals.
14516  *      * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
14517  *        set to a function to change its value on the given context.
14518  *
14519  */
14520
14521
14522 /**
14523  * @ngdoc provider
14524  * @name $parseProvider
14525  *
14526  * @description
14527  * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
14528  *  service.
14529  */
14530 function $ParseProvider() {
14531   var cacheDefault = createMap();
14532   var cacheExpensive = createMap();
14533
14534   this.$get = ['$filter', function($filter) {
14535     var noUnsafeEval = csp().noUnsafeEval;
14536     var $parseOptions = {
14537           csp: noUnsafeEval,
14538           expensiveChecks: false
14539         },
14540         $parseOptionsExpensive = {
14541           csp: noUnsafeEval,
14542           expensiveChecks: true
14543         };
14544
14545     return function $parse(exp, interceptorFn, expensiveChecks) {
14546       var parsedExpression, oneTime, cacheKey;
14547
14548       switch (typeof exp) {
14549         case 'string':
14550           exp = exp.trim();
14551           cacheKey = exp;
14552
14553           var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
14554           parsedExpression = cache[cacheKey];
14555
14556           if (!parsedExpression) {
14557             if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
14558               oneTime = true;
14559               exp = exp.substring(2);
14560             }
14561             var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
14562             var lexer = new Lexer(parseOptions);
14563             var parser = new Parser(lexer, $filter, parseOptions);
14564             parsedExpression = parser.parse(exp);
14565             if (parsedExpression.constant) {
14566               parsedExpression.$$watchDelegate = constantWatchDelegate;
14567             } else if (oneTime) {
14568               parsedExpression.$$watchDelegate = parsedExpression.literal ?
14569                   oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
14570             } else if (parsedExpression.inputs) {
14571               parsedExpression.$$watchDelegate = inputsWatchDelegate;
14572             }
14573             cache[cacheKey] = parsedExpression;
14574           }
14575           return addInterceptor(parsedExpression, interceptorFn);
14576
14577         case 'function':
14578           return addInterceptor(exp, interceptorFn);
14579
14580         default:
14581           return noop;
14582       }
14583     };
14584
14585     function expressionInputDirtyCheck(newValue, oldValueOfValue) {
14586
14587       if (newValue == null || oldValueOfValue == null) { // null/undefined
14588         return newValue === oldValueOfValue;
14589       }
14590
14591       if (typeof newValue === 'object') {
14592
14593         // attempt to convert the value to a primitive type
14594         // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
14595         //             be cheaply dirty-checked
14596         newValue = getValueOf(newValue);
14597
14598         if (typeof newValue === 'object') {
14599           // objects/arrays are not supported - deep-watching them would be too expensive
14600           return false;
14601         }
14602
14603         // fall-through to the primitive equality check
14604       }
14605
14606       //Primitive or NaN
14607       return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
14608     }
14609
14610     function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
14611       var inputExpressions = parsedExpression.inputs;
14612       var lastResult;
14613
14614       if (inputExpressions.length === 1) {
14615         var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
14616         inputExpressions = inputExpressions[0];
14617         return scope.$watch(function expressionInputWatch(scope) {
14618           var newInputValue = inputExpressions(scope);
14619           if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
14620             lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
14621             oldInputValueOf = newInputValue && getValueOf(newInputValue);
14622           }
14623           return lastResult;
14624         }, listener, objectEquality, prettyPrintExpression);
14625       }
14626
14627       var oldInputValueOfValues = [];
14628       var oldInputValues = [];
14629       for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
14630         oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
14631         oldInputValues[i] = null;
14632       }
14633
14634       return scope.$watch(function expressionInputsWatch(scope) {
14635         var changed = false;
14636
14637         for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
14638           var newInputValue = inputExpressions[i](scope);
14639           if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
14640             oldInputValues[i] = newInputValue;
14641             oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
14642           }
14643         }
14644
14645         if (changed) {
14646           lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
14647         }
14648
14649         return lastResult;
14650       }, listener, objectEquality, prettyPrintExpression);
14651     }
14652
14653     function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
14654       var unwatch, lastValue;
14655       return unwatch = scope.$watch(function oneTimeWatch(scope) {
14656         return parsedExpression(scope);
14657       }, function oneTimeListener(value, old, scope) {
14658         lastValue = value;
14659         if (isFunction(listener)) {
14660           listener.apply(this, arguments);
14661         }
14662         if (isDefined(value)) {
14663           scope.$$postDigest(function() {
14664             if (isDefined(lastValue)) {
14665               unwatch();
14666             }
14667           });
14668         }
14669       }, objectEquality);
14670     }
14671
14672     function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
14673       var unwatch, lastValue;
14674       return unwatch = scope.$watch(function oneTimeWatch(scope) {
14675         return parsedExpression(scope);
14676       }, function oneTimeListener(value, old, scope) {
14677         lastValue = value;
14678         if (isFunction(listener)) {
14679           listener.call(this, value, old, scope);
14680         }
14681         if (isAllDefined(value)) {
14682           scope.$$postDigest(function() {
14683             if (isAllDefined(lastValue)) unwatch();
14684           });
14685         }
14686       }, objectEquality);
14687
14688       function isAllDefined(value) {
14689         var allDefined = true;
14690         forEach(value, function(val) {
14691           if (!isDefined(val)) allDefined = false;
14692         });
14693         return allDefined;
14694       }
14695     }
14696
14697     function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
14698       var unwatch;
14699       return unwatch = scope.$watch(function constantWatch(scope) {
14700         unwatch();
14701         return parsedExpression(scope);
14702       }, listener, objectEquality);
14703     }
14704
14705     function addInterceptor(parsedExpression, interceptorFn) {
14706       if (!interceptorFn) return parsedExpression;
14707       var watchDelegate = parsedExpression.$$watchDelegate;
14708       var useInputs = false;
14709
14710       var regularWatch =
14711           watchDelegate !== oneTimeLiteralWatchDelegate &&
14712           watchDelegate !== oneTimeWatchDelegate;
14713
14714       var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
14715         var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
14716         return interceptorFn(value, scope, locals);
14717       } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
14718         var value = parsedExpression(scope, locals, assign, inputs);
14719         var result = interceptorFn(value, scope, locals);
14720         // we only return the interceptor's result if the
14721         // initial value is defined (for bind-once)
14722         return isDefined(value) ? result : value;
14723       };
14724
14725       // Propagate $$watchDelegates other then inputsWatchDelegate
14726       if (parsedExpression.$$watchDelegate &&
14727           parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
14728         fn.$$watchDelegate = parsedExpression.$$watchDelegate;
14729       } else if (!interceptorFn.$stateful) {
14730         // If there is an interceptor, but no watchDelegate then treat the interceptor like
14731         // we treat filters - it is assumed to be a pure function unless flagged with $stateful
14732         fn.$$watchDelegate = inputsWatchDelegate;
14733         useInputs = !parsedExpression.inputs;
14734         fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
14735       }
14736
14737       return fn;
14738     }
14739   }];
14740 }
14741
14742 /**
14743  * @ngdoc service
14744  * @name $q
14745  * @requires $rootScope
14746  *
14747  * @description
14748  * A service that helps you run functions asynchronously, and use their return values (or exceptions)
14749  * when they are done processing.
14750  *
14751  * This is an implementation of promises/deferred objects inspired by
14752  * [Kris Kowal's Q](https://github.com/kriskowal/q).
14753  *
14754  * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
14755  * implementations, and the other which resembles ES6 promises to some degree.
14756  *
14757  * # $q constructor
14758  *
14759  * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
14760  * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
14761  * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
14762  *
14763  * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
14764  * available yet.
14765  *
14766  * It can be used like so:
14767  *
14768  * ```js
14769  *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`
14770  *   // are available in the current lexical scope (they could have been injected or passed in).
14771  *
14772  *   function asyncGreet(name) {
14773  *     // perform some asynchronous operation, resolve or reject the promise when appropriate.
14774  *     return $q(function(resolve, reject) {
14775  *       setTimeout(function() {
14776  *         if (okToGreet(name)) {
14777  *           resolve('Hello, ' + name + '!');
14778  *         } else {
14779  *           reject('Greeting ' + name + ' is not allowed.');
14780  *         }
14781  *       }, 1000);
14782  *     });
14783  *   }
14784  *
14785  *   var promise = asyncGreet('Robin Hood');
14786  *   promise.then(function(greeting) {
14787  *     alert('Success: ' + greeting);
14788  *   }, function(reason) {
14789  *     alert('Failed: ' + reason);
14790  *   });
14791  * ```
14792  *
14793  * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
14794  *
14795  * Note: unlike ES6 behaviour, an exception thrown in the constructor function will NOT implicitly reject the promise.
14796  *
14797  * However, the more traditional CommonJS-style usage is still available, and documented below.
14798  *
14799  * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
14800  * interface for interacting with an object that represents the result of an action that is
14801  * performed asynchronously, and may or may not be finished at any given point in time.
14802  *
14803  * From the perspective of dealing with error handling, deferred and promise APIs are to
14804  * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
14805  *
14806  * ```js
14807  *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`
14808  *   // are available in the current lexical scope (they could have been injected or passed in).
14809  *
14810  *   function asyncGreet(name) {
14811  *     var deferred = $q.defer();
14812  *
14813  *     setTimeout(function() {
14814  *       deferred.notify('About to greet ' + name + '.');
14815  *
14816  *       if (okToGreet(name)) {
14817  *         deferred.resolve('Hello, ' + name + '!');
14818  *       } else {
14819  *         deferred.reject('Greeting ' + name + ' is not allowed.');
14820  *       }
14821  *     }, 1000);
14822  *
14823  *     return deferred.promise;
14824  *   }
14825  *
14826  *   var promise = asyncGreet('Robin Hood');
14827  *   promise.then(function(greeting) {
14828  *     alert('Success: ' + greeting);
14829  *   }, function(reason) {
14830  *     alert('Failed: ' + reason);
14831  *   }, function(update) {
14832  *     alert('Got notification: ' + update);
14833  *   });
14834  * ```
14835  *
14836  * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
14837  * comes in the way of guarantees that promise and deferred APIs make, see
14838  * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
14839  *
14840  * Additionally the promise api allows for composition that is very hard to do with the
14841  * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
14842  * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
14843  * section on serial or parallel joining of promises.
14844  *
14845  * # The Deferred API
14846  *
14847  * A new instance of deferred is constructed by calling `$q.defer()`.
14848  *
14849  * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
14850  * that can be used for signaling the successful or unsuccessful completion, as well as the status
14851  * of the task.
14852  *
14853  * **Methods**
14854  *
14855  * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
14856  *   constructed via `$q.reject`, the promise will be rejected instead.
14857  * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
14858  *   resolving it with a rejection constructed via `$q.reject`.
14859  * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
14860  *   multiple times before the promise is either resolved or rejected.
14861  *
14862  * **Properties**
14863  *
14864  * - promise – `{Promise}` – promise object associated with this deferred.
14865  *
14866  *
14867  * # The Promise API
14868  *
14869  * A new promise instance is created when a deferred instance is created and can be retrieved by
14870  * calling `deferred.promise`.
14871  *
14872  * The purpose of the promise object is to allow for interested parties to get access to the result
14873  * of the deferred task when it completes.
14874  *
14875  * **Methods**
14876  *
14877  * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
14878  *   will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
14879  *   as soon as the result is available. The callbacks are called with a single argument: the result
14880  *   or rejection reason. Additionally, the notify callback may be called zero or more times to
14881  *   provide a progress indication, before the promise is resolved or rejected.
14882  *
14883  *   This method *returns a new promise* which is resolved or rejected via the return value of the
14884  *   `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
14885  *   with the value which is resolved in that promise using
14886  *   [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
14887  *   It also notifies via the return value of the `notifyCallback` method. The promise cannot be
14888  *   resolved or rejected from the notifyCallback method.
14889  *
14890  * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
14891  *
14892  * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
14893  *   but to do so without modifying the final value. This is useful to release resources or do some
14894  *   clean-up that needs to be done whether the promise was rejected or resolved. See the [full
14895  *   specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
14896  *   more information.
14897  *
14898  * # Chaining promises
14899  *
14900  * Because calling the `then` method of a promise returns a new derived promise, it is easily
14901  * possible to create a chain of promises:
14902  *
14903  * ```js
14904  *   promiseB = promiseA.then(function(result) {
14905  *     return result + 1;
14906  *   });
14907  *
14908  *   // promiseB will be resolved immediately after promiseA is resolved and its value
14909  *   // will be the result of promiseA incremented by 1
14910  * ```
14911  *
14912  * It is possible to create chains of any length and since a promise can be resolved with another
14913  * promise (which will defer its resolution further), it is possible to pause/defer resolution of
14914  * the promises at any point in the chain. This makes it possible to implement powerful APIs like
14915  * $http's response interceptors.
14916  *
14917  *
14918  * # Differences between Kris Kowal's Q and $q
14919  *
14920  *  There are two main differences:
14921  *
14922  * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
14923  *   mechanism in angular, which means faster propagation of resolution or rejection into your
14924  *   models and avoiding unnecessary browser repaints, which would result in flickering UI.
14925  * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
14926  *   all the important functionality needed for common async tasks.
14927  *
14928  *  # Testing
14929  *
14930  *  ```js
14931  *    it('should simulate promise', inject(function($q, $rootScope) {
14932  *      var deferred = $q.defer();
14933  *      var promise = deferred.promise;
14934  *      var resolvedValue;
14935  *
14936  *      promise.then(function(value) { resolvedValue = value; });
14937  *      expect(resolvedValue).toBeUndefined();
14938  *
14939  *      // Simulate resolving of promise
14940  *      deferred.resolve(123);
14941  *      // Note that the 'then' function does not get called synchronously.
14942  *      // This is because we want the promise API to always be async, whether or not
14943  *      // it got called synchronously or asynchronously.
14944  *      expect(resolvedValue).toBeUndefined();
14945  *
14946  *      // Propagate promise resolution to 'then' functions using $apply().
14947  *      $rootScope.$apply();
14948  *      expect(resolvedValue).toEqual(123);
14949  *    }));
14950  *  ```
14951  *
14952  * @param {function(function, function)} resolver Function which is responsible for resolving or
14953  *   rejecting the newly created promise. The first parameter is a function which resolves the
14954  *   promise, the second parameter is a function which rejects the promise.
14955  *
14956  * @returns {Promise} The newly created promise.
14957  */
14958 function $QProvider() {
14959
14960   this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
14961     return qFactory(function(callback) {
14962       $rootScope.$evalAsync(callback);
14963     }, $exceptionHandler);
14964   }];
14965 }
14966
14967 function $$QProvider() {
14968   this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
14969     return qFactory(function(callback) {
14970       $browser.defer(callback);
14971     }, $exceptionHandler);
14972   }];
14973 }
14974
14975 /**
14976  * Constructs a promise manager.
14977  *
14978  * @param {function(function)} nextTick Function for executing functions in the next turn.
14979  * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
14980  *     debugging purposes.
14981  * @returns {object} Promise manager.
14982  */
14983 function qFactory(nextTick, exceptionHandler) {
14984   var $qMinErr = minErr('$q', TypeError);
14985
14986   /**
14987    * @ngdoc method
14988    * @name ng.$q#defer
14989    * @kind function
14990    *
14991    * @description
14992    * Creates a `Deferred` object which represents a task which will finish in the future.
14993    *
14994    * @returns {Deferred} Returns a new instance of deferred.
14995    */
14996   var defer = function() {
14997     var d = new Deferred();
14998     //Necessary to support unbound execution :/
14999     d.resolve = simpleBind(d, d.resolve);
15000     d.reject = simpleBind(d, d.reject);
15001     d.notify = simpleBind(d, d.notify);
15002     return d;
15003   };
15004
15005   function Promise() {
15006     this.$$state = { status: 0 };
15007   }
15008
15009   extend(Promise.prototype, {
15010     then: function(onFulfilled, onRejected, progressBack) {
15011       if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
15012         return this;
15013       }
15014       var result = new Deferred();
15015
15016       this.$$state.pending = this.$$state.pending || [];
15017       this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
15018       if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
15019
15020       return result.promise;
15021     },
15022
15023     "catch": function(callback) {
15024       return this.then(null, callback);
15025     },
15026
15027     "finally": function(callback, progressBack) {
15028       return this.then(function(value) {
15029         return handleCallback(value, true, callback);
15030       }, function(error) {
15031         return handleCallback(error, false, callback);
15032       }, progressBack);
15033     }
15034   });
15035
15036   //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
15037   function simpleBind(context, fn) {
15038     return function(value) {
15039       fn.call(context, value);
15040     };
15041   }
15042
15043   function processQueue(state) {
15044     var fn, deferred, pending;
15045
15046     pending = state.pending;
15047     state.processScheduled = false;
15048     state.pending = undefined;
15049     for (var i = 0, ii = pending.length; i < ii; ++i) {
15050       deferred = pending[i][0];
15051       fn = pending[i][state.status];
15052       try {
15053         if (isFunction(fn)) {
15054           deferred.resolve(fn(state.value));
15055         } else if (state.status === 1) {
15056           deferred.resolve(state.value);
15057         } else {
15058           deferred.reject(state.value);
15059         }
15060       } catch (e) {
15061         deferred.reject(e);
15062         exceptionHandler(e);
15063       }
15064     }
15065   }
15066
15067   function scheduleProcessQueue(state) {
15068     if (state.processScheduled || !state.pending) return;
15069     state.processScheduled = true;
15070     nextTick(function() { processQueue(state); });
15071   }
15072
15073   function Deferred() {
15074     this.promise = new Promise();
15075   }
15076
15077   extend(Deferred.prototype, {
15078     resolve: function(val) {
15079       if (this.promise.$$state.status) return;
15080       if (val === this.promise) {
15081         this.$$reject($qMinErr(
15082           'qcycle',
15083           "Expected promise to be resolved with value other than itself '{0}'",
15084           val));
15085       } else {
15086         this.$$resolve(val);
15087       }
15088
15089     },
15090
15091     $$resolve: function(val) {
15092       var then;
15093       var that = this;
15094       var done = false;
15095       try {
15096         if ((isObject(val) || isFunction(val))) then = val && val.then;
15097         if (isFunction(then)) {
15098           this.promise.$$state.status = -1;
15099           then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
15100         } else {
15101           this.promise.$$state.value = val;
15102           this.promise.$$state.status = 1;
15103           scheduleProcessQueue(this.promise.$$state);
15104         }
15105       } catch (e) {
15106         rejectPromise(e);
15107         exceptionHandler(e);
15108       }
15109
15110       function resolvePromise(val) {
15111         if (done) return;
15112         done = true;
15113         that.$$resolve(val);
15114       }
15115       function rejectPromise(val) {
15116         if (done) return;
15117         done = true;
15118         that.$$reject(val);
15119       }
15120     },
15121
15122     reject: function(reason) {
15123       if (this.promise.$$state.status) return;
15124       this.$$reject(reason);
15125     },
15126
15127     $$reject: function(reason) {
15128       this.promise.$$state.value = reason;
15129       this.promise.$$state.status = 2;
15130       scheduleProcessQueue(this.promise.$$state);
15131     },
15132
15133     notify: function(progress) {
15134       var callbacks = this.promise.$$state.pending;
15135
15136       if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
15137         nextTick(function() {
15138           var callback, result;
15139           for (var i = 0, ii = callbacks.length; i < ii; i++) {
15140             result = callbacks[i][0];
15141             callback = callbacks[i][3];
15142             try {
15143               result.notify(isFunction(callback) ? callback(progress) : progress);
15144             } catch (e) {
15145               exceptionHandler(e);
15146             }
15147           }
15148         });
15149       }
15150     }
15151   });
15152
15153   /**
15154    * @ngdoc method
15155    * @name $q#reject
15156    * @kind function
15157    *
15158    * @description
15159    * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
15160    * used to forward rejection in a chain of promises. If you are dealing with the last promise in
15161    * a promise chain, you don't need to worry about it.
15162    *
15163    * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
15164    * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
15165    * a promise error callback and you want to forward the error to the promise derived from the
15166    * current promise, you have to "rethrow" the error by returning a rejection constructed via
15167    * `reject`.
15168    *
15169    * ```js
15170    *   promiseB = promiseA.then(function(result) {
15171    *     // success: do something and resolve promiseB
15172    *     //          with the old or a new result
15173    *     return result;
15174    *   }, function(reason) {
15175    *     // error: handle the error if possible and
15176    *     //        resolve promiseB with newPromiseOrValue,
15177    *     //        otherwise forward the rejection to promiseB
15178    *     if (canHandle(reason)) {
15179    *      // handle the error and recover
15180    *      return newPromiseOrValue;
15181    *     }
15182    *     return $q.reject(reason);
15183    *   });
15184    * ```
15185    *
15186    * @param {*} reason Constant, message, exception or an object representing the rejection reason.
15187    * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
15188    */
15189   var reject = function(reason) {
15190     var result = new Deferred();
15191     result.reject(reason);
15192     return result.promise;
15193   };
15194
15195   var makePromise = function makePromise(value, resolved) {
15196     var result = new Deferred();
15197     if (resolved) {
15198       result.resolve(value);
15199     } else {
15200       result.reject(value);
15201     }
15202     return result.promise;
15203   };
15204
15205   var handleCallback = function handleCallback(value, isResolved, callback) {
15206     var callbackOutput = null;
15207     try {
15208       if (isFunction(callback)) callbackOutput = callback();
15209     } catch (e) {
15210       return makePromise(e, false);
15211     }
15212     if (isPromiseLike(callbackOutput)) {
15213       return callbackOutput.then(function() {
15214         return makePromise(value, isResolved);
15215       }, function(error) {
15216         return makePromise(error, false);
15217       });
15218     } else {
15219       return makePromise(value, isResolved);
15220     }
15221   };
15222
15223   /**
15224    * @ngdoc method
15225    * @name $q#when
15226    * @kind function
15227    *
15228    * @description
15229    * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
15230    * This is useful when you are dealing with an object that might or might not be a promise, or if
15231    * the promise comes from a source that can't be trusted.
15232    *
15233    * @param {*} value Value or a promise
15234    * @param {Function=} successCallback
15235    * @param {Function=} errorCallback
15236    * @param {Function=} progressCallback
15237    * @returns {Promise} Returns a promise of the passed value or promise
15238    */
15239
15240
15241   var when = function(value, callback, errback, progressBack) {
15242     var result = new Deferred();
15243     result.resolve(value);
15244     return result.promise.then(callback, errback, progressBack);
15245   };
15246
15247   /**
15248    * @ngdoc method
15249    * @name $q#resolve
15250    * @kind function
15251    *
15252    * @description
15253    * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
15254    *
15255    * @param {*} value Value or a promise
15256    * @param {Function=} successCallback
15257    * @param {Function=} errorCallback
15258    * @param {Function=} progressCallback
15259    * @returns {Promise} Returns a promise of the passed value or promise
15260    */
15261   var resolve = when;
15262
15263   /**
15264    * @ngdoc method
15265    * @name $q#all
15266    * @kind function
15267    *
15268    * @description
15269    * Combines multiple promises into a single promise that is resolved when all of the input
15270    * promises are resolved.
15271    *
15272    * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
15273    * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
15274    *   each value corresponding to the promise at the same index/key in the `promises` array/hash.
15275    *   If any of the promises is resolved with a rejection, this resulting promise will be rejected
15276    *   with the same rejection value.
15277    */
15278
15279   function all(promises) {
15280     var deferred = new Deferred(),
15281         counter = 0,
15282         results = isArray(promises) ? [] : {};
15283
15284     forEach(promises, function(promise, key) {
15285       counter++;
15286       when(promise).then(function(value) {
15287         if (results.hasOwnProperty(key)) return;
15288         results[key] = value;
15289         if (!(--counter)) deferred.resolve(results);
15290       }, function(reason) {
15291         if (results.hasOwnProperty(key)) return;
15292         deferred.reject(reason);
15293       });
15294     });
15295
15296     if (counter === 0) {
15297       deferred.resolve(results);
15298     }
15299
15300     return deferred.promise;
15301   }
15302
15303   var $Q = function Q(resolver) {
15304     if (!isFunction(resolver)) {
15305       throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
15306     }
15307
15308     if (!(this instanceof Q)) {
15309       // More useful when $Q is the Promise itself.
15310       return new Q(resolver);
15311     }
15312
15313     var deferred = new Deferred();
15314
15315     function resolveFn(value) {
15316       deferred.resolve(value);
15317     }
15318
15319     function rejectFn(reason) {
15320       deferred.reject(reason);
15321     }
15322
15323     resolver(resolveFn, rejectFn);
15324
15325     return deferred.promise;
15326   };
15327
15328   $Q.defer = defer;
15329   $Q.reject = reject;
15330   $Q.when = when;
15331   $Q.resolve = resolve;
15332   $Q.all = all;
15333
15334   return $Q;
15335 }
15336
15337 function $$RAFProvider() { //rAF
15338   this.$get = ['$window', '$timeout', function($window, $timeout) {
15339     var requestAnimationFrame = $window.requestAnimationFrame ||
15340                                 $window.webkitRequestAnimationFrame;
15341
15342     var cancelAnimationFrame = $window.cancelAnimationFrame ||
15343                                $window.webkitCancelAnimationFrame ||
15344                                $window.webkitCancelRequestAnimationFrame;
15345
15346     var rafSupported = !!requestAnimationFrame;
15347     var raf = rafSupported
15348       ? function(fn) {
15349           var id = requestAnimationFrame(fn);
15350           return function() {
15351             cancelAnimationFrame(id);
15352           };
15353         }
15354       : function(fn) {
15355           var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
15356           return function() {
15357             $timeout.cancel(timer);
15358           };
15359         };
15360
15361     raf.supported = rafSupported;
15362
15363     return raf;
15364   }];
15365 }
15366
15367 /**
15368  * DESIGN NOTES
15369  *
15370  * The design decisions behind the scope are heavily favored for speed and memory consumption.
15371  *
15372  * The typical use of scope is to watch the expressions, which most of the time return the same
15373  * value as last time so we optimize the operation.
15374  *
15375  * Closures construction is expensive in terms of speed as well as memory:
15376  *   - No closures, instead use prototypical inheritance for API
15377  *   - Internal state needs to be stored on scope directly, which means that private state is
15378  *     exposed as $$____ properties
15379  *
15380  * Loop operations are optimized by using while(count--) { ... }
15381  *   - This means that in order to keep the same order of execution as addition we have to add
15382  *     items to the array at the beginning (unshift) instead of at the end (push)
15383  *
15384  * Child scopes are created and removed often
15385  *   - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
15386  *
15387  * There are fewer watches than observers. This is why you don't want the observer to be implemented
15388  * in the same way as watch. Watch requires return of the initialization function which is expensive
15389  * to construct.
15390  */
15391
15392
15393 /**
15394  * @ngdoc provider
15395  * @name $rootScopeProvider
15396  * @description
15397  *
15398  * Provider for the $rootScope service.
15399  */
15400
15401 /**
15402  * @ngdoc method
15403  * @name $rootScopeProvider#digestTtl
15404  * @description
15405  *
15406  * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
15407  * assuming that the model is unstable.
15408  *
15409  * The current default is 10 iterations.
15410  *
15411  * In complex applications it's possible that the dependencies between `$watch`s will result in
15412  * several digest iterations. However if an application needs more than the default 10 digest
15413  * iterations for its model to stabilize then you should investigate what is causing the model to
15414  * continuously change during the digest.
15415  *
15416  * Increasing the TTL could have performance implications, so you should not change it without
15417  * proper justification.
15418  *
15419  * @param {number} limit The number of digest iterations.
15420  */
15421
15422
15423 /**
15424  * @ngdoc service
15425  * @name $rootScope
15426  * @description
15427  *
15428  * Every application has a single root {@link ng.$rootScope.Scope scope}.
15429  * All other scopes are descendant scopes of the root scope. Scopes provide separation
15430  * between the model and the view, via a mechanism for watching the model for changes.
15431  * They also provide event emission/broadcast and subscription facility. See the
15432  * {@link guide/scope developer guide on scopes}.
15433  */
15434 function $RootScopeProvider() {
15435   var TTL = 10;
15436   var $rootScopeMinErr = minErr('$rootScope');
15437   var lastDirtyWatch = null;
15438   var applyAsyncId = null;
15439
15440   this.digestTtl = function(value) {
15441     if (arguments.length) {
15442       TTL = value;
15443     }
15444     return TTL;
15445   };
15446
15447   function createChildScopeClass(parent) {
15448     function ChildScope() {
15449       this.$$watchers = this.$$nextSibling =
15450           this.$$childHead = this.$$childTail = null;
15451       this.$$listeners = {};
15452       this.$$listenerCount = {};
15453       this.$$watchersCount = 0;
15454       this.$id = nextUid();
15455       this.$$ChildScope = null;
15456     }
15457     ChildScope.prototype = parent;
15458     return ChildScope;
15459   }
15460
15461   this.$get = ['$exceptionHandler', '$parse', '$browser',
15462       function($exceptionHandler, $parse, $browser) {
15463
15464     function destroyChildScope($event) {
15465         $event.currentScope.$$destroyed = true;
15466     }
15467
15468     function cleanUpScope($scope) {
15469
15470       if (msie === 9) {
15471         // There is a memory leak in IE9 if all child scopes are not disconnected
15472         // completely when a scope is destroyed. So this code will recurse up through
15473         // all this scopes children
15474         //
15475         // See issue https://github.com/angular/angular.js/issues/10706
15476         $scope.$$childHead && cleanUpScope($scope.$$childHead);
15477         $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
15478       }
15479
15480       // The code below works around IE9 and V8's memory leaks
15481       //
15482       // See:
15483       // - https://code.google.com/p/v8/issues/detail?id=2073#c26
15484       // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
15485       // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
15486
15487       $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
15488           $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
15489     }
15490
15491     /**
15492      * @ngdoc type
15493      * @name $rootScope.Scope
15494      *
15495      * @description
15496      * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
15497      * {@link auto.$injector $injector}. Child scopes are created using the
15498      * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
15499      * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
15500      * an in-depth introduction and usage examples.
15501      *
15502      *
15503      * # Inheritance
15504      * A scope can inherit from a parent scope, as in this example:
15505      * ```js
15506          var parent = $rootScope;
15507          var child = parent.$new();
15508
15509          parent.salutation = "Hello";
15510          expect(child.salutation).toEqual('Hello');
15511
15512          child.salutation = "Welcome";
15513          expect(child.salutation).toEqual('Welcome');
15514          expect(parent.salutation).toEqual('Hello');
15515      * ```
15516      *
15517      * When interacting with `Scope` in tests, additional helper methods are available on the
15518      * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
15519      * details.
15520      *
15521      *
15522      * @param {Object.<string, function()>=} providers Map of service factory which need to be
15523      *                                       provided for the current scope. Defaults to {@link ng}.
15524      * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
15525      *                              append/override services provided by `providers`. This is handy
15526      *                              when unit-testing and having the need to override a default
15527      *                              service.
15528      * @returns {Object} Newly created scope.
15529      *
15530      */
15531     function Scope() {
15532       this.$id = nextUid();
15533       this.$$phase = this.$parent = this.$$watchers =
15534                      this.$$nextSibling = this.$$prevSibling =
15535                      this.$$childHead = this.$$childTail = null;
15536       this.$root = this;
15537       this.$$destroyed = false;
15538       this.$$listeners = {};
15539       this.$$listenerCount = {};
15540       this.$$watchersCount = 0;
15541       this.$$isolateBindings = null;
15542     }
15543
15544     /**
15545      * @ngdoc property
15546      * @name $rootScope.Scope#$id
15547      *
15548      * @description
15549      * Unique scope ID (monotonically increasing) useful for debugging.
15550      */
15551
15552      /**
15553       * @ngdoc property
15554       * @name $rootScope.Scope#$parent
15555       *
15556       * @description
15557       * Reference to the parent scope.
15558       */
15559
15560       /**
15561        * @ngdoc property
15562        * @name $rootScope.Scope#$root
15563        *
15564        * @description
15565        * Reference to the root scope.
15566        */
15567
15568     Scope.prototype = {
15569       constructor: Scope,
15570       /**
15571        * @ngdoc method
15572        * @name $rootScope.Scope#$new
15573        * @kind function
15574        *
15575        * @description
15576        * Creates a new child {@link ng.$rootScope.Scope scope}.
15577        *
15578        * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
15579        * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
15580        *
15581        * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
15582        * desired for the scope and its child scopes to be permanently detached from the parent and
15583        * thus stop participating in model change detection and listener notification by invoking.
15584        *
15585        * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
15586        *         parent scope. The scope is isolated, as it can not see parent scope properties.
15587        *         When creating widgets, it is useful for the widget to not accidentally read parent
15588        *         state.
15589        *
15590        * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
15591        *                              of the newly created scope. Defaults to `this` scope if not provided.
15592        *                              This is used when creating a transclude scope to correctly place it
15593        *                              in the scope hierarchy while maintaining the correct prototypical
15594        *                              inheritance.
15595        *
15596        * @returns {Object} The newly created child scope.
15597        *
15598        */
15599       $new: function(isolate, parent) {
15600         var child;
15601
15602         parent = parent || this;
15603
15604         if (isolate) {
15605           child = new Scope();
15606           child.$root = this.$root;
15607         } else {
15608           // Only create a child scope class if somebody asks for one,
15609           // but cache it to allow the VM to optimize lookups.
15610           if (!this.$$ChildScope) {
15611             this.$$ChildScope = createChildScopeClass(this);
15612           }
15613           child = new this.$$ChildScope();
15614         }
15615         child.$parent = parent;
15616         child.$$prevSibling = parent.$$childTail;
15617         if (parent.$$childHead) {
15618           parent.$$childTail.$$nextSibling = child;
15619           parent.$$childTail = child;
15620         } else {
15621           parent.$$childHead = parent.$$childTail = child;
15622         }
15623
15624         // When the new scope is not isolated or we inherit from `this`, and
15625         // the parent scope is destroyed, the property `$$destroyed` is inherited
15626         // prototypically. In all other cases, this property needs to be set
15627         // when the parent scope is destroyed.
15628         // The listener needs to be added after the parent is set
15629         if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
15630
15631         return child;
15632       },
15633
15634       /**
15635        * @ngdoc method
15636        * @name $rootScope.Scope#$watch
15637        * @kind function
15638        *
15639        * @description
15640        * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
15641        *
15642        * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
15643        *   $digest()} and should return the value that will be watched. (`watchExpression` should not change
15644        *   its value when executed multiple times with the same input because it may be executed multiple
15645        *   times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
15646        *   [idempotent](http://en.wikipedia.org/wiki/Idempotence).
15647        * - The `listener` is called only when the value from the current `watchExpression` and the
15648        *   previous call to `watchExpression` are not equal (with the exception of the initial run,
15649        *   see below). Inequality is determined according to reference inequality,
15650        *   [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
15651        *    via the `!==` Javascript operator, unless `objectEquality == true`
15652        *   (see next point)
15653        * - When `objectEquality == true`, inequality of the `watchExpression` is determined
15654        *   according to the {@link angular.equals} function. To save the value of the object for
15655        *   later comparison, the {@link angular.copy} function is used. This therefore means that
15656        *   watching complex objects will have adverse memory and performance implications.
15657        * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
15658        *   This is achieved by rerunning the watchers until no changes are detected. The rerun
15659        *   iteration limit is 10 to prevent an infinite loop deadlock.
15660        *
15661        *
15662        * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
15663        * you can register a `watchExpression` function with no `listener`. (Be prepared for
15664        * multiple calls to your `watchExpression` because it will execute multiple times in a
15665        * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
15666        *
15667        * After a watcher is registered with the scope, the `listener` fn is called asynchronously
15668        * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
15669        * watcher. In rare cases, this is undesirable because the listener is called when the result
15670        * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
15671        * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
15672        * listener was called due to initialization.
15673        *
15674        *
15675        *
15676        * # Example
15677        * ```js
15678            // let's assume that scope was dependency injected as the $rootScope
15679            var scope = $rootScope;
15680            scope.name = 'misko';
15681            scope.counter = 0;
15682
15683            expect(scope.counter).toEqual(0);
15684            scope.$watch('name', function(newValue, oldValue) {
15685              scope.counter = scope.counter + 1;
15686            });
15687            expect(scope.counter).toEqual(0);
15688
15689            scope.$digest();
15690            // the listener is always called during the first $digest loop after it was registered
15691            expect(scope.counter).toEqual(1);
15692
15693            scope.$digest();
15694            // but now it will not be called unless the value changes
15695            expect(scope.counter).toEqual(1);
15696
15697            scope.name = 'adam';
15698            scope.$digest();
15699            expect(scope.counter).toEqual(2);
15700
15701
15702
15703            // Using a function as a watchExpression
15704            var food;
15705            scope.foodCounter = 0;
15706            expect(scope.foodCounter).toEqual(0);
15707            scope.$watch(
15708              // This function returns the value being watched. It is called for each turn of the $digest loop
15709              function() { return food; },
15710              // This is the change listener, called when the value returned from the above function changes
15711              function(newValue, oldValue) {
15712                if ( newValue !== oldValue ) {
15713                  // Only increment the counter if the value changed
15714                  scope.foodCounter = scope.foodCounter + 1;
15715                }
15716              }
15717            );
15718            // No digest has been run so the counter will be zero
15719            expect(scope.foodCounter).toEqual(0);
15720
15721            // Run the digest but since food has not changed count will still be zero
15722            scope.$digest();
15723            expect(scope.foodCounter).toEqual(0);
15724
15725            // Update food and run digest.  Now the counter will increment
15726            food = 'cheeseburger';
15727            scope.$digest();
15728            expect(scope.foodCounter).toEqual(1);
15729
15730        * ```
15731        *
15732        *
15733        *
15734        * @param {(function()|string)} watchExpression Expression that is evaluated on each
15735        *    {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
15736        *    a call to the `listener`.
15737        *
15738        *    - `string`: Evaluated as {@link guide/expression expression}
15739        *    - `function(scope)`: called with current `scope` as a parameter.
15740        * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
15741        *    of `watchExpression` changes.
15742        *
15743        *    - `newVal` contains the current value of the `watchExpression`
15744        *    - `oldVal` contains the previous value of the `watchExpression`
15745        *    - `scope` refers to the current scope
15746        * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
15747        *     comparing for reference equality.
15748        * @returns {function()} Returns a deregistration function for this listener.
15749        */
15750       $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
15751         var get = $parse(watchExp);
15752
15753         if (get.$$watchDelegate) {
15754           return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
15755         }
15756         var scope = this,
15757             array = scope.$$watchers,
15758             watcher = {
15759               fn: listener,
15760               last: initWatchVal,
15761               get: get,
15762               exp: prettyPrintExpression || watchExp,
15763               eq: !!objectEquality
15764             };
15765
15766         lastDirtyWatch = null;
15767
15768         if (!isFunction(listener)) {
15769           watcher.fn = noop;
15770         }
15771
15772         if (!array) {
15773           array = scope.$$watchers = [];
15774         }
15775         // we use unshift since we use a while loop in $digest for speed.
15776         // the while loop reads in reverse order.
15777         array.unshift(watcher);
15778         incrementWatchersCount(this, 1);
15779
15780         return function deregisterWatch() {
15781           if (arrayRemove(array, watcher) >= 0) {
15782             incrementWatchersCount(scope, -1);
15783           }
15784           lastDirtyWatch = null;
15785         };
15786       },
15787
15788       /**
15789        * @ngdoc method
15790        * @name $rootScope.Scope#$watchGroup
15791        * @kind function
15792        *
15793        * @description
15794        * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
15795        * If any one expression in the collection changes the `listener` is executed.
15796        *
15797        * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
15798        *   call to $digest() to see if any items changes.
15799        * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
15800        *
15801        * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
15802        * watched using {@link ng.$rootScope.Scope#$watch $watch()}
15803        *
15804        * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
15805        *    expression in `watchExpressions` changes
15806        *    The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
15807        *    those of `watchExpression`
15808        *    and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
15809        *    those of `watchExpression`
15810        *    The `scope` refers to the current scope.
15811        * @returns {function()} Returns a de-registration function for all listeners.
15812        */
15813       $watchGroup: function(watchExpressions, listener) {
15814         var oldValues = new Array(watchExpressions.length);
15815         var newValues = new Array(watchExpressions.length);
15816         var deregisterFns = [];
15817         var self = this;
15818         var changeReactionScheduled = false;
15819         var firstRun = true;
15820
15821         if (!watchExpressions.length) {
15822           // No expressions means we call the listener ASAP
15823           var shouldCall = true;
15824           self.$evalAsync(function() {
15825             if (shouldCall) listener(newValues, newValues, self);
15826           });
15827           return function deregisterWatchGroup() {
15828             shouldCall = false;
15829           };
15830         }
15831
15832         if (watchExpressions.length === 1) {
15833           // Special case size of one
15834           return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
15835             newValues[0] = value;
15836             oldValues[0] = oldValue;
15837             listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
15838           });
15839         }
15840
15841         forEach(watchExpressions, function(expr, i) {
15842           var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
15843             newValues[i] = value;
15844             oldValues[i] = oldValue;
15845             if (!changeReactionScheduled) {
15846               changeReactionScheduled = true;
15847               self.$evalAsync(watchGroupAction);
15848             }
15849           });
15850           deregisterFns.push(unwatchFn);
15851         });
15852
15853         function watchGroupAction() {
15854           changeReactionScheduled = false;
15855
15856           if (firstRun) {
15857             firstRun = false;
15858             listener(newValues, newValues, self);
15859           } else {
15860             listener(newValues, oldValues, self);
15861           }
15862         }
15863
15864         return function deregisterWatchGroup() {
15865           while (deregisterFns.length) {
15866             deregisterFns.shift()();
15867           }
15868         };
15869       },
15870
15871
15872       /**
15873        * @ngdoc method
15874        * @name $rootScope.Scope#$watchCollection
15875        * @kind function
15876        *
15877        * @description
15878        * Shallow watches the properties of an object and fires whenever any of the properties change
15879        * (for arrays, this implies watching the array items; for object maps, this implies watching
15880        * the properties). If a change is detected, the `listener` callback is fired.
15881        *
15882        * - The `obj` collection is observed via standard $watch operation and is examined on every
15883        *   call to $digest() to see if any items have been added, removed, or moved.
15884        * - The `listener` is called whenever anything within the `obj` has changed. Examples include
15885        *   adding, removing, and moving items belonging to an object or array.
15886        *
15887        *
15888        * # Example
15889        * ```js
15890           $scope.names = ['igor', 'matias', 'misko', 'james'];
15891           $scope.dataCount = 4;
15892
15893           $scope.$watchCollection('names', function(newNames, oldNames) {
15894             $scope.dataCount = newNames.length;
15895           });
15896
15897           expect($scope.dataCount).toEqual(4);
15898           $scope.$digest();
15899
15900           //still at 4 ... no changes
15901           expect($scope.dataCount).toEqual(4);
15902
15903           $scope.names.pop();
15904           $scope.$digest();
15905
15906           //now there's been a change
15907           expect($scope.dataCount).toEqual(3);
15908        * ```
15909        *
15910        *
15911        * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
15912        *    expression value should evaluate to an object or an array which is observed on each
15913        *    {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
15914        *    collection will trigger a call to the `listener`.
15915        *
15916        * @param {function(newCollection, oldCollection, scope)} listener a callback function called
15917        *    when a change is detected.
15918        *    - The `newCollection` object is the newly modified data obtained from the `obj` expression
15919        *    - The `oldCollection` object is a copy of the former collection data.
15920        *      Due to performance considerations, the`oldCollection` value is computed only if the
15921        *      `listener` function declares two or more arguments.
15922        *    - The `scope` argument refers to the current scope.
15923        *
15924        * @returns {function()} Returns a de-registration function for this listener. When the
15925        *    de-registration function is executed, the internal watch operation is terminated.
15926        */
15927       $watchCollection: function(obj, listener) {
15928         $watchCollectionInterceptor.$stateful = true;
15929
15930         var self = this;
15931         // the current value, updated on each dirty-check run
15932         var newValue;
15933         // a shallow copy of the newValue from the last dirty-check run,
15934         // updated to match newValue during dirty-check run
15935         var oldValue;
15936         // a shallow copy of the newValue from when the last change happened
15937         var veryOldValue;
15938         // only track veryOldValue if the listener is asking for it
15939         var trackVeryOldValue = (listener.length > 1);
15940         var changeDetected = 0;
15941         var changeDetector = $parse(obj, $watchCollectionInterceptor);
15942         var internalArray = [];
15943         var internalObject = {};
15944         var initRun = true;
15945         var oldLength = 0;
15946
15947         function $watchCollectionInterceptor(_value) {
15948           newValue = _value;
15949           var newLength, key, bothNaN, newItem, oldItem;
15950
15951           // If the new value is undefined, then return undefined as the watch may be a one-time watch
15952           if (isUndefined(newValue)) return;
15953
15954           if (!isObject(newValue)) { // if primitive
15955             if (oldValue !== newValue) {
15956               oldValue = newValue;
15957               changeDetected++;
15958             }
15959           } else if (isArrayLike(newValue)) {
15960             if (oldValue !== internalArray) {
15961               // we are transitioning from something which was not an array into array.
15962               oldValue = internalArray;
15963               oldLength = oldValue.length = 0;
15964               changeDetected++;
15965             }
15966
15967             newLength = newValue.length;
15968
15969             if (oldLength !== newLength) {
15970               // if lengths do not match we need to trigger change notification
15971               changeDetected++;
15972               oldValue.length = oldLength = newLength;
15973             }
15974             // copy the items to oldValue and look for changes.
15975             for (var i = 0; i < newLength; i++) {
15976               oldItem = oldValue[i];
15977               newItem = newValue[i];
15978
15979               bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
15980               if (!bothNaN && (oldItem !== newItem)) {
15981                 changeDetected++;
15982                 oldValue[i] = newItem;
15983               }
15984             }
15985           } else {
15986             if (oldValue !== internalObject) {
15987               // we are transitioning from something which was not an object into object.
15988               oldValue = internalObject = {};
15989               oldLength = 0;
15990               changeDetected++;
15991             }
15992             // copy the items to oldValue and look for changes.
15993             newLength = 0;
15994             for (key in newValue) {
15995               if (hasOwnProperty.call(newValue, key)) {
15996                 newLength++;
15997                 newItem = newValue[key];
15998                 oldItem = oldValue[key];
15999
16000                 if (key in oldValue) {
16001                   bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
16002                   if (!bothNaN && (oldItem !== newItem)) {
16003                     changeDetected++;
16004                     oldValue[key] = newItem;
16005                   }
16006                 } else {
16007                   oldLength++;
16008                   oldValue[key] = newItem;
16009                   changeDetected++;
16010                 }
16011               }
16012             }
16013             if (oldLength > newLength) {
16014               // we used to have more keys, need to find them and destroy them.
16015               changeDetected++;
16016               for (key in oldValue) {
16017                 if (!hasOwnProperty.call(newValue, key)) {
16018                   oldLength--;
16019                   delete oldValue[key];
16020                 }
16021               }
16022             }
16023           }
16024           return changeDetected;
16025         }
16026
16027         function $watchCollectionAction() {
16028           if (initRun) {
16029             initRun = false;
16030             listener(newValue, newValue, self);
16031           } else {
16032             listener(newValue, veryOldValue, self);
16033           }
16034
16035           // make a copy for the next time a collection is changed
16036           if (trackVeryOldValue) {
16037             if (!isObject(newValue)) {
16038               //primitive
16039               veryOldValue = newValue;
16040             } else if (isArrayLike(newValue)) {
16041               veryOldValue = new Array(newValue.length);
16042               for (var i = 0; i < newValue.length; i++) {
16043                 veryOldValue[i] = newValue[i];
16044               }
16045             } else { // if object
16046               veryOldValue = {};
16047               for (var key in newValue) {
16048                 if (hasOwnProperty.call(newValue, key)) {
16049                   veryOldValue[key] = newValue[key];
16050                 }
16051               }
16052             }
16053           }
16054         }
16055
16056         return this.$watch(changeDetector, $watchCollectionAction);
16057       },
16058
16059       /**
16060        * @ngdoc method
16061        * @name $rootScope.Scope#$digest
16062        * @kind function
16063        *
16064        * @description
16065        * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
16066        * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
16067        * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
16068        * until no more listeners are firing. This means that it is possible to get into an infinite
16069        * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
16070        * iterations exceeds 10.
16071        *
16072        * Usually, you don't call `$digest()` directly in
16073        * {@link ng.directive:ngController controllers} or in
16074        * {@link ng.$compileProvider#directive directives}.
16075        * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
16076        * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
16077        *
16078        * If you want to be notified whenever `$digest()` is called,
16079        * you can register a `watchExpression` function with
16080        * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
16081        *
16082        * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
16083        *
16084        * # Example
16085        * ```js
16086            var scope = ...;
16087            scope.name = 'misko';
16088            scope.counter = 0;
16089
16090            expect(scope.counter).toEqual(0);
16091            scope.$watch('name', function(newValue, oldValue) {
16092              scope.counter = scope.counter + 1;
16093            });
16094            expect(scope.counter).toEqual(0);
16095
16096            scope.$digest();
16097            // the listener is always called during the first $digest loop after it was registered
16098            expect(scope.counter).toEqual(1);
16099
16100            scope.$digest();
16101            // but now it will not be called unless the value changes
16102            expect(scope.counter).toEqual(1);
16103
16104            scope.name = 'adam';
16105            scope.$digest();
16106            expect(scope.counter).toEqual(2);
16107        * ```
16108        *
16109        */
16110       $digest: function() {
16111         var watch, value, last,
16112             watchers,
16113             length,
16114             dirty, ttl = TTL,
16115             next, current, target = this,
16116             watchLog = [],
16117             logIdx, logMsg, asyncTask;
16118
16119         beginPhase('$digest');
16120         // Check for changes to browser url that happened in sync before the call to $digest
16121         $browser.$$checkUrlChange();
16122
16123         if (this === $rootScope && applyAsyncId !== null) {
16124           // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
16125           // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
16126           $browser.defer.cancel(applyAsyncId);
16127           flushApplyAsync();
16128         }
16129
16130         lastDirtyWatch = null;
16131
16132         do { // "while dirty" loop
16133           dirty = false;
16134           current = target;
16135
16136           while (asyncQueue.length) {
16137             try {
16138               asyncTask = asyncQueue.shift();
16139               asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
16140             } catch (e) {
16141               $exceptionHandler(e);
16142             }
16143             lastDirtyWatch = null;
16144           }
16145
16146           traverseScopesLoop:
16147           do { // "traverse the scopes" loop
16148             if ((watchers = current.$$watchers)) {
16149               // process our watches
16150               length = watchers.length;
16151               while (length--) {
16152                 try {
16153                   watch = watchers[length];
16154                   // Most common watches are on primitives, in which case we can short
16155                   // circuit it with === operator, only when === fails do we use .equals
16156                   if (watch) {
16157                     if ((value = watch.get(current)) !== (last = watch.last) &&
16158                         !(watch.eq
16159                             ? equals(value, last)
16160                             : (typeof value === 'number' && typeof last === 'number'
16161                                && isNaN(value) && isNaN(last)))) {
16162                       dirty = true;
16163                       lastDirtyWatch = watch;
16164                       watch.last = watch.eq ? copy(value, null) : value;
16165                       watch.fn(value, ((last === initWatchVal) ? value : last), current);
16166                       if (ttl < 5) {
16167                         logIdx = 4 - ttl;
16168                         if (!watchLog[logIdx]) watchLog[logIdx] = [];
16169                         watchLog[logIdx].push({
16170                           msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
16171                           newVal: value,
16172                           oldVal: last
16173                         });
16174                       }
16175                     } else if (watch === lastDirtyWatch) {
16176                       // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
16177                       // have already been tested.
16178                       dirty = false;
16179                       break traverseScopesLoop;
16180                     }
16181                   }
16182                 } catch (e) {
16183                   $exceptionHandler(e);
16184                 }
16185               }
16186             }
16187
16188             // Insanity Warning: scope depth-first traversal
16189             // yes, this code is a bit crazy, but it works and we have tests to prove it!
16190             // this piece should be kept in sync with the traversal in $broadcast
16191             if (!(next = ((current.$$watchersCount && current.$$childHead) ||
16192                 (current !== target && current.$$nextSibling)))) {
16193               while (current !== target && !(next = current.$$nextSibling)) {
16194                 current = current.$parent;
16195               }
16196             }
16197           } while ((current = next));
16198
16199           // `break traverseScopesLoop;` takes us to here
16200
16201           if ((dirty || asyncQueue.length) && !(ttl--)) {
16202             clearPhase();
16203             throw $rootScopeMinErr('infdig',
16204                 '{0} $digest() iterations reached. Aborting!\n' +
16205                 'Watchers fired in the last 5 iterations: {1}',
16206                 TTL, watchLog);
16207           }
16208
16209         } while (dirty || asyncQueue.length);
16210
16211         clearPhase();
16212
16213         while (postDigestQueue.length) {
16214           try {
16215             postDigestQueue.shift()();
16216           } catch (e) {
16217             $exceptionHandler(e);
16218           }
16219         }
16220       },
16221
16222
16223       /**
16224        * @ngdoc event
16225        * @name $rootScope.Scope#$destroy
16226        * @eventType broadcast on scope being destroyed
16227        *
16228        * @description
16229        * Broadcasted when a scope and its children are being destroyed.
16230        *
16231        * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
16232        * clean up DOM bindings before an element is removed from the DOM.
16233        */
16234
16235       /**
16236        * @ngdoc method
16237        * @name $rootScope.Scope#$destroy
16238        * @kind function
16239        *
16240        * @description
16241        * Removes the current scope (and all of its children) from the parent scope. Removal implies
16242        * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
16243        * propagate to the current scope and its children. Removal also implies that the current
16244        * scope is eligible for garbage collection.
16245        *
16246        * The `$destroy()` is usually used by directives such as
16247        * {@link ng.directive:ngRepeat ngRepeat} for managing the
16248        * unrolling of the loop.
16249        *
16250        * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
16251        * Application code can register a `$destroy` event handler that will give it a chance to
16252        * perform any necessary cleanup.
16253        *
16254        * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
16255        * clean up DOM bindings before an element is removed from the DOM.
16256        */
16257       $destroy: function() {
16258         // We can't destroy a scope that has been already destroyed.
16259         if (this.$$destroyed) return;
16260         var parent = this.$parent;
16261
16262         this.$broadcast('$destroy');
16263         this.$$destroyed = true;
16264
16265         if (this === $rootScope) {
16266           //Remove handlers attached to window when $rootScope is removed
16267           $browser.$$applicationDestroyed();
16268         }
16269
16270         incrementWatchersCount(this, -this.$$watchersCount);
16271         for (var eventName in this.$$listenerCount) {
16272           decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
16273         }
16274
16275         // sever all the references to parent scopes (after this cleanup, the current scope should
16276         // not be retained by any of our references and should be eligible for garbage collection)
16277         if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
16278         if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
16279         if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
16280         if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
16281
16282         // Disable listeners, watchers and apply/digest methods
16283         this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
16284         this.$on = this.$watch = this.$watchGroup = function() { return noop; };
16285         this.$$listeners = {};
16286
16287         // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
16288         this.$$nextSibling = null;
16289         cleanUpScope(this);
16290       },
16291
16292       /**
16293        * @ngdoc method
16294        * @name $rootScope.Scope#$eval
16295        * @kind function
16296        *
16297        * @description
16298        * Executes the `expression` on the current scope and returns the result. Any exceptions in
16299        * the expression are propagated (uncaught). This is useful when evaluating Angular
16300        * expressions.
16301        *
16302        * # Example
16303        * ```js
16304            var scope = ng.$rootScope.Scope();
16305            scope.a = 1;
16306            scope.b = 2;
16307
16308            expect(scope.$eval('a+b')).toEqual(3);
16309            expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
16310        * ```
16311        *
16312        * @param {(string|function())=} expression An angular expression to be executed.
16313        *
16314        *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.
16315        *    - `function(scope)`: execute the function with the current `scope` parameter.
16316        *
16317        * @param {(object)=} locals Local variables object, useful for overriding values in scope.
16318        * @returns {*} The result of evaluating the expression.
16319        */
16320       $eval: function(expr, locals) {
16321         return $parse(expr)(this, locals);
16322       },
16323
16324       /**
16325        * @ngdoc method
16326        * @name $rootScope.Scope#$evalAsync
16327        * @kind function
16328        *
16329        * @description
16330        * Executes the expression on the current scope at a later point in time.
16331        *
16332        * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
16333        * that:
16334        *
16335        *   - it will execute after the function that scheduled the evaluation (preferably before DOM
16336        *     rendering).
16337        *   - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
16338        *     `expression` execution.
16339        *
16340        * Any exceptions from the execution of the expression are forwarded to the
16341        * {@link ng.$exceptionHandler $exceptionHandler} service.
16342        *
16343        * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
16344        * will be scheduled. However, it is encouraged to always call code that changes the model
16345        * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
16346        *
16347        * @param {(string|function())=} expression An angular expression to be executed.
16348        *
16349        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
16350        *    - `function(scope)`: execute the function with the current `scope` parameter.
16351        *
16352        * @param {(object)=} locals Local variables object, useful for overriding values in scope.
16353        */
16354       $evalAsync: function(expr, locals) {
16355         // if we are outside of an $digest loop and this is the first time we are scheduling async
16356         // task also schedule async auto-flush
16357         if (!$rootScope.$$phase && !asyncQueue.length) {
16358           $browser.defer(function() {
16359             if (asyncQueue.length) {
16360               $rootScope.$digest();
16361             }
16362           });
16363         }
16364
16365         asyncQueue.push({scope: this, expression: expr, locals: locals});
16366       },
16367
16368       $$postDigest: function(fn) {
16369         postDigestQueue.push(fn);
16370       },
16371
16372       /**
16373        * @ngdoc method
16374        * @name $rootScope.Scope#$apply
16375        * @kind function
16376        *
16377        * @description
16378        * `$apply()` is used to execute an expression in angular from outside of the angular
16379        * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
16380        * Because we are calling into the angular framework we need to perform proper scope life
16381        * cycle of {@link ng.$exceptionHandler exception handling},
16382        * {@link ng.$rootScope.Scope#$digest executing watches}.
16383        *
16384        * ## Life cycle
16385        *
16386        * # Pseudo-Code of `$apply()`
16387        * ```js
16388            function $apply(expr) {
16389              try {
16390                return $eval(expr);
16391              } catch (e) {
16392                $exceptionHandler(e);
16393              } finally {
16394                $root.$digest();
16395              }
16396            }
16397        * ```
16398        *
16399        *
16400        * Scope's `$apply()` method transitions through the following stages:
16401        *
16402        * 1. The {@link guide/expression expression} is executed using the
16403        *    {@link ng.$rootScope.Scope#$eval $eval()} method.
16404        * 2. Any exceptions from the execution of the expression are forwarded to the
16405        *    {@link ng.$exceptionHandler $exceptionHandler} service.
16406        * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
16407        *    expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
16408        *
16409        *
16410        * @param {(string|function())=} exp An angular expression to be executed.
16411        *
16412        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
16413        *    - `function(scope)`: execute the function with current `scope` parameter.
16414        *
16415        * @returns {*} The result of evaluating the expression.
16416        */
16417       $apply: function(expr) {
16418         try {
16419           beginPhase('$apply');
16420           try {
16421             return this.$eval(expr);
16422           } finally {
16423             clearPhase();
16424           }
16425         } catch (e) {
16426           $exceptionHandler(e);
16427         } finally {
16428           try {
16429             $rootScope.$digest();
16430           } catch (e) {
16431             $exceptionHandler(e);
16432             throw e;
16433           }
16434         }
16435       },
16436
16437       /**
16438        * @ngdoc method
16439        * @name $rootScope.Scope#$applyAsync
16440        * @kind function
16441        *
16442        * @description
16443        * Schedule the invocation of $apply to occur at a later time. The actual time difference
16444        * varies across browsers, but is typically around ~10 milliseconds.
16445        *
16446        * This can be used to queue up multiple expressions which need to be evaluated in the same
16447        * digest.
16448        *
16449        * @param {(string|function())=} exp An angular expression to be executed.
16450        *
16451        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
16452        *    - `function(scope)`: execute the function with current `scope` parameter.
16453        */
16454       $applyAsync: function(expr) {
16455         var scope = this;
16456         expr && applyAsyncQueue.push($applyAsyncExpression);
16457         scheduleApplyAsync();
16458
16459         function $applyAsyncExpression() {
16460           scope.$eval(expr);
16461         }
16462       },
16463
16464       /**
16465        * @ngdoc method
16466        * @name $rootScope.Scope#$on
16467        * @kind function
16468        *
16469        * @description
16470        * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
16471        * discussion of event life cycle.
16472        *
16473        * The event listener function format is: `function(event, args...)`. The `event` object
16474        * passed into the listener has the following attributes:
16475        *
16476        *   - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
16477        *     `$broadcast`-ed.
16478        *   - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
16479        *     event propagates through the scope hierarchy, this property is set to null.
16480        *   - `name` - `{string}`: name of the event.
16481        *   - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
16482        *     further event propagation (available only for events that were `$emit`-ed).
16483        *   - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
16484        *     to true.
16485        *   - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
16486        *
16487        * @param {string} name Event name to listen on.
16488        * @param {function(event, ...args)} listener Function to call when the event is emitted.
16489        * @returns {function()} Returns a deregistration function for this listener.
16490        */
16491       $on: function(name, listener) {
16492         var namedListeners = this.$$listeners[name];
16493         if (!namedListeners) {
16494           this.$$listeners[name] = namedListeners = [];
16495         }
16496         namedListeners.push(listener);
16497
16498         var current = this;
16499         do {
16500           if (!current.$$listenerCount[name]) {
16501             current.$$listenerCount[name] = 0;
16502           }
16503           current.$$listenerCount[name]++;
16504         } while ((current = current.$parent));
16505
16506         var self = this;
16507         return function() {
16508           var indexOfListener = namedListeners.indexOf(listener);
16509           if (indexOfListener !== -1) {
16510             namedListeners[indexOfListener] = null;
16511             decrementListenerCount(self, 1, name);
16512           }
16513         };
16514       },
16515
16516
16517       /**
16518        * @ngdoc method
16519        * @name $rootScope.Scope#$emit
16520        * @kind function
16521        *
16522        * @description
16523        * Dispatches an event `name` upwards through the scope hierarchy notifying the
16524        * registered {@link ng.$rootScope.Scope#$on} listeners.
16525        *
16526        * The event life cycle starts at the scope on which `$emit` was called. All
16527        * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
16528        * notified. Afterwards, the event traverses upwards toward the root scope and calls all
16529        * registered listeners along the way. The event will stop propagating if one of the listeners
16530        * cancels it.
16531        *
16532        * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
16533        * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
16534        *
16535        * @param {string} name Event name to emit.
16536        * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
16537        * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
16538        */
16539       $emit: function(name, args) {
16540         var empty = [],
16541             namedListeners,
16542             scope = this,
16543             stopPropagation = false,
16544             event = {
16545               name: name,
16546               targetScope: scope,
16547               stopPropagation: function() {stopPropagation = true;},
16548               preventDefault: function() {
16549                 event.defaultPrevented = true;
16550               },
16551               defaultPrevented: false
16552             },
16553             listenerArgs = concat([event], arguments, 1),
16554             i, length;
16555
16556         do {
16557           namedListeners = scope.$$listeners[name] || empty;
16558           event.currentScope = scope;
16559           for (i = 0, length = namedListeners.length; i < length; i++) {
16560
16561             // if listeners were deregistered, defragment the array
16562             if (!namedListeners[i]) {
16563               namedListeners.splice(i, 1);
16564               i--;
16565               length--;
16566               continue;
16567             }
16568             try {
16569               //allow all listeners attached to the current scope to run
16570               namedListeners[i].apply(null, listenerArgs);
16571             } catch (e) {
16572               $exceptionHandler(e);
16573             }
16574           }
16575           //if any listener on the current scope stops propagation, prevent bubbling
16576           if (stopPropagation) {
16577             event.currentScope = null;
16578             return event;
16579           }
16580           //traverse upwards
16581           scope = scope.$parent;
16582         } while (scope);
16583
16584         event.currentScope = null;
16585
16586         return event;
16587       },
16588
16589
16590       /**
16591        * @ngdoc method
16592        * @name $rootScope.Scope#$broadcast
16593        * @kind function
16594        *
16595        * @description
16596        * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
16597        * registered {@link ng.$rootScope.Scope#$on} listeners.
16598        *
16599        * The event life cycle starts at the scope on which `$broadcast` was called. All
16600        * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
16601        * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
16602        * scope and calls all registered listeners along the way. The event cannot be canceled.
16603        *
16604        * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
16605        * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
16606        *
16607        * @param {string} name Event name to broadcast.
16608        * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
16609        * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
16610        */
16611       $broadcast: function(name, args) {
16612         var target = this,
16613             current = target,
16614             next = target,
16615             event = {
16616               name: name,
16617               targetScope: target,
16618               preventDefault: function() {
16619                 event.defaultPrevented = true;
16620               },
16621               defaultPrevented: false
16622             };
16623
16624         if (!target.$$listenerCount[name]) return event;
16625
16626         var listenerArgs = concat([event], arguments, 1),
16627             listeners, i, length;
16628
16629         //down while you can, then up and next sibling or up and next sibling until back at root
16630         while ((current = next)) {
16631           event.currentScope = current;
16632           listeners = current.$$listeners[name] || [];
16633           for (i = 0, length = listeners.length; i < length; i++) {
16634             // if listeners were deregistered, defragment the array
16635             if (!listeners[i]) {
16636               listeners.splice(i, 1);
16637               i--;
16638               length--;
16639               continue;
16640             }
16641
16642             try {
16643               listeners[i].apply(null, listenerArgs);
16644             } catch (e) {
16645               $exceptionHandler(e);
16646             }
16647           }
16648
16649           // Insanity Warning: scope depth-first traversal
16650           // yes, this code is a bit crazy, but it works and we have tests to prove it!
16651           // this piece should be kept in sync with the traversal in $digest
16652           // (though it differs due to having the extra check for $$listenerCount)
16653           if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
16654               (current !== target && current.$$nextSibling)))) {
16655             while (current !== target && !(next = current.$$nextSibling)) {
16656               current = current.$parent;
16657             }
16658           }
16659         }
16660
16661         event.currentScope = null;
16662         return event;
16663       }
16664     };
16665
16666     var $rootScope = new Scope();
16667
16668     //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
16669     var asyncQueue = $rootScope.$$asyncQueue = [];
16670     var postDigestQueue = $rootScope.$$postDigestQueue = [];
16671     var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
16672
16673     return $rootScope;
16674
16675
16676     function beginPhase(phase) {
16677       if ($rootScope.$$phase) {
16678         throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
16679       }
16680
16681       $rootScope.$$phase = phase;
16682     }
16683
16684     function clearPhase() {
16685       $rootScope.$$phase = null;
16686     }
16687
16688     function incrementWatchersCount(current, count) {
16689       do {
16690         current.$$watchersCount += count;
16691       } while ((current = current.$parent));
16692     }
16693
16694     function decrementListenerCount(current, count, name) {
16695       do {
16696         current.$$listenerCount[name] -= count;
16697
16698         if (current.$$listenerCount[name] === 0) {
16699           delete current.$$listenerCount[name];
16700         }
16701       } while ((current = current.$parent));
16702     }
16703
16704     /**
16705      * function used as an initial value for watchers.
16706      * because it's unique we can easily tell it apart from other values
16707      */
16708     function initWatchVal() {}
16709
16710     function flushApplyAsync() {
16711       while (applyAsyncQueue.length) {
16712         try {
16713           applyAsyncQueue.shift()();
16714         } catch (e) {
16715           $exceptionHandler(e);
16716         }
16717       }
16718       applyAsyncId = null;
16719     }
16720
16721     function scheduleApplyAsync() {
16722       if (applyAsyncId === null) {
16723         applyAsyncId = $browser.defer(function() {
16724           $rootScope.$apply(flushApplyAsync);
16725         });
16726       }
16727     }
16728   }];
16729 }
16730
16731 /**
16732  * @description
16733  * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
16734  */
16735 function $$SanitizeUriProvider() {
16736   var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
16737     imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
16738
16739   /**
16740    * @description
16741    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
16742    * urls during a[href] sanitization.
16743    *
16744    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
16745    *
16746    * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
16747    * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
16748    * regular expression. If a match is found, the original url is written into the dom. Otherwise,
16749    * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
16750    *
16751    * @param {RegExp=} regexp New regexp to whitelist urls with.
16752    * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
16753    *    chaining otherwise.
16754    */
16755   this.aHrefSanitizationWhitelist = function(regexp) {
16756     if (isDefined(regexp)) {
16757       aHrefSanitizationWhitelist = regexp;
16758       return this;
16759     }
16760     return aHrefSanitizationWhitelist;
16761   };
16762
16763
16764   /**
16765    * @description
16766    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
16767    * urls during img[src] sanitization.
16768    *
16769    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
16770    *
16771    * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
16772    * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
16773    * regular expression. If a match is found, the original url is written into the dom. Otherwise,
16774    * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
16775    *
16776    * @param {RegExp=} regexp New regexp to whitelist urls with.
16777    * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
16778    *    chaining otherwise.
16779    */
16780   this.imgSrcSanitizationWhitelist = function(regexp) {
16781     if (isDefined(regexp)) {
16782       imgSrcSanitizationWhitelist = regexp;
16783       return this;
16784     }
16785     return imgSrcSanitizationWhitelist;
16786   };
16787
16788   this.$get = function() {
16789     return function sanitizeUri(uri, isImage) {
16790       var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
16791       var normalizedVal;
16792       normalizedVal = urlResolve(uri).href;
16793       if (normalizedVal !== '' && !normalizedVal.match(regex)) {
16794         return 'unsafe:' + normalizedVal;
16795       }
16796       return uri;
16797     };
16798   };
16799 }
16800
16801 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
16802  *     Any commits to this file should be reviewed with security in mind.  *
16803  *   Changes to this file can potentially create security vulnerabilities. *
16804  *          An approval from 2 Core members with history of modifying      *
16805  *                         this file is required.                          *
16806  *                                                                         *
16807  *  Does the change somehow allow for arbitrary javascript to be executed? *
16808  *    Or allows for someone to change the prototype of built-in objects?   *
16809  *     Or gives undesired access to variables likes document or window?    *
16810  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
16811
16812 var $sceMinErr = minErr('$sce');
16813
16814 var SCE_CONTEXTS = {
16815   HTML: 'html',
16816   CSS: 'css',
16817   URL: 'url',
16818   // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
16819   // url.  (e.g. ng-include, script src, templateUrl)
16820   RESOURCE_URL: 'resourceUrl',
16821   JS: 'js'
16822 };
16823
16824 // Helper functions follow.
16825
16826 function adjustMatcher(matcher) {
16827   if (matcher === 'self') {
16828     return matcher;
16829   } else if (isString(matcher)) {
16830     // Strings match exactly except for 2 wildcards - '*' and '**'.
16831     // '*' matches any character except those from the set ':/.?&'.
16832     // '**' matches any character (like .* in a RegExp).
16833     // More than 2 *'s raises an error as it's ill defined.
16834     if (matcher.indexOf('***') > -1) {
16835       throw $sceMinErr('iwcard',
16836           'Illegal sequence *** in string matcher.  String: {0}', matcher);
16837     }
16838     matcher = escapeForRegexp(matcher).
16839                   replace('\\*\\*', '.*').
16840                   replace('\\*', '[^:/.?&;]*');
16841     return new RegExp('^' + matcher + '$');
16842   } else if (isRegExp(matcher)) {
16843     // The only other type of matcher allowed is a Regexp.
16844     // Match entire URL / disallow partial matches.
16845     // Flags are reset (i.e. no global, ignoreCase or multiline)
16846     return new RegExp('^' + matcher.source + '$');
16847   } else {
16848     throw $sceMinErr('imatcher',
16849         'Matchers may only be "self", string patterns or RegExp objects');
16850   }
16851 }
16852
16853
16854 function adjustMatchers(matchers) {
16855   var adjustedMatchers = [];
16856   if (isDefined(matchers)) {
16857     forEach(matchers, function(matcher) {
16858       adjustedMatchers.push(adjustMatcher(matcher));
16859     });
16860   }
16861   return adjustedMatchers;
16862 }
16863
16864
16865 /**
16866  * @ngdoc service
16867  * @name $sceDelegate
16868  * @kind function
16869  *
16870  * @description
16871  *
16872  * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
16873  * Contextual Escaping (SCE)} services to AngularJS.
16874  *
16875  * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
16876  * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS.  This is
16877  * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
16878  * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
16879  * work because `$sce` delegates to `$sceDelegate` for these operations.
16880  *
16881  * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
16882  *
16883  * The default instance of `$sceDelegate` should work out of the box with little pain.  While you
16884  * can override it completely to change the behavior of `$sce`, the common case would
16885  * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
16886  * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
16887  * templates.  Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
16888  * $sceDelegateProvider.resourceUrlWhitelist} and {@link
16889  * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
16890  */
16891
16892 /**
16893  * @ngdoc provider
16894  * @name $sceDelegateProvider
16895  * @description
16896  *
16897  * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
16898  * $sceDelegate} service.  This allows one to get/set the whitelists and blacklists used to ensure
16899  * that the URLs used for sourcing Angular templates are safe.  Refer {@link
16900  * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
16901  * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
16902  *
16903  * For the general details about this service in Angular, read the main page for {@link ng.$sce
16904  * Strict Contextual Escaping (SCE)}.
16905  *
16906  * **Example**:  Consider the following case. <a name="example"></a>
16907  *
16908  * - your app is hosted at url `http://myapp.example.com/`
16909  * - but some of your templates are hosted on other domains you control such as
16910  *   `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
16911  * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
16912  *
16913  * Here is what a secure configuration for this scenario might look like:
16914  *
16915  * ```
16916  *  angular.module('myApp', []).config(function($sceDelegateProvider) {
16917  *    $sceDelegateProvider.resourceUrlWhitelist([
16918  *      // Allow same origin resource loads.
16919  *      'self',
16920  *      // Allow loading from our assets domain.  Notice the difference between * and **.
16921  *      'http://srv*.assets.example.com/**'
16922  *    ]);
16923  *
16924  *    // The blacklist overrides the whitelist so the open redirect here is blocked.
16925  *    $sceDelegateProvider.resourceUrlBlacklist([
16926  *      'http://myapp.example.com/clickThru**'
16927  *    ]);
16928  *  });
16929  * ```
16930  */
16931
16932 function $SceDelegateProvider() {
16933   this.SCE_CONTEXTS = SCE_CONTEXTS;
16934
16935   // Resource URLs can also be trusted by policy.
16936   var resourceUrlWhitelist = ['self'],
16937       resourceUrlBlacklist = [];
16938
16939   /**
16940    * @ngdoc method
16941    * @name $sceDelegateProvider#resourceUrlWhitelist
16942    * @kind function
16943    *
16944    * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
16945    *     provided.  This must be an array or null.  A snapshot of this array is used so further
16946    *     changes to the array are ignored.
16947    *
16948    *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
16949    *     allowed in this array.
16950    *
16951    *     Note: **an empty whitelist array will block all URLs**!
16952    *
16953    * @return {Array} the currently set whitelist array.
16954    *
16955    * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
16956    * same origin resource requests.
16957    *
16958    * @description
16959    * Sets/Gets the whitelist of trusted resource URLs.
16960    */
16961   this.resourceUrlWhitelist = function(value) {
16962     if (arguments.length) {
16963       resourceUrlWhitelist = adjustMatchers(value);
16964     }
16965     return resourceUrlWhitelist;
16966   };
16967
16968   /**
16969    * @ngdoc method
16970    * @name $sceDelegateProvider#resourceUrlBlacklist
16971    * @kind function
16972    *
16973    * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
16974    *     provided.  This must be an array or null.  A snapshot of this array is used so further
16975    *     changes to the array are ignored.
16976    *
16977    *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
16978    *     allowed in this array.
16979    *
16980    *     The typical usage for the blacklist is to **block
16981    *     [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
16982    *     these would otherwise be trusted but actually return content from the redirected domain.
16983    *
16984    *     Finally, **the blacklist overrides the whitelist** and has the final say.
16985    *
16986    * @return {Array} the currently set blacklist array.
16987    *
16988    * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
16989    * is no blacklist.)
16990    *
16991    * @description
16992    * Sets/Gets the blacklist of trusted resource URLs.
16993    */
16994
16995   this.resourceUrlBlacklist = function(value) {
16996     if (arguments.length) {
16997       resourceUrlBlacklist = adjustMatchers(value);
16998     }
16999     return resourceUrlBlacklist;
17000   };
17001
17002   this.$get = ['$injector', function($injector) {
17003
17004     var htmlSanitizer = function htmlSanitizer(html) {
17005       throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
17006     };
17007
17008     if ($injector.has('$sanitize')) {
17009       htmlSanitizer = $injector.get('$sanitize');
17010     }
17011
17012
17013     function matchUrl(matcher, parsedUrl) {
17014       if (matcher === 'self') {
17015         return urlIsSameOrigin(parsedUrl);
17016       } else {
17017         // definitely a regex.  See adjustMatchers()
17018         return !!matcher.exec(parsedUrl.href);
17019       }
17020     }
17021
17022     function isResourceUrlAllowedByPolicy(url) {
17023       var parsedUrl = urlResolve(url.toString());
17024       var i, n, allowed = false;
17025       // Ensure that at least one item from the whitelist allows this url.
17026       for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
17027         if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
17028           allowed = true;
17029           break;
17030         }
17031       }
17032       if (allowed) {
17033         // Ensure that no item from the blacklist blocked this url.
17034         for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
17035           if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
17036             allowed = false;
17037             break;
17038           }
17039         }
17040       }
17041       return allowed;
17042     }
17043
17044     function generateHolderType(Base) {
17045       var holderType = function TrustedValueHolderType(trustedValue) {
17046         this.$$unwrapTrustedValue = function() {
17047           return trustedValue;
17048         };
17049       };
17050       if (Base) {
17051         holderType.prototype = new Base();
17052       }
17053       holderType.prototype.valueOf = function sceValueOf() {
17054         return this.$$unwrapTrustedValue();
17055       };
17056       holderType.prototype.toString = function sceToString() {
17057         return this.$$unwrapTrustedValue().toString();
17058       };
17059       return holderType;
17060     }
17061
17062     var trustedValueHolderBase = generateHolderType(),
17063         byType = {};
17064
17065     byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
17066     byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
17067     byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
17068     byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
17069     byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
17070
17071     /**
17072      * @ngdoc method
17073      * @name $sceDelegate#trustAs
17074      *
17075      * @description
17076      * Returns an object that is trusted by angular for use in specified strict
17077      * contextual escaping contexts (such as ng-bind-html, ng-include, any src
17078      * attribute interpolation, any dom event binding attribute interpolation
17079      * such as for onclick,  etc.) that uses the provided value.
17080      * See {@link ng.$sce $sce} for enabling strict contextual escaping.
17081      *
17082      * @param {string} type The kind of context in which this value is safe for use.  e.g. url,
17083      *   resourceUrl, html, js and css.
17084      * @param {*} value The value that that should be considered trusted/safe.
17085      * @returns {*} A value that can be used to stand in for the provided `value` in places
17086      * where Angular expects a $sce.trustAs() return value.
17087      */
17088     function trustAs(type, trustedValue) {
17089       var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
17090       if (!Constructor) {
17091         throw $sceMinErr('icontext',
17092             'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
17093             type, trustedValue);
17094       }
17095       if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
17096         return trustedValue;
17097       }
17098       // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting
17099       // mutable objects, we ensure here that the value passed in is actually a string.
17100       if (typeof trustedValue !== 'string') {
17101         throw $sceMinErr('itype',
17102             'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
17103             type);
17104       }
17105       return new Constructor(trustedValue);
17106     }
17107
17108     /**
17109      * @ngdoc method
17110      * @name $sceDelegate#valueOf
17111      *
17112      * @description
17113      * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
17114      * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
17115      * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
17116      *
17117      * If the passed parameter is not a value that had been returned by {@link
17118      * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
17119      *
17120      * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
17121      *      call or anything else.
17122      * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
17123      *     `$sceDelegate.trustAs`} if `value` is the result of such a call.  Otherwise, returns
17124      *     `value` unchanged.
17125      */
17126     function valueOf(maybeTrusted) {
17127       if (maybeTrusted instanceof trustedValueHolderBase) {
17128         return maybeTrusted.$$unwrapTrustedValue();
17129       } else {
17130         return maybeTrusted;
17131       }
17132     }
17133
17134     /**
17135      * @ngdoc method
17136      * @name $sceDelegate#getTrusted
17137      *
17138      * @description
17139      * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
17140      * returns the originally supplied value if the queried context type is a supertype of the
17141      * created type.  If this condition isn't satisfied, throws an exception.
17142      *
17143      * <div class="alert alert-danger">
17144      * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
17145      * (XSS) vulnerability in your application.
17146      * </div>
17147      *
17148      * @param {string} type The kind of context in which this value is to be used.
17149      * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
17150      *     `$sceDelegate.trustAs`} call.
17151      * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
17152      *     `$sceDelegate.trustAs`} if valid in this context.  Otherwise, throws an exception.
17153      */
17154     function getTrusted(type, maybeTrusted) {
17155       if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
17156         return maybeTrusted;
17157       }
17158       var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
17159       if (constructor && maybeTrusted instanceof constructor) {
17160         return maybeTrusted.$$unwrapTrustedValue();
17161       }
17162       // If we get here, then we may only take one of two actions.
17163       // 1. sanitize the value for the requested type, or
17164       // 2. throw an exception.
17165       if (type === SCE_CONTEXTS.RESOURCE_URL) {
17166         if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
17167           return maybeTrusted;
17168         } else {
17169           throw $sceMinErr('insecurl',
17170               'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: {0}',
17171               maybeTrusted.toString());
17172         }
17173       } else if (type === SCE_CONTEXTS.HTML) {
17174         return htmlSanitizer(maybeTrusted);
17175       }
17176       throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
17177     }
17178
17179     return { trustAs: trustAs,
17180              getTrusted: getTrusted,
17181              valueOf: valueOf };
17182   }];
17183 }
17184
17185
17186 /**
17187  * @ngdoc provider
17188  * @name $sceProvider
17189  * @description
17190  *
17191  * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
17192  * -   enable/disable Strict Contextual Escaping (SCE) in a module
17193  * -   override the default implementation with a custom delegate
17194  *
17195  * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
17196  */
17197
17198 /* jshint maxlen: false*/
17199
17200 /**
17201  * @ngdoc service
17202  * @name $sce
17203  * @kind function
17204  *
17205  * @description
17206  *
17207  * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
17208  *
17209  * # Strict Contextual Escaping
17210  *
17211  * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
17212  * contexts to result in a value that is marked as safe to use for that context.  One example of
17213  * such a context is binding arbitrary html controlled by the user via `ng-bind-html`.  We refer
17214  * to these contexts as privileged or SCE contexts.
17215  *
17216  * As of version 1.2, Angular ships with SCE enabled by default.
17217  *
17218  * Note:  When enabled (the default), IE<11 in quirks mode is not supported.  In this mode, IE<11 allow
17219  * one to execute arbitrary javascript by the use of the expression() syntax.  Refer
17220  * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
17221  * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
17222  * to the top of your HTML document.
17223  *
17224  * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
17225  * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
17226  *
17227  * Here's an example of a binding in a privileged context:
17228  *
17229  * ```
17230  * <input ng-model="userHtml" aria-label="User input">
17231  * <div ng-bind-html="userHtml"></div>
17232  * ```
17233  *
17234  * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user.  With SCE
17235  * disabled, this application allows the user to render arbitrary HTML into the DIV.
17236  * In a more realistic example, one may be rendering user comments, blog articles, etc. via
17237  * bindings.  (HTML is just one example of a context where rendering user controlled input creates
17238  * security vulnerabilities.)
17239  *
17240  * For the case of HTML, you might use a library, either on the client side, or on the server side,
17241  * to sanitize unsafe HTML before binding to the value and rendering it in the document.
17242  *
17243  * How would you ensure that every place that used these types of bindings was bound to a value that
17244  * was sanitized by your library (or returned as safe for rendering by your server?)  How can you
17245  * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
17246  * properties/fields and forgot to update the binding to the sanitized value?
17247  *
17248  * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
17249  * determine that something explicitly says it's safe to use a value for binding in that
17250  * context.  You can then audit your code (a simple grep would do) to ensure that this is only done
17251  * for those values that you can easily tell are safe - because they were received from your server,
17252  * sanitized by your library, etc.  You can organize your codebase to help with this - perhaps
17253  * allowing only the files in a specific directory to do this.  Ensuring that the internal API
17254  * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
17255  *
17256  * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
17257  * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
17258  * obtain values that will be accepted by SCE / privileged contexts.
17259  *
17260  *
17261  * ## How does it work?
17262  *
17263  * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
17264  * $sce.getTrusted(context, value)} rather than to the value directly.  Directives use {@link
17265  * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
17266  * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
17267  *
17268  * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
17269  * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}.  Here's the actual code (slightly
17270  * simplified):
17271  *
17272  * ```
17273  * var ngBindHtmlDirective = ['$sce', function($sce) {
17274  *   return function(scope, element, attr) {
17275  *     scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
17276  *       element.html(value || '');
17277  *     });
17278  *   };
17279  * }];
17280  * ```
17281  *
17282  * ## Impact on loading templates
17283  *
17284  * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
17285  * `templateUrl`'s specified by {@link guide/directive directives}.
17286  *
17287  * By default, Angular only loads templates from the same domain and protocol as the application
17288  * document.  This is done by calling {@link ng.$sce#getTrustedResourceUrl
17289  * $sce.getTrustedResourceUrl} on the template URL.  To load templates from other domains and/or
17290  * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
17291  * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
17292  *
17293  * *Please note*:
17294  * The browser's
17295  * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
17296  * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
17297  * policy apply in addition to this and may further restrict whether the template is successfully
17298  * loaded.  This means that without the right CORS policy, loading templates from a different domain
17299  * won't work on all browsers.  Also, loading templates from `file://` URL does not work on some
17300  * browsers.
17301  *
17302  * ## This feels like too much overhead
17303  *
17304  * It's important to remember that SCE only applies to interpolation expressions.
17305  *
17306  * If your expressions are constant literals, they're automatically trusted and you don't need to
17307  * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
17308  * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
17309  *
17310  * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
17311  * through {@link ng.$sce#getTrusted $sce.getTrusted}.  SCE doesn't play a role here.
17312  *
17313  * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
17314  * templates in `ng-include` from your application's domain without having to even know about SCE.
17315  * It blocks loading templates from other domains or loading templates over http from an https
17316  * served document.  You can change these by setting your own custom {@link
17317  * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
17318  * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
17319  *
17320  * This significantly reduces the overhead.  It is far easier to pay the small overhead and have an
17321  * application that's secure and can be audited to verify that with much more ease than bolting
17322  * security onto an application later.
17323  *
17324  * <a name="contexts"></a>
17325  * ## What trusted context types are supported?
17326  *
17327  * | Context             | Notes          |
17328  * |---------------------|----------------|
17329  * | `$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. |
17330  * | `$sce.CSS`          | For CSS that's safe to source into the application.  Currently unused.  Feel free to use it in your own directives. |
17331  * | `$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. |
17332  * | `$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` (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. |
17333  * | `$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. |
17334  *
17335  * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
17336  *
17337  *  Each element in these arrays must be one of the following:
17338  *
17339  *  - **'self'**
17340  *    - The special **string**, `'self'`, can be used to match against all URLs of the **same
17341  *      domain** as the application document using the **same protocol**.
17342  *  - **String** (except the special value `'self'`)
17343  *    - The string is matched against the full *normalized / absolute URL* of the resource
17344  *      being tested (substring matches are not good enough.)
17345  *    - There are exactly **two wildcard sequences** - `*` and `**`.  All other characters
17346  *      match themselves.
17347  *    - `*`: matches zero or more occurrences of any character other than one of the following 6
17348  *      characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'.  It's a useful wildcard for use
17349  *      in a whitelist.
17350  *    - `**`: matches zero or more occurrences of *any* character.  As such, it's not
17351  *      appropriate for use in a scheme, domain, etc. as it would match too much.  (e.g.
17352  *      http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
17353  *      not have been the intention.)  Its usage at the very end of the path is ok.  (e.g.
17354  *      http://foo.example.com/templates/**).
17355  *  - **RegExp** (*see caveat below*)
17356  *    - *Caveat*:  While regular expressions are powerful and offer great flexibility,  their syntax
17357  *      (and all the inevitable escaping) makes them *harder to maintain*.  It's easy to
17358  *      accidentally introduce a bug when one updates a complex expression (imho, all regexes should
17359  *      have good test coverage).  For instance, the use of `.` in the regex is correct only in a
17360  *      small number of cases.  A `.` character in the regex used when matching the scheme or a
17361  *      subdomain could be matched against a `:` or literal `.` that was likely not intended.   It
17362  *      is highly recommended to use the string patterns and only fall back to regular expressions
17363  *      as a last resort.
17364  *    - The regular expression must be an instance of RegExp (i.e. not a string.)  It is
17365  *      matched against the **entire** *normalized / absolute URL* of the resource being tested
17366  *      (even when the RegExp did not have the `^` and `$` codes.)  In addition, any flags
17367  *      present on the RegExp (such as multiline, global, ignoreCase) are ignored.
17368  *    - If you are generating your JavaScript from some other templating engine (not
17369  *      recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
17370  *      remember to escape your regular expression (and be aware that you might need more than
17371  *      one level of escaping depending on your templating engine and the way you interpolated
17372  *      the value.)  Do make use of your platform's escaping mechanism as it might be good
17373  *      enough before coding your own.  E.g. Ruby has
17374  *      [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
17375  *      and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
17376  *      Javascript lacks a similar built in function for escaping.  Take a look at Google
17377  *      Closure library's [goog.string.regExpEscape(s)](
17378  *      http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
17379  *
17380  * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
17381  *
17382  * ## Show me an example using SCE.
17383  *
17384  * <example module="mySceApp" deps="angular-sanitize.js">
17385  * <file name="index.html">
17386  *   <div ng-controller="AppController as myCtrl">
17387  *     <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
17388  *     <b>User comments</b><br>
17389  *     By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
17390  *     $sanitize is available.  If $sanitize isn't available, this results in an error instead of an
17391  *     exploit.
17392  *     <div class="well">
17393  *       <div ng-repeat="userComment in myCtrl.userComments">
17394  *         <b>{{userComment.name}}</b>:
17395  *         <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
17396  *         <br>
17397  *       </div>
17398  *     </div>
17399  *   </div>
17400  * </file>
17401  *
17402  * <file name="script.js">
17403  *   angular.module('mySceApp', ['ngSanitize'])
17404  *     .controller('AppController', ['$http', '$templateCache', '$sce',
17405  *       function($http, $templateCache, $sce) {
17406  *         var self = this;
17407  *         $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
17408  *           self.userComments = userComments;
17409  *         });
17410  *         self.explicitlyTrustedHtml = $sce.trustAsHtml(
17411  *             '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
17412  *             'sanitization.&quot;">Hover over this text.</span>');
17413  *       }]);
17414  * </file>
17415  *
17416  * <file name="test_data.json">
17417  * [
17418  *   { "name": "Alice",
17419  *     "htmlComment":
17420  *         "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
17421  *   },
17422  *   { "name": "Bob",
17423  *     "htmlComment": "<i>Yes!</i>  Am I the only other one?"
17424  *   }
17425  * ]
17426  * </file>
17427  *
17428  * <file name="protractor.js" type="protractor">
17429  *   describe('SCE doc demo', function() {
17430  *     it('should sanitize untrusted values', function() {
17431  *       expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
17432  *           .toBe('<span>Is <i>anyone</i> reading this?</span>');
17433  *     });
17434  *
17435  *     it('should NOT sanitize explicitly trusted values', function() {
17436  *       expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
17437  *           '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
17438  *           'sanitization.&quot;">Hover over this text.</span>');
17439  *     });
17440  *   });
17441  * </file>
17442  * </example>
17443  *
17444  *
17445  *
17446  * ## Can I disable SCE completely?
17447  *
17448  * Yes, you can.  However, this is strongly discouraged.  SCE gives you a lot of security benefits
17449  * for little coding overhead.  It will be much harder to take an SCE disabled application and
17450  * either secure it on your own or enable SCE at a later stage.  It might make sense to disable SCE
17451  * for cases where you have a lot of existing code that was written before SCE was introduced and
17452  * you're migrating them a module at a time.
17453  *
17454  * That said, here's how you can completely disable SCE:
17455  *
17456  * ```
17457  * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
17458  *   // Completely disable SCE.  For demonstration purposes only!
17459  *   // Do not use in new projects.
17460  *   $sceProvider.enabled(false);
17461  * });
17462  * ```
17463  *
17464  */
17465 /* jshint maxlen: 100 */
17466
17467 function $SceProvider() {
17468   var enabled = true;
17469
17470   /**
17471    * @ngdoc method
17472    * @name $sceProvider#enabled
17473    * @kind function
17474    *
17475    * @param {boolean=} value If provided, then enables/disables SCE.
17476    * @return {boolean} true if SCE is enabled, false otherwise.
17477    *
17478    * @description
17479    * Enables/disables SCE and returns the current value.
17480    */
17481   this.enabled = function(value) {
17482     if (arguments.length) {
17483       enabled = !!value;
17484     }
17485     return enabled;
17486   };
17487
17488
17489   /* Design notes on the default implementation for SCE.
17490    *
17491    * The API contract for the SCE delegate
17492    * -------------------------------------
17493    * The SCE delegate object must provide the following 3 methods:
17494    *
17495    * - trustAs(contextEnum, value)
17496    *     This method is used to tell the SCE service that the provided value is OK to use in the
17497    *     contexts specified by contextEnum.  It must return an object that will be accepted by
17498    *     getTrusted() for a compatible contextEnum and return this value.
17499    *
17500    * - valueOf(value)
17501    *     For values that were not produced by trustAs(), return them as is.  For values that were
17502    *     produced by trustAs(), return the corresponding input value to trustAs.  Basically, if
17503    *     trustAs is wrapping the given values into some type, this operation unwraps it when given
17504    *     such a value.
17505    *
17506    * - getTrusted(contextEnum, value)
17507    *     This function should return the a value that is safe to use in the context specified by
17508    *     contextEnum or throw and exception otherwise.
17509    *
17510    * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
17511    * opaque or wrapped in some holder object.  That happens to be an implementation detail.  For
17512    * instance, an implementation could maintain a registry of all trusted objects by context.  In
17513    * such a case, trustAs() would return the same object that was passed in.  getTrusted() would
17514    * return the same object passed in if it was found in the registry under a compatible context or
17515    * throw an exception otherwise.  An implementation might only wrap values some of the time based
17516    * on some criteria.  getTrusted() might return a value and not throw an exception for special
17517    * constants or objects even if not wrapped.  All such implementations fulfill this contract.
17518    *
17519    *
17520    * A note on the inheritance model for SCE contexts
17521    * ------------------------------------------------
17522    * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types.  This
17523    * is purely an implementation details.
17524    *
17525    * The contract is simply this:
17526    *
17527    *     getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
17528    *     will also succeed.
17529    *
17530    * Inheritance happens to capture this in a natural way.  In some future, we
17531    * may not use inheritance anymore.  That is OK because no code outside of
17532    * sce.js and sceSpecs.js would need to be aware of this detail.
17533    */
17534
17535   this.$get = ['$parse', '$sceDelegate', function(
17536                 $parse,   $sceDelegate) {
17537     // Prereq: Ensure that we're not running in IE<11 quirks mode.  In that mode, IE < 11 allow
17538     // the "expression(javascript expression)" syntax which is insecure.
17539     if (enabled && msie < 8) {
17540       throw $sceMinErr('iequirks',
17541         'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
17542         'mode.  You can fix this by adding the text <!doctype html> to the top of your HTML ' +
17543         'document.  See http://docs.angularjs.org/api/ng.$sce for more information.');
17544     }
17545
17546     var sce = shallowCopy(SCE_CONTEXTS);
17547
17548     /**
17549      * @ngdoc method
17550      * @name $sce#isEnabled
17551      * @kind function
17552      *
17553      * @return {Boolean} true if SCE is enabled, false otherwise.  If you want to set the value, you
17554      * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
17555      *
17556      * @description
17557      * Returns a boolean indicating if SCE is enabled.
17558      */
17559     sce.isEnabled = function() {
17560       return enabled;
17561     };
17562     sce.trustAs = $sceDelegate.trustAs;
17563     sce.getTrusted = $sceDelegate.getTrusted;
17564     sce.valueOf = $sceDelegate.valueOf;
17565
17566     if (!enabled) {
17567       sce.trustAs = sce.getTrusted = function(type, value) { return value; };
17568       sce.valueOf = identity;
17569     }
17570
17571     /**
17572      * @ngdoc method
17573      * @name $sce#parseAs
17574      *
17575      * @description
17576      * Converts Angular {@link guide/expression expression} into a function.  This is like {@link
17577      * ng.$parse $parse} and is identical when the expression is a literal constant.  Otherwise, it
17578      * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
17579      * *result*)}
17580      *
17581      * @param {string} type The kind of SCE context in which this result will be used.
17582      * @param {string} expression String expression to compile.
17583      * @returns {function(context, locals)} a function which represents the compiled expression:
17584      *
17585      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
17586      *      are evaluated against (typically a scope object).
17587      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
17588      *      `context`.
17589      */
17590     sce.parseAs = function sceParseAs(type, expr) {
17591       var parsed = $parse(expr);
17592       if (parsed.literal && parsed.constant) {
17593         return parsed;
17594       } else {
17595         return $parse(expr, function(value) {
17596           return sce.getTrusted(type, value);
17597         });
17598       }
17599     };
17600
17601     /**
17602      * @ngdoc method
17603      * @name $sce#trustAs
17604      *
17605      * @description
17606      * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.  As such,
17607      * returns an object that is trusted by angular for use in specified strict contextual
17608      * escaping contexts (such as ng-bind-html, ng-include, any src attribute
17609      * interpolation, any dom event binding attribute interpolation such as for onclick,  etc.)
17610      * that uses the provided value.  See * {@link ng.$sce $sce} for enabling strict contextual
17611      * escaping.
17612      *
17613      * @param {string} type The kind of context in which this value is safe for use.  e.g. url,
17614      *   resourceUrl, html, js and css.
17615      * @param {*} value The value that that should be considered trusted/safe.
17616      * @returns {*} A value that can be used to stand in for the provided `value` in places
17617      * where Angular expects a $sce.trustAs() return value.
17618      */
17619
17620     /**
17621      * @ngdoc method
17622      * @name $sce#trustAsHtml
17623      *
17624      * @description
17625      * Shorthand method.  `$sce.trustAsHtml(value)` →
17626      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
17627      *
17628      * @param {*} value The value to trustAs.
17629      * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
17630      *     $sce.getTrustedHtml(value)} to obtain the original value.  (privileged directives
17631      *     only accept expressions that are either literal constants or are the
17632      *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
17633      */
17634
17635     /**
17636      * @ngdoc method
17637      * @name $sce#trustAsUrl
17638      *
17639      * @description
17640      * Shorthand method.  `$sce.trustAsUrl(value)` →
17641      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
17642      *
17643      * @param {*} value The value to trustAs.
17644      * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
17645      *     $sce.getTrustedUrl(value)} to obtain the original value.  (privileged directives
17646      *     only accept expressions that are either literal constants or are the
17647      *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
17648      */
17649
17650     /**
17651      * @ngdoc method
17652      * @name $sce#trustAsResourceUrl
17653      *
17654      * @description
17655      * Shorthand method.  `$sce.trustAsResourceUrl(value)` →
17656      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
17657      *
17658      * @param {*} value The value to trustAs.
17659      * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
17660      *     $sce.getTrustedResourceUrl(value)} to obtain the original value.  (privileged directives
17661      *     only accept expressions that are either literal constants or are the return
17662      *     value of {@link ng.$sce#trustAs $sce.trustAs}.)
17663      */
17664
17665     /**
17666      * @ngdoc method
17667      * @name $sce#trustAsJs
17668      *
17669      * @description
17670      * Shorthand method.  `$sce.trustAsJs(value)` →
17671      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
17672      *
17673      * @param {*} value The value to trustAs.
17674      * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
17675      *     $sce.getTrustedJs(value)} to obtain the original value.  (privileged directives
17676      *     only accept expressions that are either literal constants or are the
17677      *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
17678      */
17679
17680     /**
17681      * @ngdoc method
17682      * @name $sce#getTrusted
17683      *
17684      * @description
17685      * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}.  As such,
17686      * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
17687      * originally supplied value if the queried context type is a supertype of the created type.
17688      * If this condition isn't satisfied, throws an exception.
17689      *
17690      * @param {string} type The kind of context in which this value is to be used.
17691      * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
17692      *                         call.
17693      * @returns {*} The value the was originally provided to
17694      *              {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
17695      *              Otherwise, throws an exception.
17696      */
17697
17698     /**
17699      * @ngdoc method
17700      * @name $sce#getTrustedHtml
17701      *
17702      * @description
17703      * Shorthand method.  `$sce.getTrustedHtml(value)` →
17704      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
17705      *
17706      * @param {*} value The value to pass to `$sce.getTrusted`.
17707      * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
17708      */
17709
17710     /**
17711      * @ngdoc method
17712      * @name $sce#getTrustedCss
17713      *
17714      * @description
17715      * Shorthand method.  `$sce.getTrustedCss(value)` →
17716      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
17717      *
17718      * @param {*} value The value to pass to `$sce.getTrusted`.
17719      * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
17720      */
17721
17722     /**
17723      * @ngdoc method
17724      * @name $sce#getTrustedUrl
17725      *
17726      * @description
17727      * Shorthand method.  `$sce.getTrustedUrl(value)` →
17728      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
17729      *
17730      * @param {*} value The value to pass to `$sce.getTrusted`.
17731      * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
17732      */
17733
17734     /**
17735      * @ngdoc method
17736      * @name $sce#getTrustedResourceUrl
17737      *
17738      * @description
17739      * Shorthand method.  `$sce.getTrustedResourceUrl(value)` →
17740      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
17741      *
17742      * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
17743      * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
17744      */
17745
17746     /**
17747      * @ngdoc method
17748      * @name $sce#getTrustedJs
17749      *
17750      * @description
17751      * Shorthand method.  `$sce.getTrustedJs(value)` →
17752      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
17753      *
17754      * @param {*} value The value to pass to `$sce.getTrusted`.
17755      * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
17756      */
17757
17758     /**
17759      * @ngdoc method
17760      * @name $sce#parseAsHtml
17761      *
17762      * @description
17763      * Shorthand method.  `$sce.parseAsHtml(expression string)` →
17764      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
17765      *
17766      * @param {string} expression String expression to compile.
17767      * @returns {function(context, locals)} a function which represents the compiled expression:
17768      *
17769      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
17770      *      are evaluated against (typically a scope object).
17771      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
17772      *      `context`.
17773      */
17774
17775     /**
17776      * @ngdoc method
17777      * @name $sce#parseAsCss
17778      *
17779      * @description
17780      * Shorthand method.  `$sce.parseAsCss(value)` →
17781      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
17782      *
17783      * @param {string} expression String expression to compile.
17784      * @returns {function(context, locals)} a function which represents the compiled expression:
17785      *
17786      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
17787      *      are evaluated against (typically a scope object).
17788      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
17789      *      `context`.
17790      */
17791
17792     /**
17793      * @ngdoc method
17794      * @name $sce#parseAsUrl
17795      *
17796      * @description
17797      * Shorthand method.  `$sce.parseAsUrl(value)` →
17798      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
17799      *
17800      * @param {string} expression String expression to compile.
17801      * @returns {function(context, locals)} a function which represents the compiled expression:
17802      *
17803      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
17804      *      are evaluated against (typically a scope object).
17805      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
17806      *      `context`.
17807      */
17808
17809     /**
17810      * @ngdoc method
17811      * @name $sce#parseAsResourceUrl
17812      *
17813      * @description
17814      * Shorthand method.  `$sce.parseAsResourceUrl(value)` →
17815      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
17816      *
17817      * @param {string} expression String expression to compile.
17818      * @returns {function(context, locals)} a function which represents the compiled expression:
17819      *
17820      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
17821      *      are evaluated against (typically a scope object).
17822      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
17823      *      `context`.
17824      */
17825
17826     /**
17827      * @ngdoc method
17828      * @name $sce#parseAsJs
17829      *
17830      * @description
17831      * Shorthand method.  `$sce.parseAsJs(value)` →
17832      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
17833      *
17834      * @param {string} expression String expression to compile.
17835      * @returns {function(context, locals)} a function which represents the compiled expression:
17836      *
17837      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
17838      *      are evaluated against (typically a scope object).
17839      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
17840      *      `context`.
17841      */
17842
17843     // Shorthand delegations.
17844     var parse = sce.parseAs,
17845         getTrusted = sce.getTrusted,
17846         trustAs = sce.trustAs;
17847
17848     forEach(SCE_CONTEXTS, function(enumValue, name) {
17849       var lName = lowercase(name);
17850       sce[camelCase("parse_as_" + lName)] = function(expr) {
17851         return parse(enumValue, expr);
17852       };
17853       sce[camelCase("get_trusted_" + lName)] = function(value) {
17854         return getTrusted(enumValue, value);
17855       };
17856       sce[camelCase("trust_as_" + lName)] = function(value) {
17857         return trustAs(enumValue, value);
17858       };
17859     });
17860
17861     return sce;
17862   }];
17863 }
17864
17865 /**
17866  * !!! This is an undocumented "private" service !!!
17867  *
17868  * @name $sniffer
17869  * @requires $window
17870  * @requires $document
17871  *
17872  * @property {boolean} history Does the browser support html5 history api ?
17873  * @property {boolean} transitions Does the browser support CSS transition events ?
17874  * @property {boolean} animations Does the browser support CSS animation events ?
17875  *
17876  * @description
17877  * This is very simple implementation of testing browser's features.
17878  */
17879 function $SnifferProvider() {
17880   this.$get = ['$window', '$document', function($window, $document) {
17881     var eventSupport = {},
17882         android =
17883           toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
17884         boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
17885         document = $document[0] || {},
17886         vendorPrefix,
17887         vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
17888         bodyStyle = document.body && document.body.style,
17889         transitions = false,
17890         animations = false,
17891         match;
17892
17893     if (bodyStyle) {
17894       for (var prop in bodyStyle) {
17895         if (match = vendorRegex.exec(prop)) {
17896           vendorPrefix = match[0];
17897           vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
17898           break;
17899         }
17900       }
17901
17902       if (!vendorPrefix) {
17903         vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
17904       }
17905
17906       transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
17907       animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
17908
17909       if (android && (!transitions ||  !animations)) {
17910         transitions = isString(bodyStyle.webkitTransition);
17911         animations = isString(bodyStyle.webkitAnimation);
17912       }
17913     }
17914
17915
17916     return {
17917       // Android has history.pushState, but it does not update location correctly
17918       // so let's not use the history API at all.
17919       // http://code.google.com/p/android/issues/detail?id=17471
17920       // https://github.com/angular/angular.js/issues/904
17921
17922       // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
17923       // so let's not use the history API also
17924       // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
17925       // jshint -W018
17926       history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
17927       // jshint +W018
17928       hasEvent: function(event) {
17929         // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
17930         // it. In particular the event is not fired when backspace or delete key are pressed or
17931         // when cut operation is performed.
17932         // IE10+ implements 'input' event but it erroneously fires under various situations,
17933         // e.g. when placeholder changes, or a form is focused.
17934         if (event === 'input' && msie <= 11) return false;
17935
17936         if (isUndefined(eventSupport[event])) {
17937           var divElm = document.createElement('div');
17938           eventSupport[event] = 'on' + event in divElm;
17939         }
17940
17941         return eventSupport[event];
17942       },
17943       csp: csp(),
17944       vendorPrefix: vendorPrefix,
17945       transitions: transitions,
17946       animations: animations,
17947       android: android
17948     };
17949   }];
17950 }
17951
17952 var $compileMinErr = minErr('$compile');
17953
17954 /**
17955  * @ngdoc provider
17956  * @name $templateRequestProvider
17957  * @description
17958  * Used to configure the options passed to the {@link $http} service when making a template request.
17959  *
17960  * For example, it can be used for specifying the "Accept" header that is sent to the server, when
17961  * requesting a template.
17962  */
17963 function $TemplateRequestProvider() {
17964
17965   var httpOptions;
17966
17967   /**
17968    * @ngdoc method
17969    * @name $templateRequestProvider#httpOptions
17970    * @description
17971    * The options to be passed to the {@link $http} service when making the request.
17972    * You can use this to override options such as the "Accept" header for template requests.
17973    *
17974    * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
17975    * options if not overridden here.
17976    *
17977    * @param {string=} value new value for the {@link $http} options.
17978    * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
17979    */
17980   this.httpOptions = function(val) {
17981     if (val) {
17982       httpOptions = val;
17983       return this;
17984     }
17985     return httpOptions;
17986   };
17987
17988   /**
17989    * @ngdoc service
17990    * @name $templateRequest
17991    *
17992    * @description
17993    * The `$templateRequest` service runs security checks then downloads the provided template using
17994    * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
17995    * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
17996    * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
17997    * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
17998    * when `tpl` is of type string and `$templateCache` has the matching entry.
17999    *
18000    * If you want to pass custom options to the `$http` service, such as setting the Accept header you
18001    * can configure this via {@link $templateRequestProvider#httpOptions}.
18002    *
18003    * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
18004    * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
18005    *
18006    * @return {Promise} a promise for the HTTP response data of the given URL.
18007    *
18008    * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
18009    */
18010   this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
18011
18012     function handleRequestFn(tpl, ignoreRequestError) {
18013       handleRequestFn.totalPendingRequests++;
18014
18015       // We consider the template cache holds only trusted templates, so
18016       // there's no need to go through whitelisting again for keys that already
18017       // are included in there. This also makes Angular accept any script
18018       // directive, no matter its name. However, we still need to unwrap trusted
18019       // types.
18020       if (!isString(tpl) || !$templateCache.get(tpl)) {
18021         tpl = $sce.getTrustedResourceUrl(tpl);
18022       }
18023
18024       var transformResponse = $http.defaults && $http.defaults.transformResponse;
18025
18026       if (isArray(transformResponse)) {
18027         transformResponse = transformResponse.filter(function(transformer) {
18028           return transformer !== defaultHttpResponseTransform;
18029         });
18030       } else if (transformResponse === defaultHttpResponseTransform) {
18031         transformResponse = null;
18032       }
18033
18034       return $http.get(tpl, extend({
18035           cache: $templateCache,
18036           transformResponse: transformResponse
18037         }, httpOptions))
18038         ['finally'](function() {
18039           handleRequestFn.totalPendingRequests--;
18040         })
18041         .then(function(response) {
18042           $templateCache.put(tpl, response.data);
18043           return response.data;
18044         }, handleError);
18045
18046       function handleError(resp) {
18047         if (!ignoreRequestError) {
18048           throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
18049             tpl, resp.status, resp.statusText);
18050         }
18051         return $q.reject(resp);
18052       }
18053     }
18054
18055     handleRequestFn.totalPendingRequests = 0;
18056
18057     return handleRequestFn;
18058   }];
18059 }
18060
18061 function $$TestabilityProvider() {
18062   this.$get = ['$rootScope', '$browser', '$location',
18063        function($rootScope,   $browser,   $location) {
18064
18065     /**
18066      * @name $testability
18067      *
18068      * @description
18069      * The private $$testability service provides a collection of methods for use when debugging
18070      * or by automated test and debugging tools.
18071      */
18072     var testability = {};
18073
18074     /**
18075      * @name $$testability#findBindings
18076      *
18077      * @description
18078      * Returns an array of elements that are bound (via ng-bind or {{}})
18079      * to expressions matching the input.
18080      *
18081      * @param {Element} element The element root to search from.
18082      * @param {string} expression The binding expression to match.
18083      * @param {boolean} opt_exactMatch If true, only returns exact matches
18084      *     for the expression. Filters and whitespace are ignored.
18085      */
18086     testability.findBindings = function(element, expression, opt_exactMatch) {
18087       var bindings = element.getElementsByClassName('ng-binding');
18088       var matches = [];
18089       forEach(bindings, function(binding) {
18090         var dataBinding = angular.element(binding).data('$binding');
18091         if (dataBinding) {
18092           forEach(dataBinding, function(bindingName) {
18093             if (opt_exactMatch) {
18094               var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
18095               if (matcher.test(bindingName)) {
18096                 matches.push(binding);
18097               }
18098             } else {
18099               if (bindingName.indexOf(expression) != -1) {
18100                 matches.push(binding);
18101               }
18102             }
18103           });
18104         }
18105       });
18106       return matches;
18107     };
18108
18109     /**
18110      * @name $$testability#findModels
18111      *
18112      * @description
18113      * Returns an array of elements that are two-way found via ng-model to
18114      * expressions matching the input.
18115      *
18116      * @param {Element} element The element root to search from.
18117      * @param {string} expression The model expression to match.
18118      * @param {boolean} opt_exactMatch If true, only returns exact matches
18119      *     for the expression.
18120      */
18121     testability.findModels = function(element, expression, opt_exactMatch) {
18122       var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
18123       for (var p = 0; p < prefixes.length; ++p) {
18124         var attributeEquals = opt_exactMatch ? '=' : '*=';
18125         var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
18126         var elements = element.querySelectorAll(selector);
18127         if (elements.length) {
18128           return elements;
18129         }
18130       }
18131     };
18132
18133     /**
18134      * @name $$testability#getLocation
18135      *
18136      * @description
18137      * Shortcut for getting the location in a browser agnostic way. Returns
18138      *     the path, search, and hash. (e.g. /path?a=b#hash)
18139      */
18140     testability.getLocation = function() {
18141       return $location.url();
18142     };
18143
18144     /**
18145      * @name $$testability#setLocation
18146      *
18147      * @description
18148      * Shortcut for navigating to a location without doing a full page reload.
18149      *
18150      * @param {string} url The location url (path, search and hash,
18151      *     e.g. /path?a=b#hash) to go to.
18152      */
18153     testability.setLocation = function(url) {
18154       if (url !== $location.url()) {
18155         $location.url(url);
18156         $rootScope.$digest();
18157       }
18158     };
18159
18160     /**
18161      * @name $$testability#whenStable
18162      *
18163      * @description
18164      * Calls the callback when $timeout and $http requests are completed.
18165      *
18166      * @param {function} callback
18167      */
18168     testability.whenStable = function(callback) {
18169       $browser.notifyWhenNoOutstandingRequests(callback);
18170     };
18171
18172     return testability;
18173   }];
18174 }
18175
18176 function $TimeoutProvider() {
18177   this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
18178        function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {
18179
18180     var deferreds = {};
18181
18182
18183      /**
18184       * @ngdoc service
18185       * @name $timeout
18186       *
18187       * @description
18188       * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
18189       * block and delegates any exceptions to
18190       * {@link ng.$exceptionHandler $exceptionHandler} service.
18191       *
18192       * The return value of calling `$timeout` is a promise, which will be resolved when
18193       * the delay has passed and the timeout function, if provided, is executed.
18194       *
18195       * To cancel a timeout request, call `$timeout.cancel(promise)`.
18196       *
18197       * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
18198       * synchronously flush the queue of deferred functions.
18199       *
18200       * If you only want a promise that will be resolved after some specified delay
18201       * then you can call `$timeout` without the `fn` function.
18202       *
18203       * @param {function()=} fn A function, whose execution should be delayed.
18204       * @param {number=} [delay=0] Delay in milliseconds.
18205       * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
18206       *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
18207       * @param {...*=} Pass additional parameters to the executed function.
18208       * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
18209       *   promise will be resolved with is the return value of the `fn` function.
18210       *
18211       */
18212     function timeout(fn, delay, invokeApply) {
18213       if (!isFunction(fn)) {
18214         invokeApply = delay;
18215         delay = fn;
18216         fn = noop;
18217       }
18218
18219       var args = sliceArgs(arguments, 3),
18220           skipApply = (isDefined(invokeApply) && !invokeApply),
18221           deferred = (skipApply ? $$q : $q).defer(),
18222           promise = deferred.promise,
18223           timeoutId;
18224
18225       timeoutId = $browser.defer(function() {
18226         try {
18227           deferred.resolve(fn.apply(null, args));
18228         } catch (e) {
18229           deferred.reject(e);
18230           $exceptionHandler(e);
18231         }
18232         finally {
18233           delete deferreds[promise.$$timeoutId];
18234         }
18235
18236         if (!skipApply) $rootScope.$apply();
18237       }, delay);
18238
18239       promise.$$timeoutId = timeoutId;
18240       deferreds[timeoutId] = deferred;
18241
18242       return promise;
18243     }
18244
18245
18246      /**
18247       * @ngdoc method
18248       * @name $timeout#cancel
18249       *
18250       * @description
18251       * Cancels a task associated with the `promise`. As a result of this, the promise will be
18252       * resolved with a rejection.
18253       *
18254       * @param {Promise=} promise Promise returned by the `$timeout` function.
18255       * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
18256       *   canceled.
18257       */
18258     timeout.cancel = function(promise) {
18259       if (promise && promise.$$timeoutId in deferreds) {
18260         deferreds[promise.$$timeoutId].reject('canceled');
18261         delete deferreds[promise.$$timeoutId];
18262         return $browser.defer.cancel(promise.$$timeoutId);
18263       }
18264       return false;
18265     };
18266
18267     return timeout;
18268   }];
18269 }
18270
18271 // NOTE:  The usage of window and document instead of $window and $document here is
18272 // deliberate.  This service depends on the specific behavior of anchor nodes created by the
18273 // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
18274 // cause us to break tests.  In addition, when the browser resolves a URL for XHR, it
18275 // doesn't know about mocked locations and resolves URLs to the real document - which is
18276 // exactly the behavior needed here.  There is little value is mocking these out for this
18277 // service.
18278 var urlParsingNode = document.createElement("a");
18279 var originUrl = urlResolve(window.location.href);
18280
18281
18282 /**
18283  *
18284  * Implementation Notes for non-IE browsers
18285  * ----------------------------------------
18286  * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
18287  * results both in the normalizing and parsing of the URL.  Normalizing means that a relative
18288  * URL will be resolved into an absolute URL in the context of the application document.
18289  * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
18290  * properties are all populated to reflect the normalized URL.  This approach has wide
18291  * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc.  See
18292  * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
18293  *
18294  * Implementation Notes for IE
18295  * ---------------------------
18296  * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
18297  * browsers.  However, the parsed components will not be set if the URL assigned did not specify
18298  * them.  (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.)  We
18299  * work around that by performing the parsing in a 2nd step by taking a previously normalized
18300  * URL (e.g. by assigning to a.href) and assigning it a.href again.  This correctly populates the
18301  * properties such as protocol, hostname, port, etc.
18302  *
18303  * References:
18304  *   http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
18305  *   http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
18306  *   http://url.spec.whatwg.org/#urlutils
18307  *   https://github.com/angular/angular.js/pull/2902
18308  *   http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
18309  *
18310  * @kind function
18311  * @param {string} url The URL to be parsed.
18312  * @description Normalizes and parses a URL.
18313  * @returns {object} Returns the normalized URL as a dictionary.
18314  *
18315  *   | member name   | Description    |
18316  *   |---------------|----------------|
18317  *   | href          | A normalized version of the provided URL if it was not an absolute URL |
18318  *   | protocol      | The protocol including the trailing colon                              |
18319  *   | host          | The host and port (if the port is non-default) of the normalizedUrl    |
18320  *   | search        | The search params, minus the question mark                             |
18321  *   | hash          | The hash string, minus the hash symbol
18322  *   | hostname      | The hostname
18323  *   | port          | The port, without ":"
18324  *   | pathname      | The pathname, beginning with "/"
18325  *
18326  */
18327 function urlResolve(url) {
18328   var href = url;
18329
18330   if (msie) {
18331     // Normalize before parse.  Refer Implementation Notes on why this is
18332     // done in two steps on IE.
18333     urlParsingNode.setAttribute("href", href);
18334     href = urlParsingNode.href;
18335   }
18336
18337   urlParsingNode.setAttribute('href', href);
18338
18339   // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
18340   return {
18341     href: urlParsingNode.href,
18342     protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
18343     host: urlParsingNode.host,
18344     search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
18345     hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
18346     hostname: urlParsingNode.hostname,
18347     port: urlParsingNode.port,
18348     pathname: (urlParsingNode.pathname.charAt(0) === '/')
18349       ? urlParsingNode.pathname
18350       : '/' + urlParsingNode.pathname
18351   };
18352 }
18353
18354 /**
18355  * Parse a request URL and determine whether this is a same-origin request as the application document.
18356  *
18357  * @param {string|object} requestUrl The url of the request as a string that will be resolved
18358  * or a parsed URL object.
18359  * @returns {boolean} Whether the request is for the same origin as the application document.
18360  */
18361 function urlIsSameOrigin(requestUrl) {
18362   var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
18363   return (parsed.protocol === originUrl.protocol &&
18364           parsed.host === originUrl.host);
18365 }
18366
18367 /**
18368  * @ngdoc service
18369  * @name $window
18370  *
18371  * @description
18372  * A reference to the browser's `window` object. While `window`
18373  * is globally available in JavaScript, it causes testability problems, because
18374  * it is a global variable. In angular we always refer to it through the
18375  * `$window` service, so it may be overridden, removed or mocked for testing.
18376  *
18377  * Expressions, like the one defined for the `ngClick` directive in the example
18378  * below, are evaluated with respect to the current scope.  Therefore, there is
18379  * no risk of inadvertently coding in a dependency on a global value in such an
18380  * expression.
18381  *
18382  * @example
18383    <example module="windowExample">
18384      <file name="index.html">
18385        <script>
18386          angular.module('windowExample', [])
18387            .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
18388              $scope.greeting = 'Hello, World!';
18389              $scope.doGreeting = function(greeting) {
18390                $window.alert(greeting);
18391              };
18392            }]);
18393        </script>
18394        <div ng-controller="ExampleController">
18395          <input type="text" ng-model="greeting" aria-label="greeting" />
18396          <button ng-click="doGreeting(greeting)">ALERT</button>
18397        </div>
18398      </file>
18399      <file name="protractor.js" type="protractor">
18400       it('should display the greeting in the input box', function() {
18401        element(by.model('greeting')).sendKeys('Hello, E2E Tests');
18402        // If we click the button it will block the test runner
18403        // element(':button').click();
18404       });
18405      </file>
18406    </example>
18407  */
18408 function $WindowProvider() {
18409   this.$get = valueFn(window);
18410 }
18411
18412 /**
18413  * @name $$cookieReader
18414  * @requires $document
18415  *
18416  * @description
18417  * This is a private service for reading cookies used by $http and ngCookies
18418  *
18419  * @return {Object} a key/value map of the current cookies
18420  */
18421 function $$CookieReader($document) {
18422   var rawDocument = $document[0] || {};
18423   var lastCookies = {};
18424   var lastCookieString = '';
18425
18426   function safeDecodeURIComponent(str) {
18427     try {
18428       return decodeURIComponent(str);
18429     } catch (e) {
18430       return str;
18431     }
18432   }
18433
18434   return function() {
18435     var cookieArray, cookie, i, index, name;
18436     var currentCookieString = rawDocument.cookie || '';
18437
18438     if (currentCookieString !== lastCookieString) {
18439       lastCookieString = currentCookieString;
18440       cookieArray = lastCookieString.split('; ');
18441       lastCookies = {};
18442
18443       for (i = 0; i < cookieArray.length; i++) {
18444         cookie = cookieArray[i];
18445         index = cookie.indexOf('=');
18446         if (index > 0) { //ignore nameless cookies
18447           name = safeDecodeURIComponent(cookie.substring(0, index));
18448           // the first value that is seen for a cookie is the most
18449           // specific one.  values for the same cookie name that
18450           // follow are for less specific paths.
18451           if (isUndefined(lastCookies[name])) {
18452             lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
18453           }
18454         }
18455       }
18456     }
18457     return lastCookies;
18458   };
18459 }
18460
18461 $$CookieReader.$inject = ['$document'];
18462
18463 function $$CookieReaderProvider() {
18464   this.$get = $$CookieReader;
18465 }
18466
18467 /* global currencyFilter: true,
18468  dateFilter: true,
18469  filterFilter: true,
18470  jsonFilter: true,
18471  limitToFilter: true,
18472  lowercaseFilter: true,
18473  numberFilter: true,
18474  orderByFilter: true,
18475  uppercaseFilter: true,
18476  */
18477
18478 /**
18479  * @ngdoc provider
18480  * @name $filterProvider
18481  * @description
18482  *
18483  * Filters are just functions which transform input to an output. However filters need to be
18484  * Dependency Injected. To achieve this a filter definition consists of a factory function which is
18485  * annotated with dependencies and is responsible for creating a filter function.
18486  *
18487  * <div class="alert alert-warning">
18488  * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
18489  * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
18490  * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
18491  * (`myapp_subsection_filterx`).
18492  * </div>
18493  *
18494  * ```js
18495  *   // Filter registration
18496  *   function MyModule($provide, $filterProvider) {
18497  *     // create a service to demonstrate injection (not always needed)
18498  *     $provide.value('greet', function(name){
18499  *       return 'Hello ' + name + '!';
18500  *     });
18501  *
18502  *     // register a filter factory which uses the
18503  *     // greet service to demonstrate DI.
18504  *     $filterProvider.register('greet', function(greet){
18505  *       // return the filter function which uses the greet service
18506  *       // to generate salutation
18507  *       return function(text) {
18508  *         // filters need to be forgiving so check input validity
18509  *         return text && greet(text) || text;
18510  *       };
18511  *     });
18512  *   }
18513  * ```
18514  *
18515  * The filter function is registered with the `$injector` under the filter name suffix with
18516  * `Filter`.
18517  *
18518  * ```js
18519  *   it('should be the same instance', inject(
18520  *     function($filterProvider) {
18521  *       $filterProvider.register('reverse', function(){
18522  *         return ...;
18523  *       });
18524  *     },
18525  *     function($filter, reverseFilter) {
18526  *       expect($filter('reverse')).toBe(reverseFilter);
18527  *     });
18528  * ```
18529  *
18530  *
18531  * For more information about how angular filters work, and how to create your own filters, see
18532  * {@link guide/filter Filters} in the Angular Developer Guide.
18533  */
18534
18535 /**
18536  * @ngdoc service
18537  * @name $filter
18538  * @kind function
18539  * @description
18540  * Filters are used for formatting data displayed to the user.
18541  *
18542  * The general syntax in templates is as follows:
18543  *
18544  *         {{ expression [| filter_name[:parameter_value] ... ] }}
18545  *
18546  * @param {String} name Name of the filter function to retrieve
18547  * @return {Function} the filter function
18548  * @example
18549    <example name="$filter" module="filterExample">
18550      <file name="index.html">
18551        <div ng-controller="MainCtrl">
18552         <h3>{{ originalText }}</h3>
18553         <h3>{{ filteredText }}</h3>
18554        </div>
18555      </file>
18556
18557      <file name="script.js">
18558       angular.module('filterExample', [])
18559       .controller('MainCtrl', function($scope, $filter) {
18560         $scope.originalText = 'hello';
18561         $scope.filteredText = $filter('uppercase')($scope.originalText);
18562       });
18563      </file>
18564    </example>
18565   */
18566 $FilterProvider.$inject = ['$provide'];
18567 function $FilterProvider($provide) {
18568   var suffix = 'Filter';
18569
18570   /**
18571    * @ngdoc method
18572    * @name $filterProvider#register
18573    * @param {string|Object} name Name of the filter function, or an object map of filters where
18574    *    the keys are the filter names and the values are the filter factories.
18575    *
18576    *    <div class="alert alert-warning">
18577    *    **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
18578    *    Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
18579    *    your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
18580    *    (`myapp_subsection_filterx`).
18581    *    </div>
18582     * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
18583    * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
18584    *    of the registered filter instances.
18585    */
18586   function register(name, factory) {
18587     if (isObject(name)) {
18588       var filters = {};
18589       forEach(name, function(filter, key) {
18590         filters[key] = register(key, filter);
18591       });
18592       return filters;
18593     } else {
18594       return $provide.factory(name + suffix, factory);
18595     }
18596   }
18597   this.register = register;
18598
18599   this.$get = ['$injector', function($injector) {
18600     return function(name) {
18601       return $injector.get(name + suffix);
18602     };
18603   }];
18604
18605   ////////////////////////////////////////
18606
18607   /* global
18608     currencyFilter: false,
18609     dateFilter: false,
18610     filterFilter: false,
18611     jsonFilter: false,
18612     limitToFilter: false,
18613     lowercaseFilter: false,
18614     numberFilter: false,
18615     orderByFilter: false,
18616     uppercaseFilter: false,
18617   */
18618
18619   register('currency', currencyFilter);
18620   register('date', dateFilter);
18621   register('filter', filterFilter);
18622   register('json', jsonFilter);
18623   register('limitTo', limitToFilter);
18624   register('lowercase', lowercaseFilter);
18625   register('number', numberFilter);
18626   register('orderBy', orderByFilter);
18627   register('uppercase', uppercaseFilter);
18628 }
18629
18630 /**
18631  * @ngdoc filter
18632  * @name filter
18633  * @kind function
18634  *
18635  * @description
18636  * Selects a subset of items from `array` and returns it as a new array.
18637  *
18638  * @param {Array} array The source array.
18639  * @param {string|Object|function()} expression The predicate to be used for selecting items from
18640  *   `array`.
18641  *
18642  *   Can be one of:
18643  *
18644  *   - `string`: The string is used for matching against the contents of the `array`. All strings or
18645  *     objects with string properties in `array` that match this string will be returned. This also
18646  *     applies to nested object properties.
18647  *     The predicate can be negated by prefixing the string with `!`.
18648  *
18649  *   - `Object`: A pattern object can be used to filter specific properties on objects contained
18650  *     by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
18651  *     which have property `name` containing "M" and property `phone` containing "1". A special
18652  *     property name `$` can be used (as in `{$:"text"}`) to accept a match against any
18653  *     property of the object or its nested object properties. That's equivalent to the simple
18654  *     substring match with a `string` as described above. The predicate can be negated by prefixing
18655  *     the string with `!`.
18656  *     For example `{name: "!M"}` predicate will return an array of items which have property `name`
18657  *     not containing "M".
18658  *
18659  *     Note that a named property will match properties on the same level only, while the special
18660  *     `$` property will match properties on the same level or deeper. E.g. an array item like
18661  *     `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
18662  *     **will** be matched by `{$: 'John'}`.
18663  *
18664  *   - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
18665  *     The function is called for each element of the array, with the element, its index, and
18666  *     the entire array itself as arguments.
18667  *
18668  *     The final result is an array of those elements that the predicate returned true for.
18669  *
18670  * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
18671  *     determining if the expected value (from the filter expression) and actual value (from
18672  *     the object in the array) should be considered a match.
18673  *
18674  *   Can be one of:
18675  *
18676  *   - `function(actual, expected)`:
18677  *     The function will be given the object value and the predicate value to compare and
18678  *     should return true if both values should be considered equal.
18679  *
18680  *   - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
18681  *     This is essentially strict comparison of expected and actual.
18682  *
18683  *   - `false|undefined`: A short hand for a function which will look for a substring match in case
18684  *     insensitive way.
18685  *
18686  *     Primitive values are converted to strings. Objects are not compared against primitives,
18687  *     unless they have a custom `toString` method (e.g. `Date` objects).
18688  *
18689  * @example
18690    <example>
18691      <file name="index.html">
18692        <div ng-init="friends = [{name:'John', phone:'555-1276'},
18693                                 {name:'Mary', phone:'800-BIG-MARY'},
18694                                 {name:'Mike', phone:'555-4321'},
18695                                 {name:'Adam', phone:'555-5678'},
18696                                 {name:'Julie', phone:'555-8765'},
18697                                 {name:'Juliette', phone:'555-5678'}]"></div>
18698
18699        <label>Search: <input ng-model="searchText"></label>
18700        <table id="searchTextResults">
18701          <tr><th>Name</th><th>Phone</th></tr>
18702          <tr ng-repeat="friend in friends | filter:searchText">
18703            <td>{{friend.name}}</td>
18704            <td>{{friend.phone}}</td>
18705          </tr>
18706        </table>
18707        <hr>
18708        <label>Any: <input ng-model="search.$"></label> <br>
18709        <label>Name only <input ng-model="search.name"></label><br>
18710        <label>Phone only <input ng-model="search.phone"></label><br>
18711        <label>Equality <input type="checkbox" ng-model="strict"></label><br>
18712        <table id="searchObjResults">
18713          <tr><th>Name</th><th>Phone</th></tr>
18714          <tr ng-repeat="friendObj in friends | filter:search:strict">
18715            <td>{{friendObj.name}}</td>
18716            <td>{{friendObj.phone}}</td>
18717          </tr>
18718        </table>
18719      </file>
18720      <file name="protractor.js" type="protractor">
18721        var expectFriendNames = function(expectedNames, key) {
18722          element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
18723            arr.forEach(function(wd, i) {
18724              expect(wd.getText()).toMatch(expectedNames[i]);
18725            });
18726          });
18727        };
18728
18729        it('should search across all fields when filtering with a string', function() {
18730          var searchText = element(by.model('searchText'));
18731          searchText.clear();
18732          searchText.sendKeys('m');
18733          expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
18734
18735          searchText.clear();
18736          searchText.sendKeys('76');
18737          expectFriendNames(['John', 'Julie'], 'friend');
18738        });
18739
18740        it('should search in specific fields when filtering with a predicate object', function() {
18741          var searchAny = element(by.model('search.$'));
18742          searchAny.clear();
18743          searchAny.sendKeys('i');
18744          expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
18745        });
18746        it('should use a equal comparison when comparator is true', function() {
18747          var searchName = element(by.model('search.name'));
18748          var strict = element(by.model('strict'));
18749          searchName.clear();
18750          searchName.sendKeys('Julie');
18751          strict.click();
18752          expectFriendNames(['Julie'], 'friendObj');
18753        });
18754      </file>
18755    </example>
18756  */
18757 function filterFilter() {
18758   return function(array, expression, comparator) {
18759     if (!isArrayLike(array)) {
18760       if (array == null) {
18761         return array;
18762       } else {
18763         throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
18764       }
18765     }
18766
18767     var expressionType = getTypeForFilter(expression);
18768     var predicateFn;
18769     var matchAgainstAnyProp;
18770
18771     switch (expressionType) {
18772       case 'function':
18773         predicateFn = expression;
18774         break;
18775       case 'boolean':
18776       case 'null':
18777       case 'number':
18778       case 'string':
18779         matchAgainstAnyProp = true;
18780         //jshint -W086
18781       case 'object':
18782         //jshint +W086
18783         predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
18784         break;
18785       default:
18786         return array;
18787     }
18788
18789     return Array.prototype.filter.call(array, predicateFn);
18790   };
18791 }
18792
18793 // Helper functions for `filterFilter`
18794 function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
18795   var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
18796   var predicateFn;
18797
18798   if (comparator === true) {
18799     comparator = equals;
18800   } else if (!isFunction(comparator)) {
18801     comparator = function(actual, expected) {
18802       if (isUndefined(actual)) {
18803         // No substring matching against `undefined`
18804         return false;
18805       }
18806       if ((actual === null) || (expected === null)) {
18807         // No substring matching against `null`; only match against `null`
18808         return actual === expected;
18809       }
18810       if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
18811         // Should not compare primitives against objects, unless they have custom `toString` method
18812         return false;
18813       }
18814
18815       actual = lowercase('' + actual);
18816       expected = lowercase('' + expected);
18817       return actual.indexOf(expected) !== -1;
18818     };
18819   }
18820
18821   predicateFn = function(item) {
18822     if (shouldMatchPrimitives && !isObject(item)) {
18823       return deepCompare(item, expression.$, comparator, false);
18824     }
18825     return deepCompare(item, expression, comparator, matchAgainstAnyProp);
18826   };
18827
18828   return predicateFn;
18829 }
18830
18831 function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
18832   var actualType = getTypeForFilter(actual);
18833   var expectedType = getTypeForFilter(expected);
18834
18835   if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
18836     return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
18837   } else if (isArray(actual)) {
18838     // In case `actual` is an array, consider it a match
18839     // if ANY of it's items matches `expected`
18840     return actual.some(function(item) {
18841       return deepCompare(item, expected, comparator, matchAgainstAnyProp);
18842     });
18843   }
18844
18845   switch (actualType) {
18846     case 'object':
18847       var key;
18848       if (matchAgainstAnyProp) {
18849         for (key in actual) {
18850           if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
18851             return true;
18852           }
18853         }
18854         return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
18855       } else if (expectedType === 'object') {
18856         for (key in expected) {
18857           var expectedVal = expected[key];
18858           if (isFunction(expectedVal) || isUndefined(expectedVal)) {
18859             continue;
18860           }
18861
18862           var matchAnyProperty = key === '$';
18863           var actualVal = matchAnyProperty ? actual : actual[key];
18864           if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
18865             return false;
18866           }
18867         }
18868         return true;
18869       } else {
18870         return comparator(actual, expected);
18871       }
18872       break;
18873     case 'function':
18874       return false;
18875     default:
18876       return comparator(actual, expected);
18877   }
18878 }
18879
18880 // Used for easily differentiating between `null` and actual `object`
18881 function getTypeForFilter(val) {
18882   return (val === null) ? 'null' : typeof val;
18883 }
18884
18885 /**
18886  * @ngdoc filter
18887  * @name currency
18888  * @kind function
18889  *
18890  * @description
18891  * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
18892  * symbol for current locale is used.
18893  *
18894  * @param {number} amount Input to filter.
18895  * @param {string=} symbol Currency symbol or identifier to be displayed.
18896  * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
18897  * @returns {string} Formatted number.
18898  *
18899  *
18900  * @example
18901    <example module="currencyExample">
18902      <file name="index.html">
18903        <script>
18904          angular.module('currencyExample', [])
18905            .controller('ExampleController', ['$scope', function($scope) {
18906              $scope.amount = 1234.56;
18907            }]);
18908        </script>
18909        <div ng-controller="ExampleController">
18910          <input type="number" ng-model="amount" aria-label="amount"> <br>
18911          default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
18912          custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
18913          no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
18914        </div>
18915      </file>
18916      <file name="protractor.js" type="protractor">
18917        it('should init with 1234.56', function() {
18918          expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
18919          expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
18920          expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
18921        });
18922        it('should update', function() {
18923          if (browser.params.browser == 'safari') {
18924            // Safari does not understand the minus key. See
18925            // https://github.com/angular/protractor/issues/481
18926            return;
18927          }
18928          element(by.model('amount')).clear();
18929          element(by.model('amount')).sendKeys('-1234');
18930          expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
18931          expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
18932          expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
18933        });
18934      </file>
18935    </example>
18936  */
18937 currencyFilter.$inject = ['$locale'];
18938 function currencyFilter($locale) {
18939   var formats = $locale.NUMBER_FORMATS;
18940   return function(amount, currencySymbol, fractionSize) {
18941     if (isUndefined(currencySymbol)) {
18942       currencySymbol = formats.CURRENCY_SYM;
18943     }
18944
18945     if (isUndefined(fractionSize)) {
18946       fractionSize = formats.PATTERNS[1].maxFrac;
18947     }
18948
18949     // if null or undefined pass it through
18950     return (amount == null)
18951         ? amount
18952         : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
18953             replace(/\u00A4/g, currencySymbol);
18954   };
18955 }
18956
18957 /**
18958  * @ngdoc filter
18959  * @name number
18960  * @kind function
18961  *
18962  * @description
18963  * Formats a number as text.
18964  *
18965  * If the input is null or undefined, it will just be returned.
18966  * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
18967  * If the input is not a number an empty string is returned.
18968  *
18969  *
18970  * @param {number|string} number Number to format.
18971  * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
18972  * If this is not provided then the fraction size is computed from the current locale's number
18973  * formatting pattern. In the case of the default locale, it will be 3.
18974  * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
18975  *
18976  * @example
18977    <example module="numberFilterExample">
18978      <file name="index.html">
18979        <script>
18980          angular.module('numberFilterExample', [])
18981            .controller('ExampleController', ['$scope', function($scope) {
18982              $scope.val = 1234.56789;
18983            }]);
18984        </script>
18985        <div ng-controller="ExampleController">
18986          <label>Enter number: <input ng-model='val'></label><br>
18987          Default formatting: <span id='number-default'>{{val | number}}</span><br>
18988          No fractions: <span>{{val | number:0}}</span><br>
18989          Negative number: <span>{{-val | number:4}}</span>
18990        </div>
18991      </file>
18992      <file name="protractor.js" type="protractor">
18993        it('should format numbers', function() {
18994          expect(element(by.id('number-default')).getText()).toBe('1,234.568');
18995          expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
18996          expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
18997        });
18998
18999        it('should update', function() {
19000          element(by.model('val')).clear();
19001          element(by.model('val')).sendKeys('3374.333');
19002          expect(element(by.id('number-default')).getText()).toBe('3,374.333');
19003          expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
19004          expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
19005       });
19006      </file>
19007    </example>
19008  */
19009
19010
19011 numberFilter.$inject = ['$locale'];
19012 function numberFilter($locale) {
19013   var formats = $locale.NUMBER_FORMATS;
19014   return function(number, fractionSize) {
19015
19016     // if null or undefined pass it through
19017     return (number == null)
19018         ? number
19019         : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
19020                        fractionSize);
19021   };
19022 }
19023
19024 var DECIMAL_SEP = '.';
19025 function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
19026   if (isObject(number)) return '';
19027
19028   var isNegative = number < 0;
19029   number = Math.abs(number);
19030
19031   var isInfinity = number === Infinity;
19032   if (!isInfinity && !isFinite(number)) return '';
19033
19034   var numStr = number + '',
19035       formatedText = '',
19036       hasExponent = false,
19037       parts = [];
19038
19039   if (isInfinity) formatedText = '\u221e';
19040
19041   if (!isInfinity && numStr.indexOf('e') !== -1) {
19042     var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
19043     if (match && match[2] == '-' && match[3] > fractionSize + 1) {
19044       number = 0;
19045     } else {
19046       formatedText = numStr;
19047       hasExponent = true;
19048     }
19049   }
19050
19051   if (!isInfinity && !hasExponent) {
19052     var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
19053
19054     // determine fractionSize if it is not specified
19055     if (isUndefined(fractionSize)) {
19056       fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
19057     }
19058
19059     // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
19060     // inspired by:
19061     // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
19062     number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
19063
19064     var fraction = ('' + number).split(DECIMAL_SEP);
19065     var whole = fraction[0];
19066     fraction = fraction[1] || '';
19067
19068     var i, pos = 0,
19069         lgroup = pattern.lgSize,
19070         group = pattern.gSize;
19071
19072     if (whole.length >= (lgroup + group)) {
19073       pos = whole.length - lgroup;
19074       for (i = 0; i < pos; i++) {
19075         if ((pos - i) % group === 0 && i !== 0) {
19076           formatedText += groupSep;
19077         }
19078         formatedText += whole.charAt(i);
19079       }
19080     }
19081
19082     for (i = pos; i < whole.length; i++) {
19083       if ((whole.length - i) % lgroup === 0 && i !== 0) {
19084         formatedText += groupSep;
19085       }
19086       formatedText += whole.charAt(i);
19087     }
19088
19089     // format fraction part.
19090     while (fraction.length < fractionSize) {
19091       fraction += '0';
19092     }
19093
19094     if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
19095   } else {
19096     if (fractionSize > 0 && number < 1) {
19097       formatedText = number.toFixed(fractionSize);
19098       number = parseFloat(formatedText);
19099       formatedText = formatedText.replace(DECIMAL_SEP, decimalSep);
19100     }
19101   }
19102
19103   if (number === 0) {
19104     isNegative = false;
19105   }
19106
19107   parts.push(isNegative ? pattern.negPre : pattern.posPre,
19108              formatedText,
19109              isNegative ? pattern.negSuf : pattern.posSuf);
19110   return parts.join('');
19111 }
19112
19113 function padNumber(num, digits, trim) {
19114   var neg = '';
19115   if (num < 0) {
19116     neg =  '-';
19117     num = -num;
19118   }
19119   num = '' + num;
19120   while (num.length < digits) num = '0' + num;
19121   if (trim) {
19122     num = num.substr(num.length - digits);
19123   }
19124   return neg + num;
19125 }
19126
19127
19128 function dateGetter(name, size, offset, trim) {
19129   offset = offset || 0;
19130   return function(date) {
19131     var value = date['get' + name]();
19132     if (offset > 0 || value > -offset) {
19133       value += offset;
19134     }
19135     if (value === 0 && offset == -12) value = 12;
19136     return padNumber(value, size, trim);
19137   };
19138 }
19139
19140 function dateStrGetter(name, shortForm) {
19141   return function(date, formats) {
19142     var value = date['get' + name]();
19143     var get = uppercase(shortForm ? ('SHORT' + name) : name);
19144
19145     return formats[get][value];
19146   };
19147 }
19148
19149 function timeZoneGetter(date, formats, offset) {
19150   var zone = -1 * offset;
19151   var paddedZone = (zone >= 0) ? "+" : "";
19152
19153   paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
19154                 padNumber(Math.abs(zone % 60), 2);
19155
19156   return paddedZone;
19157 }
19158
19159 function getFirstThursdayOfYear(year) {
19160     // 0 = index of January
19161     var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
19162     // 4 = index of Thursday (+1 to account for 1st = 5)
19163     // 11 = index of *next* Thursday (+1 account for 1st = 12)
19164     return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
19165 }
19166
19167 function getThursdayThisWeek(datetime) {
19168     return new Date(datetime.getFullYear(), datetime.getMonth(),
19169       // 4 = index of Thursday
19170       datetime.getDate() + (4 - datetime.getDay()));
19171 }
19172
19173 function weekGetter(size) {
19174    return function(date) {
19175       var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
19176          thisThurs = getThursdayThisWeek(date);
19177
19178       var diff = +thisThurs - +firstThurs,
19179          result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
19180
19181       return padNumber(result, size);
19182    };
19183 }
19184
19185 function ampmGetter(date, formats) {
19186   return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
19187 }
19188
19189 function eraGetter(date, formats) {
19190   return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
19191 }
19192
19193 function longEraGetter(date, formats) {
19194   return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
19195 }
19196
19197 var DATE_FORMATS = {
19198   yyyy: dateGetter('FullYear', 4),
19199     yy: dateGetter('FullYear', 2, 0, true),
19200      y: dateGetter('FullYear', 1),
19201   MMMM: dateStrGetter('Month'),
19202    MMM: dateStrGetter('Month', true),
19203     MM: dateGetter('Month', 2, 1),
19204      M: dateGetter('Month', 1, 1),
19205     dd: dateGetter('Date', 2),
19206      d: dateGetter('Date', 1),
19207     HH: dateGetter('Hours', 2),
19208      H: dateGetter('Hours', 1),
19209     hh: dateGetter('Hours', 2, -12),
19210      h: dateGetter('Hours', 1, -12),
19211     mm: dateGetter('Minutes', 2),
19212      m: dateGetter('Minutes', 1),
19213     ss: dateGetter('Seconds', 2),
19214      s: dateGetter('Seconds', 1),
19215      // while ISO 8601 requires fractions to be prefixed with `.` or `,`
19216      // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
19217    sss: dateGetter('Milliseconds', 3),
19218   EEEE: dateStrGetter('Day'),
19219    EEE: dateStrGetter('Day', true),
19220      a: ampmGetter,
19221      Z: timeZoneGetter,
19222     ww: weekGetter(2),
19223      w: weekGetter(1),
19224      G: eraGetter,
19225      GG: eraGetter,
19226      GGG: eraGetter,
19227      GGGG: longEraGetter
19228 };
19229
19230 var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
19231     NUMBER_STRING = /^\-?\d+$/;
19232
19233 /**
19234  * @ngdoc filter
19235  * @name date
19236  * @kind function
19237  *
19238  * @description
19239  *   Formats `date` to a string based on the requested `format`.
19240  *
19241  *   `format` string can be composed of the following elements:
19242  *
19243  *   * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
19244  *   * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
19245  *   * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
19246  *   * `'MMMM'`: Month in year (January-December)
19247  *   * `'MMM'`: Month in year (Jan-Dec)
19248  *   * `'MM'`: Month in year, padded (01-12)
19249  *   * `'M'`: Month in year (1-12)
19250  *   * `'dd'`: Day in month, padded (01-31)
19251  *   * `'d'`: Day in month (1-31)
19252  *   * `'EEEE'`: Day in Week,(Sunday-Saturday)
19253  *   * `'EEE'`: Day in Week, (Sun-Sat)
19254  *   * `'HH'`: Hour in day, padded (00-23)
19255  *   * `'H'`: Hour in day (0-23)
19256  *   * `'hh'`: Hour in AM/PM, padded (01-12)
19257  *   * `'h'`: Hour in AM/PM, (1-12)
19258  *   * `'mm'`: Minute in hour, padded (00-59)
19259  *   * `'m'`: Minute in hour (0-59)
19260  *   * `'ss'`: Second in minute, padded (00-59)
19261  *   * `'s'`: Second in minute (0-59)
19262  *   * `'sss'`: Millisecond in second, padded (000-999)
19263  *   * `'a'`: AM/PM marker
19264  *   * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
19265  *   * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
19266  *   * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
19267  *   * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
19268  *   * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
19269  *
19270  *   `format` string can also be one of the following predefined
19271  *   {@link guide/i18n localizable formats}:
19272  *
19273  *   * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
19274  *     (e.g. Sep 3, 2010 12:05:08 PM)
19275  *   * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US  locale (e.g. 9/3/10 12:05 PM)
19276  *   * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US  locale
19277  *     (e.g. Friday, September 3, 2010)
19278  *   * `'longDate'`: equivalent to `'MMMM d, y'` for en_US  locale (e.g. September 3, 2010)
19279  *   * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US  locale (e.g. Sep 3, 2010)
19280  *   * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
19281  *   * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
19282  *   * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
19283  *
19284  *   `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
19285  *   `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
19286  *   (e.g. `"h 'o''clock'"`).
19287  *
19288  * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
19289  *    number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
19290  *    shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
19291  *    specified in the string input, the time is considered to be in the local timezone.
19292  * @param {string=} format Formatting rules (see Description). If not specified,
19293  *    `mediumDate` is used.
19294  * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
19295  *    continental US time zone abbreviations, but for general use, use a time zone offset, for
19296  *    example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
19297  *    If not specified, the timezone of the browser will be used.
19298  * @returns {string} Formatted string or the input if input is not recognized as date/millis.
19299  *
19300  * @example
19301    <example>
19302      <file name="index.html">
19303        <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
19304            <span>{{1288323623006 | date:'medium'}}</span><br>
19305        <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
19306           <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
19307        <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
19308           <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
19309        <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
19310           <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
19311      </file>
19312      <file name="protractor.js" type="protractor">
19313        it('should format date', function() {
19314          expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
19315             toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
19316          expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
19317             toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
19318          expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
19319             toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
19320          expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
19321             toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
19322        });
19323      </file>
19324    </example>
19325  */
19326 dateFilter.$inject = ['$locale'];
19327 function dateFilter($locale) {
19328
19329
19330   var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
19331                      // 1        2       3         4          5          6          7          8  9     10      11
19332   function jsonStringToDate(string) {
19333     var match;
19334     if (match = string.match(R_ISO8601_STR)) {
19335       var date = new Date(0),
19336           tzHour = 0,
19337           tzMin  = 0,
19338           dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
19339           timeSetter = match[8] ? date.setUTCHours : date.setHours;
19340
19341       if (match[9]) {
19342         tzHour = toInt(match[9] + match[10]);
19343         tzMin = toInt(match[9] + match[11]);
19344       }
19345       dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
19346       var h = toInt(match[4] || 0) - tzHour;
19347       var m = toInt(match[5] || 0) - tzMin;
19348       var s = toInt(match[6] || 0);
19349       var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
19350       timeSetter.call(date, h, m, s, ms);
19351       return date;
19352     }
19353     return string;
19354   }
19355
19356
19357   return function(date, format, timezone) {
19358     var text = '',
19359         parts = [],
19360         fn, match;
19361
19362     format = format || 'mediumDate';
19363     format = $locale.DATETIME_FORMATS[format] || format;
19364     if (isString(date)) {
19365       date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
19366     }
19367
19368     if (isNumber(date)) {
19369       date = new Date(date);
19370     }
19371
19372     if (!isDate(date) || !isFinite(date.getTime())) {
19373       return date;
19374     }
19375
19376     while (format) {
19377       match = DATE_FORMATS_SPLIT.exec(format);
19378       if (match) {
19379         parts = concat(parts, match, 1);
19380         format = parts.pop();
19381       } else {
19382         parts.push(format);
19383         format = null;
19384       }
19385     }
19386
19387     var dateTimezoneOffset = date.getTimezoneOffset();
19388     if (timezone) {
19389       dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
19390       date = convertTimezoneToLocal(date, timezone, true);
19391     }
19392     forEach(parts, function(value) {
19393       fn = DATE_FORMATS[value];
19394       text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
19395                  : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
19396     });
19397
19398     return text;
19399   };
19400 }
19401
19402
19403 /**
19404  * @ngdoc filter
19405  * @name json
19406  * @kind function
19407  *
19408  * @description
19409  *   Allows you to convert a JavaScript object into JSON string.
19410  *
19411  *   This filter is mostly useful for debugging. When using the double curly {{value}} notation
19412  *   the binding is automatically converted to JSON.
19413  *
19414  * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
19415  * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
19416  * @returns {string} JSON string.
19417  *
19418  *
19419  * @example
19420    <example>
19421      <file name="index.html">
19422        <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
19423        <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
19424      </file>
19425      <file name="protractor.js" type="protractor">
19426        it('should jsonify filtered objects', function() {
19427          expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n  "name": ?"value"\n}/);
19428          expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n    "name": ?"value"\n}/);
19429        });
19430      </file>
19431    </example>
19432  *
19433  */
19434 function jsonFilter() {
19435   return function(object, spacing) {
19436     if (isUndefined(spacing)) {
19437         spacing = 2;
19438     }
19439     return toJson(object, spacing);
19440   };
19441 }
19442
19443
19444 /**
19445  * @ngdoc filter
19446  * @name lowercase
19447  * @kind function
19448  * @description
19449  * Converts string to lowercase.
19450  * @see angular.lowercase
19451  */
19452 var lowercaseFilter = valueFn(lowercase);
19453
19454
19455 /**
19456  * @ngdoc filter
19457  * @name uppercase
19458  * @kind function
19459  * @description
19460  * Converts string to uppercase.
19461  * @see angular.uppercase
19462  */
19463 var uppercaseFilter = valueFn(uppercase);
19464
19465 /**
19466  * @ngdoc filter
19467  * @name limitTo
19468  * @kind function
19469  *
19470  * @description
19471  * Creates a new array or string containing only a specified number of elements. The elements
19472  * are taken from either the beginning or the end of the source array, string or number, as specified by
19473  * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
19474  * converted to a string.
19475  *
19476  * @param {Array|string|number} input Source array, string or number to be limited.
19477  * @param {string|number} limit The length of the returned array or string. If the `limit` number
19478  *     is positive, `limit` number of items from the beginning of the source array/string are copied.
19479  *     If the number is negative, `limit` number  of items from the end of the source array/string
19480  *     are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
19481  *     the input will be returned unchanged.
19482  * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
19483  *     indicates an offset from the end of `input`. Defaults to `0`.
19484  * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
19485  *     had less than `limit` elements.
19486  *
19487  * @example
19488    <example module="limitToExample">
19489      <file name="index.html">
19490        <script>
19491          angular.module('limitToExample', [])
19492            .controller('ExampleController', ['$scope', function($scope) {
19493              $scope.numbers = [1,2,3,4,5,6,7,8,9];
19494              $scope.letters = "abcdefghi";
19495              $scope.longNumber = 2345432342;
19496              $scope.numLimit = 3;
19497              $scope.letterLimit = 3;
19498              $scope.longNumberLimit = 3;
19499            }]);
19500        </script>
19501        <div ng-controller="ExampleController">
19502          <label>
19503             Limit {{numbers}} to:
19504             <input type="number" step="1" ng-model="numLimit">
19505          </label>
19506          <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
19507          <label>
19508             Limit {{letters}} to:
19509             <input type="number" step="1" ng-model="letterLimit">
19510          </label>
19511          <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
19512          <label>
19513             Limit {{longNumber}} to:
19514             <input type="number" step="1" ng-model="longNumberLimit">
19515          </label>
19516          <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
19517        </div>
19518      </file>
19519      <file name="protractor.js" type="protractor">
19520        var numLimitInput = element(by.model('numLimit'));
19521        var letterLimitInput = element(by.model('letterLimit'));
19522        var longNumberLimitInput = element(by.model('longNumberLimit'));
19523        var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
19524        var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
19525        var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
19526
19527        it('should limit the number array to first three items', function() {
19528          expect(numLimitInput.getAttribute('value')).toBe('3');
19529          expect(letterLimitInput.getAttribute('value')).toBe('3');
19530          expect(longNumberLimitInput.getAttribute('value')).toBe('3');
19531          expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
19532          expect(limitedLetters.getText()).toEqual('Output letters: abc');
19533          expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
19534        });
19535
19536        // There is a bug in safari and protractor that doesn't like the minus key
19537        // it('should update the output when -3 is entered', function() {
19538        //   numLimitInput.clear();
19539        //   numLimitInput.sendKeys('-3');
19540        //   letterLimitInput.clear();
19541        //   letterLimitInput.sendKeys('-3');
19542        //   longNumberLimitInput.clear();
19543        //   longNumberLimitInput.sendKeys('-3');
19544        //   expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
19545        //   expect(limitedLetters.getText()).toEqual('Output letters: ghi');
19546        //   expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
19547        // });
19548
19549        it('should not exceed the maximum size of input array', function() {
19550          numLimitInput.clear();
19551          numLimitInput.sendKeys('100');
19552          letterLimitInput.clear();
19553          letterLimitInput.sendKeys('100');
19554          longNumberLimitInput.clear();
19555          longNumberLimitInput.sendKeys('100');
19556          expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
19557          expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
19558          expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
19559        });
19560      </file>
19561    </example>
19562 */
19563 function limitToFilter() {
19564   return function(input, limit, begin) {
19565     if (Math.abs(Number(limit)) === Infinity) {
19566       limit = Number(limit);
19567     } else {
19568       limit = toInt(limit);
19569     }
19570     if (isNaN(limit)) return input;
19571
19572     if (isNumber(input)) input = input.toString();
19573     if (!isArray(input) && !isString(input)) return input;
19574
19575     begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
19576     begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
19577
19578     if (limit >= 0) {
19579       return input.slice(begin, begin + limit);
19580     } else {
19581       if (begin === 0) {
19582         return input.slice(limit, input.length);
19583       } else {
19584         return input.slice(Math.max(0, begin + limit), begin);
19585       }
19586     }
19587   };
19588 }
19589
19590 /**
19591  * @ngdoc filter
19592  * @name orderBy
19593  * @kind function
19594  *
19595  * @description
19596  * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
19597  * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
19598  * as expected, make sure they are actually being saved as numbers and not strings.
19599  * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
19600  *
19601  * @param {Array} array The array (or array-like object) to sort.
19602  * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
19603  *    used by the comparator to determine the order of elements.
19604  *
19605  *    Can be one of:
19606  *
19607  *    - `function`: Getter function. The result of this function will be sorted using the
19608  *      `<`, `===`, `>` operator.
19609  *    - `string`: An Angular expression. The result of this expression is used to compare elements
19610  *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
19611  *      3 first characters of a property called `name`). The result of a constant expression
19612  *      is interpreted as a property name to be used in comparisons (for example `"special name"`
19613  *      to sort object by the value of their `special name` property). An expression can be
19614  *      optionally prefixed with `+` or `-` to control ascending or descending sort order
19615  *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
19616  *      element itself is used to compare where sorting.
19617  *    - `Array`: An array of function or string predicates. The first predicate in the array
19618  *      is used for sorting, but when two items are equivalent, the next predicate is used.
19619  *
19620  *    If the predicate is missing or empty then it defaults to `'+'`.
19621  *
19622  * @param {boolean=} reverse Reverse the order of the array.
19623  * @returns {Array} Sorted copy of the source array.
19624  *
19625  *
19626  * @example
19627  * The example below demonstrates a simple ngRepeat, where the data is sorted
19628  * by age in descending order (predicate is set to `'-age'`).
19629  * `reverse` is not set, which means it defaults to `false`.
19630    <example module="orderByExample">
19631      <file name="index.html">
19632        <script>
19633          angular.module('orderByExample', [])
19634            .controller('ExampleController', ['$scope', function($scope) {
19635              $scope.friends =
19636                  [{name:'John', phone:'555-1212', age:10},
19637                   {name:'Mary', phone:'555-9876', age:19},
19638                   {name:'Mike', phone:'555-4321', age:21},
19639                   {name:'Adam', phone:'555-5678', age:35},
19640                   {name:'Julie', phone:'555-8765', age:29}];
19641            }]);
19642        </script>
19643        <div ng-controller="ExampleController">
19644          <table class="friend">
19645            <tr>
19646              <th>Name</th>
19647              <th>Phone Number</th>
19648              <th>Age</th>
19649            </tr>
19650            <tr ng-repeat="friend in friends | orderBy:'-age'">
19651              <td>{{friend.name}}</td>
19652              <td>{{friend.phone}}</td>
19653              <td>{{friend.age}}</td>
19654            </tr>
19655          </table>
19656        </div>
19657      </file>
19658    </example>
19659  *
19660  * The predicate and reverse parameters can be controlled dynamically through scope properties,
19661  * as shown in the next example.
19662  * @example
19663    <example module="orderByExample">
19664      <file name="index.html">
19665        <script>
19666          angular.module('orderByExample', [])
19667            .controller('ExampleController', ['$scope', function($scope) {
19668              $scope.friends =
19669                  [{name:'John', phone:'555-1212', age:10},
19670                   {name:'Mary', phone:'555-9876', age:19},
19671                   {name:'Mike', phone:'555-4321', age:21},
19672                   {name:'Adam', phone:'555-5678', age:35},
19673                   {name:'Julie', phone:'555-8765', age:29}];
19674              $scope.predicate = 'age';
19675              $scope.reverse = true;
19676              $scope.order = function(predicate) {
19677                $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
19678                $scope.predicate = predicate;
19679              };
19680            }]);
19681        </script>
19682        <style type="text/css">
19683          .sortorder:after {
19684            content: '\25b2';
19685          }
19686          .sortorder.reverse:after {
19687            content: '\25bc';
19688          }
19689        </style>
19690        <div ng-controller="ExampleController">
19691          <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
19692          <hr/>
19693          [ <a href="" ng-click="predicate=''">unsorted</a> ]
19694          <table class="friend">
19695            <tr>
19696              <th>
19697                <a href="" ng-click="order('name')">Name</a>
19698                <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
19699              </th>
19700              <th>
19701                <a href="" ng-click="order('phone')">Phone Number</a>
19702                <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
19703              </th>
19704              <th>
19705                <a href="" ng-click="order('age')">Age</a>
19706                <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
19707              </th>
19708            </tr>
19709            <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
19710              <td>{{friend.name}}</td>
19711              <td>{{friend.phone}}</td>
19712              <td>{{friend.age}}</td>
19713            </tr>
19714          </table>
19715        </div>
19716      </file>
19717    </example>
19718  *
19719  * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
19720  * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
19721  * desired parameters.
19722  *
19723  * Example:
19724  *
19725  * @example
19726   <example module="orderByExample">
19727     <file name="index.html">
19728       <div ng-controller="ExampleController">
19729         <table class="friend">
19730           <tr>
19731             <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
19732               (<a href="" ng-click="order('-name',false)">^</a>)</th>
19733             <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
19734             <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
19735           </tr>
19736           <tr ng-repeat="friend in friends">
19737             <td>{{friend.name}}</td>
19738             <td>{{friend.phone}}</td>
19739             <td>{{friend.age}}</td>
19740           </tr>
19741         </table>
19742       </div>
19743     </file>
19744
19745     <file name="script.js">
19746       angular.module('orderByExample', [])
19747         .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
19748           var orderBy = $filter('orderBy');
19749           $scope.friends = [
19750             { name: 'John',    phone: '555-1212',    age: 10 },
19751             { name: 'Mary',    phone: '555-9876',    age: 19 },
19752             { name: 'Mike',    phone: '555-4321',    age: 21 },
19753             { name: 'Adam',    phone: '555-5678',    age: 35 },
19754             { name: 'Julie',   phone: '555-8765',    age: 29 }
19755           ];
19756           $scope.order = function(predicate, reverse) {
19757             $scope.friends = orderBy($scope.friends, predicate, reverse);
19758           };
19759           $scope.order('-age',false);
19760         }]);
19761     </file>
19762 </example>
19763  */
19764 orderByFilter.$inject = ['$parse'];
19765 function orderByFilter($parse) {
19766   return function(array, sortPredicate, reverseOrder) {
19767
19768     if (array == null) return array;
19769     if (!isArrayLike(array)) {
19770       throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
19771     }
19772
19773     if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
19774     if (sortPredicate.length === 0) { sortPredicate = ['+']; }
19775
19776     var predicates = processPredicates(sortPredicate, reverseOrder);
19777     // Add a predicate at the end that evaluates to the element index. This makes the
19778     // sort stable as it works as a tie-breaker when all the input predicates cannot
19779     // distinguish between two elements.
19780     predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
19781
19782     // The next three lines are a version of a Swartzian Transform idiom from Perl
19783     // (sometimes called the Decorate-Sort-Undecorate idiom)
19784     // See https://en.wikipedia.org/wiki/Schwartzian_transform
19785     var compareValues = Array.prototype.map.call(array, getComparisonObject);
19786     compareValues.sort(doComparison);
19787     array = compareValues.map(function(item) { return item.value; });
19788
19789     return array;
19790
19791     function getComparisonObject(value, index) {
19792       return {
19793         value: value,
19794         predicateValues: predicates.map(function(predicate) {
19795           return getPredicateValue(predicate.get(value), index);
19796         })
19797       };
19798     }
19799
19800     function doComparison(v1, v2) {
19801       var result = 0;
19802       for (var index=0, length = predicates.length; index < length; ++index) {
19803         result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
19804         if (result) break;
19805       }
19806       return result;
19807     }
19808   };
19809
19810   function processPredicates(sortPredicate, reverseOrder) {
19811     reverseOrder = reverseOrder ? -1 : 1;
19812     return sortPredicate.map(function(predicate) {
19813       var descending = 1, get = identity;
19814
19815       if (isFunction(predicate)) {
19816         get = predicate;
19817       } else if (isString(predicate)) {
19818         if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
19819           descending = predicate.charAt(0) == '-' ? -1 : 1;
19820           predicate = predicate.substring(1);
19821         }
19822         if (predicate !== '') {
19823           get = $parse(predicate);
19824           if (get.constant) {
19825             var key = get();
19826             get = function(value) { return value[key]; };
19827           }
19828         }
19829       }
19830       return { get: get, descending: descending * reverseOrder };
19831     });
19832   }
19833
19834   function isPrimitive(value) {
19835     switch (typeof value) {
19836       case 'number': /* falls through */
19837       case 'boolean': /* falls through */
19838       case 'string':
19839         return true;
19840       default:
19841         return false;
19842     }
19843   }
19844
19845   function objectValue(value, index) {
19846     // If `valueOf` is a valid function use that
19847     if (typeof value.valueOf === 'function') {
19848       value = value.valueOf();
19849       if (isPrimitive(value)) return value;
19850     }
19851     // If `toString` is a valid function and not the one from `Object.prototype` use that
19852     if (hasCustomToString(value)) {
19853       value = value.toString();
19854       if (isPrimitive(value)) return value;
19855     }
19856     // We have a basic object so we use the position of the object in the collection
19857     return index;
19858   }
19859
19860   function getPredicateValue(value, index) {
19861     var type = typeof value;
19862     if (value === null) {
19863       type = 'string';
19864       value = 'null';
19865     } else if (type === 'string') {
19866       value = value.toLowerCase();
19867     } else if (type === 'object') {
19868       value = objectValue(value, index);
19869     }
19870     return { value: value, type: type };
19871   }
19872
19873   function compare(v1, v2) {
19874     var result = 0;
19875     if (v1.type === v2.type) {
19876       if (v1.value !== v2.value) {
19877         result = v1.value < v2.value ? -1 : 1;
19878       }
19879     } else {
19880       result = v1.type < v2.type ? -1 : 1;
19881     }
19882     return result;
19883   }
19884 }
19885
19886 function ngDirective(directive) {
19887   if (isFunction(directive)) {
19888     directive = {
19889       link: directive
19890     };
19891   }
19892   directive.restrict = directive.restrict || 'AC';
19893   return valueFn(directive);
19894 }
19895
19896 /**
19897  * @ngdoc directive
19898  * @name a
19899  * @restrict E
19900  *
19901  * @description
19902  * Modifies the default behavior of the html A tag so that the default action is prevented when
19903  * the href attribute is empty.
19904  *
19905  * This change permits the easy creation of action links with the `ngClick` directive
19906  * without changing the location or causing page reloads, e.g.:
19907  * `<a href="" ng-click="list.addItem()">Add Item</a>`
19908  */
19909 var htmlAnchorDirective = valueFn({
19910   restrict: 'E',
19911   compile: function(element, attr) {
19912     if (!attr.href && !attr.xlinkHref) {
19913       return function(scope, element) {
19914         // If the linked element is not an anchor tag anymore, do nothing
19915         if (element[0].nodeName.toLowerCase() !== 'a') return;
19916
19917         // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
19918         var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
19919                    'xlink:href' : 'href';
19920         element.on('click', function(event) {
19921           // if we have no href url, then don't navigate anywhere.
19922           if (!element.attr(href)) {
19923             event.preventDefault();
19924           }
19925         });
19926       };
19927     }
19928   }
19929 });
19930
19931 /**
19932  * @ngdoc directive
19933  * @name ngHref
19934  * @restrict A
19935  * @priority 99
19936  *
19937  * @description
19938  * Using Angular markup like `{{hash}}` in an href attribute will
19939  * make the link go to the wrong URL if the user clicks it before
19940  * Angular has a chance to replace the `{{hash}}` markup with its
19941  * value. Until Angular replaces the markup the link will be broken
19942  * and will most likely return a 404 error. The `ngHref` directive
19943  * solves this problem.
19944  *
19945  * The wrong way to write it:
19946  * ```html
19947  * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
19948  * ```
19949  *
19950  * The correct way to write it:
19951  * ```html
19952  * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
19953  * ```
19954  *
19955  * @element A
19956  * @param {template} ngHref any string which can contain `{{}}` markup.
19957  *
19958  * @example
19959  * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
19960  * in links and their different behaviors:
19961     <example>
19962       <file name="index.html">
19963         <input ng-model="value" /><br />
19964         <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
19965         <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
19966         <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
19967         <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
19968         <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
19969         <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
19970       </file>
19971       <file name="protractor.js" type="protractor">
19972         it('should execute ng-click but not reload when href without value', function() {
19973           element(by.id('link-1')).click();
19974           expect(element(by.model('value')).getAttribute('value')).toEqual('1');
19975           expect(element(by.id('link-1')).getAttribute('href')).toBe('');
19976         });
19977
19978         it('should execute ng-click but not reload when href empty string', function() {
19979           element(by.id('link-2')).click();
19980           expect(element(by.model('value')).getAttribute('value')).toEqual('2');
19981           expect(element(by.id('link-2')).getAttribute('href')).toBe('');
19982         });
19983
19984         it('should execute ng-click and change url when ng-href specified', function() {
19985           expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
19986
19987           element(by.id('link-3')).click();
19988
19989           // At this point, we navigate away from an Angular page, so we need
19990           // to use browser.driver to get the base webdriver.
19991
19992           browser.wait(function() {
19993             return browser.driver.getCurrentUrl().then(function(url) {
19994               return url.match(/\/123$/);
19995             });
19996           }, 5000, 'page should navigate to /123');
19997         });
19998
19999         it('should execute ng-click but not reload when href empty string and name specified', function() {
20000           element(by.id('link-4')).click();
20001           expect(element(by.model('value')).getAttribute('value')).toEqual('4');
20002           expect(element(by.id('link-4')).getAttribute('href')).toBe('');
20003         });
20004
20005         it('should execute ng-click but not reload when no href but name specified', function() {
20006           element(by.id('link-5')).click();
20007           expect(element(by.model('value')).getAttribute('value')).toEqual('5');
20008           expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
20009         });
20010
20011         it('should only change url when only ng-href', function() {
20012           element(by.model('value')).clear();
20013           element(by.model('value')).sendKeys('6');
20014           expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
20015
20016           element(by.id('link-6')).click();
20017
20018           // At this point, we navigate away from an Angular page, so we need
20019           // to use browser.driver to get the base webdriver.
20020           browser.wait(function() {
20021             return browser.driver.getCurrentUrl().then(function(url) {
20022               return url.match(/\/6$/);
20023             });
20024           }, 5000, 'page should navigate to /6');
20025         });
20026       </file>
20027     </example>
20028  */
20029
20030 /**
20031  * @ngdoc directive
20032  * @name ngSrc
20033  * @restrict A
20034  * @priority 99
20035  *
20036  * @description
20037  * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
20038  * work right: The browser will fetch from the URL with the literal
20039  * text `{{hash}}` until Angular replaces the expression inside
20040  * `{{hash}}`. The `ngSrc` directive solves this problem.
20041  *
20042  * The buggy way to write it:
20043  * ```html
20044  * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
20045  * ```
20046  *
20047  * The correct way to write it:
20048  * ```html
20049  * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
20050  * ```
20051  *
20052  * @element IMG
20053  * @param {template} ngSrc any string which can contain `{{}}` markup.
20054  */
20055
20056 /**
20057  * @ngdoc directive
20058  * @name ngSrcset
20059  * @restrict A
20060  * @priority 99
20061  *
20062  * @description
20063  * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
20064  * work right: The browser will fetch from the URL with the literal
20065  * text `{{hash}}` until Angular replaces the expression inside
20066  * `{{hash}}`. The `ngSrcset` directive solves this problem.
20067  *
20068  * The buggy way to write it:
20069  * ```html
20070  * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
20071  * ```
20072  *
20073  * The correct way to write it:
20074  * ```html
20075  * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
20076  * ```
20077  *
20078  * @element IMG
20079  * @param {template} ngSrcset any string which can contain `{{}}` markup.
20080  */
20081
20082 /**
20083  * @ngdoc directive
20084  * @name ngDisabled
20085  * @restrict A
20086  * @priority 100
20087  *
20088  * @description
20089  *
20090  * This directive sets the `disabled` attribute on the element if the
20091  * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
20092  *
20093  * A special directive is necessary because we cannot use interpolation inside the `disabled`
20094  * attribute.  The following example would make the button enabled on Chrome/Firefox
20095  * but not on older IEs:
20096  *
20097  * ```html
20098  * <!-- See below for an example of ng-disabled being used correctly -->
20099  * <div ng-init="isDisabled = false">
20100  *  <button disabled="{{isDisabled}}">Disabled</button>
20101  * </div>
20102  * ```
20103  *
20104  * This is because the HTML specification does not require browsers to preserve the values of
20105  * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
20106  * If we put an Angular interpolation expression into such an attribute then the
20107  * binding information would be lost when the browser removes the attribute.
20108  *
20109  * @example
20110     <example>
20111       <file name="index.html">
20112         <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
20113         <button ng-model="button" ng-disabled="checked">Button</button>
20114       </file>
20115       <file name="protractor.js" type="protractor">
20116         it('should toggle button', function() {
20117           expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
20118           element(by.model('checked')).click();
20119           expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
20120         });
20121       </file>
20122     </example>
20123  *
20124  * @element INPUT
20125  * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
20126  *     then the `disabled` attribute will be set on the element
20127  */
20128
20129
20130 /**
20131  * @ngdoc directive
20132  * @name ngChecked
20133  * @restrict A
20134  * @priority 100
20135  *
20136  * @description
20137  * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
20138  *
20139  * Note that this directive should not be used together with {@link ngModel `ngModel`},
20140  * as this can lead to unexpected behavior.
20141  *
20142  * ### Why do we need `ngChecked`?
20143  *
20144  * The HTML specification does not require browsers to preserve the values of boolean attributes
20145  * such as checked. (Their presence means true and their absence means false.)
20146  * If we put an Angular interpolation expression into such an attribute then the
20147  * binding information would be lost when the browser removes the attribute.
20148  * The `ngChecked` directive solves this problem for the `checked` attribute.
20149  * This complementary directive is not removed by the browser and so provides
20150  * a permanent reliable place to store the binding information.
20151  * @example
20152     <example>
20153       <file name="index.html">
20154         <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
20155         <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
20156       </file>
20157       <file name="protractor.js" type="protractor">
20158         it('should check both checkBoxes', function() {
20159           expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
20160           element(by.model('master')).click();
20161           expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
20162         });
20163       </file>
20164     </example>
20165  *
20166  * @element INPUT
20167  * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
20168  *     then the `checked` attribute will be set on the element
20169  */
20170
20171
20172 /**
20173  * @ngdoc directive
20174  * @name ngReadonly
20175  * @restrict A
20176  * @priority 100
20177  *
20178  * @description
20179  * The HTML specification does not require browsers to preserve the values of boolean attributes
20180  * such as readonly. (Their presence means true and their absence means false.)
20181  * If we put an Angular interpolation expression into such an attribute then the
20182  * binding information would be lost when the browser removes the attribute.
20183  * The `ngReadonly` directive solves this problem for the `readonly` attribute.
20184  * This complementary directive is not removed by the browser and so provides
20185  * a permanent reliable place to store the binding information.
20186  * @example
20187     <example>
20188       <file name="index.html">
20189         <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
20190         <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
20191       </file>
20192       <file name="protractor.js" type="protractor">
20193         it('should toggle readonly attr', function() {
20194           expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
20195           element(by.model('checked')).click();
20196           expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
20197         });
20198       </file>
20199     </example>
20200  *
20201  * @element INPUT
20202  * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
20203  *     then special attribute "readonly" will be set on the element
20204  */
20205
20206
20207 /**
20208  * @ngdoc directive
20209  * @name ngSelected
20210  * @restrict A
20211  * @priority 100
20212  *
20213  * @description
20214  * The HTML specification does not require browsers to preserve the values of boolean attributes
20215  * such as selected. (Their presence means true and their absence means false.)
20216  * If we put an Angular interpolation expression into such an attribute then the
20217  * binding information would be lost when the browser removes the attribute.
20218  * The `ngSelected` directive solves this problem for the `selected` attribute.
20219  * This complementary directive is not removed by the browser and so provides
20220  * a permanent reliable place to store the binding information.
20221  *
20222  * @example
20223     <example>
20224       <file name="index.html">
20225         <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
20226         <select aria-label="ngSelected demo">
20227           <option>Hello!</option>
20228           <option id="greet" ng-selected="selected">Greetings!</option>
20229         </select>
20230       </file>
20231       <file name="protractor.js" type="protractor">
20232         it('should select Greetings!', function() {
20233           expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
20234           element(by.model('selected')).click();
20235           expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
20236         });
20237       </file>
20238     </example>
20239  *
20240  * @element OPTION
20241  * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
20242  *     then special attribute "selected" will be set on the element
20243  */
20244
20245 /**
20246  * @ngdoc directive
20247  * @name ngOpen
20248  * @restrict A
20249  * @priority 100
20250  *
20251  * @description
20252  * The HTML specification does not require browsers to preserve the values of boolean attributes
20253  * such as open. (Their presence means true and their absence means false.)
20254  * If we put an Angular interpolation expression into such an attribute then the
20255  * binding information would be lost when the browser removes the attribute.
20256  * The `ngOpen` directive solves this problem for the `open` attribute.
20257  * This complementary directive is not removed by the browser and so provides
20258  * a permanent reliable place to store the binding information.
20259  * @example
20260      <example>
20261        <file name="index.html">
20262          <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
20263          <details id="details" ng-open="open">
20264             <summary>Show/Hide me</summary>
20265          </details>
20266        </file>
20267        <file name="protractor.js" type="protractor">
20268          it('should toggle open', function() {
20269            expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
20270            element(by.model('open')).click();
20271            expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
20272          });
20273        </file>
20274      </example>
20275  *
20276  * @element DETAILS
20277  * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
20278  *     then special attribute "open" will be set on the element
20279  */
20280
20281 var ngAttributeAliasDirectives = {};
20282
20283 // boolean attrs are evaluated
20284 forEach(BOOLEAN_ATTR, function(propName, attrName) {
20285   // binding to multiple is not supported
20286   if (propName == "multiple") return;
20287
20288   function defaultLinkFn(scope, element, attr) {
20289     scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
20290       attr.$set(attrName, !!value);
20291     });
20292   }
20293
20294   var normalized = directiveNormalize('ng-' + attrName);
20295   var linkFn = defaultLinkFn;
20296
20297   if (propName === 'checked') {
20298     linkFn = function(scope, element, attr) {
20299       // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
20300       if (attr.ngModel !== attr[normalized]) {
20301         defaultLinkFn(scope, element, attr);
20302       }
20303     };
20304   }
20305
20306   ngAttributeAliasDirectives[normalized] = function() {
20307     return {
20308       restrict: 'A',
20309       priority: 100,
20310       link: linkFn
20311     };
20312   };
20313 });
20314
20315 // aliased input attrs are evaluated
20316 forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
20317   ngAttributeAliasDirectives[ngAttr] = function() {
20318     return {
20319       priority: 100,
20320       link: function(scope, element, attr) {
20321         //special case ngPattern when a literal regular expression value
20322         //is used as the expression (this way we don't have to watch anything).
20323         if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
20324           var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
20325           if (match) {
20326             attr.$set("ngPattern", new RegExp(match[1], match[2]));
20327             return;
20328           }
20329         }
20330
20331         scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
20332           attr.$set(ngAttr, value);
20333         });
20334       }
20335     };
20336   };
20337 });
20338
20339 // ng-src, ng-srcset, ng-href are interpolated
20340 forEach(['src', 'srcset', 'href'], function(attrName) {
20341   var normalized = directiveNormalize('ng-' + attrName);
20342   ngAttributeAliasDirectives[normalized] = function() {
20343     return {
20344       priority: 99, // it needs to run after the attributes are interpolated
20345       link: function(scope, element, attr) {
20346         var propName = attrName,
20347             name = attrName;
20348
20349         if (attrName === 'href' &&
20350             toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
20351           name = 'xlinkHref';
20352           attr.$attr[name] = 'xlink:href';
20353           propName = null;
20354         }
20355
20356         attr.$observe(normalized, function(value) {
20357           if (!value) {
20358             if (attrName === 'href') {
20359               attr.$set(name, null);
20360             }
20361             return;
20362           }
20363
20364           attr.$set(name, value);
20365
20366           // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
20367           // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
20368           // to set the property as well to achieve the desired effect.
20369           // we use attr[attrName] value since $set can sanitize the url.
20370           if (msie && propName) element.prop(propName, attr[name]);
20371         });
20372       }
20373     };
20374   };
20375 });
20376
20377 /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
20378  */
20379 var nullFormCtrl = {
20380   $addControl: noop,
20381   $$renameControl: nullFormRenameControl,
20382   $removeControl: noop,
20383   $setValidity: noop,
20384   $setDirty: noop,
20385   $setPristine: noop,
20386   $setSubmitted: noop
20387 },
20388 SUBMITTED_CLASS = 'ng-submitted';
20389
20390 function nullFormRenameControl(control, name) {
20391   control.$name = name;
20392 }
20393
20394 /**
20395  * @ngdoc type
20396  * @name form.FormController
20397  *
20398  * @property {boolean} $pristine True if user has not interacted with the form yet.
20399  * @property {boolean} $dirty True if user has already interacted with the form.
20400  * @property {boolean} $valid True if all of the containing forms and controls are valid.
20401  * @property {boolean} $invalid True if at least one containing control or form is invalid.
20402  * @property {boolean} $pending True if at least one containing control or form is pending.
20403  * @property {boolean} $submitted True if user has submitted the form even if its invalid.
20404  *
20405  * @property {Object} $error Is an object hash, containing references to controls or
20406  *  forms with failing validators, where:
20407  *
20408  *  - keys are validation tokens (error names),
20409  *  - values are arrays of controls or forms that have a failing validator for given error name.
20410  *
20411  *  Built-in validation tokens:
20412  *
20413  *  - `email`
20414  *  - `max`
20415  *  - `maxlength`
20416  *  - `min`
20417  *  - `minlength`
20418  *  - `number`
20419  *  - `pattern`
20420  *  - `required`
20421  *  - `url`
20422  *  - `date`
20423  *  - `datetimelocal`
20424  *  - `time`
20425  *  - `week`
20426  *  - `month`
20427  *
20428  * @description
20429  * `FormController` keeps track of all its controls and nested forms as well as the state of them,
20430  * such as being valid/invalid or dirty/pristine.
20431  *
20432  * Each {@link ng.directive:form form} directive creates an instance
20433  * of `FormController`.
20434  *
20435  */
20436 //asks for $scope to fool the BC controller module
20437 FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
20438 function FormController(element, attrs, $scope, $animate, $interpolate) {
20439   var form = this,
20440       controls = [];
20441
20442   // init state
20443   form.$error = {};
20444   form.$$success = {};
20445   form.$pending = undefined;
20446   form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
20447   form.$dirty = false;
20448   form.$pristine = true;
20449   form.$valid = true;
20450   form.$invalid = false;
20451   form.$submitted = false;
20452   form.$$parentForm = nullFormCtrl;
20453
20454   /**
20455    * @ngdoc method
20456    * @name form.FormController#$rollbackViewValue
20457    *
20458    * @description
20459    * Rollback all form controls pending updates to the `$modelValue`.
20460    *
20461    * Updates may be pending by a debounced event or because the input is waiting for a some future
20462    * event defined in `ng-model-options`. This method is typically needed by the reset button of
20463    * a form that uses `ng-model-options` to pend updates.
20464    */
20465   form.$rollbackViewValue = function() {
20466     forEach(controls, function(control) {
20467       control.$rollbackViewValue();
20468     });
20469   };
20470
20471   /**
20472    * @ngdoc method
20473    * @name form.FormController#$commitViewValue
20474    *
20475    * @description
20476    * Commit all form controls pending updates to the `$modelValue`.
20477    *
20478    * Updates may be pending by a debounced event or because the input is waiting for a some future
20479    * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
20480    * usually handles calling this in response to input events.
20481    */
20482   form.$commitViewValue = function() {
20483     forEach(controls, function(control) {
20484       control.$commitViewValue();
20485     });
20486   };
20487
20488   /**
20489    * @ngdoc method
20490    * @name form.FormController#$addControl
20491    * @param {object} control control object, either a {@link form.FormController} or an
20492    * {@link ngModel.NgModelController}
20493    *
20494    * @description
20495    * Register a control with the form. Input elements using ngModelController do this automatically
20496    * when they are linked.
20497    *
20498    * Note that the current state of the control will not be reflected on the new parent form. This
20499    * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
20500    * state.
20501    *
20502    * However, if the method is used programmatically, for example by adding dynamically created controls,
20503    * or controls that have been previously removed without destroying their corresponding DOM element,
20504    * it's the developers responsiblity to make sure the current state propagates to the parent form.
20505    *
20506    * For example, if an input control is added that is already `$dirty` and has `$error` properties,
20507    * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
20508    */
20509   form.$addControl = function(control) {
20510     // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
20511     // and not added to the scope.  Now we throw an error.
20512     assertNotHasOwnProperty(control.$name, 'input');
20513     controls.push(control);
20514
20515     if (control.$name) {
20516       form[control.$name] = control;
20517     }
20518
20519     control.$$parentForm = form;
20520   };
20521
20522   // Private API: rename a form control
20523   form.$$renameControl = function(control, newName) {
20524     var oldName = control.$name;
20525
20526     if (form[oldName] === control) {
20527       delete form[oldName];
20528     }
20529     form[newName] = control;
20530     control.$name = newName;
20531   };
20532
20533   /**
20534    * @ngdoc method
20535    * @name form.FormController#$removeControl
20536    * @param {object} control control object, either a {@link form.FormController} or an
20537    * {@link ngModel.NgModelController}
20538    *
20539    * @description
20540    * Deregister a control from the form.
20541    *
20542    * Input elements using ngModelController do this automatically when they are destroyed.
20543    *
20544    * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
20545    * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
20546    * different from case to case. For example, removing the only `$dirty` control from a form may or
20547    * may not mean that the form is still `$dirty`.
20548    */
20549   form.$removeControl = function(control) {
20550     if (control.$name && form[control.$name] === control) {
20551       delete form[control.$name];
20552     }
20553     forEach(form.$pending, function(value, name) {
20554       form.$setValidity(name, null, control);
20555     });
20556     forEach(form.$error, function(value, name) {
20557       form.$setValidity(name, null, control);
20558     });
20559     forEach(form.$$success, function(value, name) {
20560       form.$setValidity(name, null, control);
20561     });
20562
20563     arrayRemove(controls, control);
20564     control.$$parentForm = nullFormCtrl;
20565   };
20566
20567
20568   /**
20569    * @ngdoc method
20570    * @name form.FormController#$setValidity
20571    *
20572    * @description
20573    * Sets the validity of a form control.
20574    *
20575    * This method will also propagate to parent forms.
20576    */
20577   addSetValidityMethod({
20578     ctrl: this,
20579     $element: element,
20580     set: function(object, property, controller) {
20581       var list = object[property];
20582       if (!list) {
20583         object[property] = [controller];
20584       } else {
20585         var index = list.indexOf(controller);
20586         if (index === -1) {
20587           list.push(controller);
20588         }
20589       }
20590     },
20591     unset: function(object, property, controller) {
20592       var list = object[property];
20593       if (!list) {
20594         return;
20595       }
20596       arrayRemove(list, controller);
20597       if (list.length === 0) {
20598         delete object[property];
20599       }
20600     },
20601     $animate: $animate
20602   });
20603
20604   /**
20605    * @ngdoc method
20606    * @name form.FormController#$setDirty
20607    *
20608    * @description
20609    * Sets the form to a dirty state.
20610    *
20611    * This method can be called to add the 'ng-dirty' class and set the form to a dirty
20612    * state (ng-dirty class). This method will also propagate to parent forms.
20613    */
20614   form.$setDirty = function() {
20615     $animate.removeClass(element, PRISTINE_CLASS);
20616     $animate.addClass(element, DIRTY_CLASS);
20617     form.$dirty = true;
20618     form.$pristine = false;
20619     form.$$parentForm.$setDirty();
20620   };
20621
20622   /**
20623    * @ngdoc method
20624    * @name form.FormController#$setPristine
20625    *
20626    * @description
20627    * Sets the form to its pristine state.
20628    *
20629    * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
20630    * state (ng-pristine class). This method will also propagate to all the controls contained
20631    * in this form.
20632    *
20633    * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
20634    * saving or resetting it.
20635    */
20636   form.$setPristine = function() {
20637     $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
20638     form.$dirty = false;
20639     form.$pristine = true;
20640     form.$submitted = false;
20641     forEach(controls, function(control) {
20642       control.$setPristine();
20643     });
20644   };
20645
20646   /**
20647    * @ngdoc method
20648    * @name form.FormController#$setUntouched
20649    *
20650    * @description
20651    * Sets the form to its untouched state.
20652    *
20653    * This method can be called to remove the 'ng-touched' class and set the form controls to their
20654    * untouched state (ng-untouched class).
20655    *
20656    * Setting a form controls back to their untouched state is often useful when setting the form
20657    * back to its pristine state.
20658    */
20659   form.$setUntouched = function() {
20660     forEach(controls, function(control) {
20661       control.$setUntouched();
20662     });
20663   };
20664
20665   /**
20666    * @ngdoc method
20667    * @name form.FormController#$setSubmitted
20668    *
20669    * @description
20670    * Sets the form to its submitted state.
20671    */
20672   form.$setSubmitted = function() {
20673     $animate.addClass(element, SUBMITTED_CLASS);
20674     form.$submitted = true;
20675     form.$$parentForm.$setSubmitted();
20676   };
20677 }
20678
20679 /**
20680  * @ngdoc directive
20681  * @name ngForm
20682  * @restrict EAC
20683  *
20684  * @description
20685  * Nestable alias of {@link ng.directive:form `form`} directive. HTML
20686  * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
20687  * sub-group of controls needs to be determined.
20688  *
20689  * Note: the purpose of `ngForm` is to group controls,
20690  * but not to be a replacement for the `<form>` tag with all of its capabilities
20691  * (e.g. posting to the server, ...).
20692  *
20693  * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
20694  *                       related scope, under this name.
20695  *
20696  */
20697
20698  /**
20699  * @ngdoc directive
20700  * @name form
20701  * @restrict E
20702  *
20703  * @description
20704  * Directive that instantiates
20705  * {@link form.FormController FormController}.
20706  *
20707  * If the `name` attribute is specified, the form controller is published onto the current scope under
20708  * this name.
20709  *
20710  * # Alias: {@link ng.directive:ngForm `ngForm`}
20711  *
20712  * In Angular, forms can be nested. This means that the outer form is valid when all of the child
20713  * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
20714  * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
20715  * `<form>` but can be nested.  This allows you to have nested forms, which is very useful when
20716  * using Angular validation directives in forms that are dynamically generated using the
20717  * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
20718  * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
20719  * `ngForm` directive and nest these in an outer `form` element.
20720  *
20721  *
20722  * # CSS classes
20723  *  - `ng-valid` is set if the form is valid.
20724  *  - `ng-invalid` is set if the form is invalid.
20725  *  - `ng-pending` is set if the form is pending.
20726  *  - `ng-pristine` is set if the form is pristine.
20727  *  - `ng-dirty` is set if the form is dirty.
20728  *  - `ng-submitted` is set if the form was submitted.
20729  *
20730  * Keep in mind that ngAnimate can detect each of these classes when added and removed.
20731  *
20732  *
20733  * # Submitting a form and preventing the default action
20734  *
20735  * Since the role of forms in client-side Angular applications is different than in classical
20736  * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
20737  * page reload that sends the data to the server. Instead some javascript logic should be triggered
20738  * to handle the form submission in an application-specific way.
20739  *
20740  * For this reason, Angular prevents the default action (form submission to the server) unless the
20741  * `<form>` element has an `action` attribute specified.
20742  *
20743  * You can use one of the following two ways to specify what javascript method should be called when
20744  * a form is submitted:
20745  *
20746  * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
20747  * - {@link ng.directive:ngClick ngClick} directive on the first
20748   *  button or input field of type submit (input[type=submit])
20749  *
20750  * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
20751  * or {@link ng.directive:ngClick ngClick} directives.
20752  * This is because of the following form submission rules in the HTML specification:
20753  *
20754  * - If a form has only one input field then hitting enter in this field triggers form submit
20755  * (`ngSubmit`)
20756  * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
20757  * doesn't trigger submit
20758  * - if a form has one or more input fields and one or more buttons or input[type=submit] then
20759  * hitting enter in any of the input fields will trigger the click handler on the *first* button or
20760  * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
20761  *
20762  * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
20763  * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
20764  * to have access to the updated model.
20765  *
20766  * ## Animation Hooks
20767  *
20768  * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
20769  * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
20770  * other validations that are performed within the form. Animations in ngForm are similar to how
20771  * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
20772  * as JS animations.
20773  *
20774  * The following example shows a simple way to utilize CSS transitions to style a form element
20775  * that has been rendered as invalid after it has been validated:
20776  *
20777  * <pre>
20778  * //be sure to include ngAnimate as a module to hook into more
20779  * //advanced animations
20780  * .my-form {
20781  *   transition:0.5s linear all;
20782  *   background: white;
20783  * }
20784  * .my-form.ng-invalid {
20785  *   background: red;
20786  *   color:white;
20787  * }
20788  * </pre>
20789  *
20790  * @example
20791     <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
20792       <file name="index.html">
20793        <script>
20794          angular.module('formExample', [])
20795            .controller('FormController', ['$scope', function($scope) {
20796              $scope.userType = 'guest';
20797            }]);
20798        </script>
20799        <style>
20800         .my-form {
20801           transition:all linear 0.5s;
20802           background: transparent;
20803         }
20804         .my-form.ng-invalid {
20805           background: red;
20806         }
20807        </style>
20808        <form name="myForm" ng-controller="FormController" class="my-form">
20809          userType: <input name="input" ng-model="userType" required>
20810          <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
20811          <code>userType = {{userType}}</code><br>
20812          <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
20813          <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
20814          <code>myForm.$valid = {{myForm.$valid}}</code><br>
20815          <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
20816         </form>
20817       </file>
20818       <file name="protractor.js" type="protractor">
20819         it('should initialize to model', function() {
20820           var userType = element(by.binding('userType'));
20821           var valid = element(by.binding('myForm.input.$valid'));
20822
20823           expect(userType.getText()).toContain('guest');
20824           expect(valid.getText()).toContain('true');
20825         });
20826
20827         it('should be invalid if empty', function() {
20828           var userType = element(by.binding('userType'));
20829           var valid = element(by.binding('myForm.input.$valid'));
20830           var userInput = element(by.model('userType'));
20831
20832           userInput.clear();
20833           userInput.sendKeys('');
20834
20835           expect(userType.getText()).toEqual('userType =');
20836           expect(valid.getText()).toContain('false');
20837         });
20838       </file>
20839     </example>
20840  *
20841  * @param {string=} name Name of the form. If specified, the form controller will be published into
20842  *                       related scope, under this name.
20843  */
20844 var formDirectiveFactory = function(isNgForm) {
20845   return ['$timeout', '$parse', function($timeout, $parse) {
20846     var formDirective = {
20847       name: 'form',
20848       restrict: isNgForm ? 'EAC' : 'E',
20849       require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
20850       controller: FormController,
20851       compile: function ngFormCompile(formElement, attr) {
20852         // Setup initial state of the control
20853         formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
20854
20855         var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
20856
20857         return {
20858           pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
20859             var controller = ctrls[0];
20860
20861             // if `action` attr is not present on the form, prevent the default action (submission)
20862             if (!('action' in attr)) {
20863               // we can't use jq events because if a form is destroyed during submission the default
20864               // action is not prevented. see #1238
20865               //
20866               // IE 9 is not affected because it doesn't fire a submit event and try to do a full
20867               // page reload if the form was destroyed by submission of the form via a click handler
20868               // on a button in the form. Looks like an IE9 specific bug.
20869               var handleFormSubmission = function(event) {
20870                 scope.$apply(function() {
20871                   controller.$commitViewValue();
20872                   controller.$setSubmitted();
20873                 });
20874
20875                 event.preventDefault();
20876               };
20877
20878               addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
20879
20880               // unregister the preventDefault listener so that we don't not leak memory but in a
20881               // way that will achieve the prevention of the default action.
20882               formElement.on('$destroy', function() {
20883                 $timeout(function() {
20884                   removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
20885                 }, 0, false);
20886               });
20887             }
20888
20889             var parentFormCtrl = ctrls[1] || controller.$$parentForm;
20890             parentFormCtrl.$addControl(controller);
20891
20892             var setter = nameAttr ? getSetter(controller.$name) : noop;
20893
20894             if (nameAttr) {
20895               setter(scope, controller);
20896               attr.$observe(nameAttr, function(newValue) {
20897                 if (controller.$name === newValue) return;
20898                 setter(scope, undefined);
20899                 controller.$$parentForm.$$renameControl(controller, newValue);
20900                 setter = getSetter(controller.$name);
20901                 setter(scope, controller);
20902               });
20903             }
20904             formElement.on('$destroy', function() {
20905               controller.$$parentForm.$removeControl(controller);
20906               setter(scope, undefined);
20907               extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
20908             });
20909           }
20910         };
20911       }
20912     };
20913
20914     return formDirective;
20915
20916     function getSetter(expression) {
20917       if (expression === '') {
20918         //create an assignable expression, so forms with an empty name can be renamed later
20919         return $parse('this[""]').assign;
20920       }
20921       return $parse(expression).assign || noop;
20922     }
20923   }];
20924 };
20925
20926 var formDirective = formDirectiveFactory();
20927 var ngFormDirective = formDirectiveFactory(true);
20928
20929 /* global VALID_CLASS: false,
20930   INVALID_CLASS: false,
20931   PRISTINE_CLASS: false,
20932   DIRTY_CLASS: false,
20933   UNTOUCHED_CLASS: false,
20934   TOUCHED_CLASS: false,
20935   ngModelMinErr: false,
20936 */
20937
20938 // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
20939 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)/;
20940 // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
20941 var URL_REGEXP = /^[A-Za-z][A-Za-z\d.+-]*:\/*(?:\w+(?::\w+)?@)?[^\s/]+(?::\d+)?(?:\/[\w#!:.?+=&%@\-/]*)?$/;
20942 var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
20943 var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
20944 var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
20945 var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
20946 var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
20947 var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
20948 var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
20949
20950 var inputType = {
20951
20952   /**
20953    * @ngdoc input
20954    * @name input[text]
20955    *
20956    * @description
20957    * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
20958    *
20959    *
20960    * @param {string} ngModel Assignable angular expression to data-bind to.
20961    * @param {string=} name Property name of the form under which the control is published.
20962    * @param {string=} required Adds `required` validation error key if the value is not entered.
20963    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
20964    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
20965    *    `required` when you want to data-bind to the `required` attribute.
20966    * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
20967    *    minlength.
20968    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
20969    *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
20970    *    any length.
20971    * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
20972    *    that contains the regular expression body that will be converted to a regular expression
20973    *    as in the ngPattern directive.
20974    * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
20975    *    a RegExp found by evaluating the Angular expression given in the attribute value.
20976    *    If the expression evaluates to a RegExp object, then this is used directly.
20977    *    If the expression evaluates to a string, then it will be converted to a RegExp
20978    *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
20979    *    `new RegExp('^abc$')`.<br />
20980    *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
20981    *    start at the index of the last search's match, thus not taking the whole input value into
20982    *    account.
20983    * @param {string=} ngChange Angular expression to be executed when input changes due to user
20984    *    interaction with the input element.
20985    * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
20986    *    This parameter is ignored for input[type=password] controls, which will never trim the
20987    *    input.
20988    *
20989    * @example
20990       <example name="text-input-directive" module="textInputExample">
20991         <file name="index.html">
20992          <script>
20993            angular.module('textInputExample', [])
20994              .controller('ExampleController', ['$scope', function($scope) {
20995                $scope.example = {
20996                  text: 'guest',
20997                  word: /^\s*\w*\s*$/
20998                };
20999              }]);
21000          </script>
21001          <form name="myForm" ng-controller="ExampleController">
21002            <label>Single word:
21003              <input type="text" name="input" ng-model="example.text"
21004                     ng-pattern="example.word" required ng-trim="false">
21005            </label>
21006            <div role="alert">
21007              <span class="error" ng-show="myForm.input.$error.required">
21008                Required!</span>
21009              <span class="error" ng-show="myForm.input.$error.pattern">
21010                Single word only!</span>
21011            </div>
21012            <tt>text = {{example.text}}</tt><br/>
21013            <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21014            <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21015            <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21016            <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21017           </form>
21018         </file>
21019         <file name="protractor.js" type="protractor">
21020           var text = element(by.binding('example.text'));
21021           var valid = element(by.binding('myForm.input.$valid'));
21022           var input = element(by.model('example.text'));
21023
21024           it('should initialize to model', function() {
21025             expect(text.getText()).toContain('guest');
21026             expect(valid.getText()).toContain('true');
21027           });
21028
21029           it('should be invalid if empty', function() {
21030             input.clear();
21031             input.sendKeys('');
21032
21033             expect(text.getText()).toEqual('text =');
21034             expect(valid.getText()).toContain('false');
21035           });
21036
21037           it('should be invalid if multi word', function() {
21038             input.clear();
21039             input.sendKeys('hello world');
21040
21041             expect(valid.getText()).toContain('false');
21042           });
21043         </file>
21044       </example>
21045    */
21046   'text': textInputType,
21047
21048     /**
21049      * @ngdoc input
21050      * @name input[date]
21051      *
21052      * @description
21053      * Input with date validation and transformation. In browsers that do not yet support
21054      * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
21055      * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
21056      * modern browsers do not yet support this input type, it is important to provide cues to users on the
21057      * expected input format via a placeholder or label.
21058      *
21059      * The model must always be a Date object, otherwise Angular will throw an error.
21060      * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21061      *
21062      * The timezone to be used to read/write the `Date` instance in the model can be defined using
21063      * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21064      *
21065      * @param {string} ngModel Assignable angular expression to data-bind to.
21066      * @param {string=} name Property name of the form under which the control is published.
21067      * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
21068      *   valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
21069      *   (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
21070      *   constraint validation.
21071      * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
21072      *   a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
21073      *   (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
21074      *   constraint validation.
21075      * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
21076      *   the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21077      * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
21078      *   the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21079      * @param {string=} required Sets `required` validation error key if the value is not entered.
21080      * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21081      *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21082      *    `required` when you want to data-bind to the `required` attribute.
21083      * @param {string=} ngChange Angular expression to be executed when input changes due to user
21084      *    interaction with the input element.
21085      *
21086      * @example
21087      <example name="date-input-directive" module="dateInputExample">
21088      <file name="index.html">
21089        <script>
21090           angular.module('dateInputExample', [])
21091             .controller('DateController', ['$scope', function($scope) {
21092               $scope.example = {
21093                 value: new Date(2013, 9, 22)
21094               };
21095             }]);
21096        </script>
21097        <form name="myForm" ng-controller="DateController as dateCtrl">
21098           <label for="exampleInput">Pick a date in 2013:</label>
21099           <input type="date" id="exampleInput" name="input" ng-model="example.value"
21100               placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
21101           <div role="alert">
21102             <span class="error" ng-show="myForm.input.$error.required">
21103                 Required!</span>
21104             <span class="error" ng-show="myForm.input.$error.date">
21105                 Not a valid date!</span>
21106            </div>
21107            <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
21108            <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21109            <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21110            <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21111            <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21112        </form>
21113      </file>
21114      <file name="protractor.js" type="protractor">
21115         var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
21116         var valid = element(by.binding('myForm.input.$valid'));
21117         var input = element(by.model('example.value'));
21118
21119         // currently protractor/webdriver does not support
21120         // sending keys to all known HTML5 input controls
21121         // for various browsers (see https://github.com/angular/protractor/issues/562).
21122         function setInput(val) {
21123           // set the value of the element and force validation.
21124           var scr = "var ipt = document.getElementById('exampleInput'); " +
21125           "ipt.value = '" + val + "';" +
21126           "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21127           browser.executeScript(scr);
21128         }
21129
21130         it('should initialize to model', function() {
21131           expect(value.getText()).toContain('2013-10-22');
21132           expect(valid.getText()).toContain('myForm.input.$valid = true');
21133         });
21134
21135         it('should be invalid if empty', function() {
21136           setInput('');
21137           expect(value.getText()).toEqual('value =');
21138           expect(valid.getText()).toContain('myForm.input.$valid = false');
21139         });
21140
21141         it('should be invalid if over max', function() {
21142           setInput('2015-01-01');
21143           expect(value.getText()).toContain('');
21144           expect(valid.getText()).toContain('myForm.input.$valid = false');
21145         });
21146      </file>
21147      </example>
21148      */
21149   'date': createDateInputType('date', DATE_REGEXP,
21150          createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
21151          'yyyy-MM-dd'),
21152
21153    /**
21154     * @ngdoc input
21155     * @name input[datetime-local]
21156     *
21157     * @description
21158     * Input with datetime validation and transformation. In browsers that do not yet support
21159     * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21160     * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
21161     *
21162     * The model must always be a Date object, otherwise Angular will throw an error.
21163     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21164     *
21165     * The timezone to be used to read/write the `Date` instance in the model can be defined using
21166     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21167     *
21168     * @param {string} ngModel Assignable angular expression to data-bind to.
21169     * @param {string=} name Property name of the form under which the control is published.
21170     * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21171     *   This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
21172     *   inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
21173     *   Note that `min` will also add native HTML5 constraint validation.
21174     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21175     *   This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
21176     *   inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
21177     *   Note that `max` will also add native HTML5 constraint validation.
21178     * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
21179     *   the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21180     * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
21181     *   the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21182     * @param {string=} required Sets `required` validation error key if the value is not entered.
21183     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21184     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21185     *    `required` when you want to data-bind to the `required` attribute.
21186     * @param {string=} ngChange Angular expression to be executed when input changes due to user
21187     *    interaction with the input element.
21188     *
21189     * @example
21190     <example name="datetimelocal-input-directive" module="dateExample">
21191     <file name="index.html">
21192       <script>
21193         angular.module('dateExample', [])
21194           .controller('DateController', ['$scope', function($scope) {
21195             $scope.example = {
21196               value: new Date(2010, 11, 28, 14, 57)
21197             };
21198           }]);
21199       </script>
21200       <form name="myForm" ng-controller="DateController as dateCtrl">
21201         <label for="exampleInput">Pick a date between in 2013:</label>
21202         <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
21203             placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
21204         <div role="alert">
21205           <span class="error" ng-show="myForm.input.$error.required">
21206               Required!</span>
21207           <span class="error" ng-show="myForm.input.$error.datetimelocal">
21208               Not a valid date!</span>
21209         </div>
21210         <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
21211         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21212         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21213         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21214         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21215       </form>
21216     </file>
21217     <file name="protractor.js" type="protractor">
21218       var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
21219       var valid = element(by.binding('myForm.input.$valid'));
21220       var input = element(by.model('example.value'));
21221
21222       // currently protractor/webdriver does not support
21223       // sending keys to all known HTML5 input controls
21224       // for various browsers (https://github.com/angular/protractor/issues/562).
21225       function setInput(val) {
21226         // set the value of the element and force validation.
21227         var scr = "var ipt = document.getElementById('exampleInput'); " +
21228         "ipt.value = '" + val + "';" +
21229         "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21230         browser.executeScript(scr);
21231       }
21232
21233       it('should initialize to model', function() {
21234         expect(value.getText()).toContain('2010-12-28T14:57:00');
21235         expect(valid.getText()).toContain('myForm.input.$valid = true');
21236       });
21237
21238       it('should be invalid if empty', function() {
21239         setInput('');
21240         expect(value.getText()).toEqual('value =');
21241         expect(valid.getText()).toContain('myForm.input.$valid = false');
21242       });
21243
21244       it('should be invalid if over max', function() {
21245         setInput('2015-01-01T23:59:00');
21246         expect(value.getText()).toContain('');
21247         expect(valid.getText()).toContain('myForm.input.$valid = false');
21248       });
21249     </file>
21250     </example>
21251     */
21252   'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
21253       createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
21254       'yyyy-MM-ddTHH:mm:ss.sss'),
21255
21256   /**
21257    * @ngdoc input
21258    * @name input[time]
21259    *
21260    * @description
21261    * Input with time validation and transformation. In browsers that do not yet support
21262    * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21263    * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
21264    * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
21265    *
21266    * The model must always be a Date object, otherwise Angular will throw an error.
21267    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21268    *
21269    * The timezone to be used to read/write the `Date` instance in the model can be defined using
21270    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21271    *
21272    * @param {string} ngModel Assignable angular expression to data-bind to.
21273    * @param {string=} name Property name of the form under which the control is published.
21274    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21275    *   This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
21276    *   attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
21277    *   native HTML5 constraint validation.
21278    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21279    *   This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
21280    *   attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
21281    *   native HTML5 constraint validation.
21282    * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
21283    *   `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21284    * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
21285    *   `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21286    * @param {string=} required Sets `required` validation error key if the value is not entered.
21287    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21288    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21289    *    `required` when you want to data-bind to the `required` attribute.
21290    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21291    *    interaction with the input element.
21292    *
21293    * @example
21294    <example name="time-input-directive" module="timeExample">
21295    <file name="index.html">
21296      <script>
21297       angular.module('timeExample', [])
21298         .controller('DateController', ['$scope', function($scope) {
21299           $scope.example = {
21300             value: new Date(1970, 0, 1, 14, 57, 0)
21301           };
21302         }]);
21303      </script>
21304      <form name="myForm" ng-controller="DateController as dateCtrl">
21305         <label for="exampleInput">Pick a between 8am and 5pm:</label>
21306         <input type="time" id="exampleInput" name="input" ng-model="example.value"
21307             placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
21308         <div role="alert">
21309           <span class="error" ng-show="myForm.input.$error.required">
21310               Required!</span>
21311           <span class="error" ng-show="myForm.input.$error.time">
21312               Not a valid date!</span>
21313         </div>
21314         <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
21315         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21316         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21317         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21318         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21319      </form>
21320    </file>
21321    <file name="protractor.js" type="protractor">
21322       var value = element(by.binding('example.value | date: "HH:mm:ss"'));
21323       var valid = element(by.binding('myForm.input.$valid'));
21324       var input = element(by.model('example.value'));
21325
21326       // currently protractor/webdriver does not support
21327       // sending keys to all known HTML5 input controls
21328       // for various browsers (https://github.com/angular/protractor/issues/562).
21329       function setInput(val) {
21330         // set the value of the element and force validation.
21331         var scr = "var ipt = document.getElementById('exampleInput'); " +
21332         "ipt.value = '" + val + "';" +
21333         "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21334         browser.executeScript(scr);
21335       }
21336
21337       it('should initialize to model', function() {
21338         expect(value.getText()).toContain('14:57:00');
21339         expect(valid.getText()).toContain('myForm.input.$valid = true');
21340       });
21341
21342       it('should be invalid if empty', function() {
21343         setInput('');
21344         expect(value.getText()).toEqual('value =');
21345         expect(valid.getText()).toContain('myForm.input.$valid = false');
21346       });
21347
21348       it('should be invalid if over max', function() {
21349         setInput('23:59:00');
21350         expect(value.getText()).toContain('');
21351         expect(valid.getText()).toContain('myForm.input.$valid = false');
21352       });
21353    </file>
21354    </example>
21355    */
21356   'time': createDateInputType('time', TIME_REGEXP,
21357       createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
21358      'HH:mm:ss.sss'),
21359
21360    /**
21361     * @ngdoc input
21362     * @name input[week]
21363     *
21364     * @description
21365     * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
21366     * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21367     * week format (yyyy-W##), for example: `2013-W02`.
21368     *
21369     * The model must always be a Date object, otherwise Angular will throw an error.
21370     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21371     *
21372     * The timezone to be used to read/write the `Date` instance in the model can be defined using
21373     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21374     *
21375     * @param {string} ngModel Assignable angular expression to data-bind to.
21376     * @param {string=} name Property name of the form under which the control is published.
21377     * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21378     *   This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
21379     *   attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
21380     *   native HTML5 constraint validation.
21381     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21382     *   This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
21383     *   attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
21384     *   native HTML5 constraint validation.
21385     * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
21386     *   the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21387     * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
21388     *   the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21389     * @param {string=} required Sets `required` validation error key if the value is not entered.
21390     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21391     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21392     *    `required` when you want to data-bind to the `required` attribute.
21393     * @param {string=} ngChange Angular expression to be executed when input changes due to user
21394     *    interaction with the input element.
21395     *
21396     * @example
21397     <example name="week-input-directive" module="weekExample">
21398     <file name="index.html">
21399       <script>
21400       angular.module('weekExample', [])
21401         .controller('DateController', ['$scope', function($scope) {
21402           $scope.example = {
21403             value: new Date(2013, 0, 3)
21404           };
21405         }]);
21406       </script>
21407       <form name="myForm" ng-controller="DateController as dateCtrl">
21408         <label>Pick a date between in 2013:
21409           <input id="exampleInput" type="week" name="input" ng-model="example.value"
21410                  placeholder="YYYY-W##" min="2012-W32"
21411                  max="2013-W52" required />
21412         </label>
21413         <div role="alert">
21414           <span class="error" ng-show="myForm.input.$error.required">
21415               Required!</span>
21416           <span class="error" ng-show="myForm.input.$error.week">
21417               Not a valid date!</span>
21418         </div>
21419         <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
21420         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21421         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21422         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21423         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21424       </form>
21425     </file>
21426     <file name="protractor.js" type="protractor">
21427       var value = element(by.binding('example.value | date: "yyyy-Www"'));
21428       var valid = element(by.binding('myForm.input.$valid'));
21429       var input = element(by.model('example.value'));
21430
21431       // currently protractor/webdriver does not support
21432       // sending keys to all known HTML5 input controls
21433       // for various browsers (https://github.com/angular/protractor/issues/562).
21434       function setInput(val) {
21435         // set the value of the element and force validation.
21436         var scr = "var ipt = document.getElementById('exampleInput'); " +
21437         "ipt.value = '" + val + "';" +
21438         "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21439         browser.executeScript(scr);
21440       }
21441
21442       it('should initialize to model', function() {
21443         expect(value.getText()).toContain('2013-W01');
21444         expect(valid.getText()).toContain('myForm.input.$valid = true');
21445       });
21446
21447       it('should be invalid if empty', function() {
21448         setInput('');
21449         expect(value.getText()).toEqual('value =');
21450         expect(valid.getText()).toContain('myForm.input.$valid = false');
21451       });
21452
21453       it('should be invalid if over max', function() {
21454         setInput('2015-W01');
21455         expect(value.getText()).toContain('');
21456         expect(valid.getText()).toContain('myForm.input.$valid = false');
21457       });
21458     </file>
21459     </example>
21460     */
21461   'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
21462
21463   /**
21464    * @ngdoc input
21465    * @name input[month]
21466    *
21467    * @description
21468    * Input with month validation and transformation. In browsers that do not yet support
21469    * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21470    * month format (yyyy-MM), for example: `2009-01`.
21471    *
21472    * The model must always be a Date object, otherwise Angular will throw an error.
21473    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21474    * If the model is not set to the first of the month, the next view to model update will set it
21475    * to the first of the month.
21476    *
21477    * The timezone to be used to read/write the `Date` instance in the model can be defined using
21478    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21479    *
21480    * @param {string} ngModel Assignable angular expression to data-bind to.
21481    * @param {string=} name Property name of the form under which the control is published.
21482    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21483    *   This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
21484    *   attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
21485    *   native HTML5 constraint validation.
21486    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21487    *   This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
21488    *   attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
21489    *   native HTML5 constraint validation.
21490    * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
21491    *   the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21492    * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
21493    *   the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21494
21495    * @param {string=} required Sets `required` validation error key if the value is not entered.
21496    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21497    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21498    *    `required` when you want to data-bind to the `required` attribute.
21499    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21500    *    interaction with the input element.
21501    *
21502    * @example
21503    <example name="month-input-directive" module="monthExample">
21504    <file name="index.html">
21505      <script>
21506       angular.module('monthExample', [])
21507         .controller('DateController', ['$scope', function($scope) {
21508           $scope.example = {
21509             value: new Date(2013, 9, 1)
21510           };
21511         }]);
21512      </script>
21513      <form name="myForm" ng-controller="DateController as dateCtrl">
21514        <label for="exampleInput">Pick a month in 2013:</label>
21515        <input id="exampleInput" type="month" name="input" ng-model="example.value"
21516           placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
21517        <div role="alert">
21518          <span class="error" ng-show="myForm.input.$error.required">
21519             Required!</span>
21520          <span class="error" ng-show="myForm.input.$error.month">
21521             Not a valid month!</span>
21522        </div>
21523        <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
21524        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21525        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21526        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21527        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21528      </form>
21529    </file>
21530    <file name="protractor.js" type="protractor">
21531       var value = element(by.binding('example.value | date: "yyyy-MM"'));
21532       var valid = element(by.binding('myForm.input.$valid'));
21533       var input = element(by.model('example.value'));
21534
21535       // currently protractor/webdriver does not support
21536       // sending keys to all known HTML5 input controls
21537       // for various browsers (https://github.com/angular/protractor/issues/562).
21538       function setInput(val) {
21539         // set the value of the element and force validation.
21540         var scr = "var ipt = document.getElementById('exampleInput'); " +
21541         "ipt.value = '" + val + "';" +
21542         "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21543         browser.executeScript(scr);
21544       }
21545
21546       it('should initialize to model', function() {
21547         expect(value.getText()).toContain('2013-10');
21548         expect(valid.getText()).toContain('myForm.input.$valid = true');
21549       });
21550
21551       it('should be invalid if empty', function() {
21552         setInput('');
21553         expect(value.getText()).toEqual('value =');
21554         expect(valid.getText()).toContain('myForm.input.$valid = false');
21555       });
21556
21557       it('should be invalid if over max', function() {
21558         setInput('2015-01');
21559         expect(value.getText()).toContain('');
21560         expect(valid.getText()).toContain('myForm.input.$valid = false');
21561       });
21562    </file>
21563    </example>
21564    */
21565   'month': createDateInputType('month', MONTH_REGEXP,
21566      createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
21567      'yyyy-MM'),
21568
21569   /**
21570    * @ngdoc input
21571    * @name input[number]
21572    *
21573    * @description
21574    * Text input with number validation and transformation. Sets the `number` validation
21575    * error if not a valid number.
21576    *
21577    * <div class="alert alert-warning">
21578    * The model must always be of type `number` otherwise Angular will throw an error.
21579    * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
21580    * error docs for more information and an example of how to convert your model if necessary.
21581    * </div>
21582    *
21583    * ## Issues with HTML5 constraint validation
21584    *
21585    * In browsers that follow the
21586    * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
21587    * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
21588    * If a non-number is entered in the input, the browser will report the value as an empty string,
21589    * which means the view / model values in `ngModel` and subsequently the scope value
21590    * will also be an empty string.
21591    *
21592    *
21593    * @param {string} ngModel Assignable angular expression to data-bind to.
21594    * @param {string=} name Property name of the form under which the control is published.
21595    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21596    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21597    * @param {string=} required Sets `required` validation error key if the value is not entered.
21598    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21599    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21600    *    `required` when you want to data-bind to the `required` attribute.
21601    * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
21602    *    minlength.
21603    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
21604    *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
21605    *    any length.
21606    * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
21607    *    that contains the regular expression body that will be converted to a regular expression
21608    *    as in the ngPattern directive.
21609    * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
21610    *    a RegExp found by evaluating the Angular expression given in the attribute value.
21611    *    If the expression evaluates to a RegExp object, then this is used directly.
21612    *    If the expression evaluates to a string, then it will be converted to a RegExp
21613    *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
21614    *    `new RegExp('^abc$')`.<br />
21615    *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
21616    *    start at the index of the last search's match, thus not taking the whole input value into
21617    *    account.
21618    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21619    *    interaction with the input element.
21620    *
21621    * @example
21622       <example name="number-input-directive" module="numberExample">
21623         <file name="index.html">
21624          <script>
21625            angular.module('numberExample', [])
21626              .controller('ExampleController', ['$scope', function($scope) {
21627                $scope.example = {
21628                  value: 12
21629                };
21630              }]);
21631          </script>
21632          <form name="myForm" ng-controller="ExampleController">
21633            <label>Number:
21634              <input type="number" name="input" ng-model="example.value"
21635                     min="0" max="99" required>
21636           </label>
21637            <div role="alert">
21638              <span class="error" ng-show="myForm.input.$error.required">
21639                Required!</span>
21640              <span class="error" ng-show="myForm.input.$error.number">
21641                Not valid number!</span>
21642            </div>
21643            <tt>value = {{example.value}}</tt><br/>
21644            <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21645            <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21646            <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21647            <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21648           </form>
21649         </file>
21650         <file name="protractor.js" type="protractor">
21651           var value = element(by.binding('example.value'));
21652           var valid = element(by.binding('myForm.input.$valid'));
21653           var input = element(by.model('example.value'));
21654
21655           it('should initialize to model', function() {
21656             expect(value.getText()).toContain('12');
21657             expect(valid.getText()).toContain('true');
21658           });
21659
21660           it('should be invalid if empty', function() {
21661             input.clear();
21662             input.sendKeys('');
21663             expect(value.getText()).toEqual('value =');
21664             expect(valid.getText()).toContain('false');
21665           });
21666
21667           it('should be invalid if over max', function() {
21668             input.clear();
21669             input.sendKeys('123');
21670             expect(value.getText()).toEqual('value =');
21671             expect(valid.getText()).toContain('false');
21672           });
21673         </file>
21674       </example>
21675    */
21676   'number': numberInputType,
21677
21678
21679   /**
21680    * @ngdoc input
21681    * @name input[url]
21682    *
21683    * @description
21684    * Text input with URL validation. Sets the `url` validation error key if the content is not a
21685    * valid URL.
21686    *
21687    * <div class="alert alert-warning">
21688    * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
21689    * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
21690    * the built-in validators (see the {@link guide/forms Forms guide})
21691    * </div>
21692    *
21693    * @param {string} ngModel Assignable angular expression to data-bind to.
21694    * @param {string=} name Property name of the form under which the control is published.
21695    * @param {string=} required Sets `required` validation error key if the value is not entered.
21696    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21697    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21698    *    `required` when you want to data-bind to the `required` attribute.
21699    * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
21700    *    minlength.
21701    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
21702    *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
21703    *    any length.
21704    * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
21705    *    that contains the regular expression body that will be converted to a regular expression
21706    *    as in the ngPattern directive.
21707    * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
21708    *    a RegExp found by evaluating the Angular expression given in the attribute value.
21709    *    If the expression evaluates to a RegExp object, then this is used directly.
21710    *    If the expression evaluates to a string, then it will be converted to a RegExp
21711    *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
21712    *    `new RegExp('^abc$')`.<br />
21713    *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
21714    *    start at the index of the last search's match, thus not taking the whole input value into
21715    *    account.
21716    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21717    *    interaction with the input element.
21718    *
21719    * @example
21720       <example name="url-input-directive" module="urlExample">
21721         <file name="index.html">
21722          <script>
21723            angular.module('urlExample', [])
21724              .controller('ExampleController', ['$scope', function($scope) {
21725                $scope.url = {
21726                  text: 'http://google.com'
21727                };
21728              }]);
21729          </script>
21730          <form name="myForm" ng-controller="ExampleController">
21731            <label>URL:
21732              <input type="url" name="input" ng-model="url.text" required>
21733            <label>
21734            <div role="alert">
21735              <span class="error" ng-show="myForm.input.$error.required">
21736                Required!</span>
21737              <span class="error" ng-show="myForm.input.$error.url">
21738                Not valid url!</span>
21739            </div>
21740            <tt>text = {{url.text}}</tt><br/>
21741            <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21742            <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21743            <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21744            <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21745            <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
21746           </form>
21747         </file>
21748         <file name="protractor.js" type="protractor">
21749           var text = element(by.binding('url.text'));
21750           var valid = element(by.binding('myForm.input.$valid'));
21751           var input = element(by.model('url.text'));
21752
21753           it('should initialize to model', function() {
21754             expect(text.getText()).toContain('http://google.com');
21755             expect(valid.getText()).toContain('true');
21756           });
21757
21758           it('should be invalid if empty', function() {
21759             input.clear();
21760             input.sendKeys('');
21761
21762             expect(text.getText()).toEqual('text =');
21763             expect(valid.getText()).toContain('false');
21764           });
21765
21766           it('should be invalid if not url', function() {
21767             input.clear();
21768             input.sendKeys('box');
21769
21770             expect(valid.getText()).toContain('false');
21771           });
21772         </file>
21773       </example>
21774    */
21775   'url': urlInputType,
21776
21777
21778   /**
21779    * @ngdoc input
21780    * @name input[email]
21781    *
21782    * @description
21783    * Text input with email validation. Sets the `email` validation error key if not a valid email
21784    * address.
21785    *
21786    * <div class="alert alert-warning">
21787    * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
21788    * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
21789    * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
21790    * </div>
21791    *
21792    * @param {string} ngModel Assignable angular expression to data-bind to.
21793    * @param {string=} name Property name of the form under which the control is published.
21794    * @param {string=} required Sets `required` validation error key if the value is not entered.
21795    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21796    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21797    *    `required` when you want to data-bind to the `required` attribute.
21798    * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
21799    *    minlength.
21800    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
21801    *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
21802    *    any length.
21803    * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
21804    *    that contains the regular expression body that will be converted to a regular expression
21805    *    as in the ngPattern directive.
21806    * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
21807    *    a RegExp found by evaluating the Angular expression given in the attribute value.
21808    *    If the expression evaluates to a RegExp object, then this is used directly.
21809    *    If the expression evaluates to a string, then it will be converted to a RegExp
21810    *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
21811    *    `new RegExp('^abc$')`.<br />
21812    *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
21813    *    start at the index of the last search's match, thus not taking the whole input value into
21814    *    account.
21815    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21816    *    interaction with the input element.
21817    *
21818    * @example
21819       <example name="email-input-directive" module="emailExample">
21820         <file name="index.html">
21821          <script>
21822            angular.module('emailExample', [])
21823              .controller('ExampleController', ['$scope', function($scope) {
21824                $scope.email = {
21825                  text: 'me@example.com'
21826                };
21827              }]);
21828          </script>
21829            <form name="myForm" ng-controller="ExampleController">
21830              <label>Email:
21831                <input type="email" name="input" ng-model="email.text" required>
21832              </label>
21833              <div role="alert">
21834                <span class="error" ng-show="myForm.input.$error.required">
21835                  Required!</span>
21836                <span class="error" ng-show="myForm.input.$error.email">
21837                  Not valid email!</span>
21838              </div>
21839              <tt>text = {{email.text}}</tt><br/>
21840              <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21841              <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21842              <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21843              <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21844              <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
21845            </form>
21846          </file>
21847         <file name="protractor.js" type="protractor">
21848           var text = element(by.binding('email.text'));
21849           var valid = element(by.binding('myForm.input.$valid'));
21850           var input = element(by.model('email.text'));
21851
21852           it('should initialize to model', function() {
21853             expect(text.getText()).toContain('me@example.com');
21854             expect(valid.getText()).toContain('true');
21855           });
21856
21857           it('should be invalid if empty', function() {
21858             input.clear();
21859             input.sendKeys('');
21860             expect(text.getText()).toEqual('text =');
21861             expect(valid.getText()).toContain('false');
21862           });
21863
21864           it('should be invalid if not email', function() {
21865             input.clear();
21866             input.sendKeys('xxx');
21867
21868             expect(valid.getText()).toContain('false');
21869           });
21870         </file>
21871       </example>
21872    */
21873   'email': emailInputType,
21874
21875
21876   /**
21877    * @ngdoc input
21878    * @name input[radio]
21879    *
21880    * @description
21881    * HTML radio button.
21882    *
21883    * @param {string} ngModel Assignable angular expression to data-bind to.
21884    * @param {string} value The value to which the `ngModel` expression should be set when selected.
21885    *    Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
21886    *    too. Use `ngValue` if you need complex models (`number`, `object`, ...).
21887    * @param {string=} name Property name of the form under which the control is published.
21888    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21889    *    interaction with the input element.
21890    * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
21891    *    is selected. Should be used instead of the `value` attribute if you need
21892    *    a non-string `ngModel` (`boolean`, `array`, ...).
21893    *
21894    * @example
21895       <example name="radio-input-directive" module="radioExample">
21896         <file name="index.html">
21897          <script>
21898            angular.module('radioExample', [])
21899              .controller('ExampleController', ['$scope', function($scope) {
21900                $scope.color = {
21901                  name: 'blue'
21902                };
21903                $scope.specialValue = {
21904                  "id": "12345",
21905                  "value": "green"
21906                };
21907              }]);
21908          </script>
21909          <form name="myForm" ng-controller="ExampleController">
21910            <label>
21911              <input type="radio" ng-model="color.name" value="red">
21912              Red
21913            </label><br/>
21914            <label>
21915              <input type="radio" ng-model="color.name" ng-value="specialValue">
21916              Green
21917            </label><br/>
21918            <label>
21919              <input type="radio" ng-model="color.name" value="blue">
21920              Blue
21921            </label><br/>
21922            <tt>color = {{color.name | json}}</tt><br/>
21923           </form>
21924           Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
21925         </file>
21926         <file name="protractor.js" type="protractor">
21927           it('should change state', function() {
21928             var color = element(by.binding('color.name'));
21929
21930             expect(color.getText()).toContain('blue');
21931
21932             element.all(by.model('color.name')).get(0).click();
21933
21934             expect(color.getText()).toContain('red');
21935           });
21936         </file>
21937       </example>
21938    */
21939   'radio': radioInputType,
21940
21941
21942   /**
21943    * @ngdoc input
21944    * @name input[checkbox]
21945    *
21946    * @description
21947    * HTML checkbox.
21948    *
21949    * @param {string} ngModel Assignable angular expression to data-bind to.
21950    * @param {string=} name Property name of the form under which the control is published.
21951    * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
21952    * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
21953    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21954    *    interaction with the input element.
21955    *
21956    * @example
21957       <example name="checkbox-input-directive" module="checkboxExample">
21958         <file name="index.html">
21959          <script>
21960            angular.module('checkboxExample', [])
21961              .controller('ExampleController', ['$scope', function($scope) {
21962                $scope.checkboxModel = {
21963                 value1 : true,
21964                 value2 : 'YES'
21965               };
21966              }]);
21967          </script>
21968          <form name="myForm" ng-controller="ExampleController">
21969            <label>Value1:
21970              <input type="checkbox" ng-model="checkboxModel.value1">
21971            </label><br/>
21972            <label>Value2:
21973              <input type="checkbox" ng-model="checkboxModel.value2"
21974                     ng-true-value="'YES'" ng-false-value="'NO'">
21975             </label><br/>
21976            <tt>value1 = {{checkboxModel.value1}}</tt><br/>
21977            <tt>value2 = {{checkboxModel.value2}}</tt><br/>
21978           </form>
21979         </file>
21980         <file name="protractor.js" type="protractor">
21981           it('should change state', function() {
21982             var value1 = element(by.binding('checkboxModel.value1'));
21983             var value2 = element(by.binding('checkboxModel.value2'));
21984
21985             expect(value1.getText()).toContain('true');
21986             expect(value2.getText()).toContain('YES');
21987
21988             element(by.model('checkboxModel.value1')).click();
21989             element(by.model('checkboxModel.value2')).click();
21990
21991             expect(value1.getText()).toContain('false');
21992             expect(value2.getText()).toContain('NO');
21993           });
21994         </file>
21995       </example>
21996    */
21997   'checkbox': checkboxInputType,
21998
21999   'hidden': noop,
22000   'button': noop,
22001   'submit': noop,
22002   'reset': noop,
22003   'file': noop
22004 };
22005
22006 function stringBasedInputType(ctrl) {
22007   ctrl.$formatters.push(function(value) {
22008     return ctrl.$isEmpty(value) ? value : value.toString();
22009   });
22010 }
22011
22012 function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22013   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22014   stringBasedInputType(ctrl);
22015 }
22016
22017 function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22018   var type = lowercase(element[0].type);
22019
22020   // In composition mode, users are still inputing intermediate text buffer,
22021   // hold the listener until composition is done.
22022   // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
22023   if (!$sniffer.android) {
22024     var composing = false;
22025
22026     element.on('compositionstart', function(data) {
22027       composing = true;
22028     });
22029
22030     element.on('compositionend', function() {
22031       composing = false;
22032       listener();
22033     });
22034   }
22035
22036   var listener = function(ev) {
22037     if (timeout) {
22038       $browser.defer.cancel(timeout);
22039       timeout = null;
22040     }
22041     if (composing) return;
22042     var value = element.val(),
22043         event = ev && ev.type;
22044
22045     // By default we will trim the value
22046     // If the attribute ng-trim exists we will avoid trimming
22047     // If input type is 'password', the value is never trimmed
22048     if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
22049       value = trim(value);
22050     }
22051
22052     // If a control is suffering from bad input (due to native validators), browsers discard its
22053     // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
22054     // control's value is the same empty value twice in a row.
22055     if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
22056       ctrl.$setViewValue(value, event);
22057     }
22058   };
22059
22060   // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
22061   // input event on backspace, delete or cut
22062   if ($sniffer.hasEvent('input')) {
22063     element.on('input', listener);
22064   } else {
22065     var timeout;
22066
22067     var deferListener = function(ev, input, origValue) {
22068       if (!timeout) {
22069         timeout = $browser.defer(function() {
22070           timeout = null;
22071           if (!input || input.value !== origValue) {
22072             listener(ev);
22073           }
22074         });
22075       }
22076     };
22077
22078     element.on('keydown', function(event) {
22079       var key = event.keyCode;
22080
22081       // ignore
22082       //    command            modifiers                   arrows
22083       if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
22084
22085       deferListener(event, this, this.value);
22086     });
22087
22088     // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
22089     if ($sniffer.hasEvent('paste')) {
22090       element.on('paste cut', deferListener);
22091     }
22092   }
22093
22094   // if user paste into input using mouse on older browser
22095   // or form autocomplete on newer browser, we need "change" event to catch it
22096   element.on('change', listener);
22097
22098   ctrl.$render = function() {
22099     // Workaround for Firefox validation #12102.
22100     var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
22101     if (element.val() !== value) {
22102       element.val(value);
22103     }
22104   };
22105 }
22106
22107 function weekParser(isoWeek, existingDate) {
22108   if (isDate(isoWeek)) {
22109     return isoWeek;
22110   }
22111
22112   if (isString(isoWeek)) {
22113     WEEK_REGEXP.lastIndex = 0;
22114     var parts = WEEK_REGEXP.exec(isoWeek);
22115     if (parts) {
22116       var year = +parts[1],
22117           week = +parts[2],
22118           hours = 0,
22119           minutes = 0,
22120           seconds = 0,
22121           milliseconds = 0,
22122           firstThurs = getFirstThursdayOfYear(year),
22123           addDays = (week - 1) * 7;
22124
22125       if (existingDate) {
22126         hours = existingDate.getHours();
22127         minutes = existingDate.getMinutes();
22128         seconds = existingDate.getSeconds();
22129         milliseconds = existingDate.getMilliseconds();
22130       }
22131
22132       return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
22133     }
22134   }
22135
22136   return NaN;
22137 }
22138
22139 function createDateParser(regexp, mapping) {
22140   return function(iso, date) {
22141     var parts, map;
22142
22143     if (isDate(iso)) {
22144       return iso;
22145     }
22146
22147     if (isString(iso)) {
22148       // When a date is JSON'ified to wraps itself inside of an extra
22149       // set of double quotes. This makes the date parsing code unable
22150       // to match the date string and parse it as a date.
22151       if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
22152         iso = iso.substring(1, iso.length - 1);
22153       }
22154       if (ISO_DATE_REGEXP.test(iso)) {
22155         return new Date(iso);
22156       }
22157       regexp.lastIndex = 0;
22158       parts = regexp.exec(iso);
22159
22160       if (parts) {
22161         parts.shift();
22162         if (date) {
22163           map = {
22164             yyyy: date.getFullYear(),
22165             MM: date.getMonth() + 1,
22166             dd: date.getDate(),
22167             HH: date.getHours(),
22168             mm: date.getMinutes(),
22169             ss: date.getSeconds(),
22170             sss: date.getMilliseconds() / 1000
22171           };
22172         } else {
22173           map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
22174         }
22175
22176         forEach(parts, function(part, index) {
22177           if (index < mapping.length) {
22178             map[mapping[index]] = +part;
22179           }
22180         });
22181         return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
22182       }
22183     }
22184
22185     return NaN;
22186   };
22187 }
22188
22189 function createDateInputType(type, regexp, parseDate, format) {
22190   return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
22191     badInputChecker(scope, element, attr, ctrl);
22192     baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22193     var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
22194     var previousDate;
22195
22196     ctrl.$$parserName = type;
22197     ctrl.$parsers.push(function(value) {
22198       if (ctrl.$isEmpty(value)) return null;
22199       if (regexp.test(value)) {
22200         // Note: We cannot read ctrl.$modelValue, as there might be a different
22201         // parser/formatter in the processing chain so that the model
22202         // contains some different data format!
22203         var parsedDate = parseDate(value, previousDate);
22204         if (timezone) {
22205           parsedDate = convertTimezoneToLocal(parsedDate, timezone);
22206         }
22207         return parsedDate;
22208       }
22209       return undefined;
22210     });
22211
22212     ctrl.$formatters.push(function(value) {
22213       if (value && !isDate(value)) {
22214         throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
22215       }
22216       if (isValidDate(value)) {
22217         previousDate = value;
22218         if (previousDate && timezone) {
22219           previousDate = convertTimezoneToLocal(previousDate, timezone, true);
22220         }
22221         return $filter('date')(value, format, timezone);
22222       } else {
22223         previousDate = null;
22224         return '';
22225       }
22226     });
22227
22228     if (isDefined(attr.min) || attr.ngMin) {
22229       var minVal;
22230       ctrl.$validators.min = function(value) {
22231         return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
22232       };
22233       attr.$observe('min', function(val) {
22234         minVal = parseObservedDateValue(val);
22235         ctrl.$validate();
22236       });
22237     }
22238
22239     if (isDefined(attr.max) || attr.ngMax) {
22240       var maxVal;
22241       ctrl.$validators.max = function(value) {
22242         return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
22243       };
22244       attr.$observe('max', function(val) {
22245         maxVal = parseObservedDateValue(val);
22246         ctrl.$validate();
22247       });
22248     }
22249
22250     function isValidDate(value) {
22251       // Invalid Date: getTime() returns NaN
22252       return value && !(value.getTime && value.getTime() !== value.getTime());
22253     }
22254
22255     function parseObservedDateValue(val) {
22256       return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
22257     }
22258   };
22259 }
22260
22261 function badInputChecker(scope, element, attr, ctrl) {
22262   var node = element[0];
22263   var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
22264   if (nativeValidation) {
22265     ctrl.$parsers.push(function(value) {
22266       var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
22267       return validity.badInput || validity.typeMismatch ? undefined : value;
22268     });
22269   }
22270 }
22271
22272 function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22273   badInputChecker(scope, element, attr, ctrl);
22274   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22275
22276   ctrl.$$parserName = 'number';
22277   ctrl.$parsers.push(function(value) {
22278     if (ctrl.$isEmpty(value))      return null;
22279     if (NUMBER_REGEXP.test(value)) return parseFloat(value);
22280     return undefined;
22281   });
22282
22283   ctrl.$formatters.push(function(value) {
22284     if (!ctrl.$isEmpty(value)) {
22285       if (!isNumber(value)) {
22286         throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
22287       }
22288       value = value.toString();
22289     }
22290     return value;
22291   });
22292
22293   if (isDefined(attr.min) || attr.ngMin) {
22294     var minVal;
22295     ctrl.$validators.min = function(value) {
22296       return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
22297     };
22298
22299     attr.$observe('min', function(val) {
22300       if (isDefined(val) && !isNumber(val)) {
22301         val = parseFloat(val, 10);
22302       }
22303       minVal = isNumber(val) && !isNaN(val) ? val : undefined;
22304       // TODO(matsko): implement validateLater to reduce number of validations
22305       ctrl.$validate();
22306     });
22307   }
22308
22309   if (isDefined(attr.max) || attr.ngMax) {
22310     var maxVal;
22311     ctrl.$validators.max = function(value) {
22312       return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
22313     };
22314
22315     attr.$observe('max', function(val) {
22316       if (isDefined(val) && !isNumber(val)) {
22317         val = parseFloat(val, 10);
22318       }
22319       maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
22320       // TODO(matsko): implement validateLater to reduce number of validations
22321       ctrl.$validate();
22322     });
22323   }
22324 }
22325
22326 function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22327   // Note: no badInputChecker here by purpose as `url` is only a validation
22328   // in browsers, i.e. we can always read out input.value even if it is not valid!
22329   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22330   stringBasedInputType(ctrl);
22331
22332   ctrl.$$parserName = 'url';
22333   ctrl.$validators.url = function(modelValue, viewValue) {
22334     var value = modelValue || viewValue;
22335     return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
22336   };
22337 }
22338
22339 function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22340   // Note: no badInputChecker here by purpose as `url` is only a validation
22341   // in browsers, i.e. we can always read out input.value even if it is not valid!
22342   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22343   stringBasedInputType(ctrl);
22344
22345   ctrl.$$parserName = 'email';
22346   ctrl.$validators.email = function(modelValue, viewValue) {
22347     var value = modelValue || viewValue;
22348     return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
22349   };
22350 }
22351
22352 function radioInputType(scope, element, attr, ctrl) {
22353   // make the name unique, if not defined
22354   if (isUndefined(attr.name)) {
22355     element.attr('name', nextUid());
22356   }
22357
22358   var listener = function(ev) {
22359     if (element[0].checked) {
22360       ctrl.$setViewValue(attr.value, ev && ev.type);
22361     }
22362   };
22363
22364   element.on('click', listener);
22365
22366   ctrl.$render = function() {
22367     var value = attr.value;
22368     element[0].checked = (value == ctrl.$viewValue);
22369   };
22370
22371   attr.$observe('value', ctrl.$render);
22372 }
22373
22374 function parseConstantExpr($parse, context, name, expression, fallback) {
22375   var parseFn;
22376   if (isDefined(expression)) {
22377     parseFn = $parse(expression);
22378     if (!parseFn.constant) {
22379       throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
22380                                    '`{1}`.', name, expression);
22381     }
22382     return parseFn(context);
22383   }
22384   return fallback;
22385 }
22386
22387 function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
22388   var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
22389   var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
22390
22391   var listener = function(ev) {
22392     ctrl.$setViewValue(element[0].checked, ev && ev.type);
22393   };
22394
22395   element.on('click', listener);
22396
22397   ctrl.$render = function() {
22398     element[0].checked = ctrl.$viewValue;
22399   };
22400
22401   // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
22402   // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
22403   // it to a boolean.
22404   ctrl.$isEmpty = function(value) {
22405     return value === false;
22406   };
22407
22408   ctrl.$formatters.push(function(value) {
22409     return equals(value, trueValue);
22410   });
22411
22412   ctrl.$parsers.push(function(value) {
22413     return value ? trueValue : falseValue;
22414   });
22415 }
22416
22417
22418 /**
22419  * @ngdoc directive
22420  * @name textarea
22421  * @restrict E
22422  *
22423  * @description
22424  * HTML textarea element control with angular data-binding. The data-binding and validation
22425  * properties of this element are exactly the same as those of the
22426  * {@link ng.directive:input input element}.
22427  *
22428  * @param {string} ngModel Assignable angular expression to data-bind to.
22429  * @param {string=} name Property name of the form under which the control is published.
22430  * @param {string=} required Sets `required` validation error key if the value is not entered.
22431  * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22432  *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22433  *    `required` when you want to data-bind to the `required` attribute.
22434  * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22435  *    minlength.
22436  * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22437  *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
22438  *    length.
22439  * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
22440  *    a RegExp found by evaluating the Angular expression given in the attribute value.
22441  *    If the expression evaluates to a RegExp object, then this is used directly.
22442  *    If the expression evaluates to a string, then it will be converted to a RegExp
22443  *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22444  *    `new RegExp('^abc$')`.<br />
22445  *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22446  *    start at the index of the last search's match, thus not taking the whole input value into
22447  *    account.
22448  * @param {string=} ngChange Angular expression to be executed when input changes due to user
22449  *    interaction with the input element.
22450  * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
22451  */
22452
22453
22454 /**
22455  * @ngdoc directive
22456  * @name input
22457  * @restrict E
22458  *
22459  * @description
22460  * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
22461  * input state control, and validation.
22462  * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
22463  *
22464  * <div class="alert alert-warning">
22465  * **Note:** Not every feature offered is available for all input types.
22466  * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
22467  * </div>
22468  *
22469  * @param {string} ngModel Assignable angular expression to data-bind to.
22470  * @param {string=} name Property name of the form under which the control is published.
22471  * @param {string=} required Sets `required` validation error key if the value is not entered.
22472  * @param {boolean=} ngRequired Sets `required` attribute if set to true
22473  * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22474  *    minlength.
22475  * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22476  *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
22477  *    length.
22478  * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
22479  *    a RegExp found by evaluating the Angular expression given in the attribute value.
22480  *    If the expression evaluates to a RegExp object, then this is used directly.
22481  *    If the expression evaluates to a string, then it will be converted to a RegExp
22482  *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22483  *    `new RegExp('^abc$')`.<br />
22484  *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22485  *    start at the index of the last search's match, thus not taking the whole input value into
22486  *    account.
22487  * @param {string=} ngChange Angular expression to be executed when input changes due to user
22488  *    interaction with the input element.
22489  * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
22490  *    This parameter is ignored for input[type=password] controls, which will never trim the
22491  *    input.
22492  *
22493  * @example
22494     <example name="input-directive" module="inputExample">
22495       <file name="index.html">
22496        <script>
22497           angular.module('inputExample', [])
22498             .controller('ExampleController', ['$scope', function($scope) {
22499               $scope.user = {name: 'guest', last: 'visitor'};
22500             }]);
22501        </script>
22502        <div ng-controller="ExampleController">
22503          <form name="myForm">
22504            <label>
22505               User name:
22506               <input type="text" name="userName" ng-model="user.name" required>
22507            </label>
22508            <div role="alert">
22509              <span class="error" ng-show="myForm.userName.$error.required">
22510               Required!</span>
22511            </div>
22512            <label>
22513               Last name:
22514               <input type="text" name="lastName" ng-model="user.last"
22515               ng-minlength="3" ng-maxlength="10">
22516            </label>
22517            <div role="alert">
22518              <span class="error" ng-show="myForm.lastName.$error.minlength">
22519                Too short!</span>
22520              <span class="error" ng-show="myForm.lastName.$error.maxlength">
22521                Too long!</span>
22522            </div>
22523          </form>
22524          <hr>
22525          <tt>user = {{user}}</tt><br/>
22526          <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
22527          <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
22528          <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
22529          <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
22530          <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22531          <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22532          <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
22533          <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
22534        </div>
22535       </file>
22536       <file name="protractor.js" type="protractor">
22537         var user = element(by.exactBinding('user'));
22538         var userNameValid = element(by.binding('myForm.userName.$valid'));
22539         var lastNameValid = element(by.binding('myForm.lastName.$valid'));
22540         var lastNameError = element(by.binding('myForm.lastName.$error'));
22541         var formValid = element(by.binding('myForm.$valid'));
22542         var userNameInput = element(by.model('user.name'));
22543         var userLastInput = element(by.model('user.last'));
22544
22545         it('should initialize to model', function() {
22546           expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
22547           expect(userNameValid.getText()).toContain('true');
22548           expect(formValid.getText()).toContain('true');
22549         });
22550
22551         it('should be invalid if empty when required', function() {
22552           userNameInput.clear();
22553           userNameInput.sendKeys('');
22554
22555           expect(user.getText()).toContain('{"last":"visitor"}');
22556           expect(userNameValid.getText()).toContain('false');
22557           expect(formValid.getText()).toContain('false');
22558         });
22559
22560         it('should be valid if empty when min length is set', function() {
22561           userLastInput.clear();
22562           userLastInput.sendKeys('');
22563
22564           expect(user.getText()).toContain('{"name":"guest","last":""}');
22565           expect(lastNameValid.getText()).toContain('true');
22566           expect(formValid.getText()).toContain('true');
22567         });
22568
22569         it('should be invalid if less than required min length', function() {
22570           userLastInput.clear();
22571           userLastInput.sendKeys('xx');
22572
22573           expect(user.getText()).toContain('{"name":"guest"}');
22574           expect(lastNameValid.getText()).toContain('false');
22575           expect(lastNameError.getText()).toContain('minlength');
22576           expect(formValid.getText()).toContain('false');
22577         });
22578
22579         it('should be invalid if longer than max length', function() {
22580           userLastInput.clear();
22581           userLastInput.sendKeys('some ridiculously long name');
22582
22583           expect(user.getText()).toContain('{"name":"guest"}');
22584           expect(lastNameValid.getText()).toContain('false');
22585           expect(lastNameError.getText()).toContain('maxlength');
22586           expect(formValid.getText()).toContain('false');
22587         });
22588       </file>
22589     </example>
22590  */
22591 var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
22592     function($browser, $sniffer, $filter, $parse) {
22593   return {
22594     restrict: 'E',
22595     require: ['?ngModel'],
22596     link: {
22597       pre: function(scope, element, attr, ctrls) {
22598         if (ctrls[0]) {
22599           (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
22600                                                               $browser, $filter, $parse);
22601         }
22602       }
22603     }
22604   };
22605 }];
22606
22607
22608
22609 var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
22610 /**
22611  * @ngdoc directive
22612  * @name ngValue
22613  *
22614  * @description
22615  * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
22616  * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
22617  * the bound value.
22618  *
22619  * `ngValue` is useful when dynamically generating lists of radio buttons using
22620  * {@link ngRepeat `ngRepeat`}, as shown below.
22621  *
22622  * Likewise, `ngValue` can be used to generate `<option>` elements for
22623  * the {@link select `select`} element. In that case however, only strings are supported
22624  * for the `value `attribute, so the resulting `ngModel` will always be a string.
22625  * Support for `select` models with non-string values is available via `ngOptions`.
22626  *
22627  * @element input
22628  * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
22629  *   of the `input` element
22630  *
22631  * @example
22632     <example name="ngValue-directive" module="valueExample">
22633       <file name="index.html">
22634        <script>
22635           angular.module('valueExample', [])
22636             .controller('ExampleController', ['$scope', function($scope) {
22637               $scope.names = ['pizza', 'unicorns', 'robots'];
22638               $scope.my = { favorite: 'unicorns' };
22639             }]);
22640        </script>
22641         <form ng-controller="ExampleController">
22642           <h2>Which is your favorite?</h2>
22643             <label ng-repeat="name in names" for="{{name}}">
22644               {{name}}
22645               <input type="radio"
22646                      ng-model="my.favorite"
22647                      ng-value="name"
22648                      id="{{name}}"
22649                      name="favorite">
22650             </label>
22651           <div>You chose {{my.favorite}}</div>
22652         </form>
22653       </file>
22654       <file name="protractor.js" type="protractor">
22655         var favorite = element(by.binding('my.favorite'));
22656
22657         it('should initialize to model', function() {
22658           expect(favorite.getText()).toContain('unicorns');
22659         });
22660         it('should bind the values to the inputs', function() {
22661           element.all(by.model('my.favorite')).get(0).click();
22662           expect(favorite.getText()).toContain('pizza');
22663         });
22664       </file>
22665     </example>
22666  */
22667 var ngValueDirective = function() {
22668   return {
22669     restrict: 'A',
22670     priority: 100,
22671     compile: function(tpl, tplAttr) {
22672       if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
22673         return function ngValueConstantLink(scope, elm, attr) {
22674           attr.$set('value', scope.$eval(attr.ngValue));
22675         };
22676       } else {
22677         return function ngValueLink(scope, elm, attr) {
22678           scope.$watch(attr.ngValue, function valueWatchAction(value) {
22679             attr.$set('value', value);
22680           });
22681         };
22682       }
22683     }
22684   };
22685 };
22686
22687 /**
22688  * @ngdoc directive
22689  * @name ngBind
22690  * @restrict AC
22691  *
22692  * @description
22693  * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
22694  * with the value of a given expression, and to update the text content when the value of that
22695  * expression changes.
22696  *
22697  * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
22698  * `{{ expression }}` which is similar but less verbose.
22699  *
22700  * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
22701  * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
22702  * element attribute, it makes the bindings invisible to the user while the page is loading.
22703  *
22704  * An alternative solution to this problem would be using the
22705  * {@link ng.directive:ngCloak ngCloak} directive.
22706  *
22707  *
22708  * @element ANY
22709  * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
22710  *
22711  * @example
22712  * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
22713    <example module="bindExample">
22714      <file name="index.html">
22715        <script>
22716          angular.module('bindExample', [])
22717            .controller('ExampleController', ['$scope', function($scope) {
22718              $scope.name = 'Whirled';
22719            }]);
22720        </script>
22721        <div ng-controller="ExampleController">
22722          <label>Enter name: <input type="text" ng-model="name"></label><br>
22723          Hello <span ng-bind="name"></span>!
22724        </div>
22725      </file>
22726      <file name="protractor.js" type="protractor">
22727        it('should check ng-bind', function() {
22728          var nameInput = element(by.model('name'));
22729
22730          expect(element(by.binding('name')).getText()).toBe('Whirled');
22731          nameInput.clear();
22732          nameInput.sendKeys('world');
22733          expect(element(by.binding('name')).getText()).toBe('world');
22734        });
22735      </file>
22736    </example>
22737  */
22738 var ngBindDirective = ['$compile', function($compile) {
22739   return {
22740     restrict: 'AC',
22741     compile: function ngBindCompile(templateElement) {
22742       $compile.$$addBindingClass(templateElement);
22743       return function ngBindLink(scope, element, attr) {
22744         $compile.$$addBindingInfo(element, attr.ngBind);
22745         element = element[0];
22746         scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
22747           element.textContent = isUndefined(value) ? '' : value;
22748         });
22749       };
22750     }
22751   };
22752 }];
22753
22754
22755 /**
22756  * @ngdoc directive
22757  * @name ngBindTemplate
22758  *
22759  * @description
22760  * The `ngBindTemplate` directive specifies that the element
22761  * text content should be replaced with the interpolation of the template
22762  * in the `ngBindTemplate` attribute.
22763  * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
22764  * expressions. This directive is needed since some HTML elements
22765  * (such as TITLE and OPTION) cannot contain SPAN elements.
22766  *
22767  * @element ANY
22768  * @param {string} ngBindTemplate template of form
22769  *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
22770  *
22771  * @example
22772  * Try it here: enter text in text box and watch the greeting change.
22773    <example module="bindExample">
22774      <file name="index.html">
22775        <script>
22776          angular.module('bindExample', [])
22777            .controller('ExampleController', ['$scope', function($scope) {
22778              $scope.salutation = 'Hello';
22779              $scope.name = 'World';
22780            }]);
22781        </script>
22782        <div ng-controller="ExampleController">
22783         <label>Salutation: <input type="text" ng-model="salutation"></label><br>
22784         <label>Name: <input type="text" ng-model="name"></label><br>
22785         <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
22786        </div>
22787      </file>
22788      <file name="protractor.js" type="protractor">
22789        it('should check ng-bind', function() {
22790          var salutationElem = element(by.binding('salutation'));
22791          var salutationInput = element(by.model('salutation'));
22792          var nameInput = element(by.model('name'));
22793
22794          expect(salutationElem.getText()).toBe('Hello World!');
22795
22796          salutationInput.clear();
22797          salutationInput.sendKeys('Greetings');
22798          nameInput.clear();
22799          nameInput.sendKeys('user');
22800
22801          expect(salutationElem.getText()).toBe('Greetings user!');
22802        });
22803      </file>
22804    </example>
22805  */
22806 var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
22807   return {
22808     compile: function ngBindTemplateCompile(templateElement) {
22809       $compile.$$addBindingClass(templateElement);
22810       return function ngBindTemplateLink(scope, element, attr) {
22811         var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
22812         $compile.$$addBindingInfo(element, interpolateFn.expressions);
22813         element = element[0];
22814         attr.$observe('ngBindTemplate', function(value) {
22815           element.textContent = isUndefined(value) ? '' : value;
22816         });
22817       };
22818     }
22819   };
22820 }];
22821
22822
22823 /**
22824  * @ngdoc directive
22825  * @name ngBindHtml
22826  *
22827  * @description
22828  * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
22829  * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
22830  * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
22831  * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
22832  * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
22833  *
22834  * You may also bypass sanitization for values you know are safe. To do so, bind to
22835  * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}.  See the example
22836  * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
22837  *
22838  * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
22839  * will have an exception (instead of an exploit.)
22840  *
22841  * @element ANY
22842  * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
22843  *
22844  * @example
22845
22846    <example module="bindHtmlExample" deps="angular-sanitize.js">
22847      <file name="index.html">
22848        <div ng-controller="ExampleController">
22849         <p ng-bind-html="myHTML"></p>
22850        </div>
22851      </file>
22852
22853      <file name="script.js">
22854        angular.module('bindHtmlExample', ['ngSanitize'])
22855          .controller('ExampleController', ['$scope', function($scope) {
22856            $scope.myHTML =
22857               'I am an <code>HTML</code>string with ' +
22858               '<a href="#">links!</a> and other <em>stuff</em>';
22859          }]);
22860      </file>
22861
22862      <file name="protractor.js" type="protractor">
22863        it('should check ng-bind-html', function() {
22864          expect(element(by.binding('myHTML')).getText()).toBe(
22865              'I am an HTMLstring with links! and other stuff');
22866        });
22867      </file>
22868    </example>
22869  */
22870 var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
22871   return {
22872     restrict: 'A',
22873     compile: function ngBindHtmlCompile(tElement, tAttrs) {
22874       var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
22875       var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
22876         return (value || '').toString();
22877       });
22878       $compile.$$addBindingClass(tElement);
22879
22880       return function ngBindHtmlLink(scope, element, attr) {
22881         $compile.$$addBindingInfo(element, attr.ngBindHtml);
22882
22883         scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
22884           // we re-evaluate the expr because we want a TrustedValueHolderType
22885           // for $sce, not a string
22886           element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
22887         });
22888       };
22889     }
22890   };
22891 }];
22892
22893 /**
22894  * @ngdoc directive
22895  * @name ngChange
22896  *
22897  * @description
22898  * Evaluate the given expression when the user changes the input.
22899  * The expression is evaluated immediately, unlike the JavaScript onchange event
22900  * which only triggers at the end of a change (usually, when the user leaves the
22901  * form element or presses the return key).
22902  *
22903  * The `ngChange` expression is only evaluated when a change in the input value causes
22904  * a new value to be committed to the model.
22905  *
22906  * It will not be evaluated:
22907  * * if the value returned from the `$parsers` transformation pipeline has not changed
22908  * * if the input has continued to be invalid since the model will stay `null`
22909  * * if the model is changed programmatically and not by a change to the input value
22910  *
22911  *
22912  * Note, this directive requires `ngModel` to be present.
22913  *
22914  * @element input
22915  * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
22916  * in input value.
22917  *
22918  * @example
22919  * <example name="ngChange-directive" module="changeExample">
22920  *   <file name="index.html">
22921  *     <script>
22922  *       angular.module('changeExample', [])
22923  *         .controller('ExampleController', ['$scope', function($scope) {
22924  *           $scope.counter = 0;
22925  *           $scope.change = function() {
22926  *             $scope.counter++;
22927  *           };
22928  *         }]);
22929  *     </script>
22930  *     <div ng-controller="ExampleController">
22931  *       <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
22932  *       <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
22933  *       <label for="ng-change-example2">Confirmed</label><br />
22934  *       <tt>debug = {{confirmed}}</tt><br/>
22935  *       <tt>counter = {{counter}}</tt><br/>
22936  *     </div>
22937  *   </file>
22938  *   <file name="protractor.js" type="protractor">
22939  *     var counter = element(by.binding('counter'));
22940  *     var debug = element(by.binding('confirmed'));
22941  *
22942  *     it('should evaluate the expression if changing from view', function() {
22943  *       expect(counter.getText()).toContain('0');
22944  *
22945  *       element(by.id('ng-change-example1')).click();
22946  *
22947  *       expect(counter.getText()).toContain('1');
22948  *       expect(debug.getText()).toContain('true');
22949  *     });
22950  *
22951  *     it('should not evaluate the expression if changing from model', function() {
22952  *       element(by.id('ng-change-example2')).click();
22953
22954  *       expect(counter.getText()).toContain('0');
22955  *       expect(debug.getText()).toContain('true');
22956  *     });
22957  *   </file>
22958  * </example>
22959  */
22960 var ngChangeDirective = valueFn({
22961   restrict: 'A',
22962   require: 'ngModel',
22963   link: function(scope, element, attr, ctrl) {
22964     ctrl.$viewChangeListeners.push(function() {
22965       scope.$eval(attr.ngChange);
22966     });
22967   }
22968 });
22969
22970 function classDirective(name, selector) {
22971   name = 'ngClass' + name;
22972   return ['$animate', function($animate) {
22973     return {
22974       restrict: 'AC',
22975       link: function(scope, element, attr) {
22976         var oldVal;
22977
22978         scope.$watch(attr[name], ngClassWatchAction, true);
22979
22980         attr.$observe('class', function(value) {
22981           ngClassWatchAction(scope.$eval(attr[name]));
22982         });
22983
22984
22985         if (name !== 'ngClass') {
22986           scope.$watch('$index', function($index, old$index) {
22987             // jshint bitwise: false
22988             var mod = $index & 1;
22989             if (mod !== (old$index & 1)) {
22990               var classes = arrayClasses(scope.$eval(attr[name]));
22991               mod === selector ?
22992                 addClasses(classes) :
22993                 removeClasses(classes);
22994             }
22995           });
22996         }
22997
22998         function addClasses(classes) {
22999           var newClasses = digestClassCounts(classes, 1);
23000           attr.$addClass(newClasses);
23001         }
23002
23003         function removeClasses(classes) {
23004           var newClasses = digestClassCounts(classes, -1);
23005           attr.$removeClass(newClasses);
23006         }
23007
23008         function digestClassCounts(classes, count) {
23009           // Use createMap() to prevent class assumptions involving property
23010           // names in Object.prototype
23011           var classCounts = element.data('$classCounts') || createMap();
23012           var classesToUpdate = [];
23013           forEach(classes, function(className) {
23014             if (count > 0 || classCounts[className]) {
23015               classCounts[className] = (classCounts[className] || 0) + count;
23016               if (classCounts[className] === +(count > 0)) {
23017                 classesToUpdate.push(className);
23018               }
23019             }
23020           });
23021           element.data('$classCounts', classCounts);
23022           return classesToUpdate.join(' ');
23023         }
23024
23025         function updateClasses(oldClasses, newClasses) {
23026           var toAdd = arrayDifference(newClasses, oldClasses);
23027           var toRemove = arrayDifference(oldClasses, newClasses);
23028           toAdd = digestClassCounts(toAdd, 1);
23029           toRemove = digestClassCounts(toRemove, -1);
23030           if (toAdd && toAdd.length) {
23031             $animate.addClass(element, toAdd);
23032           }
23033           if (toRemove && toRemove.length) {
23034             $animate.removeClass(element, toRemove);
23035           }
23036         }
23037
23038         function ngClassWatchAction(newVal) {
23039           if (selector === true || scope.$index % 2 === selector) {
23040             var newClasses = arrayClasses(newVal || []);
23041             if (!oldVal) {
23042               addClasses(newClasses);
23043             } else if (!equals(newVal,oldVal)) {
23044               var oldClasses = arrayClasses(oldVal);
23045               updateClasses(oldClasses, newClasses);
23046             }
23047           }
23048           oldVal = shallowCopy(newVal);
23049         }
23050       }
23051     };
23052
23053     function arrayDifference(tokens1, tokens2) {
23054       var values = [];
23055
23056       outer:
23057       for (var i = 0; i < tokens1.length; i++) {
23058         var token = tokens1[i];
23059         for (var j = 0; j < tokens2.length; j++) {
23060           if (token == tokens2[j]) continue outer;
23061         }
23062         values.push(token);
23063       }
23064       return values;
23065     }
23066
23067     function arrayClasses(classVal) {
23068       var classes = [];
23069       if (isArray(classVal)) {
23070         forEach(classVal, function(v) {
23071           classes = classes.concat(arrayClasses(v));
23072         });
23073         return classes;
23074       } else if (isString(classVal)) {
23075         return classVal.split(' ');
23076       } else if (isObject(classVal)) {
23077         forEach(classVal, function(v, k) {
23078           if (v) {
23079             classes = classes.concat(k.split(' '));
23080           }
23081         });
23082         return classes;
23083       }
23084       return classVal;
23085     }
23086   }];
23087 }
23088
23089 /**
23090  * @ngdoc directive
23091  * @name ngClass
23092  * @restrict AC
23093  *
23094  * @description
23095  * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
23096  * an expression that represents all classes to be added.
23097  *
23098  * The directive operates in three different ways, depending on which of three types the expression
23099  * evaluates to:
23100  *
23101  * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
23102  * names.
23103  *
23104  * 2. If the expression evaluates to an object, then for each key-value pair of the
23105  * object with a truthy value the corresponding key is used as a class name.
23106  *
23107  * 3. If the expression evaluates to an array, each element of the array should either be a string as in
23108  * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
23109  * to give you more control over what CSS classes appear. See the code below for an example of this.
23110  *
23111  *
23112  * The directive won't add duplicate classes if a particular class was already set.
23113  *
23114  * When the expression changes, the previously added classes are removed and only then are the
23115  * new classes added.
23116  *
23117  * @animations
23118  * **add** - happens just before the class is applied to the elements
23119  *
23120  * **remove** - happens just before the class is removed from the element
23121  *
23122  * @element ANY
23123  * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
23124  *   of the evaluation can be a string representing space delimited class
23125  *   names, an array, or a map of class names to boolean values. In the case of a map, the
23126  *   names of the properties whose values are truthy will be added as css classes to the
23127  *   element.
23128  *
23129  * @example Example that demonstrates basic bindings via ngClass directive.
23130    <example>
23131      <file name="index.html">
23132        <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
23133        <label>
23134           <input type="checkbox" ng-model="deleted">
23135           deleted (apply "strike" class)
23136        </label><br>
23137        <label>
23138           <input type="checkbox" ng-model="important">
23139           important (apply "bold" class)
23140        </label><br>
23141        <label>
23142           <input type="checkbox" ng-model="error">
23143           error (apply "has-error" class)
23144        </label>
23145        <hr>
23146        <p ng-class="style">Using String Syntax</p>
23147        <input type="text" ng-model="style"
23148               placeholder="Type: bold strike red" aria-label="Type: bold strike red">
23149        <hr>
23150        <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
23151        <input ng-model="style1"
23152               placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
23153        <input ng-model="style2"
23154               placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
23155        <input ng-model="style3"
23156               placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
23157        <hr>
23158        <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
23159        <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
23160        <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
23161      </file>
23162      <file name="style.css">
23163        .strike {
23164            text-decoration: line-through;
23165        }
23166        .bold {
23167            font-weight: bold;
23168        }
23169        .red {
23170            color: red;
23171        }
23172        .has-error {
23173            color: red;
23174            background-color: yellow;
23175        }
23176        .orange {
23177            color: orange;
23178        }
23179      </file>
23180      <file name="protractor.js" type="protractor">
23181        var ps = element.all(by.css('p'));
23182
23183        it('should let you toggle the class', function() {
23184
23185          expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
23186          expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
23187
23188          element(by.model('important')).click();
23189          expect(ps.first().getAttribute('class')).toMatch(/bold/);
23190
23191          element(by.model('error')).click();
23192          expect(ps.first().getAttribute('class')).toMatch(/has-error/);
23193        });
23194
23195        it('should let you toggle string example', function() {
23196          expect(ps.get(1).getAttribute('class')).toBe('');
23197          element(by.model('style')).clear();
23198          element(by.model('style')).sendKeys('red');
23199          expect(ps.get(1).getAttribute('class')).toBe('red');
23200        });
23201
23202        it('array example should have 3 classes', function() {
23203          expect(ps.get(2).getAttribute('class')).toBe('');
23204          element(by.model('style1')).sendKeys('bold');
23205          element(by.model('style2')).sendKeys('strike');
23206          element(by.model('style3')).sendKeys('red');
23207          expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
23208        });
23209
23210        it('array with map example should have 2 classes', function() {
23211          expect(ps.last().getAttribute('class')).toBe('');
23212          element(by.model('style4')).sendKeys('bold');
23213          element(by.model('warning')).click();
23214          expect(ps.last().getAttribute('class')).toBe('bold orange');
23215        });
23216      </file>
23217    </example>
23218
23219    ## Animations
23220
23221    The example below demonstrates how to perform animations using ngClass.
23222
23223    <example module="ngAnimate" deps="angular-animate.js" animations="true">
23224      <file name="index.html">
23225       <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
23226       <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
23227       <br>
23228       <span class="base-class" ng-class="myVar">Sample Text</span>
23229      </file>
23230      <file name="style.css">
23231        .base-class {
23232          transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
23233        }
23234
23235        .base-class.my-class {
23236          color: red;
23237          font-size:3em;
23238        }
23239      </file>
23240      <file name="protractor.js" type="protractor">
23241        it('should check ng-class', function() {
23242          expect(element(by.css('.base-class')).getAttribute('class')).not.
23243            toMatch(/my-class/);
23244
23245          element(by.id('setbtn')).click();
23246
23247          expect(element(by.css('.base-class')).getAttribute('class')).
23248            toMatch(/my-class/);
23249
23250          element(by.id('clearbtn')).click();
23251
23252          expect(element(by.css('.base-class')).getAttribute('class')).not.
23253            toMatch(/my-class/);
23254        });
23255      </file>
23256    </example>
23257
23258
23259    ## ngClass and pre-existing CSS3 Transitions/Animations
23260    The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
23261    Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
23262    any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
23263    to view the step by step details of {@link $animate#addClass $animate.addClass} and
23264    {@link $animate#removeClass $animate.removeClass}.
23265  */
23266 var ngClassDirective = classDirective('', true);
23267
23268 /**
23269  * @ngdoc directive
23270  * @name ngClassOdd
23271  * @restrict AC
23272  *
23273  * @description
23274  * The `ngClassOdd` and `ngClassEven` directives work exactly as
23275  * {@link ng.directive:ngClass ngClass}, except they work in
23276  * conjunction with `ngRepeat` and take effect only on odd (even) rows.
23277  *
23278  * This directive can be applied only within the scope of an
23279  * {@link ng.directive:ngRepeat ngRepeat}.
23280  *
23281  * @element ANY
23282  * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
23283  *   of the evaluation can be a string representing space delimited class names or an array.
23284  *
23285  * @example
23286    <example>
23287      <file name="index.html">
23288         <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23289           <li ng-repeat="name in names">
23290            <span ng-class-odd="'odd'" ng-class-even="'even'">
23291              {{name}}
23292            </span>
23293           </li>
23294         </ol>
23295      </file>
23296      <file name="style.css">
23297        .odd {
23298          color: red;
23299        }
23300        .even {
23301          color: blue;
23302        }
23303      </file>
23304      <file name="protractor.js" type="protractor">
23305        it('should check ng-class-odd and ng-class-even', function() {
23306          expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
23307            toMatch(/odd/);
23308          expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
23309            toMatch(/even/);
23310        });
23311      </file>
23312    </example>
23313  */
23314 var ngClassOddDirective = classDirective('Odd', 0);
23315
23316 /**
23317  * @ngdoc directive
23318  * @name ngClassEven
23319  * @restrict AC
23320  *
23321  * @description
23322  * The `ngClassOdd` and `ngClassEven` directives work exactly as
23323  * {@link ng.directive:ngClass ngClass}, except they work in
23324  * conjunction with `ngRepeat` and take effect only on odd (even) rows.
23325  *
23326  * This directive can be applied only within the scope of an
23327  * {@link ng.directive:ngRepeat ngRepeat}.
23328  *
23329  * @element ANY
23330  * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
23331  *   result of the evaluation can be a string representing space delimited class names or an array.
23332  *
23333  * @example
23334    <example>
23335      <file name="index.html">
23336         <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23337           <li ng-repeat="name in names">
23338            <span ng-class-odd="'odd'" ng-class-even="'even'">
23339              {{name}} &nbsp; &nbsp; &nbsp;
23340            </span>
23341           </li>
23342         </ol>
23343      </file>
23344      <file name="style.css">
23345        .odd {
23346          color: red;
23347        }
23348        .even {
23349          color: blue;
23350        }
23351      </file>
23352      <file name="protractor.js" type="protractor">
23353        it('should check ng-class-odd and ng-class-even', function() {
23354          expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
23355            toMatch(/odd/);
23356          expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
23357            toMatch(/even/);
23358        });
23359      </file>
23360    </example>
23361  */
23362 var ngClassEvenDirective = classDirective('Even', 1);
23363
23364 /**
23365  * @ngdoc directive
23366  * @name ngCloak
23367  * @restrict AC
23368  *
23369  * @description
23370  * The `ngCloak` directive is used to prevent the Angular html template from being briefly
23371  * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
23372  * directive to avoid the undesirable flicker effect caused by the html template display.
23373  *
23374  * The directive can be applied to the `<body>` element, but the preferred usage is to apply
23375  * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
23376  * of the browser view.
23377  *
23378  * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
23379  * `angular.min.js`.
23380  * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
23381  *
23382  * ```css
23383  * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
23384  *   display: none !important;
23385  * }
23386  * ```
23387  *
23388  * When this css rule is loaded by the browser, all html elements (including their children) that
23389  * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
23390  * during the compilation of the template it deletes the `ngCloak` element attribute, making
23391  * the compiled element visible.
23392  *
23393  * For the best result, the `angular.js` script must be loaded in the head section of the html
23394  * document; alternatively, the css rule above must be included in the external stylesheet of the
23395  * application.
23396  *
23397  * @element ANY
23398  *
23399  * @example
23400    <example>
23401      <file name="index.html">
23402         <div id="template1" ng-cloak>{{ 'hello' }}</div>
23403         <div id="template2" class="ng-cloak">{{ 'world' }}</div>
23404      </file>
23405      <file name="protractor.js" type="protractor">
23406        it('should remove the template directive and css class', function() {
23407          expect($('#template1').getAttribute('ng-cloak')).
23408            toBeNull();
23409          expect($('#template2').getAttribute('ng-cloak')).
23410            toBeNull();
23411        });
23412      </file>
23413    </example>
23414  *
23415  */
23416 var ngCloakDirective = ngDirective({
23417   compile: function(element, attr) {
23418     attr.$set('ngCloak', undefined);
23419     element.removeClass('ng-cloak');
23420   }
23421 });
23422
23423 /**
23424  * @ngdoc directive
23425  * @name ngController
23426  *
23427  * @description
23428  * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
23429  * supports the principles behind the Model-View-Controller design pattern.
23430  *
23431  * MVC components in angular:
23432  *
23433  * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
23434  *   are accessed through bindings.
23435  * * View — The template (HTML with data bindings) that is rendered into the View.
23436  * * Controller — The `ngController` directive specifies a Controller class; the class contains business
23437  *   logic behind the application to decorate the scope with functions and values
23438  *
23439  * Note that you can also attach controllers to the DOM by declaring it in a route definition
23440  * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
23441  * again using `ng-controller` in the template itself.  This will cause the controller to be attached
23442  * and executed twice.
23443  *
23444  * @element ANY
23445  * @scope
23446  * @priority 500
23447  * @param {expression} ngController Name of a constructor function registered with the current
23448  * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
23449  * that on the current scope evaluates to a constructor function.
23450  *
23451  * The controller instance can be published into a scope property by specifying
23452  * `ng-controller="as propertyName"`.
23453  *
23454  * If the current `$controllerProvider` is configured to use globals (via
23455  * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
23456  * also be the name of a globally accessible constructor function (not recommended).
23457  *
23458  * @example
23459  * Here is a simple form for editing user contact information. Adding, removing, clearing, and
23460  * greeting are methods declared on the controller (see source tab). These methods can
23461  * easily be called from the angular markup. Any changes to the data are automatically reflected
23462  * in the View without the need for a manual update.
23463  *
23464  * Two different declaration styles are included below:
23465  *
23466  * * one binds methods and properties directly onto the controller using `this`:
23467  * `ng-controller="SettingsController1 as settings"`
23468  * * one injects `$scope` into the controller:
23469  * `ng-controller="SettingsController2"`
23470  *
23471  * The second option is more common in the Angular community, and is generally used in boilerplates
23472  * and in this guide. However, there are advantages to binding properties directly to the controller
23473  * and avoiding scope.
23474  *
23475  * * Using `controller as` makes it obvious which controller you are accessing in the template when
23476  * multiple controllers apply to an element.
23477  * * If you are writing your controllers as classes you have easier access to the properties and
23478  * methods, which will appear on the scope, from inside the controller code.
23479  * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
23480  * inheritance masking primitives.
23481  *
23482  * This example demonstrates the `controller as` syntax.
23483  *
23484  * <example name="ngControllerAs" module="controllerAsExample">
23485  *   <file name="index.html">
23486  *    <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
23487  *      <label>Name: <input type="text" ng-model="settings.name"/></label>
23488  *      <button ng-click="settings.greet()">greet</button><br/>
23489  *      Contact:
23490  *      <ul>
23491  *        <li ng-repeat="contact in settings.contacts">
23492  *          <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
23493  *             <option>phone</option>
23494  *             <option>email</option>
23495  *          </select>
23496  *          <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
23497  *          <button ng-click="settings.clearContact(contact)">clear</button>
23498  *          <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
23499  *        </li>
23500  *        <li><button ng-click="settings.addContact()">add</button></li>
23501  *     </ul>
23502  *    </div>
23503  *   </file>
23504  *   <file name="app.js">
23505  *    angular.module('controllerAsExample', [])
23506  *      .controller('SettingsController1', SettingsController1);
23507  *
23508  *    function SettingsController1() {
23509  *      this.name = "John Smith";
23510  *      this.contacts = [
23511  *        {type: 'phone', value: '408 555 1212'},
23512  *        {type: 'email', value: 'john.smith@example.org'} ];
23513  *    }
23514  *
23515  *    SettingsController1.prototype.greet = function() {
23516  *      alert(this.name);
23517  *    };
23518  *
23519  *    SettingsController1.prototype.addContact = function() {
23520  *      this.contacts.push({type: 'email', value: 'yourname@example.org'});
23521  *    };
23522  *
23523  *    SettingsController1.prototype.removeContact = function(contactToRemove) {
23524  *     var index = this.contacts.indexOf(contactToRemove);
23525  *      this.contacts.splice(index, 1);
23526  *    };
23527  *
23528  *    SettingsController1.prototype.clearContact = function(contact) {
23529  *      contact.type = 'phone';
23530  *      contact.value = '';
23531  *    };
23532  *   </file>
23533  *   <file name="protractor.js" type="protractor">
23534  *     it('should check controller as', function() {
23535  *       var container = element(by.id('ctrl-as-exmpl'));
23536  *         expect(container.element(by.model('settings.name'))
23537  *           .getAttribute('value')).toBe('John Smith');
23538  *
23539  *       var firstRepeat =
23540  *           container.element(by.repeater('contact in settings.contacts').row(0));
23541  *       var secondRepeat =
23542  *           container.element(by.repeater('contact in settings.contacts').row(1));
23543  *
23544  *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
23545  *           .toBe('408 555 1212');
23546  *
23547  *       expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
23548  *           .toBe('john.smith@example.org');
23549  *
23550  *       firstRepeat.element(by.buttonText('clear')).click();
23551  *
23552  *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
23553  *           .toBe('');
23554  *
23555  *       container.element(by.buttonText('add')).click();
23556  *
23557  *       expect(container.element(by.repeater('contact in settings.contacts').row(2))
23558  *           .element(by.model('contact.value'))
23559  *           .getAttribute('value'))
23560  *           .toBe('yourname@example.org');
23561  *     });
23562  *   </file>
23563  * </example>
23564  *
23565  * This example demonstrates the "attach to `$scope`" style of controller.
23566  *
23567  * <example name="ngController" module="controllerExample">
23568  *  <file name="index.html">
23569  *   <div id="ctrl-exmpl" ng-controller="SettingsController2">
23570  *     <label>Name: <input type="text" ng-model="name"/></label>
23571  *     <button ng-click="greet()">greet</button><br/>
23572  *     Contact:
23573  *     <ul>
23574  *       <li ng-repeat="contact in contacts">
23575  *         <select ng-model="contact.type" id="select_{{$index}}">
23576  *            <option>phone</option>
23577  *            <option>email</option>
23578  *         </select>
23579  *         <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
23580  *         <button ng-click="clearContact(contact)">clear</button>
23581  *         <button ng-click="removeContact(contact)">X</button>
23582  *       </li>
23583  *       <li>[ <button ng-click="addContact()">add</button> ]</li>
23584  *    </ul>
23585  *   </div>
23586  *  </file>
23587  *  <file name="app.js">
23588  *   angular.module('controllerExample', [])
23589  *     .controller('SettingsController2', ['$scope', SettingsController2]);
23590  *
23591  *   function SettingsController2($scope) {
23592  *     $scope.name = "John Smith";
23593  *     $scope.contacts = [
23594  *       {type:'phone', value:'408 555 1212'},
23595  *       {type:'email', value:'john.smith@example.org'} ];
23596  *
23597  *     $scope.greet = function() {
23598  *       alert($scope.name);
23599  *     };
23600  *
23601  *     $scope.addContact = function() {
23602  *       $scope.contacts.push({type:'email', value:'yourname@example.org'});
23603  *     };
23604  *
23605  *     $scope.removeContact = function(contactToRemove) {
23606  *       var index = $scope.contacts.indexOf(contactToRemove);
23607  *       $scope.contacts.splice(index, 1);
23608  *     };
23609  *
23610  *     $scope.clearContact = function(contact) {
23611  *       contact.type = 'phone';
23612  *       contact.value = '';
23613  *     };
23614  *   }
23615  *  </file>
23616  *  <file name="protractor.js" type="protractor">
23617  *    it('should check controller', function() {
23618  *      var container = element(by.id('ctrl-exmpl'));
23619  *
23620  *      expect(container.element(by.model('name'))
23621  *          .getAttribute('value')).toBe('John Smith');
23622  *
23623  *      var firstRepeat =
23624  *          container.element(by.repeater('contact in contacts').row(0));
23625  *      var secondRepeat =
23626  *          container.element(by.repeater('contact in contacts').row(1));
23627  *
23628  *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
23629  *          .toBe('408 555 1212');
23630  *      expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
23631  *          .toBe('john.smith@example.org');
23632  *
23633  *      firstRepeat.element(by.buttonText('clear')).click();
23634  *
23635  *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
23636  *          .toBe('');
23637  *
23638  *      container.element(by.buttonText('add')).click();
23639  *
23640  *      expect(container.element(by.repeater('contact in contacts').row(2))
23641  *          .element(by.model('contact.value'))
23642  *          .getAttribute('value'))
23643  *          .toBe('yourname@example.org');
23644  *    });
23645  *  </file>
23646  *</example>
23647
23648  */
23649 var ngControllerDirective = [function() {
23650   return {
23651     restrict: 'A',
23652     scope: true,
23653     controller: '@',
23654     priority: 500
23655   };
23656 }];
23657
23658 /**
23659  * @ngdoc directive
23660  * @name ngCsp
23661  *
23662  * @element html
23663  * @description
23664  *
23665  * Angular has some features that can break certain
23666  * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
23667  *
23668  * If you intend to implement these rules then you must tell Angular not to use these features.
23669  *
23670  * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
23671  *
23672  *
23673  * The following rules affect Angular:
23674  *
23675  * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
23676  * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
23677  * increase in the speed of evaluating Angular expressions.
23678  *
23679  * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
23680  * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
23681  * To make these directives work when a CSP rule is blocking inline styles, you must link to the
23682  * `angular-csp.css` in your HTML manually.
23683  *
23684  * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
23685  * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
23686  * however, triggers a CSP error to be logged in the console:
23687  *
23688  * ```
23689  * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
23690  * script in the following Content Security Policy directive: "default-src 'self'". Note that
23691  * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
23692  * ```
23693  *
23694  * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
23695  * directive on an element of the HTML document that appears before the `<script>` tag that loads
23696  * the `angular.js` file.
23697  *
23698  * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
23699  *
23700  * You can specify which of the CSP related Angular features should be deactivated by providing
23701  * a value for the `ng-csp` attribute. The options are as follows:
23702  *
23703  * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
23704  *
23705  * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
23706  *
23707  * You can use these values in the following combinations:
23708  *
23709  *
23710  * * No declaration means that Angular will assume that you can do inline styles, but it will do
23711  * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
23712  * of Angular.
23713  *
23714  * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
23715  * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
23716  * of Angular.
23717  *
23718  * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
23719  * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
23720  *
23721  * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
23722  * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
23723  *
23724  * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
23725  * styles nor use eval, which is the same as an empty: ng-csp.
23726  * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
23727  *
23728  * @example
23729  * This example shows how to apply the `ngCsp` directive to the `html` tag.
23730    ```html
23731      <!doctype html>
23732      <html ng-app ng-csp>
23733      ...
23734      ...
23735      </html>
23736    ```
23737   * @example
23738       // Note: the suffix `.csp` in the example name triggers
23739       // csp mode in our http server!
23740       <example name="example.csp" module="cspExample" ng-csp="true">
23741         <file name="index.html">
23742           <div ng-controller="MainController as ctrl">
23743             <div>
23744               <button ng-click="ctrl.inc()" id="inc">Increment</button>
23745               <span id="counter">
23746                 {{ctrl.counter}}
23747               </span>
23748             </div>
23749
23750             <div>
23751               <button ng-click="ctrl.evil()" id="evil">Evil</button>
23752               <span id="evilError">
23753                 {{ctrl.evilError}}
23754               </span>
23755             </div>
23756           </div>
23757         </file>
23758         <file name="script.js">
23759            angular.module('cspExample', [])
23760              .controller('MainController', function() {
23761                 this.counter = 0;
23762                 this.inc = function() {
23763                   this.counter++;
23764                 };
23765                 this.evil = function() {
23766                   // jshint evil:true
23767                   try {
23768                     eval('1+2');
23769                   } catch (e) {
23770                     this.evilError = e.message;
23771                   }
23772                 };
23773               });
23774         </file>
23775         <file name="protractor.js" type="protractor">
23776           var util, webdriver;
23777
23778           var incBtn = element(by.id('inc'));
23779           var counter = element(by.id('counter'));
23780           var evilBtn = element(by.id('evil'));
23781           var evilError = element(by.id('evilError'));
23782
23783           function getAndClearSevereErrors() {
23784             return browser.manage().logs().get('browser').then(function(browserLog) {
23785               return browserLog.filter(function(logEntry) {
23786                 return logEntry.level.value > webdriver.logging.Level.WARNING.value;
23787               });
23788             });
23789           }
23790
23791           function clearErrors() {
23792             getAndClearSevereErrors();
23793           }
23794
23795           function expectNoErrors() {
23796             getAndClearSevereErrors().then(function(filteredLog) {
23797               expect(filteredLog.length).toEqual(0);
23798               if (filteredLog.length) {
23799                 console.log('browser console errors: ' + util.inspect(filteredLog));
23800               }
23801             });
23802           }
23803
23804           function expectError(regex) {
23805             getAndClearSevereErrors().then(function(filteredLog) {
23806               var found = false;
23807               filteredLog.forEach(function(log) {
23808                 if (log.message.match(regex)) {
23809                   found = true;
23810                 }
23811               });
23812               if (!found) {
23813                 throw new Error('expected an error that matches ' + regex);
23814               }
23815             });
23816           }
23817
23818           beforeEach(function() {
23819             util = require('util');
23820             webdriver = require('protractor/node_modules/selenium-webdriver');
23821           });
23822
23823           // For now, we only test on Chrome,
23824           // as Safari does not load the page with Protractor's injected scripts,
23825           // and Firefox webdriver always disables content security policy (#6358)
23826           if (browser.params.browser !== 'chrome') {
23827             return;
23828           }
23829
23830           it('should not report errors when the page is loaded', function() {
23831             // clear errors so we are not dependent on previous tests
23832             clearErrors();
23833             // Need to reload the page as the page is already loaded when
23834             // we come here
23835             browser.driver.getCurrentUrl().then(function(url) {
23836               browser.get(url);
23837             });
23838             expectNoErrors();
23839           });
23840
23841           it('should evaluate expressions', function() {
23842             expect(counter.getText()).toEqual('0');
23843             incBtn.click();
23844             expect(counter.getText()).toEqual('1');
23845             expectNoErrors();
23846           });
23847
23848           it('should throw and report an error when using "eval"', function() {
23849             evilBtn.click();
23850             expect(evilError.getText()).toMatch(/Content Security Policy/);
23851             expectError(/Content Security Policy/);
23852           });
23853         </file>
23854       </example>
23855   */
23856
23857 // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
23858 // bootstrap the system (before $parse is instantiated), for this reason we just have
23859 // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
23860
23861 /**
23862  * @ngdoc directive
23863  * @name ngClick
23864  *
23865  * @description
23866  * The ngClick directive allows you to specify custom behavior when
23867  * an element is clicked.
23868  *
23869  * @element ANY
23870  * @priority 0
23871  * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
23872  * click. ({@link guide/expression#-event- Event object is available as `$event`})
23873  *
23874  * @example
23875    <example>
23876      <file name="index.html">
23877       <button ng-click="count = count + 1" ng-init="count=0">
23878         Increment
23879       </button>
23880       <span>
23881         count: {{count}}
23882       </span>
23883      </file>
23884      <file name="protractor.js" type="protractor">
23885        it('should check ng-click', function() {
23886          expect(element(by.binding('count')).getText()).toMatch('0');
23887          element(by.css('button')).click();
23888          expect(element(by.binding('count')).getText()).toMatch('1');
23889        });
23890      </file>
23891    </example>
23892  */
23893 /*
23894  * A collection of directives that allows creation of custom event handlers that are defined as
23895  * angular expressions and are compiled and executed within the current scope.
23896  */
23897 var ngEventDirectives = {};
23898
23899 // For events that might fire synchronously during DOM manipulation
23900 // we need to execute their event handlers asynchronously using $evalAsync,
23901 // so that they are not executed in an inconsistent state.
23902 var forceAsyncEvents = {
23903   'blur': true,
23904   'focus': true
23905 };
23906 forEach(
23907   'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
23908   function(eventName) {
23909     var directiveName = directiveNormalize('ng-' + eventName);
23910     ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
23911       return {
23912         restrict: 'A',
23913         compile: function($element, attr) {
23914           // We expose the powerful $event object on the scope that provides access to the Window,
23915           // etc. that isn't protected by the fast paths in $parse.  We explicitly request better
23916           // checks at the cost of speed since event handler expressions are not executed as
23917           // frequently as regular change detection.
23918           var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
23919           return function ngEventHandler(scope, element) {
23920             element.on(eventName, function(event) {
23921               var callback = function() {
23922                 fn(scope, {$event:event});
23923               };
23924               if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
23925                 scope.$evalAsync(callback);
23926               } else {
23927                 scope.$apply(callback);
23928               }
23929             });
23930           };
23931         }
23932       };
23933     }];
23934   }
23935 );
23936
23937 /**
23938  * @ngdoc directive
23939  * @name ngDblclick
23940  *
23941  * @description
23942  * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
23943  *
23944  * @element ANY
23945  * @priority 0
23946  * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
23947  * a dblclick. (The Event object is available as `$event`)
23948  *
23949  * @example
23950    <example>
23951      <file name="index.html">
23952       <button ng-dblclick="count = count + 1" ng-init="count=0">
23953         Increment (on double click)
23954       </button>
23955       count: {{count}}
23956      </file>
23957    </example>
23958  */
23959
23960
23961 /**
23962  * @ngdoc directive
23963  * @name ngMousedown
23964  *
23965  * @description
23966  * The ngMousedown directive allows you to specify custom behavior on mousedown event.
23967  *
23968  * @element ANY
23969  * @priority 0
23970  * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
23971  * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
23972  *
23973  * @example
23974    <example>
23975      <file name="index.html">
23976       <button ng-mousedown="count = count + 1" ng-init="count=0">
23977         Increment (on mouse down)
23978       </button>
23979       count: {{count}}
23980      </file>
23981    </example>
23982  */
23983
23984
23985 /**
23986  * @ngdoc directive
23987  * @name ngMouseup
23988  *
23989  * @description
23990  * Specify custom behavior on mouseup event.
23991  *
23992  * @element ANY
23993  * @priority 0
23994  * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
23995  * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
23996  *
23997  * @example
23998    <example>
23999      <file name="index.html">
24000       <button ng-mouseup="count = count + 1" ng-init="count=0">
24001         Increment (on mouse up)
24002       </button>
24003       count: {{count}}
24004      </file>
24005    </example>
24006  */
24007
24008 /**
24009  * @ngdoc directive
24010  * @name ngMouseover
24011  *
24012  * @description
24013  * Specify custom behavior on mouseover event.
24014  *
24015  * @element ANY
24016  * @priority 0
24017  * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
24018  * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
24019  *
24020  * @example
24021    <example>
24022      <file name="index.html">
24023       <button ng-mouseover="count = count + 1" ng-init="count=0">
24024         Increment (when mouse is over)
24025       </button>
24026       count: {{count}}
24027      </file>
24028    </example>
24029  */
24030
24031
24032 /**
24033  * @ngdoc directive
24034  * @name ngMouseenter
24035  *
24036  * @description
24037  * Specify custom behavior on mouseenter event.
24038  *
24039  * @element ANY
24040  * @priority 0
24041  * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
24042  * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
24043  *
24044  * @example
24045    <example>
24046      <file name="index.html">
24047       <button ng-mouseenter="count = count + 1" ng-init="count=0">
24048         Increment (when mouse enters)
24049       </button>
24050       count: {{count}}
24051      </file>
24052    </example>
24053  */
24054
24055
24056 /**
24057  * @ngdoc directive
24058  * @name ngMouseleave
24059  *
24060  * @description
24061  * Specify custom behavior on mouseleave event.
24062  *
24063  * @element ANY
24064  * @priority 0
24065  * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
24066  * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
24067  *
24068  * @example
24069    <example>
24070      <file name="index.html">
24071       <button ng-mouseleave="count = count + 1" ng-init="count=0">
24072         Increment (when mouse leaves)
24073       </button>
24074       count: {{count}}
24075      </file>
24076    </example>
24077  */
24078
24079
24080 /**
24081  * @ngdoc directive
24082  * @name ngMousemove
24083  *
24084  * @description
24085  * Specify custom behavior on mousemove event.
24086  *
24087  * @element ANY
24088  * @priority 0
24089  * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
24090  * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
24091  *
24092  * @example
24093    <example>
24094      <file name="index.html">
24095       <button ng-mousemove="count = count + 1" ng-init="count=0">
24096         Increment (when mouse moves)
24097       </button>
24098       count: {{count}}
24099      </file>
24100    </example>
24101  */
24102
24103
24104 /**
24105  * @ngdoc directive
24106  * @name ngKeydown
24107  *
24108  * @description
24109  * Specify custom behavior on keydown event.
24110  *
24111  * @element ANY
24112  * @priority 0
24113  * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
24114  * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
24115  *
24116  * @example
24117    <example>
24118      <file name="index.html">
24119       <input ng-keydown="count = count + 1" ng-init="count=0">
24120       key down count: {{count}}
24121      </file>
24122    </example>
24123  */
24124
24125
24126 /**
24127  * @ngdoc directive
24128  * @name ngKeyup
24129  *
24130  * @description
24131  * Specify custom behavior on keyup event.
24132  *
24133  * @element ANY
24134  * @priority 0
24135  * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
24136  * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
24137  *
24138  * @example
24139    <example>
24140      <file name="index.html">
24141        <p>Typing in the input box below updates the key count</p>
24142        <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
24143
24144        <p>Typing in the input box below updates the keycode</p>
24145        <input ng-keyup="event=$event">
24146        <p>event keyCode: {{ event.keyCode }}</p>
24147        <p>event altKey: {{ event.altKey }}</p>
24148      </file>
24149    </example>
24150  */
24151
24152
24153 /**
24154  * @ngdoc directive
24155  * @name ngKeypress
24156  *
24157  * @description
24158  * Specify custom behavior on keypress event.
24159  *
24160  * @element ANY
24161  * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
24162  * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
24163  * and can be interrogated for keyCode, altKey, etc.)
24164  *
24165  * @example
24166    <example>
24167      <file name="index.html">
24168       <input ng-keypress="count = count + 1" ng-init="count=0">
24169       key press count: {{count}}
24170      </file>
24171    </example>
24172  */
24173
24174
24175 /**
24176  * @ngdoc directive
24177  * @name ngSubmit
24178  *
24179  * @description
24180  * Enables binding angular expressions to onsubmit events.
24181  *
24182  * Additionally it prevents the default action (which for form means sending the request to the
24183  * server and reloading the current page), but only if the form does not contain `action`,
24184  * `data-action`, or `x-action` attributes.
24185  *
24186  * <div class="alert alert-warning">
24187  * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
24188  * `ngSubmit` handlers together. See the
24189  * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
24190  * for a detailed discussion of when `ngSubmit` may be triggered.
24191  * </div>
24192  *
24193  * @element form
24194  * @priority 0
24195  * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
24196  * ({@link guide/expression#-event- Event object is available as `$event`})
24197  *
24198  * @example
24199    <example module="submitExample">
24200      <file name="index.html">
24201       <script>
24202         angular.module('submitExample', [])
24203           .controller('ExampleController', ['$scope', function($scope) {
24204             $scope.list = [];
24205             $scope.text = 'hello';
24206             $scope.submit = function() {
24207               if ($scope.text) {
24208                 $scope.list.push(this.text);
24209                 $scope.text = '';
24210               }
24211             };
24212           }]);
24213       </script>
24214       <form ng-submit="submit()" ng-controller="ExampleController">
24215         Enter text and hit enter:
24216         <input type="text" ng-model="text" name="text" />
24217         <input type="submit" id="submit" value="Submit" />
24218         <pre>list={{list}}</pre>
24219       </form>
24220      </file>
24221      <file name="protractor.js" type="protractor">
24222        it('should check ng-submit', function() {
24223          expect(element(by.binding('list')).getText()).toBe('list=[]');
24224          element(by.css('#submit')).click();
24225          expect(element(by.binding('list')).getText()).toContain('hello');
24226          expect(element(by.model('text')).getAttribute('value')).toBe('');
24227        });
24228        it('should ignore empty strings', function() {
24229          expect(element(by.binding('list')).getText()).toBe('list=[]');
24230          element(by.css('#submit')).click();
24231          element(by.css('#submit')).click();
24232          expect(element(by.binding('list')).getText()).toContain('hello');
24233         });
24234      </file>
24235    </example>
24236  */
24237
24238 /**
24239  * @ngdoc directive
24240  * @name ngFocus
24241  *
24242  * @description
24243  * Specify custom behavior on focus event.
24244  *
24245  * Note: As the `focus` event is executed synchronously when calling `input.focus()`
24246  * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
24247  * during an `$apply` to ensure a consistent state.
24248  *
24249  * @element window, input, select, textarea, a
24250  * @priority 0
24251  * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
24252  * focus. ({@link guide/expression#-event- Event object is available as `$event`})
24253  *
24254  * @example
24255  * See {@link ng.directive:ngClick ngClick}
24256  */
24257
24258 /**
24259  * @ngdoc directive
24260  * @name ngBlur
24261  *
24262  * @description
24263  * Specify custom behavior on blur event.
24264  *
24265  * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
24266  * an element has lost focus.
24267  *
24268  * Note: As the `blur` event is executed synchronously also during DOM manipulations
24269  * (e.g. removing a focussed input),
24270  * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
24271  * during an `$apply` to ensure a consistent state.
24272  *
24273  * @element window, input, select, textarea, a
24274  * @priority 0
24275  * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
24276  * blur. ({@link guide/expression#-event- Event object is available as `$event`})
24277  *
24278  * @example
24279  * See {@link ng.directive:ngClick ngClick}
24280  */
24281
24282 /**
24283  * @ngdoc directive
24284  * @name ngCopy
24285  *
24286  * @description
24287  * Specify custom behavior on copy event.
24288  *
24289  * @element window, input, select, textarea, a
24290  * @priority 0
24291  * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
24292  * copy. ({@link guide/expression#-event- Event object is available as `$event`})
24293  *
24294  * @example
24295    <example>
24296      <file name="index.html">
24297       <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
24298       copied: {{copied}}
24299      </file>
24300    </example>
24301  */
24302
24303 /**
24304  * @ngdoc directive
24305  * @name ngCut
24306  *
24307  * @description
24308  * Specify custom behavior on cut event.
24309  *
24310  * @element window, input, select, textarea, a
24311  * @priority 0
24312  * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
24313  * cut. ({@link guide/expression#-event- Event object is available as `$event`})
24314  *
24315  * @example
24316    <example>
24317      <file name="index.html">
24318       <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
24319       cut: {{cut}}
24320      </file>
24321    </example>
24322  */
24323
24324 /**
24325  * @ngdoc directive
24326  * @name ngPaste
24327  *
24328  * @description
24329  * Specify custom behavior on paste event.
24330  *
24331  * @element window, input, select, textarea, a
24332  * @priority 0
24333  * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
24334  * paste. ({@link guide/expression#-event- Event object is available as `$event`})
24335  *
24336  * @example
24337    <example>
24338      <file name="index.html">
24339       <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
24340       pasted: {{paste}}
24341      </file>
24342    </example>
24343  */
24344
24345 /**
24346  * @ngdoc directive
24347  * @name ngIf
24348  * @restrict A
24349  * @multiElement
24350  *
24351  * @description
24352  * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
24353  * {expression}. If the expression assigned to `ngIf` evaluates to a false
24354  * value then the element is removed from the DOM, otherwise a clone of the
24355  * element is reinserted into the DOM.
24356  *
24357  * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
24358  * element in the DOM rather than changing its visibility via the `display` css property.  A common
24359  * case when this difference is significant is when using css selectors that rely on an element's
24360  * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
24361  *
24362  * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
24363  * is created when the element is restored.  The scope created within `ngIf` inherits from
24364  * its parent scope using
24365  * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
24366  * An important implication of this is if `ngModel` is used within `ngIf` to bind to
24367  * a javascript primitive defined in the parent scope. In this case any modifications made to the
24368  * variable within the child scope will override (hide) the value in the parent scope.
24369  *
24370  * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
24371  * is if an element's class attribute is directly modified after it's compiled, using something like
24372  * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
24373  * the added class will be lost because the original compiled state is used to regenerate the element.
24374  *
24375  * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
24376  * and `leave` effects.
24377  *
24378  * @animations
24379  * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
24380  * leave - happens just before the `ngIf` contents are removed from the DOM
24381  *
24382  * @element ANY
24383  * @scope
24384  * @priority 600
24385  * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
24386  *     the element is removed from the DOM tree. If it is truthy a copy of the compiled
24387  *     element is added to the DOM tree.
24388  *
24389  * @example
24390   <example module="ngAnimate" deps="angular-animate.js" animations="true">
24391     <file name="index.html">
24392       <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
24393       Show when checked:
24394       <span ng-if="checked" class="animate-if">
24395         This is removed when the checkbox is unchecked.
24396       </span>
24397     </file>
24398     <file name="animations.css">
24399       .animate-if {
24400         background:white;
24401         border:1px solid black;
24402         padding:10px;
24403       }
24404
24405       .animate-if.ng-enter, .animate-if.ng-leave {
24406         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
24407       }
24408
24409       .animate-if.ng-enter,
24410       .animate-if.ng-leave.ng-leave-active {
24411         opacity:0;
24412       }
24413
24414       .animate-if.ng-leave,
24415       .animate-if.ng-enter.ng-enter-active {
24416         opacity:1;
24417       }
24418     </file>
24419   </example>
24420  */
24421 var ngIfDirective = ['$animate', function($animate) {
24422   return {
24423     multiElement: true,
24424     transclude: 'element',
24425     priority: 600,
24426     terminal: true,
24427     restrict: 'A',
24428     $$tlb: true,
24429     link: function($scope, $element, $attr, ctrl, $transclude) {
24430         var block, childScope, previousElements;
24431         $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
24432
24433           if (value) {
24434             if (!childScope) {
24435               $transclude(function(clone, newScope) {
24436                 childScope = newScope;
24437                 clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
24438                 // Note: We only need the first/last node of the cloned nodes.
24439                 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
24440                 // by a directive with templateUrl when its template arrives.
24441                 block = {
24442                   clone: clone
24443                 };
24444                 $animate.enter(clone, $element.parent(), $element);
24445               });
24446             }
24447           } else {
24448             if (previousElements) {
24449               previousElements.remove();
24450               previousElements = null;
24451             }
24452             if (childScope) {
24453               childScope.$destroy();
24454               childScope = null;
24455             }
24456             if (block) {
24457               previousElements = getBlockNodes(block.clone);
24458               $animate.leave(previousElements).then(function() {
24459                 previousElements = null;
24460               });
24461               block = null;
24462             }
24463           }
24464         });
24465     }
24466   };
24467 }];
24468
24469 /**
24470  * @ngdoc directive
24471  * @name ngInclude
24472  * @restrict ECA
24473  *
24474  * @description
24475  * Fetches, compiles and includes an external HTML fragment.
24476  *
24477  * By default, the template URL is restricted to the same domain and protocol as the
24478  * application document. This is done by calling {@link $sce#getTrustedResourceUrl
24479  * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
24480  * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
24481  * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
24482  * ng.$sce Strict Contextual Escaping}.
24483  *
24484  * In addition, the browser's
24485  * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
24486  * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
24487  * policy may further restrict whether the template is successfully loaded.
24488  * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
24489  * access on some browsers.
24490  *
24491  * @animations
24492  * enter - animation is used to bring new content into the browser.
24493  * leave - animation is used to animate existing content away.
24494  *
24495  * The enter and leave animation occur concurrently.
24496  *
24497  * @scope
24498  * @priority 400
24499  *
24500  * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
24501  *                 make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
24502  * @param {string=} onload Expression to evaluate when a new partial is loaded.
24503  *                  <div class="alert alert-warning">
24504  *                  **Note:** When using onload on SVG elements in IE11, the browser will try to call
24505  *                  a function with the name on the window element, which will usually throw a
24506  *                  "function is undefined" error. To fix this, you can instead use `data-onload` or a
24507  *                  different form that {@link guide/directive#normalization matches} `onload`.
24508  *                  </div>
24509    *
24510  * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
24511  *                  $anchorScroll} to scroll the viewport after the content is loaded.
24512  *
24513  *                  - If the attribute is not set, disable scrolling.
24514  *                  - If the attribute is set without value, enable scrolling.
24515  *                  - Otherwise enable scrolling only if the expression evaluates to truthy value.
24516  *
24517  * @example
24518   <example module="includeExample" deps="angular-animate.js" animations="true">
24519     <file name="index.html">
24520      <div ng-controller="ExampleController">
24521        <select ng-model="template" ng-options="t.name for t in templates">
24522         <option value="">(blank)</option>
24523        </select>
24524        url of the template: <code>{{template.url}}</code>
24525        <hr/>
24526        <div class="slide-animate-container">
24527          <div class="slide-animate" ng-include="template.url"></div>
24528        </div>
24529      </div>
24530     </file>
24531     <file name="script.js">
24532       angular.module('includeExample', ['ngAnimate'])
24533         .controller('ExampleController', ['$scope', function($scope) {
24534           $scope.templates =
24535             [ { name: 'template1.html', url: 'template1.html'},
24536               { name: 'template2.html', url: 'template2.html'} ];
24537           $scope.template = $scope.templates[0];
24538         }]);
24539      </file>
24540     <file name="template1.html">
24541       Content of template1.html
24542     </file>
24543     <file name="template2.html">
24544       Content of template2.html
24545     </file>
24546     <file name="animations.css">
24547       .slide-animate-container {
24548         position:relative;
24549         background:white;
24550         border:1px solid black;
24551         height:40px;
24552         overflow:hidden;
24553       }
24554
24555       .slide-animate {
24556         padding:10px;
24557       }
24558
24559       .slide-animate.ng-enter, .slide-animate.ng-leave {
24560         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
24561
24562         position:absolute;
24563         top:0;
24564         left:0;
24565         right:0;
24566         bottom:0;
24567         display:block;
24568         padding:10px;
24569       }
24570
24571       .slide-animate.ng-enter {
24572         top:-50px;
24573       }
24574       .slide-animate.ng-enter.ng-enter-active {
24575         top:0;
24576       }
24577
24578       .slide-animate.ng-leave {
24579         top:0;
24580       }
24581       .slide-animate.ng-leave.ng-leave-active {
24582         top:50px;
24583       }
24584     </file>
24585     <file name="protractor.js" type="protractor">
24586       var templateSelect = element(by.model('template'));
24587       var includeElem = element(by.css('[ng-include]'));
24588
24589       it('should load template1.html', function() {
24590         expect(includeElem.getText()).toMatch(/Content of template1.html/);
24591       });
24592
24593       it('should load template2.html', function() {
24594         if (browser.params.browser == 'firefox') {
24595           // Firefox can't handle using selects
24596           // See https://github.com/angular/protractor/issues/480
24597           return;
24598         }
24599         templateSelect.click();
24600         templateSelect.all(by.css('option')).get(2).click();
24601         expect(includeElem.getText()).toMatch(/Content of template2.html/);
24602       });
24603
24604       it('should change to blank', function() {
24605         if (browser.params.browser == 'firefox') {
24606           // Firefox can't handle using selects
24607           return;
24608         }
24609         templateSelect.click();
24610         templateSelect.all(by.css('option')).get(0).click();
24611         expect(includeElem.isPresent()).toBe(false);
24612       });
24613     </file>
24614   </example>
24615  */
24616
24617
24618 /**
24619  * @ngdoc event
24620  * @name ngInclude#$includeContentRequested
24621  * @eventType emit on the scope ngInclude was declared in
24622  * @description
24623  * Emitted every time the ngInclude content is requested.
24624  *
24625  * @param {Object} angularEvent Synthetic event object.
24626  * @param {String} src URL of content to load.
24627  */
24628
24629
24630 /**
24631  * @ngdoc event
24632  * @name ngInclude#$includeContentLoaded
24633  * @eventType emit on the current ngInclude scope
24634  * @description
24635  * Emitted every time the ngInclude content is reloaded.
24636  *
24637  * @param {Object} angularEvent Synthetic event object.
24638  * @param {String} src URL of content to load.
24639  */
24640
24641
24642 /**
24643  * @ngdoc event
24644  * @name ngInclude#$includeContentError
24645  * @eventType emit on the scope ngInclude was declared in
24646  * @description
24647  * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
24648  *
24649  * @param {Object} angularEvent Synthetic event object.
24650  * @param {String} src URL of content to load.
24651  */
24652 var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
24653                   function($templateRequest,   $anchorScroll,   $animate) {
24654   return {
24655     restrict: 'ECA',
24656     priority: 400,
24657     terminal: true,
24658     transclude: 'element',
24659     controller: angular.noop,
24660     compile: function(element, attr) {
24661       var srcExp = attr.ngInclude || attr.src,
24662           onloadExp = attr.onload || '',
24663           autoScrollExp = attr.autoscroll;
24664
24665       return function(scope, $element, $attr, ctrl, $transclude) {
24666         var changeCounter = 0,
24667             currentScope,
24668             previousElement,
24669             currentElement;
24670
24671         var cleanupLastIncludeContent = function() {
24672           if (previousElement) {
24673             previousElement.remove();
24674             previousElement = null;
24675           }
24676           if (currentScope) {
24677             currentScope.$destroy();
24678             currentScope = null;
24679           }
24680           if (currentElement) {
24681             $animate.leave(currentElement).then(function() {
24682               previousElement = null;
24683             });
24684             previousElement = currentElement;
24685             currentElement = null;
24686           }
24687         };
24688
24689         scope.$watch(srcExp, function ngIncludeWatchAction(src) {
24690           var afterAnimation = function() {
24691             if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
24692               $anchorScroll();
24693             }
24694           };
24695           var thisChangeId = ++changeCounter;
24696
24697           if (src) {
24698             //set the 2nd param to true to ignore the template request error so that the inner
24699             //contents and scope can be cleaned up.
24700             $templateRequest(src, true).then(function(response) {
24701               if (thisChangeId !== changeCounter) return;
24702               var newScope = scope.$new();
24703               ctrl.template = response;
24704
24705               // Note: This will also link all children of ng-include that were contained in the original
24706               // html. If that content contains controllers, ... they could pollute/change the scope.
24707               // However, using ng-include on an element with additional content does not make sense...
24708               // Note: We can't remove them in the cloneAttchFn of $transclude as that
24709               // function is called before linking the content, which would apply child
24710               // directives to non existing elements.
24711               var clone = $transclude(newScope, function(clone) {
24712                 cleanupLastIncludeContent();
24713                 $animate.enter(clone, null, $element).then(afterAnimation);
24714               });
24715
24716               currentScope = newScope;
24717               currentElement = clone;
24718
24719               currentScope.$emit('$includeContentLoaded', src);
24720               scope.$eval(onloadExp);
24721             }, function() {
24722               if (thisChangeId === changeCounter) {
24723                 cleanupLastIncludeContent();
24724                 scope.$emit('$includeContentError', src);
24725               }
24726             });
24727             scope.$emit('$includeContentRequested', src);
24728           } else {
24729             cleanupLastIncludeContent();
24730             ctrl.template = null;
24731           }
24732         });
24733       };
24734     }
24735   };
24736 }];
24737
24738 // This directive is called during the $transclude call of the first `ngInclude` directive.
24739 // It will replace and compile the content of the element with the loaded template.
24740 // We need this directive so that the element content is already filled when
24741 // the link function of another directive on the same element as ngInclude
24742 // is called.
24743 var ngIncludeFillContentDirective = ['$compile',
24744   function($compile) {
24745     return {
24746       restrict: 'ECA',
24747       priority: -400,
24748       require: 'ngInclude',
24749       link: function(scope, $element, $attr, ctrl) {
24750         if (/SVG/.test($element[0].toString())) {
24751           // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
24752           // support innerHTML, so detect this here and try to generate the contents
24753           // specially.
24754           $element.empty();
24755           $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
24756               function namespaceAdaptedClone(clone) {
24757             $element.append(clone);
24758           }, {futureParentElement: $element});
24759           return;
24760         }
24761
24762         $element.html(ctrl.template);
24763         $compile($element.contents())(scope);
24764       }
24765     };
24766   }];
24767
24768 /**
24769  * @ngdoc directive
24770  * @name ngInit
24771  * @restrict AC
24772  *
24773  * @description
24774  * The `ngInit` directive allows you to evaluate an expression in the
24775  * current scope.
24776  *
24777  * <div class="alert alert-danger">
24778  * This directive can be abused to add unnecessary amounts of logic into your templates.
24779  * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
24780  * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
24781  * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
24782  * rather than `ngInit` to initialize values on a scope.
24783  * </div>
24784  *
24785  * <div class="alert alert-warning">
24786  * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
24787  * sure you have parentheses to ensure correct operator precedence:
24788  * <pre class="prettyprint">
24789  * `<div ng-init="test1 = ($index | toString)"></div>`
24790  * </pre>
24791  * </div>
24792  *
24793  * @priority 450
24794  *
24795  * @element ANY
24796  * @param {expression} ngInit {@link guide/expression Expression} to eval.
24797  *
24798  * @example
24799    <example module="initExample">
24800      <file name="index.html">
24801    <script>
24802      angular.module('initExample', [])
24803        .controller('ExampleController', ['$scope', function($scope) {
24804          $scope.list = [['a', 'b'], ['c', 'd']];
24805        }]);
24806    </script>
24807    <div ng-controller="ExampleController">
24808      <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
24809        <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
24810           <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
24811        </div>
24812      </div>
24813    </div>
24814      </file>
24815      <file name="protractor.js" type="protractor">
24816        it('should alias index positions', function() {
24817          var elements = element.all(by.css('.example-init'));
24818          expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
24819          expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
24820          expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
24821          expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
24822        });
24823      </file>
24824    </example>
24825  */
24826 var ngInitDirective = ngDirective({
24827   priority: 450,
24828   compile: function() {
24829     return {
24830       pre: function(scope, element, attrs) {
24831         scope.$eval(attrs.ngInit);
24832       }
24833     };
24834   }
24835 });
24836
24837 /**
24838  * @ngdoc directive
24839  * @name ngList
24840  *
24841  * @description
24842  * Text input that converts between a delimited string and an array of strings. The default
24843  * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
24844  * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
24845  *
24846  * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
24847  * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
24848  *   list item is respected. This implies that the user of the directive is responsible for
24849  *   dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
24850  *   tab or newline character.
24851  * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
24852  *   when joining the list items back together) and whitespace around each list item is stripped
24853  *   before it is added to the model.
24854  *
24855  * ### Example with Validation
24856  *
24857  * <example name="ngList-directive" module="listExample">
24858  *   <file name="app.js">
24859  *      angular.module('listExample', [])
24860  *        .controller('ExampleController', ['$scope', function($scope) {
24861  *          $scope.names = ['morpheus', 'neo', 'trinity'];
24862  *        }]);
24863  *   </file>
24864  *   <file name="index.html">
24865  *    <form name="myForm" ng-controller="ExampleController">
24866  *      <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
24867  *      <span role="alert">
24868  *        <span class="error" ng-show="myForm.namesInput.$error.required">
24869  *        Required!</span>
24870  *      </span>
24871  *      <br>
24872  *      <tt>names = {{names}}</tt><br/>
24873  *      <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
24874  *      <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
24875  *      <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
24876  *      <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
24877  *     </form>
24878  *   </file>
24879  *   <file name="protractor.js" type="protractor">
24880  *     var listInput = element(by.model('names'));
24881  *     var names = element(by.exactBinding('names'));
24882  *     var valid = element(by.binding('myForm.namesInput.$valid'));
24883  *     var error = element(by.css('span.error'));
24884  *
24885  *     it('should initialize to model', function() {
24886  *       expect(names.getText()).toContain('["morpheus","neo","trinity"]');
24887  *       expect(valid.getText()).toContain('true');
24888  *       expect(error.getCssValue('display')).toBe('none');
24889  *     });
24890  *
24891  *     it('should be invalid if empty', function() {
24892  *       listInput.clear();
24893  *       listInput.sendKeys('');
24894  *
24895  *       expect(names.getText()).toContain('');
24896  *       expect(valid.getText()).toContain('false');
24897  *       expect(error.getCssValue('display')).not.toBe('none');
24898  *     });
24899  *   </file>
24900  * </example>
24901  *
24902  * ### Example - splitting on newline
24903  * <example name="ngList-directive-newlines">
24904  *   <file name="index.html">
24905  *    <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
24906  *    <pre>{{ list | json }}</pre>
24907  *   </file>
24908  *   <file name="protractor.js" type="protractor">
24909  *     it("should split the text by newlines", function() {
24910  *       var listInput = element(by.model('list'));
24911  *       var output = element(by.binding('list | json'));
24912  *       listInput.sendKeys('abc\ndef\nghi');
24913  *       expect(output.getText()).toContain('[\n  "abc",\n  "def",\n  "ghi"\n]');
24914  *     });
24915  *   </file>
24916  * </example>
24917  *
24918  * @element input
24919  * @param {string=} ngList optional delimiter that should be used to split the value.
24920  */
24921 var ngListDirective = function() {
24922   return {
24923     restrict: 'A',
24924     priority: 100,
24925     require: 'ngModel',
24926     link: function(scope, element, attr, ctrl) {
24927       // We want to control whitespace trimming so we use this convoluted approach
24928       // to access the ngList attribute, which doesn't pre-trim the attribute
24929       var ngList = element.attr(attr.$attr.ngList) || ', ';
24930       var trimValues = attr.ngTrim !== 'false';
24931       var separator = trimValues ? trim(ngList) : ngList;
24932
24933       var parse = function(viewValue) {
24934         // If the viewValue is invalid (say required but empty) it will be `undefined`
24935         if (isUndefined(viewValue)) return;
24936
24937         var list = [];
24938
24939         if (viewValue) {
24940           forEach(viewValue.split(separator), function(value) {
24941             if (value) list.push(trimValues ? trim(value) : value);
24942           });
24943         }
24944
24945         return list;
24946       };
24947
24948       ctrl.$parsers.push(parse);
24949       ctrl.$formatters.push(function(value) {
24950         if (isArray(value)) {
24951           return value.join(ngList);
24952         }
24953
24954         return undefined;
24955       });
24956
24957       // Override the standard $isEmpty because an empty array means the input is empty.
24958       ctrl.$isEmpty = function(value) {
24959         return !value || !value.length;
24960       };
24961     }
24962   };
24963 };
24964
24965 /* global VALID_CLASS: true,
24966   INVALID_CLASS: true,
24967   PRISTINE_CLASS: true,
24968   DIRTY_CLASS: true,
24969   UNTOUCHED_CLASS: true,
24970   TOUCHED_CLASS: true,
24971 */
24972
24973 var VALID_CLASS = 'ng-valid',
24974     INVALID_CLASS = 'ng-invalid',
24975     PRISTINE_CLASS = 'ng-pristine',
24976     DIRTY_CLASS = 'ng-dirty',
24977     UNTOUCHED_CLASS = 'ng-untouched',
24978     TOUCHED_CLASS = 'ng-touched',
24979     PENDING_CLASS = 'ng-pending',
24980     EMPTY_CLASS = 'ng-empty',
24981     NOT_EMPTY_CLASS = 'ng-not-empty';
24982
24983 var ngModelMinErr = minErr('ngModel');
24984
24985 /**
24986  * @ngdoc type
24987  * @name ngModel.NgModelController
24988  *
24989  * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
24990  * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
24991  * is set.
24992  * @property {*} $modelValue The value in the model that the control is bound to.
24993  * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
24994        the control reads value from the DOM. The functions are called in array order, each passing
24995        its return value through to the next. The last return value is forwarded to the
24996        {@link ngModel.NgModelController#$validators `$validators`} collection.
24997
24998 Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
24999 `$viewValue`}.
25000
25001 Returning `undefined` from a parser means a parse error occurred. In that case,
25002 no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
25003 will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
25004 is set to `true`. The parse error is stored in `ngModel.$error.parse`.
25005
25006  *
25007  * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
25008        the model value changes. The functions are called in reverse array order, each passing the value through to the
25009        next. The last return value is used as the actual DOM value.
25010        Used to format / convert values for display in the control.
25011  * ```js
25012  * function formatter(value) {
25013  *   if (value) {
25014  *     return value.toUpperCase();
25015  *   }
25016  * }
25017  * ngModel.$formatters.push(formatter);
25018  * ```
25019  *
25020  * @property {Object.<string, function>} $validators A collection of validators that are applied
25021  *      whenever the model value changes. The key value within the object refers to the name of the
25022  *      validator while the function refers to the validation operation. The validation operation is
25023  *      provided with the model value as an argument and must return a true or false value depending
25024  *      on the response of that validation.
25025  *
25026  * ```js
25027  * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
25028  *   var value = modelValue || viewValue;
25029  *   return /[0-9]+/.test(value) &&
25030  *          /[a-z]+/.test(value) &&
25031  *          /[A-Z]+/.test(value) &&
25032  *          /\W+/.test(value);
25033  * };
25034  * ```
25035  *
25036  * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
25037  *      perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
25038  *      is expected to return a promise when it is run during the model validation process. Once the promise
25039  *      is delivered then the validation status will be set to true when fulfilled and false when rejected.
25040  *      When the asynchronous validators are triggered, each of the validators will run in parallel and the model
25041  *      value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
25042  *      is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
25043  *      will only run once all synchronous validators have passed.
25044  *
25045  * Please note that if $http is used then it is important that the server returns a success HTTP response code
25046  * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
25047  *
25048  * ```js
25049  * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
25050  *   var value = modelValue || viewValue;
25051  *
25052  *   // Lookup user by username
25053  *   return $http.get('/api/users/' + value).
25054  *      then(function resolved() {
25055  *        //username exists, this means validation fails
25056  *        return $q.reject('exists');
25057  *      }, function rejected() {
25058  *        //username does not exist, therefore this validation passes
25059  *        return true;
25060  *      });
25061  * };
25062  * ```
25063  *
25064  * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
25065  *     view value has changed. It is called with no arguments, and its return value is ignored.
25066  *     This can be used in place of additional $watches against the model value.
25067  *
25068  * @property {Object} $error An object hash with all failing validator ids as keys.
25069  * @property {Object} $pending An object hash with all pending validator ids as keys.
25070  *
25071  * @property {boolean} $untouched True if control has not lost focus yet.
25072  * @property {boolean} $touched True if control has lost focus.
25073  * @property {boolean} $pristine True if user has not interacted with the control yet.
25074  * @property {boolean} $dirty True if user has already interacted with the control.
25075  * @property {boolean} $valid True if there is no error.
25076  * @property {boolean} $invalid True if at least one error on the control.
25077  * @property {string} $name The name attribute of the control.
25078  *
25079  * @description
25080  *
25081  * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
25082  * The controller contains services for data-binding, validation, CSS updates, and value formatting
25083  * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
25084  * listening to DOM events.
25085  * Such DOM related logic should be provided by other directives which make use of
25086  * `NgModelController` for data-binding to control elements.
25087  * Angular provides this DOM logic for most {@link input `input`} elements.
25088  * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
25089  * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
25090  *
25091  * @example
25092  * ### Custom Control Example
25093  * This example shows how to use `NgModelController` with a custom control to achieve
25094  * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
25095  * collaborate together to achieve the desired result.
25096  *
25097  * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
25098  * contents be edited in place by the user.
25099  *
25100  * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
25101  * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
25102  * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
25103  * that content using the `$sce` service.
25104  *
25105  * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
25106     <file name="style.css">
25107       [contenteditable] {
25108         border: 1px solid black;
25109         background-color: white;
25110         min-height: 20px;
25111       }
25112
25113       .ng-invalid {
25114         border: 1px solid red;
25115       }
25116
25117     </file>
25118     <file name="script.js">
25119       angular.module('customControl', ['ngSanitize']).
25120         directive('contenteditable', ['$sce', function($sce) {
25121           return {
25122             restrict: 'A', // only activate on element attribute
25123             require: '?ngModel', // get a hold of NgModelController
25124             link: function(scope, element, attrs, ngModel) {
25125               if (!ngModel) return; // do nothing if no ng-model
25126
25127               // Specify how UI should be updated
25128               ngModel.$render = function() {
25129                 element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
25130               };
25131
25132               // Listen for change events to enable binding
25133               element.on('blur keyup change', function() {
25134                 scope.$evalAsync(read);
25135               });
25136               read(); // initialize
25137
25138               // Write data to the model
25139               function read() {
25140                 var html = element.html();
25141                 // When we clear the content editable the browser leaves a <br> behind
25142                 // If strip-br attribute is provided then we strip this out
25143                 if ( attrs.stripBr && html == '<br>' ) {
25144                   html = '';
25145                 }
25146                 ngModel.$setViewValue(html);
25147               }
25148             }
25149           };
25150         }]);
25151     </file>
25152     <file name="index.html">
25153       <form name="myForm">
25154        <div contenteditable
25155             name="myWidget" ng-model="userContent"
25156             strip-br="true"
25157             required>Change me!</div>
25158         <span ng-show="myForm.myWidget.$error.required">Required!</span>
25159        <hr>
25160        <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
25161       </form>
25162     </file>
25163     <file name="protractor.js" type="protractor">
25164     it('should data-bind and become invalid', function() {
25165       if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
25166         // SafariDriver can't handle contenteditable
25167         // and Firefox driver can't clear contenteditables very well
25168         return;
25169       }
25170       var contentEditable = element(by.css('[contenteditable]'));
25171       var content = 'Change me!';
25172
25173       expect(contentEditable.getText()).toEqual(content);
25174
25175       contentEditable.clear();
25176       contentEditable.sendKeys(protractor.Key.BACK_SPACE);
25177       expect(contentEditable.getText()).toEqual('');
25178       expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
25179     });
25180     </file>
25181  * </example>
25182  *
25183  *
25184  */
25185 var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
25186     function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
25187   this.$viewValue = Number.NaN;
25188   this.$modelValue = Number.NaN;
25189   this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
25190   this.$validators = {};
25191   this.$asyncValidators = {};
25192   this.$parsers = [];
25193   this.$formatters = [];
25194   this.$viewChangeListeners = [];
25195   this.$untouched = true;
25196   this.$touched = false;
25197   this.$pristine = true;
25198   this.$dirty = false;
25199   this.$valid = true;
25200   this.$invalid = false;
25201   this.$error = {}; // keep invalid keys here
25202   this.$$success = {}; // keep valid keys here
25203   this.$pending = undefined; // keep pending keys here
25204   this.$name = $interpolate($attr.name || '', false)($scope);
25205   this.$$parentForm = nullFormCtrl;
25206
25207   var parsedNgModel = $parse($attr.ngModel),
25208       parsedNgModelAssign = parsedNgModel.assign,
25209       ngModelGet = parsedNgModel,
25210       ngModelSet = parsedNgModelAssign,
25211       pendingDebounce = null,
25212       parserValid,
25213       ctrl = this;
25214
25215   this.$$setOptions = function(options) {
25216     ctrl.$options = options;
25217     if (options && options.getterSetter) {
25218       var invokeModelGetter = $parse($attr.ngModel + '()'),
25219           invokeModelSetter = $parse($attr.ngModel + '($$$p)');
25220
25221       ngModelGet = function($scope) {
25222         var modelValue = parsedNgModel($scope);
25223         if (isFunction(modelValue)) {
25224           modelValue = invokeModelGetter($scope);
25225         }
25226         return modelValue;
25227       };
25228       ngModelSet = function($scope, newValue) {
25229         if (isFunction(parsedNgModel($scope))) {
25230           invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
25231         } else {
25232           parsedNgModelAssign($scope, ctrl.$modelValue);
25233         }
25234       };
25235     } else if (!parsedNgModel.assign) {
25236       throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
25237           $attr.ngModel, startingTag($element));
25238     }
25239   };
25240
25241   /**
25242    * @ngdoc method
25243    * @name ngModel.NgModelController#$render
25244    *
25245    * @description
25246    * Called when the view needs to be updated. It is expected that the user of the ng-model
25247    * directive will implement this method.
25248    *
25249    * The `$render()` method is invoked in the following situations:
25250    *
25251    * * `$rollbackViewValue()` is called.  If we are rolling back the view value to the last
25252    *   committed value then `$render()` is called to update the input control.
25253    * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
25254    *   the `$viewValue` are different from last time.
25255    *
25256    * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
25257    * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
25258    * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
25259    * invoked if you only change a property on the objects.
25260    */
25261   this.$render = noop;
25262
25263   /**
25264    * @ngdoc method
25265    * @name ngModel.NgModelController#$isEmpty
25266    *
25267    * @description
25268    * This is called when we need to determine if the value of an input is empty.
25269    *
25270    * For instance, the required directive does this to work out if the input has data or not.
25271    *
25272    * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
25273    *
25274    * You can override this for input directives whose concept of being empty is different from the
25275    * default. The `checkboxInputType` directive does this because in its case a value of `false`
25276    * implies empty.
25277    *
25278    * @param {*} value The value of the input to check for emptiness.
25279    * @returns {boolean} True if `value` is "empty".
25280    */
25281   this.$isEmpty = function(value) {
25282     return isUndefined(value) || value === '' || value === null || value !== value;
25283   };
25284
25285   this.$$updateEmptyClasses = function(value) {
25286     if (ctrl.$isEmpty(value)) {
25287       $animate.removeClass($element, NOT_EMPTY_CLASS);
25288       $animate.addClass($element, EMPTY_CLASS);
25289     } else {
25290       $animate.removeClass($element, EMPTY_CLASS);
25291       $animate.addClass($element, NOT_EMPTY_CLASS);
25292     }
25293   };
25294
25295
25296   var currentValidationRunId = 0;
25297
25298   /**
25299    * @ngdoc method
25300    * @name ngModel.NgModelController#$setValidity
25301    *
25302    * @description
25303    * Change the validity state, and notify the form.
25304    *
25305    * This method can be called within $parsers/$formatters or a custom validation implementation.
25306    * However, in most cases it should be sufficient to use the `ngModel.$validators` and
25307    * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
25308    *
25309    * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
25310    *        to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
25311    *        (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
25312    *        The `validationErrorKey` should be in camelCase and will get converted into dash-case
25313    *        for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
25314    *        class and can be bound to as  `{{someForm.someControl.$error.myError}}` .
25315    * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
25316    *                          or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
25317    *                          Skipped is used by Angular when validators do not run because of parse errors and
25318    *                          when `$asyncValidators` do not run because any of the `$validators` failed.
25319    */
25320   addSetValidityMethod({
25321     ctrl: this,
25322     $element: $element,
25323     set: function(object, property) {
25324       object[property] = true;
25325     },
25326     unset: function(object, property) {
25327       delete object[property];
25328     },
25329     $animate: $animate
25330   });
25331
25332   /**
25333    * @ngdoc method
25334    * @name ngModel.NgModelController#$setPristine
25335    *
25336    * @description
25337    * Sets the control to its pristine state.
25338    *
25339    * This method can be called to remove the `ng-dirty` class and set the control to its pristine
25340    * state (`ng-pristine` class). A model is considered to be pristine when the control
25341    * has not been changed from when first compiled.
25342    */
25343   this.$setPristine = function() {
25344     ctrl.$dirty = false;
25345     ctrl.$pristine = true;
25346     $animate.removeClass($element, DIRTY_CLASS);
25347     $animate.addClass($element, PRISTINE_CLASS);
25348   };
25349
25350   /**
25351    * @ngdoc method
25352    * @name ngModel.NgModelController#$setDirty
25353    *
25354    * @description
25355    * Sets the control to its dirty state.
25356    *
25357    * This method can be called to remove the `ng-pristine` class and set the control to its dirty
25358    * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
25359    * from when first compiled.
25360    */
25361   this.$setDirty = function() {
25362     ctrl.$dirty = true;
25363     ctrl.$pristine = false;
25364     $animate.removeClass($element, PRISTINE_CLASS);
25365     $animate.addClass($element, DIRTY_CLASS);
25366     ctrl.$$parentForm.$setDirty();
25367   };
25368
25369   /**
25370    * @ngdoc method
25371    * @name ngModel.NgModelController#$setUntouched
25372    *
25373    * @description
25374    * Sets the control to its untouched state.
25375    *
25376    * This method can be called to remove the `ng-touched` class and set the control to its
25377    * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
25378    * by default, however this function can be used to restore that state if the model has
25379    * already been touched by the user.
25380    */
25381   this.$setUntouched = function() {
25382     ctrl.$touched = false;
25383     ctrl.$untouched = true;
25384     $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
25385   };
25386
25387   /**
25388    * @ngdoc method
25389    * @name ngModel.NgModelController#$setTouched
25390    *
25391    * @description
25392    * Sets the control to its touched state.
25393    *
25394    * This method can be called to remove the `ng-untouched` class and set the control to its
25395    * touched state (`ng-touched` class). A model is considered to be touched when the user has
25396    * first focused the control element and then shifted focus away from the control (blur event).
25397    */
25398   this.$setTouched = function() {
25399     ctrl.$touched = true;
25400     ctrl.$untouched = false;
25401     $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
25402   };
25403
25404   /**
25405    * @ngdoc method
25406    * @name ngModel.NgModelController#$rollbackViewValue
25407    *
25408    * @description
25409    * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
25410    * which may be caused by a pending debounced event or because the input is waiting for a some
25411    * future event.
25412    *
25413    * If you have an input that uses `ng-model-options` to set up debounced events or events such
25414    * as blur you can have a situation where there is a period when the `$viewValue`
25415    * is out of synch with the ngModel's `$modelValue`.
25416    *
25417    * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
25418    * programmatically before these debounced/future events have resolved/occurred, because Angular's
25419    * dirty checking mechanism is not able to tell whether the model has actually changed or not.
25420    *
25421    * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
25422    * input which may have such events pending. This is important in order to make sure that the
25423    * input field will be updated with the new model value and any pending operations are cancelled.
25424    *
25425    * <example name="ng-model-cancel-update" module="cancel-update-example">
25426    *   <file name="app.js">
25427    *     angular.module('cancel-update-example', [])
25428    *
25429    *     .controller('CancelUpdateController', ['$scope', function($scope) {
25430    *       $scope.resetWithCancel = function(e) {
25431    *         if (e.keyCode == 27) {
25432    *           $scope.myForm.myInput1.$rollbackViewValue();
25433    *           $scope.myValue = '';
25434    *         }
25435    *       };
25436    *       $scope.resetWithoutCancel = function(e) {
25437    *         if (e.keyCode == 27) {
25438    *           $scope.myValue = '';
25439    *         }
25440    *       };
25441    *     }]);
25442    *   </file>
25443    *   <file name="index.html">
25444    *     <div ng-controller="CancelUpdateController">
25445    *       <p>Try typing something in each input.  See that the model only updates when you
25446    *          blur off the input.
25447    *        </p>
25448    *        <p>Now see what happens if you start typing then press the Escape key</p>
25449    *
25450    *       <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
25451    *         <p id="inputDescription1">With $rollbackViewValue()</p>
25452    *         <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
25453    *                ng-keydown="resetWithCancel($event)"><br/>
25454    *         myValue: "{{ myValue }}"
25455    *
25456    *         <p id="inputDescription2">Without $rollbackViewValue()</p>
25457    *         <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
25458    *                ng-keydown="resetWithoutCancel($event)"><br/>
25459    *         myValue: "{{ myValue }}"
25460    *       </form>
25461    *     </div>
25462    *   </file>
25463    * </example>
25464    */
25465   this.$rollbackViewValue = function() {
25466     $timeout.cancel(pendingDebounce);
25467     ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
25468     ctrl.$render();
25469   };
25470
25471   /**
25472    * @ngdoc method
25473    * @name ngModel.NgModelController#$validate
25474    *
25475    * @description
25476    * Runs each of the registered validators (first synchronous validators and then
25477    * asynchronous validators).
25478    * If the validity changes to invalid, the model will be set to `undefined`,
25479    * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
25480    * If the validity changes to valid, it will set the model to the last available valid
25481    * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
25482    */
25483   this.$validate = function() {
25484     // ignore $validate before model is initialized
25485     if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
25486       return;
25487     }
25488
25489     var viewValue = ctrl.$$lastCommittedViewValue;
25490     // Note: we use the $$rawModelValue as $modelValue might have been
25491     // set to undefined during a view -> model update that found validation
25492     // errors. We can't parse the view here, since that could change
25493     // the model although neither viewValue nor the model on the scope changed
25494     var modelValue = ctrl.$$rawModelValue;
25495
25496     var prevValid = ctrl.$valid;
25497     var prevModelValue = ctrl.$modelValue;
25498
25499     var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
25500
25501     ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
25502       // If there was no change in validity, don't update the model
25503       // This prevents changing an invalid modelValue to undefined
25504       if (!allowInvalid && prevValid !== allValid) {
25505         // Note: Don't check ctrl.$valid here, as we could have
25506         // external validators (e.g. calculated on the server),
25507         // that just call $setValidity and need the model value
25508         // to calculate their validity.
25509         ctrl.$modelValue = allValid ? modelValue : undefined;
25510
25511         if (ctrl.$modelValue !== prevModelValue) {
25512           ctrl.$$writeModelToScope();
25513         }
25514       }
25515     });
25516
25517   };
25518
25519   this.$$runValidators = function(modelValue, viewValue, doneCallback) {
25520     currentValidationRunId++;
25521     var localValidationRunId = currentValidationRunId;
25522
25523     // check parser error
25524     if (!processParseErrors()) {
25525       validationDone(false);
25526       return;
25527     }
25528     if (!processSyncValidators()) {
25529       validationDone(false);
25530       return;
25531     }
25532     processAsyncValidators();
25533
25534     function processParseErrors() {
25535       var errorKey = ctrl.$$parserName || 'parse';
25536       if (isUndefined(parserValid)) {
25537         setValidity(errorKey, null);
25538       } else {
25539         if (!parserValid) {
25540           forEach(ctrl.$validators, function(v, name) {
25541             setValidity(name, null);
25542           });
25543           forEach(ctrl.$asyncValidators, function(v, name) {
25544             setValidity(name, null);
25545           });
25546         }
25547         // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
25548         setValidity(errorKey, parserValid);
25549         return parserValid;
25550       }
25551       return true;
25552     }
25553
25554     function processSyncValidators() {
25555       var syncValidatorsValid = true;
25556       forEach(ctrl.$validators, function(validator, name) {
25557         var result = validator(modelValue, viewValue);
25558         syncValidatorsValid = syncValidatorsValid && result;
25559         setValidity(name, result);
25560       });
25561       if (!syncValidatorsValid) {
25562         forEach(ctrl.$asyncValidators, function(v, name) {
25563           setValidity(name, null);
25564         });
25565         return false;
25566       }
25567       return true;
25568     }
25569
25570     function processAsyncValidators() {
25571       var validatorPromises = [];
25572       var allValid = true;
25573       forEach(ctrl.$asyncValidators, function(validator, name) {
25574         var promise = validator(modelValue, viewValue);
25575         if (!isPromiseLike(promise)) {
25576           throw ngModelMinErr("$asyncValidators",
25577             "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
25578         }
25579         setValidity(name, undefined);
25580         validatorPromises.push(promise.then(function() {
25581           setValidity(name, true);
25582         }, function(error) {
25583           allValid = false;
25584           setValidity(name, false);
25585         }));
25586       });
25587       if (!validatorPromises.length) {
25588         validationDone(true);
25589       } else {
25590         $q.all(validatorPromises).then(function() {
25591           validationDone(allValid);
25592         }, noop);
25593       }
25594     }
25595
25596     function setValidity(name, isValid) {
25597       if (localValidationRunId === currentValidationRunId) {
25598         ctrl.$setValidity(name, isValid);
25599       }
25600     }
25601
25602     function validationDone(allValid) {
25603       if (localValidationRunId === currentValidationRunId) {
25604
25605         doneCallback(allValid);
25606       }
25607     }
25608   };
25609
25610   /**
25611    * @ngdoc method
25612    * @name ngModel.NgModelController#$commitViewValue
25613    *
25614    * @description
25615    * Commit a pending update to the `$modelValue`.
25616    *
25617    * Updates may be pending by a debounced event or because the input is waiting for a some future
25618    * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
25619    * usually handles calling this in response to input events.
25620    */
25621   this.$commitViewValue = function() {
25622     var viewValue = ctrl.$viewValue;
25623
25624     $timeout.cancel(pendingDebounce);
25625
25626     // If the view value has not changed then we should just exit, except in the case where there is
25627     // a native validator on the element. In this case the validation state may have changed even though
25628     // the viewValue has stayed empty.
25629     if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
25630       return;
25631     }
25632     ctrl.$$updateEmptyClasses(viewValue);
25633     ctrl.$$lastCommittedViewValue = viewValue;
25634
25635     // change to dirty
25636     if (ctrl.$pristine) {
25637       this.$setDirty();
25638     }
25639     this.$$parseAndValidate();
25640   };
25641
25642   this.$$parseAndValidate = function() {
25643     var viewValue = ctrl.$$lastCommittedViewValue;
25644     var modelValue = viewValue;
25645     parserValid = isUndefined(modelValue) ? undefined : true;
25646
25647     if (parserValid) {
25648       for (var i = 0; i < ctrl.$parsers.length; i++) {
25649         modelValue = ctrl.$parsers[i](modelValue);
25650         if (isUndefined(modelValue)) {
25651           parserValid = false;
25652           break;
25653         }
25654       }
25655     }
25656     if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
25657       // ctrl.$modelValue has not been touched yet...
25658       ctrl.$modelValue = ngModelGet($scope);
25659     }
25660     var prevModelValue = ctrl.$modelValue;
25661     var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
25662     ctrl.$$rawModelValue = modelValue;
25663
25664     if (allowInvalid) {
25665       ctrl.$modelValue = modelValue;
25666       writeToModelIfNeeded();
25667     }
25668
25669     // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
25670     // This can happen if e.g. $setViewValue is called from inside a parser
25671     ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
25672       if (!allowInvalid) {
25673         // Note: Don't check ctrl.$valid here, as we could have
25674         // external validators (e.g. calculated on the server),
25675         // that just call $setValidity and need the model value
25676         // to calculate their validity.
25677         ctrl.$modelValue = allValid ? modelValue : undefined;
25678         writeToModelIfNeeded();
25679       }
25680     });
25681
25682     function writeToModelIfNeeded() {
25683       if (ctrl.$modelValue !== prevModelValue) {
25684         ctrl.$$writeModelToScope();
25685       }
25686     }
25687   };
25688
25689   this.$$writeModelToScope = function() {
25690     ngModelSet($scope, ctrl.$modelValue);
25691     forEach(ctrl.$viewChangeListeners, function(listener) {
25692       try {
25693         listener();
25694       } catch (e) {
25695         $exceptionHandler(e);
25696       }
25697     });
25698   };
25699
25700   /**
25701    * @ngdoc method
25702    * @name ngModel.NgModelController#$setViewValue
25703    *
25704    * @description
25705    * Update the view value.
25706    *
25707    * This method should be called when a control wants to change the view value; typically,
25708    * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
25709    * directive calls it when the value of the input changes and {@link ng.directive:select select}
25710    * calls it when an option is selected.
25711    *
25712    * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
25713    * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
25714    * value sent directly for processing, finally to be applied to `$modelValue` and then the
25715    * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
25716    * in the `$viewChangeListeners` list, are called.
25717    *
25718    * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
25719    * and the `default` trigger is not listed, all those actions will remain pending until one of the
25720    * `updateOn` events is triggered on the DOM element.
25721    * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
25722    * directive is used with a custom debounce for this particular event.
25723    * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
25724    * is specified, once the timer runs out.
25725    *
25726    * When used with standard inputs, the view value will always be a string (which is in some cases
25727    * parsed into another type, such as a `Date` object for `input[date]`.)
25728    * However, custom controls might also pass objects to this method. In this case, we should make
25729    * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
25730    * perform a deep watch of objects, it only looks for a change of identity. If you only change
25731    * the property of the object then ngModel will not realise that the object has changed and
25732    * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
25733    * not change properties of the copy once it has been passed to `$setViewValue`.
25734    * Otherwise you may cause the model value on the scope to change incorrectly.
25735    *
25736    * <div class="alert alert-info">
25737    * In any case, the value passed to the method should always reflect the current value
25738    * of the control. For example, if you are calling `$setViewValue` for an input element,
25739    * you should pass the input DOM value. Otherwise, the control and the scope model become
25740    * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
25741    * the control's DOM value in any way. If we want to change the control's DOM value
25742    * programmatically, we should update the `ngModel` scope expression. Its new value will be
25743    * picked up by the model controller, which will run it through the `$formatters`, `$render` it
25744    * to update the DOM, and finally call `$validate` on it.
25745    * </div>
25746    *
25747    * @param {*} value value from the view.
25748    * @param {string} trigger Event that triggered the update.
25749    */
25750   this.$setViewValue = function(value, trigger) {
25751     ctrl.$viewValue = value;
25752     if (!ctrl.$options || ctrl.$options.updateOnDefault) {
25753       ctrl.$$debounceViewValueCommit(trigger);
25754     }
25755   };
25756
25757   this.$$debounceViewValueCommit = function(trigger) {
25758     var debounceDelay = 0,
25759         options = ctrl.$options,
25760         debounce;
25761
25762     if (options && isDefined(options.debounce)) {
25763       debounce = options.debounce;
25764       if (isNumber(debounce)) {
25765         debounceDelay = debounce;
25766       } else if (isNumber(debounce[trigger])) {
25767         debounceDelay = debounce[trigger];
25768       } else if (isNumber(debounce['default'])) {
25769         debounceDelay = debounce['default'];
25770       }
25771     }
25772
25773     $timeout.cancel(pendingDebounce);
25774     if (debounceDelay) {
25775       pendingDebounce = $timeout(function() {
25776         ctrl.$commitViewValue();
25777       }, debounceDelay);
25778     } else if ($rootScope.$$phase) {
25779       ctrl.$commitViewValue();
25780     } else {
25781       $scope.$apply(function() {
25782         ctrl.$commitViewValue();
25783       });
25784     }
25785   };
25786
25787   // model -> value
25788   // Note: we cannot use a normal scope.$watch as we want to detect the following:
25789   // 1. scope value is 'a'
25790   // 2. user enters 'b'
25791   // 3. ng-change kicks in and reverts scope value to 'a'
25792   //    -> scope value did not change since the last digest as
25793   //       ng-change executes in apply phase
25794   // 4. view should be changed back to 'a'
25795   $scope.$watch(function ngModelWatch() {
25796     var modelValue = ngModelGet($scope);
25797
25798     // if scope model value and ngModel value are out of sync
25799     // TODO(perf): why not move this to the action fn?
25800     if (modelValue !== ctrl.$modelValue &&
25801        // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
25802        (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
25803     ) {
25804       ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
25805       parserValid = undefined;
25806
25807       var formatters = ctrl.$formatters,
25808           idx = formatters.length;
25809
25810       var viewValue = modelValue;
25811       while (idx--) {
25812         viewValue = formatters[idx](viewValue);
25813       }
25814       if (ctrl.$viewValue !== viewValue) {
25815         ctrl.$$updateEmptyClasses(viewValue);
25816         ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
25817         ctrl.$render();
25818
25819         ctrl.$$runValidators(modelValue, viewValue, noop);
25820       }
25821     }
25822
25823     return modelValue;
25824   });
25825 }];
25826
25827
25828 /**
25829  * @ngdoc directive
25830  * @name ngModel
25831  *
25832  * @element input
25833  * @priority 1
25834  *
25835  * @description
25836  * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
25837  * property on the scope using {@link ngModel.NgModelController NgModelController},
25838  * which is created and exposed by this directive.
25839  *
25840  * `ngModel` is responsible for:
25841  *
25842  * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
25843  *   require.
25844  * - Providing validation behavior (i.e. required, number, email, url).
25845  * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
25846  * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
25847  *   `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
25848  * - Registering the control with its parent {@link ng.directive:form form}.
25849  *
25850  * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
25851  * current scope. If the property doesn't already exist on this scope, it will be created
25852  * implicitly and added to the scope.
25853  *
25854  * For best practices on using `ngModel`, see:
25855  *
25856  *  - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
25857  *
25858  * For basic examples, how to use `ngModel`, see:
25859  *
25860  *  - {@link ng.directive:input input}
25861  *    - {@link input[text] text}
25862  *    - {@link input[checkbox] checkbox}
25863  *    - {@link input[radio] radio}
25864  *    - {@link input[number] number}
25865  *    - {@link input[email] email}
25866  *    - {@link input[url] url}
25867  *    - {@link input[date] date}
25868  *    - {@link input[datetime-local] datetime-local}
25869  *    - {@link input[time] time}
25870  *    - {@link input[month] month}
25871  *    - {@link input[week] week}
25872  *  - {@link ng.directive:select select}
25873  *  - {@link ng.directive:textarea textarea}
25874  *
25875  * # CSS classes
25876  * The following CSS classes are added and removed on the associated input/select/textarea element
25877  * depending on the validity of the model.
25878  *
25879  *  - `ng-valid`: the model is valid
25880  *  - `ng-invalid`: the model is invalid
25881  *  - `ng-valid-[key]`: for each valid key added by `$setValidity`
25882  *  - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
25883  *  - `ng-pristine`: the control hasn't been interacted with yet
25884  *  - `ng-dirty`: the control has been interacted with
25885  *  - `ng-touched`: the control has been blurred
25886  *  - `ng-untouched`: the control hasn't been blurred
25887  *  - `ng-pending`: any `$asyncValidators` are unfulfilled
25888  *  - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
25889  *     by the {@link ngModel.NgModelController#$isEmpty} method
25890  *  - `ng-not-empty`: the view contains a non-empty value
25891  *
25892  * Keep in mind that ngAnimate can detect each of these classes when added and removed.
25893  *
25894  * ## Animation Hooks
25895  *
25896  * Animations within models are triggered when any of the associated CSS classes are added and removed
25897  * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
25898  * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
25899  * The animations that are triggered within ngModel are similar to how they work in ngClass and
25900  * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
25901  *
25902  * The following example shows a simple way to utilize CSS transitions to style an input element
25903  * that has been rendered as invalid after it has been validated:
25904  *
25905  * <pre>
25906  * //be sure to include ngAnimate as a module to hook into more
25907  * //advanced animations
25908  * .my-input {
25909  *   transition:0.5s linear all;
25910  *   background: white;
25911  * }
25912  * .my-input.ng-invalid {
25913  *   background: red;
25914  *   color:white;
25915  * }
25916  * </pre>
25917  *
25918  * @example
25919  * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
25920      <file name="index.html">
25921        <script>
25922         angular.module('inputExample', [])
25923           .controller('ExampleController', ['$scope', function($scope) {
25924             $scope.val = '1';
25925           }]);
25926        </script>
25927        <style>
25928          .my-input {
25929            transition:all linear 0.5s;
25930            background: transparent;
25931          }
25932          .my-input.ng-invalid {
25933            color:white;
25934            background: red;
25935          }
25936        </style>
25937        <p id="inputDescription">
25938         Update input to see transitions when valid/invalid.
25939         Integer is a valid value.
25940        </p>
25941        <form name="testForm" ng-controller="ExampleController">
25942          <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
25943                 aria-describedby="inputDescription" />
25944        </form>
25945      </file>
25946  * </example>
25947  *
25948  * ## Binding to a getter/setter
25949  *
25950  * Sometimes it's helpful to bind `ngModel` to a getter/setter function.  A getter/setter is a
25951  * function that returns a representation of the model when called with zero arguments, and sets
25952  * the internal state of a model when called with an argument. It's sometimes useful to use this
25953  * for models that have an internal representation that's different from what the model exposes
25954  * to the view.
25955  *
25956  * <div class="alert alert-success">
25957  * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
25958  * frequently than other parts of your code.
25959  * </div>
25960  *
25961  * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
25962  * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
25963  * a `<form>`, which will enable this behavior for all `<input>`s within it. See
25964  * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
25965  *
25966  * The following example shows how to use `ngModel` with a getter/setter:
25967  *
25968  * @example
25969  * <example name="ngModel-getter-setter" module="getterSetterExample">
25970      <file name="index.html">
25971        <div ng-controller="ExampleController">
25972          <form name="userForm">
25973            <label>Name:
25974              <input type="text" name="userName"
25975                     ng-model="user.name"
25976                     ng-model-options="{ getterSetter: true }" />
25977            </label>
25978          </form>
25979          <pre>user.name = <span ng-bind="user.name()"></span></pre>
25980        </div>
25981      </file>
25982      <file name="app.js">
25983        angular.module('getterSetterExample', [])
25984          .controller('ExampleController', ['$scope', function($scope) {
25985            var _name = 'Brian';
25986            $scope.user = {
25987              name: function(newName) {
25988               // Note that newName can be undefined for two reasons:
25989               // 1. Because it is called as a getter and thus called with no arguments
25990               // 2. Because the property should actually be set to undefined. This happens e.g. if the
25991               //    input is invalid
25992               return arguments.length ? (_name = newName) : _name;
25993              }
25994            };
25995          }]);
25996      </file>
25997  * </example>
25998  */
25999 var ngModelDirective = ['$rootScope', function($rootScope) {
26000   return {
26001     restrict: 'A',
26002     require: ['ngModel', '^?form', '^?ngModelOptions'],
26003     controller: NgModelController,
26004     // Prelink needs to run before any input directive
26005     // so that we can set the NgModelOptions in NgModelController
26006     // before anyone else uses it.
26007     priority: 1,
26008     compile: function ngModelCompile(element) {
26009       // Setup initial state of the control
26010       element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
26011
26012       return {
26013         pre: function ngModelPreLink(scope, element, attr, ctrls) {
26014           var modelCtrl = ctrls[0],
26015               formCtrl = ctrls[1] || modelCtrl.$$parentForm;
26016
26017           modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
26018
26019           // notify others, especially parent forms
26020           formCtrl.$addControl(modelCtrl);
26021
26022           attr.$observe('name', function(newValue) {
26023             if (modelCtrl.$name !== newValue) {
26024               modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
26025             }
26026           });
26027
26028           scope.$on('$destroy', function() {
26029             modelCtrl.$$parentForm.$removeControl(modelCtrl);
26030           });
26031         },
26032         post: function ngModelPostLink(scope, element, attr, ctrls) {
26033           var modelCtrl = ctrls[0];
26034           if (modelCtrl.$options && modelCtrl.$options.updateOn) {
26035             element.on(modelCtrl.$options.updateOn, function(ev) {
26036               modelCtrl.$$debounceViewValueCommit(ev && ev.type);
26037             });
26038           }
26039
26040           element.on('blur', function(ev) {
26041             if (modelCtrl.$touched) return;
26042
26043             if ($rootScope.$$phase) {
26044               scope.$evalAsync(modelCtrl.$setTouched);
26045             } else {
26046               scope.$apply(modelCtrl.$setTouched);
26047             }
26048           });
26049         }
26050       };
26051     }
26052   };
26053 }];
26054
26055 var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
26056
26057 /**
26058  * @ngdoc directive
26059  * @name ngModelOptions
26060  *
26061  * @description
26062  * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
26063  * events that will trigger a model update and/or a debouncing delay so that the actual update only
26064  * takes place when a timer expires; this timer will be reset after another change takes place.
26065  *
26066  * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
26067  * be different from the value in the actual model. This means that if you update the model you
26068  * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
26069  * order to make sure it is synchronized with the model and that any debounced action is canceled.
26070  *
26071  * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
26072  * method is by making sure the input is placed inside a form that has a `name` attribute. This is
26073  * important because `form` controllers are published to the related scope under the name in their
26074  * `name` attribute.
26075  *
26076  * Any pending changes will take place immediately when an enclosing form is submitted via the
26077  * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
26078  * to have access to the updated model.
26079  *
26080  * `ngModelOptions` has an effect on the element it's declared on and its descendants.
26081  *
26082  * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
26083  *   - `updateOn`: string specifying which event should the input be bound to. You can set several
26084  *     events using an space delimited list. There is a special event called `default` that
26085  *     matches the default events belonging of the control.
26086  *   - `debounce`: integer value which contains the debounce model update value in milliseconds. A
26087  *     value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
26088  *     custom value for each event. For example:
26089  *     `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
26090  *   - `allowInvalid`: boolean value which indicates that the model can be set with values that did
26091  *     not validate correctly instead of the default behavior of setting the model to undefined.
26092  *   - `getterSetter`: boolean value which determines whether or not to treat functions bound to
26093        `ngModel` as getters/setters.
26094  *   - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
26095  *     `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
26096  *     continental US time zone abbreviations, but for general use, use a time zone offset, for
26097  *     example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
26098  *     If not specified, the timezone of the browser will be used.
26099  *
26100  * @example
26101
26102   The following example shows how to override immediate updates. Changes on the inputs within the
26103   form will update the model only when the control loses focus (blur event). If `escape` key is
26104   pressed while the input field is focused, the value is reset to the value in the current model.
26105
26106   <example name="ngModelOptions-directive-blur" module="optionsExample">
26107     <file name="index.html">
26108       <div ng-controller="ExampleController">
26109         <form name="userForm">
26110           <label>Name:
26111             <input type="text" name="userName"
26112                    ng-model="user.name"
26113                    ng-model-options="{ updateOn: 'blur' }"
26114                    ng-keyup="cancel($event)" />
26115           </label><br />
26116           <label>Other data:
26117             <input type="text" ng-model="user.data" />
26118           </label><br />
26119         </form>
26120         <pre>user.name = <span ng-bind="user.name"></span></pre>
26121         <pre>user.data = <span ng-bind="user.data"></span></pre>
26122       </div>
26123     </file>
26124     <file name="app.js">
26125       angular.module('optionsExample', [])
26126         .controller('ExampleController', ['$scope', function($scope) {
26127           $scope.user = { name: 'John', data: '' };
26128
26129           $scope.cancel = function(e) {
26130             if (e.keyCode == 27) {
26131               $scope.userForm.userName.$rollbackViewValue();
26132             }
26133           };
26134         }]);
26135     </file>
26136     <file name="protractor.js" type="protractor">
26137       var model = element(by.binding('user.name'));
26138       var input = element(by.model('user.name'));
26139       var other = element(by.model('user.data'));
26140
26141       it('should allow custom events', function() {
26142         input.sendKeys(' Doe');
26143         input.click();
26144         expect(model.getText()).toEqual('John');
26145         other.click();
26146         expect(model.getText()).toEqual('John Doe');
26147       });
26148
26149       it('should $rollbackViewValue when model changes', function() {
26150         input.sendKeys(' Doe');
26151         expect(input.getAttribute('value')).toEqual('John Doe');
26152         input.sendKeys(protractor.Key.ESCAPE);
26153         expect(input.getAttribute('value')).toEqual('John');
26154         other.click();
26155         expect(model.getText()).toEqual('John');
26156       });
26157     </file>
26158   </example>
26159
26160   This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
26161   If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
26162
26163   <example name="ngModelOptions-directive-debounce" module="optionsExample">
26164     <file name="index.html">
26165       <div ng-controller="ExampleController">
26166         <form name="userForm">
26167           <label>Name:
26168             <input type="text" name="userName"
26169                    ng-model="user.name"
26170                    ng-model-options="{ debounce: 1000 }" />
26171           </label>
26172           <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
26173           <br />
26174         </form>
26175         <pre>user.name = <span ng-bind="user.name"></span></pre>
26176       </div>
26177     </file>
26178     <file name="app.js">
26179       angular.module('optionsExample', [])
26180         .controller('ExampleController', ['$scope', function($scope) {
26181           $scope.user = { name: 'Igor' };
26182         }]);
26183     </file>
26184   </example>
26185
26186   This one shows how to bind to getter/setters:
26187
26188   <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
26189     <file name="index.html">
26190       <div ng-controller="ExampleController">
26191         <form name="userForm">
26192           <label>Name:
26193             <input type="text" name="userName"
26194                    ng-model="user.name"
26195                    ng-model-options="{ getterSetter: true }" />
26196           </label>
26197         </form>
26198         <pre>user.name = <span ng-bind="user.name()"></span></pre>
26199       </div>
26200     </file>
26201     <file name="app.js">
26202       angular.module('getterSetterExample', [])
26203         .controller('ExampleController', ['$scope', function($scope) {
26204           var _name = 'Brian';
26205           $scope.user = {
26206             name: function(newName) {
26207               // Note that newName can be undefined for two reasons:
26208               // 1. Because it is called as a getter and thus called with no arguments
26209               // 2. Because the property should actually be set to undefined. This happens e.g. if the
26210               //    input is invalid
26211               return arguments.length ? (_name = newName) : _name;
26212             }
26213           };
26214         }]);
26215     </file>
26216   </example>
26217  */
26218 var ngModelOptionsDirective = function() {
26219   return {
26220     restrict: 'A',
26221     controller: ['$scope', '$attrs', function($scope, $attrs) {
26222       var that = this;
26223       this.$options = copy($scope.$eval($attrs.ngModelOptions));
26224       // Allow adding/overriding bound events
26225       if (isDefined(this.$options.updateOn)) {
26226         this.$options.updateOnDefault = false;
26227         // extract "default" pseudo-event from list of events that can trigger a model update
26228         this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
26229           that.$options.updateOnDefault = true;
26230           return ' ';
26231         }));
26232       } else {
26233         this.$options.updateOnDefault = true;
26234       }
26235     }]
26236   };
26237 };
26238
26239
26240
26241 // helper methods
26242 function addSetValidityMethod(context) {
26243   var ctrl = context.ctrl,
26244       $element = context.$element,
26245       classCache = {},
26246       set = context.set,
26247       unset = context.unset,
26248       $animate = context.$animate;
26249
26250   classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
26251
26252   ctrl.$setValidity = setValidity;
26253
26254   function setValidity(validationErrorKey, state, controller) {
26255     if (isUndefined(state)) {
26256       createAndSet('$pending', validationErrorKey, controller);
26257     } else {
26258       unsetAndCleanup('$pending', validationErrorKey, controller);
26259     }
26260     if (!isBoolean(state)) {
26261       unset(ctrl.$error, validationErrorKey, controller);
26262       unset(ctrl.$$success, validationErrorKey, controller);
26263     } else {
26264       if (state) {
26265         unset(ctrl.$error, validationErrorKey, controller);
26266         set(ctrl.$$success, validationErrorKey, controller);
26267       } else {
26268         set(ctrl.$error, validationErrorKey, controller);
26269         unset(ctrl.$$success, validationErrorKey, controller);
26270       }
26271     }
26272     if (ctrl.$pending) {
26273       cachedToggleClass(PENDING_CLASS, true);
26274       ctrl.$valid = ctrl.$invalid = undefined;
26275       toggleValidationCss('', null);
26276     } else {
26277       cachedToggleClass(PENDING_CLASS, false);
26278       ctrl.$valid = isObjectEmpty(ctrl.$error);
26279       ctrl.$invalid = !ctrl.$valid;
26280       toggleValidationCss('', ctrl.$valid);
26281     }
26282
26283     // re-read the state as the set/unset methods could have
26284     // combined state in ctrl.$error[validationError] (used for forms),
26285     // where setting/unsetting only increments/decrements the value,
26286     // and does not replace it.
26287     var combinedState;
26288     if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
26289       combinedState = undefined;
26290     } else if (ctrl.$error[validationErrorKey]) {
26291       combinedState = false;
26292     } else if (ctrl.$$success[validationErrorKey]) {
26293       combinedState = true;
26294     } else {
26295       combinedState = null;
26296     }
26297
26298     toggleValidationCss(validationErrorKey, combinedState);
26299     ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
26300   }
26301
26302   function createAndSet(name, value, controller) {
26303     if (!ctrl[name]) {
26304       ctrl[name] = {};
26305     }
26306     set(ctrl[name], value, controller);
26307   }
26308
26309   function unsetAndCleanup(name, value, controller) {
26310     if (ctrl[name]) {
26311       unset(ctrl[name], value, controller);
26312     }
26313     if (isObjectEmpty(ctrl[name])) {
26314       ctrl[name] = undefined;
26315     }
26316   }
26317
26318   function cachedToggleClass(className, switchValue) {
26319     if (switchValue && !classCache[className]) {
26320       $animate.addClass($element, className);
26321       classCache[className] = true;
26322     } else if (!switchValue && classCache[className]) {
26323       $animate.removeClass($element, className);
26324       classCache[className] = false;
26325     }
26326   }
26327
26328   function toggleValidationCss(validationErrorKey, isValid) {
26329     validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
26330
26331     cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
26332     cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
26333   }
26334 }
26335
26336 function isObjectEmpty(obj) {
26337   if (obj) {
26338     for (var prop in obj) {
26339       if (obj.hasOwnProperty(prop)) {
26340         return false;
26341       }
26342     }
26343   }
26344   return true;
26345 }
26346
26347 /**
26348  * @ngdoc directive
26349  * @name ngNonBindable
26350  * @restrict AC
26351  * @priority 1000
26352  *
26353  * @description
26354  * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
26355  * DOM element. This is useful if the element contains what appears to be Angular directives and
26356  * bindings but which should be ignored by Angular. This could be the case if you have a site that
26357  * displays snippets of code, for instance.
26358  *
26359  * @element ANY
26360  *
26361  * @example
26362  * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
26363  * but the one wrapped in `ngNonBindable` is left alone.
26364  *
26365  * @example
26366     <example>
26367       <file name="index.html">
26368         <div>Normal: {{1 + 2}}</div>
26369         <div ng-non-bindable>Ignored: {{1 + 2}}</div>
26370       </file>
26371       <file name="protractor.js" type="protractor">
26372        it('should check ng-non-bindable', function() {
26373          expect(element(by.binding('1 + 2')).getText()).toContain('3');
26374          expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
26375        });
26376       </file>
26377     </example>
26378  */
26379 var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
26380
26381 /* global jqLiteRemove */
26382
26383 var ngOptionsMinErr = minErr('ngOptions');
26384
26385 /**
26386  * @ngdoc directive
26387  * @name ngOptions
26388  * @restrict A
26389  *
26390  * @description
26391  *
26392  * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
26393  * elements for the `<select>` element using the array or object obtained by evaluating the
26394  * `ngOptions` comprehension expression.
26395  *
26396  * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
26397  * similar result. However, `ngOptions` provides some benefits such as reducing memory and
26398  * increasing speed by not creating a new scope for each repeated instance, as well as providing
26399  * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
26400  * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
26401  *  to a non-string value. This is because an option element can only be bound to string values at
26402  * present.
26403  *
26404  * When an item in the `<select>` menu is selected, the array element or object property
26405  * represented by the selected option will be bound to the model identified by the `ngModel`
26406  * directive.
26407  *
26408  * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
26409  * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
26410  * option. See example below for demonstration.
26411  *
26412  * ## Complex Models (objects or collections)
26413  *
26414  * By default, `ngModel` watches the model by reference, not value. This is important to know when
26415  * binding the select to a model that is an object or a collection.
26416  *
26417  * One issue occurs if you want to preselect an option. For example, if you set
26418  * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
26419  * because the objects are not identical. So by default, you should always reference the item in your collection
26420  * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
26421  *
26422  * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
26423  * of the item not by reference, but by the result of the `track by` expression. For example, if your
26424  * collection items have an id property, you would `track by item.id`.
26425  *
26426  * A different issue with objects or collections is that ngModel won't detect if an object property or
26427  * a collection item changes. For that reason, `ngOptions` additionally watches the model using
26428  * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
26429  * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
26430  * has not changed identity, but only a property on the object or an item in the collection changes.
26431  *
26432  * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
26433  * if the model is an array). This means that changing a property deeper than the first level inside the
26434  * object/collection will not trigger a re-rendering.
26435  *
26436  * ## `select` **`as`**
26437  *
26438  * Using `select` **`as`** will bind the result of the `select` expression to the model, but
26439  * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
26440  * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
26441  * is used, the result of that expression will be set as the value of the `option` and `select` elements.
26442  *
26443  *
26444  * ### `select` **`as`** and **`track by`**
26445  *
26446  * <div class="alert alert-warning">
26447  * Be careful when using `select` **`as`** and **`track by`** in the same expression.
26448  * </div>
26449  *
26450  * Given this array of items on the $scope:
26451  *
26452  * ```js
26453  * $scope.items = [{
26454  *   id: 1,
26455  *   label: 'aLabel',
26456  *   subItem: { name: 'aSubItem' }
26457  * }, {
26458  *   id: 2,
26459  *   label: 'bLabel',
26460  *   subItem: { name: 'bSubItem' }
26461  * }];
26462  * ```
26463  *
26464  * This will work:
26465  *
26466  * ```html
26467  * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
26468  * ```
26469  * ```js
26470  * $scope.selected = $scope.items[0];
26471  * ```
26472  *
26473  * but this will not work:
26474  *
26475  * ```html
26476  * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
26477  * ```
26478  * ```js
26479  * $scope.selected = $scope.items[0].subItem;
26480  * ```
26481  *
26482  * In both examples, the **`track by`** expression is applied successfully to each `item` in the
26483  * `items` array. Because the selected option has been set programmatically in the controller, the
26484  * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
26485  * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
26486  * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
26487  * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
26488  * is not matched against any `<option>` and the `<select>` appears as having no selected value.
26489  *
26490  *
26491  * @param {string} ngModel Assignable angular expression to data-bind to.
26492  * @param {string=} name Property name of the form under which the control is published.
26493  * @param {string=} required The control is considered valid only if value is entered.
26494  * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
26495  *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
26496  *    `required` when you want to data-bind to the `required` attribute.
26497  * @param {comprehension_expression=} ngOptions in one of the following forms:
26498  *
26499  *   * for array data sources:
26500  *     * `label` **`for`** `value` **`in`** `array`
26501  *     * `select` **`as`** `label` **`for`** `value` **`in`** `array`
26502  *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
26503  *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
26504  *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
26505  *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
26506  *     * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
26507  *        (for including a filter with `track by`)
26508  *   * for object data sources:
26509  *     * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
26510  *     * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
26511  *     * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
26512  *     * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
26513  *     * `select` **`as`** `label` **`group by`** `group`
26514  *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`
26515  *     * `select` **`as`** `label` **`disable when`** `disable`
26516  *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`
26517  *
26518  * Where:
26519  *
26520  *   * `array` / `object`: an expression which evaluates to an array / object to iterate over.
26521  *   * `value`: local variable which will refer to each item in the `array` or each property value
26522  *      of `object` during iteration.
26523  *   * `key`: local variable which will refer to a property name in `object` during iteration.
26524  *   * `label`: The result of this expression will be the label for `<option>` element. The
26525  *     `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
26526  *   * `select`: The result of this expression will be bound to the model of the parent `<select>`
26527  *      element. If not specified, `select` expression will default to `value`.
26528  *   * `group`: The result of this expression will be used to group options using the `<optgroup>`
26529  *      DOM element.
26530  *   * `disable`: The result of this expression will be used to disable the rendered `<option>`
26531  *      element. Return `true` to disable.
26532  *   * `trackexpr`: Used when working with an array of objects. The result of this expression will be
26533  *      used to identify the objects in the array. The `trackexpr` will most likely refer to the
26534  *     `value` variable (e.g. `value.propertyName`). With this the selection is preserved
26535  *      even when the options are recreated (e.g. reloaded from the server).
26536  *
26537  * @example
26538     <example module="selectExample">
26539       <file name="index.html">
26540         <script>
26541         angular.module('selectExample', [])
26542           .controller('ExampleController', ['$scope', function($scope) {
26543             $scope.colors = [
26544               {name:'black', shade:'dark'},
26545               {name:'white', shade:'light', notAnOption: true},
26546               {name:'red', shade:'dark'},
26547               {name:'blue', shade:'dark', notAnOption: true},
26548               {name:'yellow', shade:'light', notAnOption: false}
26549             ];
26550             $scope.myColor = $scope.colors[2]; // red
26551           }]);
26552         </script>
26553         <div ng-controller="ExampleController">
26554           <ul>
26555             <li ng-repeat="color in colors">
26556               <label>Name: <input ng-model="color.name"></label>
26557               <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
26558               <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
26559             </li>
26560             <li>
26561               <button ng-click="colors.push({})">add</button>
26562             </li>
26563           </ul>
26564           <hr/>
26565           <label>Color (null not allowed):
26566             <select ng-model="myColor" ng-options="color.name for color in colors"></select>
26567           </label><br/>
26568           <label>Color (null allowed):
26569           <span  class="nullable">
26570             <select ng-model="myColor" ng-options="color.name for color in colors">
26571               <option value="">-- choose color --</option>
26572             </select>
26573           </span></label><br/>
26574
26575           <label>Color grouped by shade:
26576             <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
26577             </select>
26578           </label><br/>
26579
26580           <label>Color grouped by shade, with some disabled:
26581             <select ng-model="myColor"
26582                   ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
26583             </select>
26584           </label><br/>
26585
26586
26587
26588           Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
26589           <br/>
26590           <hr/>
26591           Currently selected: {{ {selected_color:myColor} }}
26592           <div style="border:solid 1px black; height:20px"
26593                ng-style="{'background-color':myColor.name}">
26594           </div>
26595         </div>
26596       </file>
26597       <file name="protractor.js" type="protractor">
26598          it('should check ng-options', function() {
26599            expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
26600            element.all(by.model('myColor')).first().click();
26601            element.all(by.css('select[ng-model="myColor"] option')).first().click();
26602            expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
26603            element(by.css('.nullable select[ng-model="myColor"]')).click();
26604            element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
26605            expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
26606          });
26607       </file>
26608     </example>
26609  */
26610
26611 // jshint maxlen: false
26612 //                     //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
26613 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]+?))?$/;
26614                         // 1: value expression (valueFn)
26615                         // 2: label expression (displayFn)
26616                         // 3: group by expression (groupByFn)
26617                         // 4: disable when expression (disableWhenFn)
26618                         // 5: array item variable name
26619                         // 6: object item key variable name
26620                         // 7: object item value variable name
26621                         // 8: collection expression
26622                         // 9: track by expression
26623 // jshint maxlen: 100
26624
26625
26626 var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
26627
26628   function parseOptionsExpression(optionsExp, selectElement, scope) {
26629
26630     var match = optionsExp.match(NG_OPTIONS_REGEXP);
26631     if (!(match)) {
26632       throw ngOptionsMinErr('iexp',
26633         "Expected expression in form of " +
26634         "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
26635         " but got '{0}'. Element: {1}",
26636         optionsExp, startingTag(selectElement));
26637     }
26638
26639     // Extract the parts from the ngOptions expression
26640
26641     // The variable name for the value of the item in the collection
26642     var valueName = match[5] || match[7];
26643     // The variable name for the key of the item in the collection
26644     var keyName = match[6];
26645
26646     // An expression that generates the viewValue for an option if there is a label expression
26647     var selectAs = / as /.test(match[0]) && match[1];
26648     // An expression that is used to track the id of each object in the options collection
26649     var trackBy = match[9];
26650     // An expression that generates the viewValue for an option if there is no label expression
26651     var valueFn = $parse(match[2] ? match[1] : valueName);
26652     var selectAsFn = selectAs && $parse(selectAs);
26653     var viewValueFn = selectAsFn || valueFn;
26654     var trackByFn = trackBy && $parse(trackBy);
26655
26656     // Get the value by which we are going to track the option
26657     // if we have a trackFn then use that (passing scope and locals)
26658     // otherwise just hash the given viewValue
26659     var getTrackByValueFn = trackBy ?
26660                               function(value, locals) { return trackByFn(scope, locals); } :
26661                               function getHashOfValue(value) { return hashKey(value); };
26662     var getTrackByValue = function(value, key) {
26663       return getTrackByValueFn(value, getLocals(value, key));
26664     };
26665
26666     var displayFn = $parse(match[2] || match[1]);
26667     var groupByFn = $parse(match[3] || '');
26668     var disableWhenFn = $parse(match[4] || '');
26669     var valuesFn = $parse(match[8]);
26670
26671     var locals = {};
26672     var getLocals = keyName ? function(value, key) {
26673       locals[keyName] = key;
26674       locals[valueName] = value;
26675       return locals;
26676     } : function(value) {
26677       locals[valueName] = value;
26678       return locals;
26679     };
26680
26681
26682     function Option(selectValue, viewValue, label, group, disabled) {
26683       this.selectValue = selectValue;
26684       this.viewValue = viewValue;
26685       this.label = label;
26686       this.group = group;
26687       this.disabled = disabled;
26688     }
26689
26690     function getOptionValuesKeys(optionValues) {
26691       var optionValuesKeys;
26692
26693       if (!keyName && isArrayLike(optionValues)) {
26694         optionValuesKeys = optionValues;
26695       } else {
26696         // if object, extract keys, in enumeration order, unsorted
26697         optionValuesKeys = [];
26698         for (var itemKey in optionValues) {
26699           if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
26700             optionValuesKeys.push(itemKey);
26701           }
26702         }
26703       }
26704       return optionValuesKeys;
26705     }
26706
26707     return {
26708       trackBy: trackBy,
26709       getTrackByValue: getTrackByValue,
26710       getWatchables: $parse(valuesFn, function(optionValues) {
26711         // Create a collection of things that we would like to watch (watchedArray)
26712         // so that they can all be watched using a single $watchCollection
26713         // that only runs the handler once if anything changes
26714         var watchedArray = [];
26715         optionValues = optionValues || [];
26716
26717         var optionValuesKeys = getOptionValuesKeys(optionValues);
26718         var optionValuesLength = optionValuesKeys.length;
26719         for (var index = 0; index < optionValuesLength; index++) {
26720           var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
26721           var value = optionValues[key];
26722
26723           var locals = getLocals(optionValues[key], key);
26724           var selectValue = getTrackByValueFn(optionValues[key], locals);
26725           watchedArray.push(selectValue);
26726
26727           // Only need to watch the displayFn if there is a specific label expression
26728           if (match[2] || match[1]) {
26729             var label = displayFn(scope, locals);
26730             watchedArray.push(label);
26731           }
26732
26733           // Only need to watch the disableWhenFn if there is a specific disable expression
26734           if (match[4]) {
26735             var disableWhen = disableWhenFn(scope, locals);
26736             watchedArray.push(disableWhen);
26737           }
26738         }
26739         return watchedArray;
26740       }),
26741
26742       getOptions: function() {
26743
26744         var optionItems = [];
26745         var selectValueMap = {};
26746
26747         // The option values were already computed in the `getWatchables` fn,
26748         // which must have been called to trigger `getOptions`
26749         var optionValues = valuesFn(scope) || [];
26750         var optionValuesKeys = getOptionValuesKeys(optionValues);
26751         var optionValuesLength = optionValuesKeys.length;
26752
26753         for (var index = 0; index < optionValuesLength; index++) {
26754           var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
26755           var value = optionValues[key];
26756           var locals = getLocals(value, key);
26757           var viewValue = viewValueFn(scope, locals);
26758           var selectValue = getTrackByValueFn(viewValue, locals);
26759           var label = displayFn(scope, locals);
26760           var group = groupByFn(scope, locals);
26761           var disabled = disableWhenFn(scope, locals);
26762           var optionItem = new Option(selectValue, viewValue, label, group, disabled);
26763
26764           optionItems.push(optionItem);
26765           selectValueMap[selectValue] = optionItem;
26766         }
26767
26768         return {
26769           items: optionItems,
26770           selectValueMap: selectValueMap,
26771           getOptionFromViewValue: function(value) {
26772             return selectValueMap[getTrackByValue(value)];
26773           },
26774           getViewValueFromOption: function(option) {
26775             // If the viewValue could be an object that may be mutated by the application,
26776             // we need to make a copy and not return the reference to the value on the option.
26777             return trackBy ? angular.copy(option.viewValue) : option.viewValue;
26778           }
26779         };
26780       }
26781     };
26782   }
26783
26784
26785   // we can't just jqLite('<option>') since jqLite is not smart enough
26786   // to create it in <select> and IE barfs otherwise.
26787   var optionTemplate = document.createElement('option'),
26788       optGroupTemplate = document.createElement('optgroup');
26789
26790     function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
26791
26792       var selectCtrl = ctrls[0];
26793       var ngModelCtrl = ctrls[1];
26794       var multiple = attr.multiple;
26795
26796       // The emptyOption allows the application developer to provide their own custom "empty"
26797       // option when the viewValue does not match any of the option values.
26798       var emptyOption;
26799       for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
26800         if (children[i].value === '') {
26801           emptyOption = children.eq(i);
26802           break;
26803         }
26804       }
26805
26806       var providedEmptyOption = !!emptyOption;
26807
26808       var unknownOption = jqLite(optionTemplate.cloneNode(false));
26809       unknownOption.val('?');
26810
26811       var options;
26812       var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
26813
26814
26815       var renderEmptyOption = function() {
26816         if (!providedEmptyOption) {
26817           selectElement.prepend(emptyOption);
26818         }
26819         selectElement.val('');
26820         emptyOption.prop('selected', true); // needed for IE
26821         emptyOption.attr('selected', true);
26822       };
26823
26824       var removeEmptyOption = function() {
26825         if (!providedEmptyOption) {
26826           emptyOption.remove();
26827         }
26828       };
26829
26830
26831       var renderUnknownOption = function() {
26832         selectElement.prepend(unknownOption);
26833         selectElement.val('?');
26834         unknownOption.prop('selected', true); // needed for IE
26835         unknownOption.attr('selected', true);
26836       };
26837
26838       var removeUnknownOption = function() {
26839         unknownOption.remove();
26840       };
26841
26842       // Update the controller methods for multiple selectable options
26843       if (!multiple) {
26844
26845         selectCtrl.writeValue = function writeNgOptionsValue(value) {
26846           var option = options.getOptionFromViewValue(value);
26847
26848           if (option && !option.disabled) {
26849             if (selectElement[0].value !== option.selectValue) {
26850               removeUnknownOption();
26851               removeEmptyOption();
26852
26853               selectElement[0].value = option.selectValue;
26854               option.element.selected = true;
26855               option.element.setAttribute('selected', 'selected');
26856             }
26857           } else {
26858             if (value === null || providedEmptyOption) {
26859               removeUnknownOption();
26860               renderEmptyOption();
26861             } else {
26862               removeEmptyOption();
26863               renderUnknownOption();
26864             }
26865           }
26866         };
26867
26868         selectCtrl.readValue = function readNgOptionsValue() {
26869
26870           var selectedOption = options.selectValueMap[selectElement.val()];
26871
26872           if (selectedOption && !selectedOption.disabled) {
26873             removeEmptyOption();
26874             removeUnknownOption();
26875             return options.getViewValueFromOption(selectedOption);
26876           }
26877           return null;
26878         };
26879
26880         // If we are using `track by` then we must watch the tracked value on the model
26881         // since ngModel only watches for object identity change
26882         if (ngOptions.trackBy) {
26883           scope.$watch(
26884             function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
26885             function() { ngModelCtrl.$render(); }
26886           );
26887         }
26888
26889       } else {
26890
26891         ngModelCtrl.$isEmpty = function(value) {
26892           return !value || value.length === 0;
26893         };
26894
26895
26896         selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
26897           options.items.forEach(function(option) {
26898             option.element.selected = false;
26899           });
26900
26901           if (value) {
26902             value.forEach(function(item) {
26903               var option = options.getOptionFromViewValue(item);
26904               if (option && !option.disabled) option.element.selected = true;
26905             });
26906           }
26907         };
26908
26909
26910         selectCtrl.readValue = function readNgOptionsMultiple() {
26911           var selectedValues = selectElement.val() || [],
26912               selections = [];
26913
26914           forEach(selectedValues, function(value) {
26915             var option = options.selectValueMap[value];
26916             if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
26917           });
26918
26919           return selections;
26920         };
26921
26922         // If we are using `track by` then we must watch these tracked values on the model
26923         // since ngModel only watches for object identity change
26924         if (ngOptions.trackBy) {
26925
26926           scope.$watchCollection(function() {
26927             if (isArray(ngModelCtrl.$viewValue)) {
26928               return ngModelCtrl.$viewValue.map(function(value) {
26929                 return ngOptions.getTrackByValue(value);
26930               });
26931             }
26932           }, function() {
26933             ngModelCtrl.$render();
26934           });
26935
26936         }
26937       }
26938
26939
26940       if (providedEmptyOption) {
26941
26942         // we need to remove it before calling selectElement.empty() because otherwise IE will
26943         // remove the label from the element. wtf?
26944         emptyOption.remove();
26945
26946         // compile the element since there might be bindings in it
26947         $compile(emptyOption)(scope);
26948
26949         // remove the class, which is added automatically because we recompile the element and it
26950         // becomes the compilation root
26951         emptyOption.removeClass('ng-scope');
26952       } else {
26953         emptyOption = jqLite(optionTemplate.cloneNode(false));
26954       }
26955
26956       // We need to do this here to ensure that the options object is defined
26957       // when we first hit it in writeNgOptionsValue
26958       updateOptions();
26959
26960       // We will re-render the option elements if the option values or labels change
26961       scope.$watchCollection(ngOptions.getWatchables, updateOptions);
26962
26963       // ------------------------------------------------------------------ //
26964
26965
26966       function updateOptionElement(option, element) {
26967         option.element = element;
26968         element.disabled = option.disabled;
26969         // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
26970         // selects in certain circumstances when multiple selects are next to each other and display
26971         // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
26972         // See https://github.com/angular/angular.js/issues/11314 for more info.
26973         // This is unfortunately untestable with unit / e2e tests
26974         if (option.label !== element.label) {
26975           element.label = option.label;
26976           element.textContent = option.label;
26977         }
26978         if (option.value !== element.value) element.value = option.selectValue;
26979       }
26980
26981       function addOrReuseElement(parent, current, type, templateElement) {
26982         var element;
26983         // Check whether we can reuse the next element
26984         if (current && lowercase(current.nodeName) === type) {
26985           // The next element is the right type so reuse it
26986           element = current;
26987         } else {
26988           // The next element is not the right type so create a new one
26989           element = templateElement.cloneNode(false);
26990           if (!current) {
26991             // There are no more elements so just append it to the select
26992             parent.appendChild(element);
26993           } else {
26994             // The next element is not a group so insert the new one
26995             parent.insertBefore(element, current);
26996           }
26997         }
26998         return element;
26999       }
27000
27001
27002       function removeExcessElements(current) {
27003         var next;
27004         while (current) {
27005           next = current.nextSibling;
27006           jqLiteRemove(current);
27007           current = next;
27008         }
27009       }
27010
27011
27012       function skipEmptyAndUnknownOptions(current) {
27013         var emptyOption_ = emptyOption && emptyOption[0];
27014         var unknownOption_ = unknownOption && unknownOption[0];
27015
27016         // We cannot rely on the extracted empty option being the same as the compiled empty option,
27017         // because the compiled empty option might have been replaced by a comment because
27018         // it had an "element" transclusion directive on it (such as ngIf)
27019         if (emptyOption_ || unknownOption_) {
27020           while (current &&
27021                 (current === emptyOption_ ||
27022                 current === unknownOption_ ||
27023                 current.nodeType === NODE_TYPE_COMMENT ||
27024                 current.value === '')) {
27025             current = current.nextSibling;
27026           }
27027         }
27028         return current;
27029       }
27030
27031
27032       function updateOptions() {
27033
27034         var previousValue = options && selectCtrl.readValue();
27035
27036         options = ngOptions.getOptions();
27037
27038         var groupMap = {};
27039         var currentElement = selectElement[0].firstChild;
27040
27041         // Ensure that the empty option is always there if it was explicitly provided
27042         if (providedEmptyOption) {
27043           selectElement.prepend(emptyOption);
27044         }
27045
27046         currentElement = skipEmptyAndUnknownOptions(currentElement);
27047
27048         options.items.forEach(function updateOption(option) {
27049           var group;
27050           var groupElement;
27051           var optionElement;
27052
27053           if (isDefined(option.group)) {
27054
27055             // This option is to live in a group
27056             // See if we have already created this group
27057             group = groupMap[option.group];
27058
27059             if (!group) {
27060
27061               // We have not already created this group
27062               groupElement = addOrReuseElement(selectElement[0],
27063                                                currentElement,
27064                                                'optgroup',
27065                                                optGroupTemplate);
27066               // Move to the next element
27067               currentElement = groupElement.nextSibling;
27068
27069               // Update the label on the group element
27070               groupElement.label = option.group;
27071
27072               // Store it for use later
27073               group = groupMap[option.group] = {
27074                 groupElement: groupElement,
27075                 currentOptionElement: groupElement.firstChild
27076               };
27077
27078             }
27079
27080             // So now we have a group for this option we add the option to the group
27081             optionElement = addOrReuseElement(group.groupElement,
27082                                               group.currentOptionElement,
27083                                               'option',
27084                                               optionTemplate);
27085             updateOptionElement(option, optionElement);
27086             // Move to the next element
27087             group.currentOptionElement = optionElement.nextSibling;
27088
27089           } else {
27090
27091             // This option is not in a group
27092             optionElement = addOrReuseElement(selectElement[0],
27093                                               currentElement,
27094                                               'option',
27095                                               optionTemplate);
27096             updateOptionElement(option, optionElement);
27097             // Move to the next element
27098             currentElement = optionElement.nextSibling;
27099           }
27100         });
27101
27102
27103         // Now remove all excess options and group
27104         Object.keys(groupMap).forEach(function(key) {
27105           removeExcessElements(groupMap[key].currentOptionElement);
27106         });
27107         removeExcessElements(currentElement);
27108
27109         ngModelCtrl.$render();
27110
27111         // Check to see if the value has changed due to the update to the options
27112         if (!ngModelCtrl.$isEmpty(previousValue)) {
27113           var nextValue = selectCtrl.readValue();
27114           if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
27115             ngModelCtrl.$setViewValue(nextValue);
27116             ngModelCtrl.$render();
27117           }
27118         }
27119
27120       }
27121   }
27122
27123   return {
27124     restrict: 'A',
27125     terminal: true,
27126     require: ['select', 'ngModel'],
27127     link: {
27128       pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
27129         // Deactivate the SelectController.register method to prevent
27130         // option directives from accidentally registering themselves
27131         // (and unwanted $destroy handlers etc.)
27132         ctrls[0].registerOption = noop;
27133       },
27134       post: ngOptionsPostLink
27135     }
27136   };
27137 }];
27138
27139 /**
27140  * @ngdoc directive
27141  * @name ngPluralize
27142  * @restrict EA
27143  *
27144  * @description
27145  * `ngPluralize` is a directive that displays messages according to en-US localization rules.
27146  * These rules are bundled with angular.js, but can be overridden
27147  * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
27148  * by specifying the mappings between
27149  * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
27150  * and the strings to be displayed.
27151  *
27152  * # Plural categories and explicit number rules
27153  * There are two
27154  * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
27155  * in Angular's default en-US locale: "one" and "other".
27156  *
27157  * While a plural category may match many numbers (for example, in en-US locale, "other" can match
27158  * any number that is not 1), an explicit number rule can only match one number. For example, the
27159  * explicit number rule for "3" matches the number 3. There are examples of plural categories
27160  * and explicit number rules throughout the rest of this documentation.
27161  *
27162  * # Configuring ngPluralize
27163  * You configure ngPluralize by providing 2 attributes: `count` and `when`.
27164  * You can also provide an optional attribute, `offset`.
27165  *
27166  * The value of the `count` attribute can be either a string or an {@link guide/expression
27167  * Angular expression}; these are evaluated on the current scope for its bound value.
27168  *
27169  * The `when` attribute specifies the mappings between plural categories and the actual
27170  * string to be displayed. The value of the attribute should be a JSON object.
27171  *
27172  * The following example shows how to configure ngPluralize:
27173  *
27174  * ```html
27175  * <ng-pluralize count="personCount"
27176                  when="{'0': 'Nobody is viewing.',
27177  *                      'one': '1 person is viewing.',
27178  *                      'other': '{} people are viewing.'}">
27179  * </ng-pluralize>
27180  *```
27181  *
27182  * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
27183  * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
27184  * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
27185  * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
27186  * show "a dozen people are viewing".
27187  *
27188  * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
27189  * into pluralized strings. In the previous example, Angular will replace `{}` with
27190  * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
27191  * for <span ng-non-bindable>{{numberExpression}}</span>.
27192  *
27193  * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
27194  * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
27195  *
27196  * # Configuring ngPluralize with offset
27197  * The `offset` attribute allows further customization of pluralized text, which can result in
27198  * a better user experience. For example, instead of the message "4 people are viewing this document",
27199  * you might display "John, Kate and 2 others are viewing this document".
27200  * The offset attribute allows you to offset a number by any desired value.
27201  * Let's take a look at an example:
27202  *
27203  * ```html
27204  * <ng-pluralize count="personCount" offset=2
27205  *               when="{'0': 'Nobody is viewing.',
27206  *                      '1': '{{person1}} is viewing.',
27207  *                      '2': '{{person1}} and {{person2}} are viewing.',
27208  *                      'one': '{{person1}}, {{person2}} and one other person are viewing.',
27209  *                      'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
27210  * </ng-pluralize>
27211  * ```
27212  *
27213  * Notice that we are still using two plural categories(one, other), but we added
27214  * three explicit number rules 0, 1 and 2.
27215  * When one person, perhaps John, views the document, "John is viewing" will be shown.
27216  * When three people view the document, no explicit number rule is found, so
27217  * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
27218  * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
27219  * is shown.
27220  *
27221  * Note that when you specify offsets, you must provide explicit number rules for
27222  * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
27223  * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
27224  * plural categories "one" and "other".
27225  *
27226  * @param {string|expression} count The variable to be bound to.
27227  * @param {string} when The mapping between plural category to its corresponding strings.
27228  * @param {number=} offset Offset to deduct from the total number.
27229  *
27230  * @example
27231     <example module="pluralizeExample">
27232       <file name="index.html">
27233         <script>
27234           angular.module('pluralizeExample', [])
27235             .controller('ExampleController', ['$scope', function($scope) {
27236               $scope.person1 = 'Igor';
27237               $scope.person2 = 'Misko';
27238               $scope.personCount = 1;
27239             }]);
27240         </script>
27241         <div ng-controller="ExampleController">
27242           <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
27243           <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
27244           <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
27245
27246           <!--- Example with simple pluralization rules for en locale --->
27247           Without Offset:
27248           <ng-pluralize count="personCount"
27249                         when="{'0': 'Nobody is viewing.',
27250                                'one': '1 person is viewing.',
27251                                'other': '{} people are viewing.'}">
27252           </ng-pluralize><br>
27253
27254           <!--- Example with offset --->
27255           With Offset(2):
27256           <ng-pluralize count="personCount" offset=2
27257                         when="{'0': 'Nobody is viewing.',
27258                                '1': '{{person1}} is viewing.',
27259                                '2': '{{person1}} and {{person2}} are viewing.',
27260                                'one': '{{person1}}, {{person2}} and one other person are viewing.',
27261                                'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
27262           </ng-pluralize>
27263         </div>
27264       </file>
27265       <file name="protractor.js" type="protractor">
27266         it('should show correct pluralized string', function() {
27267           var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
27268           var withOffset = element.all(by.css('ng-pluralize')).get(1);
27269           var countInput = element(by.model('personCount'));
27270
27271           expect(withoutOffset.getText()).toEqual('1 person is viewing.');
27272           expect(withOffset.getText()).toEqual('Igor is viewing.');
27273
27274           countInput.clear();
27275           countInput.sendKeys('0');
27276
27277           expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
27278           expect(withOffset.getText()).toEqual('Nobody is viewing.');
27279
27280           countInput.clear();
27281           countInput.sendKeys('2');
27282
27283           expect(withoutOffset.getText()).toEqual('2 people are viewing.');
27284           expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
27285
27286           countInput.clear();
27287           countInput.sendKeys('3');
27288
27289           expect(withoutOffset.getText()).toEqual('3 people are viewing.');
27290           expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
27291
27292           countInput.clear();
27293           countInput.sendKeys('4');
27294
27295           expect(withoutOffset.getText()).toEqual('4 people are viewing.');
27296           expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
27297         });
27298         it('should show data-bound names', function() {
27299           var withOffset = element.all(by.css('ng-pluralize')).get(1);
27300           var personCount = element(by.model('personCount'));
27301           var person1 = element(by.model('person1'));
27302           var person2 = element(by.model('person2'));
27303           personCount.clear();
27304           personCount.sendKeys('4');
27305           person1.clear();
27306           person1.sendKeys('Di');
27307           person2.clear();
27308           person2.sendKeys('Vojta');
27309           expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
27310         });
27311       </file>
27312     </example>
27313  */
27314 var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
27315   var BRACE = /{}/g,
27316       IS_WHEN = /^when(Minus)?(.+)$/;
27317
27318   return {
27319     link: function(scope, element, attr) {
27320       var numberExp = attr.count,
27321           whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
27322           offset = attr.offset || 0,
27323           whens = scope.$eval(whenExp) || {},
27324           whensExpFns = {},
27325           startSymbol = $interpolate.startSymbol(),
27326           endSymbol = $interpolate.endSymbol(),
27327           braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
27328           watchRemover = angular.noop,
27329           lastCount;
27330
27331       forEach(attr, function(expression, attributeName) {
27332         var tmpMatch = IS_WHEN.exec(attributeName);
27333         if (tmpMatch) {
27334           var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
27335           whens[whenKey] = element.attr(attr.$attr[attributeName]);
27336         }
27337       });
27338       forEach(whens, function(expression, key) {
27339         whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
27340
27341       });
27342
27343       scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
27344         var count = parseFloat(newVal);
27345         var countIsNaN = isNaN(count);
27346
27347         if (!countIsNaN && !(count in whens)) {
27348           // If an explicit number rule such as 1, 2, 3... is defined, just use it.
27349           // Otherwise, check it against pluralization rules in $locale service.
27350           count = $locale.pluralCat(count - offset);
27351         }
27352
27353         // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
27354         // In JS `NaN !== NaN`, so we have to exlicitly check.
27355         if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
27356           watchRemover();
27357           var whenExpFn = whensExpFns[count];
27358           if (isUndefined(whenExpFn)) {
27359             if (newVal != null) {
27360               $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
27361             }
27362             watchRemover = noop;
27363             updateElementText();
27364           } else {
27365             watchRemover = scope.$watch(whenExpFn, updateElementText);
27366           }
27367           lastCount = count;
27368         }
27369       });
27370
27371       function updateElementText(newText) {
27372         element.text(newText || '');
27373       }
27374     }
27375   };
27376 }];
27377
27378 /**
27379  * @ngdoc directive
27380  * @name ngRepeat
27381  * @multiElement
27382  *
27383  * @description
27384  * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
27385  * instance gets its own scope, where the given loop variable is set to the current collection item,
27386  * and `$index` is set to the item index or key.
27387  *
27388  * Special properties are exposed on the local scope of each template instance, including:
27389  *
27390  * | Variable  | Type            | Details                                                                     |
27391  * |-----------|-----------------|-----------------------------------------------------------------------------|
27392  * | `$index`  | {@type number}  | iterator offset of the repeated element (0..length-1)                       |
27393  * | `$first`  | {@type boolean} | true if the repeated element is first in the iterator.                      |
27394  * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
27395  * | `$last`   | {@type boolean} | true if the repeated element is last in the iterator.                       |
27396  * | `$even`   | {@type boolean} | true if the iterator position `$index` is even (otherwise false).           |
27397  * | `$odd`    | {@type boolean} | true if the iterator position `$index` is odd (otherwise false).            |
27398  *
27399  * <div class="alert alert-info">
27400  *   Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
27401  *   This may be useful when, for instance, nesting ngRepeats.
27402  * </div>
27403  *
27404  *
27405  * # Iterating over object properties
27406  *
27407  * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
27408  * syntax:
27409  *
27410  * ```js
27411  * <div ng-repeat="(key, value) in myObj"> ... </div>
27412  * ```
27413  *
27414  * You need to be aware that the JavaScript specification does not define the order of keys
27415  * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
27416  * used to sort the keys alphabetically.)
27417  *
27418  * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
27419  * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
27420  * keys in the order in which they were defined, although there are exceptions when keys are deleted
27421  * and reinstated. See the [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
27422  *
27423  * If this is not desired, the recommended workaround is to convert your object into an array
27424  * that is sorted into the order that you prefer before providing it to `ngRepeat`.  You could
27425  * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
27426  * or implement a `$watch` on the object yourself.
27427  *
27428  *
27429  * # Tracking and Duplicates
27430  *
27431  * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
27432  * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
27433  *
27434  * * When an item is added, a new instance of the template is added to the DOM.
27435  * * When an item is removed, its template instance is removed from the DOM.
27436  * * When items are reordered, their respective templates are reordered in the DOM.
27437  *
27438  * To minimize creation of DOM elements, `ngRepeat` uses a function
27439  * to "keep track" of all items in the collection and their corresponding DOM elements.
27440  * For example, if an item is added to the collection, ngRepeat will know that all other items
27441  * already have DOM elements, and will not re-render them.
27442  *
27443  * The default tracking function (which tracks items by their identity) does not allow
27444  * duplicate items in arrays. This is because when there are duplicates, it is not possible
27445  * to maintain a one-to-one mapping between collection items and DOM elements.
27446  *
27447  * If you do need to repeat duplicate items, you can substitute the default tracking behavior
27448  * with your own using the `track by` expression.
27449  *
27450  * For example, you may track items by the index of each item in the collection, using the
27451  * special scope property `$index`:
27452  * ```html
27453  *    <div ng-repeat="n in [42, 42, 43, 43] track by $index">
27454  *      {{n}}
27455  *    </div>
27456  * ```
27457  *
27458  * You may also use arbitrary expressions in `track by`, including references to custom functions
27459  * on the scope:
27460  * ```html
27461  *    <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
27462  *      {{n}}
27463  *    </div>
27464  * ```
27465  *
27466  * <div class="alert alert-success">
27467  * If you are working with objects that have an identifier property, you should track
27468  * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
27469  * will not have to rebuild the DOM elements for items it has already rendered, even if the
27470  * JavaScript objects in the collection have been substituted for new ones. For large collections,
27471  * this signifincantly improves rendering performance. If you don't have a unique identifier,
27472  * `track by $index` can also provide a performance boost.
27473  * </div>
27474  * ```html
27475  *    <div ng-repeat="model in collection track by model.id">
27476  *      {{model.name}}
27477  *    </div>
27478  * ```
27479  *
27480  * When no `track by` expression is provided, it is equivalent to tracking by the built-in
27481  * `$id` function, which tracks items by their identity:
27482  * ```html
27483  *    <div ng-repeat="obj in collection track by $id(obj)">
27484  *      {{obj.prop}}
27485  *    </div>
27486  * ```
27487  *
27488  * <div class="alert alert-warning">
27489  * **Note:** `track by` must always be the last expression:
27490  * </div>
27491  * ```
27492  * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
27493  *     {{model.name}}
27494  * </div>
27495  * ```
27496  *
27497  * # Special repeat start and end points
27498  * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
27499  * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
27500  * 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)
27501  * up to and including the ending HTML tag where **ng-repeat-end** is placed.
27502  *
27503  * The example below makes use of this feature:
27504  * ```html
27505  *   <header ng-repeat-start="item in items">
27506  *     Header {{ item }}
27507  *   </header>
27508  *   <div class="body">
27509  *     Body {{ item }}
27510  *   </div>
27511  *   <footer ng-repeat-end>
27512  *     Footer {{ item }}
27513  *   </footer>
27514  * ```
27515  *
27516  * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
27517  * ```html
27518  *   <header>
27519  *     Header A
27520  *   </header>
27521  *   <div class="body">
27522  *     Body A
27523  *   </div>
27524  *   <footer>
27525  *     Footer A
27526  *   </footer>
27527  *   <header>
27528  *     Header B
27529  *   </header>
27530  *   <div class="body">
27531  *     Body B
27532  *   </div>
27533  *   <footer>
27534  *     Footer B
27535  *   </footer>
27536  * ```
27537  *
27538  * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
27539  * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
27540  *
27541  * @animations
27542  * **.enter** - when a new item is added to the list or when an item is revealed after a filter
27543  *
27544  * **.leave** - when an item is removed from the list or when an item is filtered out
27545  *
27546  * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
27547  *
27548  * @element ANY
27549  * @scope
27550  * @priority 1000
27551  * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
27552  *   formats are currently supported:
27553  *
27554  *   * `variable in expression` – where variable is the user defined loop variable and `expression`
27555  *     is a scope expression giving the collection to enumerate.
27556  *
27557  *     For example: `album in artist.albums`.
27558  *
27559  *   * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
27560  *     and `expression` is the scope expression giving the collection to enumerate.
27561  *
27562  *     For example: `(name, age) in {'adam':10, 'amalie':12}`.
27563  *
27564  *   * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
27565  *     which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
27566  *     is specified, ng-repeat associates elements by identity. It is an error to have
27567  *     more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
27568  *     mapped to the same DOM element, which is not possible.)
27569  *
27570  *     Note that the tracking expression must come last, after any filters, and the alias expression.
27571  *
27572  *     For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
27573  *     will be associated by item identity in the array.
27574  *
27575  *     For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
27576  *     `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
27577  *     with the corresponding item in the array by identity. Moving the same object in array would move the DOM
27578  *     element in the same way in the DOM.
27579  *
27580  *     For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
27581  *     case the object identity does not matter. Two objects are considered equivalent as long as their `id`
27582  *     property is same.
27583  *
27584  *     For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
27585  *     to items in conjunction with a tracking expression.
27586  *
27587  *   * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
27588  *     intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
27589  *     when a filter is active on the repeater, but the filtered result set is empty.
27590  *
27591  *     For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
27592  *     the items have been processed through the filter.
27593  *
27594  *     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
27595  *     (and not as operator, inside an expression).
27596  *
27597  *     For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
27598  *
27599  * @example
27600  * This example initializes the scope to a list of names and
27601  * then uses `ngRepeat` to display every person:
27602   <example module="ngAnimate" deps="angular-animate.js" animations="true">
27603     <file name="index.html">
27604       <div ng-init="friends = [
27605         {name:'John', age:25, gender:'boy'},
27606         {name:'Jessie', age:30, gender:'girl'},
27607         {name:'Johanna', age:28, gender:'girl'},
27608         {name:'Joy', age:15, gender:'girl'},
27609         {name:'Mary', age:28, gender:'girl'},
27610         {name:'Peter', age:95, gender:'boy'},
27611         {name:'Sebastian', age:50, gender:'boy'},
27612         {name:'Erika', age:27, gender:'girl'},
27613         {name:'Patrick', age:40, gender:'boy'},
27614         {name:'Samantha', age:60, gender:'girl'}
27615       ]">
27616         I have {{friends.length}} friends. They are:
27617         <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
27618         <ul class="example-animate-container">
27619           <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
27620             [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
27621           </li>
27622           <li class="animate-repeat" ng-if="results.length == 0">
27623             <strong>No results found...</strong>
27624           </li>
27625         </ul>
27626       </div>
27627     </file>
27628     <file name="animations.css">
27629       .example-animate-container {
27630         background:white;
27631         border:1px solid black;
27632         list-style:none;
27633         margin:0;
27634         padding:0 10px;
27635       }
27636
27637       .animate-repeat {
27638         line-height:40px;
27639         list-style:none;
27640         box-sizing:border-box;
27641       }
27642
27643       .animate-repeat.ng-move,
27644       .animate-repeat.ng-enter,
27645       .animate-repeat.ng-leave {
27646         transition:all linear 0.5s;
27647       }
27648
27649       .animate-repeat.ng-leave.ng-leave-active,
27650       .animate-repeat.ng-move,
27651       .animate-repeat.ng-enter {
27652         opacity:0;
27653         max-height:0;
27654       }
27655
27656       .animate-repeat.ng-leave,
27657       .animate-repeat.ng-move.ng-move-active,
27658       .animate-repeat.ng-enter.ng-enter-active {
27659         opacity:1;
27660         max-height:40px;
27661       }
27662     </file>
27663     <file name="protractor.js" type="protractor">
27664       var friends = element.all(by.repeater('friend in friends'));
27665
27666       it('should render initial data set', function() {
27667         expect(friends.count()).toBe(10);
27668         expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
27669         expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
27670         expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
27671         expect(element(by.binding('friends.length')).getText())
27672             .toMatch("I have 10 friends. They are:");
27673       });
27674
27675        it('should update repeater when filter predicate changes', function() {
27676          expect(friends.count()).toBe(10);
27677
27678          element(by.model('q')).sendKeys('ma');
27679
27680          expect(friends.count()).toBe(2);
27681          expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
27682          expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
27683        });
27684       </file>
27685     </example>
27686  */
27687 var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
27688   var NG_REMOVED = '$$NG_REMOVED';
27689   var ngRepeatMinErr = minErr('ngRepeat');
27690
27691   var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
27692     // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
27693     scope[valueIdentifier] = value;
27694     if (keyIdentifier) scope[keyIdentifier] = key;
27695     scope.$index = index;
27696     scope.$first = (index === 0);
27697     scope.$last = (index === (arrayLength - 1));
27698     scope.$middle = !(scope.$first || scope.$last);
27699     // jshint bitwise: false
27700     scope.$odd = !(scope.$even = (index&1) === 0);
27701     // jshint bitwise: true
27702   };
27703
27704   var getBlockStart = function(block) {
27705     return block.clone[0];
27706   };
27707
27708   var getBlockEnd = function(block) {
27709     return block.clone[block.clone.length - 1];
27710   };
27711
27712
27713   return {
27714     restrict: 'A',
27715     multiElement: true,
27716     transclude: 'element',
27717     priority: 1000,
27718     terminal: true,
27719     $$tlb: true,
27720     compile: function ngRepeatCompile($element, $attr) {
27721       var expression = $attr.ngRepeat;
27722       var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
27723
27724       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*$/);
27725
27726       if (!match) {
27727         throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
27728             expression);
27729       }
27730
27731       var lhs = match[1];
27732       var rhs = match[2];
27733       var aliasAs = match[3];
27734       var trackByExp = match[4];
27735
27736       match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
27737
27738       if (!match) {
27739         throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
27740             lhs);
27741       }
27742       var valueIdentifier = match[3] || match[1];
27743       var keyIdentifier = match[2];
27744
27745       if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
27746           /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
27747         throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
27748           aliasAs);
27749       }
27750
27751       var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
27752       var hashFnLocals = {$id: hashKey};
27753
27754       if (trackByExp) {
27755         trackByExpGetter = $parse(trackByExp);
27756       } else {
27757         trackByIdArrayFn = function(key, value) {
27758           return hashKey(value);
27759         };
27760         trackByIdObjFn = function(key) {
27761           return key;
27762         };
27763       }
27764
27765       return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
27766
27767         if (trackByExpGetter) {
27768           trackByIdExpFn = function(key, value, index) {
27769             // assign key, value, and $index to the locals so that they can be used in hash functions
27770             if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
27771             hashFnLocals[valueIdentifier] = value;
27772             hashFnLocals.$index = index;
27773             return trackByExpGetter($scope, hashFnLocals);
27774           };
27775         }
27776
27777         // Store a list of elements from previous run. This is a hash where key is the item from the
27778         // iterator, and the value is objects with following properties.
27779         //   - scope: bound scope
27780         //   - element: previous element.
27781         //   - index: position
27782         //
27783         // We are using no-proto object so that we don't need to guard against inherited props via
27784         // hasOwnProperty.
27785         var lastBlockMap = createMap();
27786
27787         //watch props
27788         $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
27789           var index, length,
27790               previousNode = $element[0],     // node that cloned nodes should be inserted after
27791                                               // initialized to the comment node anchor
27792               nextNode,
27793               // Same as lastBlockMap but it has the current state. It will become the
27794               // lastBlockMap on the next iteration.
27795               nextBlockMap = createMap(),
27796               collectionLength,
27797               key, value, // key/value of iteration
27798               trackById,
27799               trackByIdFn,
27800               collectionKeys,
27801               block,       // last object information {scope, element, id}
27802               nextBlockOrder,
27803               elementsToRemove;
27804
27805           if (aliasAs) {
27806             $scope[aliasAs] = collection;
27807           }
27808
27809           if (isArrayLike(collection)) {
27810             collectionKeys = collection;
27811             trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
27812           } else {
27813             trackByIdFn = trackByIdExpFn || trackByIdObjFn;
27814             // if object, extract keys, in enumeration order, unsorted
27815             collectionKeys = [];
27816             for (var itemKey in collection) {
27817               if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
27818                 collectionKeys.push(itemKey);
27819               }
27820             }
27821           }
27822
27823           collectionLength = collectionKeys.length;
27824           nextBlockOrder = new Array(collectionLength);
27825
27826           // locate existing items
27827           for (index = 0; index < collectionLength; index++) {
27828             key = (collection === collectionKeys) ? index : collectionKeys[index];
27829             value = collection[key];
27830             trackById = trackByIdFn(key, value, index);
27831             if (lastBlockMap[trackById]) {
27832               // found previously seen block
27833               block = lastBlockMap[trackById];
27834               delete lastBlockMap[trackById];
27835               nextBlockMap[trackById] = block;
27836               nextBlockOrder[index] = block;
27837             } else if (nextBlockMap[trackById]) {
27838               // if collision detected. restore lastBlockMap and throw an error
27839               forEach(nextBlockOrder, function(block) {
27840                 if (block && block.scope) lastBlockMap[block.id] = block;
27841               });
27842               throw ngRepeatMinErr('dupes',
27843                   "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
27844                   expression, trackById, value);
27845             } else {
27846               // new never before seen block
27847               nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
27848               nextBlockMap[trackById] = true;
27849             }
27850           }
27851
27852           // remove leftover items
27853           for (var blockKey in lastBlockMap) {
27854             block = lastBlockMap[blockKey];
27855             elementsToRemove = getBlockNodes(block.clone);
27856             $animate.leave(elementsToRemove);
27857             if (elementsToRemove[0].parentNode) {
27858               // if the element was not removed yet because of pending animation, mark it as deleted
27859               // so that we can ignore it later
27860               for (index = 0, length = elementsToRemove.length; index < length; index++) {
27861                 elementsToRemove[index][NG_REMOVED] = true;
27862               }
27863             }
27864             block.scope.$destroy();
27865           }
27866
27867           // we are not using forEach for perf reasons (trying to avoid #call)
27868           for (index = 0; index < collectionLength; index++) {
27869             key = (collection === collectionKeys) ? index : collectionKeys[index];
27870             value = collection[key];
27871             block = nextBlockOrder[index];
27872
27873             if (block.scope) {
27874               // if we have already seen this object, then we need to reuse the
27875               // associated scope/element
27876
27877               nextNode = previousNode;
27878
27879               // skip nodes that are already pending removal via leave animation
27880               do {
27881                 nextNode = nextNode.nextSibling;
27882               } while (nextNode && nextNode[NG_REMOVED]);
27883
27884               if (getBlockStart(block) != nextNode) {
27885                 // existing item which got moved
27886                 $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
27887               }
27888               previousNode = getBlockEnd(block);
27889               updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
27890             } else {
27891               // new item which we don't know about
27892               $transclude(function ngRepeatTransclude(clone, scope) {
27893                 block.scope = scope;
27894                 // http://jsperf.com/clone-vs-createcomment
27895                 var endNode = ngRepeatEndComment.cloneNode(false);
27896                 clone[clone.length++] = endNode;
27897
27898                 // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
27899                 $animate.enter(clone, null, jqLite(previousNode));
27900                 previousNode = endNode;
27901                 // Note: We only need the first/last node of the cloned nodes.
27902                 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
27903                 // by a directive with templateUrl when its template arrives.
27904                 block.clone = clone;
27905                 nextBlockMap[block.id] = block;
27906                 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
27907               });
27908             }
27909           }
27910           lastBlockMap = nextBlockMap;
27911         });
27912       };
27913     }
27914   };
27915 }];
27916
27917 var NG_HIDE_CLASS = 'ng-hide';
27918 var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
27919 /**
27920  * @ngdoc directive
27921  * @name ngShow
27922  * @multiElement
27923  *
27924  * @description
27925  * The `ngShow` directive shows or hides the given HTML element based on the expression
27926  * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
27927  * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
27928  * in AngularJS and sets the display style to none (using an !important flag).
27929  * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
27930  *
27931  * ```html
27932  * <!-- when $scope.myValue is truthy (element is visible) -->
27933  * <div ng-show="myValue"></div>
27934  *
27935  * <!-- when $scope.myValue is falsy (element is hidden) -->
27936  * <div ng-show="myValue" class="ng-hide"></div>
27937  * ```
27938  *
27939  * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
27940  * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
27941  * from the element causing the element not to appear hidden.
27942  *
27943  * ## Why is !important used?
27944  *
27945  * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
27946  * can be easily overridden by heavier selectors. For example, something as simple
27947  * as changing the display style on a HTML list item would make hidden elements appear visible.
27948  * This also becomes a bigger issue when dealing with CSS frameworks.
27949  *
27950  * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
27951  * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
27952  * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
27953  *
27954  * ### Overriding `.ng-hide`
27955  *
27956  * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
27957  * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
27958  * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
27959  * with extra animation classes that can be added.
27960  *
27961  * ```css
27962  * .ng-hide:not(.ng-hide-animate) {
27963  *   /&#42; this is just another form of hiding an element &#42;/
27964  *   display: block!important;
27965  *   position: absolute;
27966  *   top: -9999px;
27967  *   left: -9999px;
27968  * }
27969  * ```
27970  *
27971  * By default you don't need to override in CSS anything and the animations will work around the display style.
27972  *
27973  * ## A note about animations with `ngShow`
27974  *
27975  * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
27976  * is true and false. This system works like the animation system present with ngClass except that
27977  * you must also include the !important flag to override the display property
27978  * so that you can perform an animation when the element is hidden during the time of the animation.
27979  *
27980  * ```css
27981  * //
27982  * //a working example can be found at the bottom of this page
27983  * //
27984  * .my-element.ng-hide-add, .my-element.ng-hide-remove {
27985  *   /&#42; this is required as of 1.3x to properly
27986  *      apply all styling in a show/hide animation &#42;/
27987  *   transition: 0s linear all;
27988  * }
27989  *
27990  * .my-element.ng-hide-add-active,
27991  * .my-element.ng-hide-remove-active {
27992  *   /&#42; the transition is defined in the active class &#42;/
27993  *   transition: 1s linear all;
27994  * }
27995  *
27996  * .my-element.ng-hide-add { ... }
27997  * .my-element.ng-hide-add.ng-hide-add-active { ... }
27998  * .my-element.ng-hide-remove { ... }
27999  * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
28000  * ```
28001  *
28002  * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
28003  * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
28004  *
28005  * @animations
28006  * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
28007  * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
28008  *
28009  * @element ANY
28010  * @param {expression} ngShow If the {@link guide/expression expression} is truthy
28011  *     then the element is shown or hidden respectively.
28012  *
28013  * @example
28014   <example module="ngAnimate" deps="angular-animate.js" animations="true">
28015     <file name="index.html">
28016       Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
28017       <div>
28018         Show:
28019         <div class="check-element animate-show" ng-show="checked">
28020           <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
28021         </div>
28022       </div>
28023       <div>
28024         Hide:
28025         <div class="check-element animate-show" ng-hide="checked">
28026           <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
28027         </div>
28028       </div>
28029     </file>
28030     <file name="glyphicons.css">
28031       @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
28032     </file>
28033     <file name="animations.css">
28034       .animate-show {
28035         line-height: 20px;
28036         opacity: 1;
28037         padding: 10px;
28038         border: 1px solid black;
28039         background: white;
28040       }
28041
28042       .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
28043         transition: all linear 0.5s;
28044       }
28045
28046       .animate-show.ng-hide {
28047         line-height: 0;
28048         opacity: 0;
28049         padding: 0 10px;
28050       }
28051
28052       .check-element {
28053         padding: 10px;
28054         border: 1px solid black;
28055         background: white;
28056       }
28057     </file>
28058     <file name="protractor.js" type="protractor">
28059       var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
28060       var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
28061
28062       it('should check ng-show / ng-hide', function() {
28063         expect(thumbsUp.isDisplayed()).toBeFalsy();
28064         expect(thumbsDown.isDisplayed()).toBeTruthy();
28065
28066         element(by.model('checked')).click();
28067
28068         expect(thumbsUp.isDisplayed()).toBeTruthy();
28069         expect(thumbsDown.isDisplayed()).toBeFalsy();
28070       });
28071     </file>
28072   </example>
28073  */
28074 var ngShowDirective = ['$animate', function($animate) {
28075   return {
28076     restrict: 'A',
28077     multiElement: true,
28078     link: function(scope, element, attr) {
28079       scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
28080         // we're adding a temporary, animation-specific class for ng-hide since this way
28081         // we can control when the element is actually displayed on screen without having
28082         // to have a global/greedy CSS selector that breaks when other animations are run.
28083         // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
28084         $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
28085           tempClasses: NG_HIDE_IN_PROGRESS_CLASS
28086         });
28087       });
28088     }
28089   };
28090 }];
28091
28092
28093 /**
28094  * @ngdoc directive
28095  * @name ngHide
28096  * @multiElement
28097  *
28098  * @description
28099  * The `ngHide` directive shows or hides the given HTML element based on the expression
28100  * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
28101  * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
28102  * in AngularJS and sets the display style to none (using an !important flag).
28103  * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
28104  *
28105  * ```html
28106  * <!-- when $scope.myValue is truthy (element is hidden) -->
28107  * <div ng-hide="myValue" class="ng-hide"></div>
28108  *
28109  * <!-- when $scope.myValue is falsy (element is visible) -->
28110  * <div ng-hide="myValue"></div>
28111  * ```
28112  *
28113  * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
28114  * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
28115  * from the element causing the element not to appear hidden.
28116  *
28117  * ## Why is !important used?
28118  *
28119  * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
28120  * can be easily overridden by heavier selectors. For example, something as simple
28121  * as changing the display style on a HTML list item would make hidden elements appear visible.
28122  * This also becomes a bigger issue when dealing with CSS frameworks.
28123  *
28124  * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
28125  * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
28126  * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
28127  *
28128  * ### Overriding `.ng-hide`
28129  *
28130  * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
28131  * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
28132  * class in CSS:
28133  *
28134  * ```css
28135  * .ng-hide {
28136  *   /&#42; this is just another form of hiding an element &#42;/
28137  *   display: block!important;
28138  *   position: absolute;
28139  *   top: -9999px;
28140  *   left: -9999px;
28141  * }
28142  * ```
28143  *
28144  * By default you don't need to override in CSS anything and the animations will work around the display style.
28145  *
28146  * ## A note about animations with `ngHide`
28147  *
28148  * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
28149  * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
28150  * CSS class is added and removed for you instead of your own CSS class.
28151  *
28152  * ```css
28153  * //
28154  * //a working example can be found at the bottom of this page
28155  * //
28156  * .my-element.ng-hide-add, .my-element.ng-hide-remove {
28157  *   transition: 0.5s linear all;
28158  * }
28159  *
28160  * .my-element.ng-hide-add { ... }
28161  * .my-element.ng-hide-add.ng-hide-add-active { ... }
28162  * .my-element.ng-hide-remove { ... }
28163  * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
28164  * ```
28165  *
28166  * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
28167  * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
28168  *
28169  * @animations
28170  * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
28171  * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
28172  *
28173  * @element ANY
28174  * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
28175  *     the element is shown or hidden respectively.
28176  *
28177  * @example
28178   <example module="ngAnimate" deps="angular-animate.js" animations="true">
28179     <file name="index.html">
28180       Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
28181       <div>
28182         Show:
28183         <div class="check-element animate-hide" ng-show="checked">
28184           <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
28185         </div>
28186       </div>
28187       <div>
28188         Hide:
28189         <div class="check-element animate-hide" ng-hide="checked">
28190           <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
28191         </div>
28192       </div>
28193     </file>
28194     <file name="glyphicons.css">
28195       @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
28196     </file>
28197     <file name="animations.css">
28198       .animate-hide {
28199         transition: all linear 0.5s;
28200         line-height: 20px;
28201         opacity: 1;
28202         padding: 10px;
28203         border: 1px solid black;
28204         background: white;
28205       }
28206
28207       .animate-hide.ng-hide {
28208         line-height: 0;
28209         opacity: 0;
28210         padding: 0 10px;
28211       }
28212
28213       .check-element {
28214         padding: 10px;
28215         border: 1px solid black;
28216         background: white;
28217       }
28218     </file>
28219     <file name="protractor.js" type="protractor">
28220       var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
28221       var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
28222
28223       it('should check ng-show / ng-hide', function() {
28224         expect(thumbsUp.isDisplayed()).toBeFalsy();
28225         expect(thumbsDown.isDisplayed()).toBeTruthy();
28226
28227         element(by.model('checked')).click();
28228
28229         expect(thumbsUp.isDisplayed()).toBeTruthy();
28230         expect(thumbsDown.isDisplayed()).toBeFalsy();
28231       });
28232     </file>
28233   </example>
28234  */
28235 var ngHideDirective = ['$animate', function($animate) {
28236   return {
28237     restrict: 'A',
28238     multiElement: true,
28239     link: function(scope, element, attr) {
28240       scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
28241         // The comment inside of the ngShowDirective explains why we add and
28242         // remove a temporary class for the show/hide animation
28243         $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
28244           tempClasses: NG_HIDE_IN_PROGRESS_CLASS
28245         });
28246       });
28247     }
28248   };
28249 }];
28250
28251 /**
28252  * @ngdoc directive
28253  * @name ngStyle
28254  * @restrict AC
28255  *
28256  * @description
28257  * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
28258  *
28259  * @element ANY
28260  * @param {expression} ngStyle
28261  *
28262  * {@link guide/expression Expression} which evals to an
28263  * object whose keys are CSS style names and values are corresponding values for those CSS
28264  * keys.
28265  *
28266  * Since some CSS style names are not valid keys for an object, they must be quoted.
28267  * See the 'background-color' style in the example below.
28268  *
28269  * @example
28270    <example>
28271      <file name="index.html">
28272         <input type="button" value="set color" ng-click="myStyle={color:'red'}">
28273         <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
28274         <input type="button" value="clear" ng-click="myStyle={}">
28275         <br/>
28276         <span ng-style="myStyle">Sample Text</span>
28277         <pre>myStyle={{myStyle}}</pre>
28278      </file>
28279      <file name="style.css">
28280        span {
28281          color: black;
28282        }
28283      </file>
28284      <file name="protractor.js" type="protractor">
28285        var colorSpan = element(by.css('span'));
28286
28287        it('should check ng-style', function() {
28288          expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
28289          element(by.css('input[value=\'set color\']')).click();
28290          expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
28291          element(by.css('input[value=clear]')).click();
28292          expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
28293        });
28294      </file>
28295    </example>
28296  */
28297 var ngStyleDirective = ngDirective(function(scope, element, attr) {
28298   scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
28299     if (oldStyles && (newStyles !== oldStyles)) {
28300       forEach(oldStyles, function(val, style) { element.css(style, '');});
28301     }
28302     if (newStyles) element.css(newStyles);
28303   }, true);
28304 });
28305
28306 /**
28307  * @ngdoc directive
28308  * @name ngSwitch
28309  * @restrict EA
28310  *
28311  * @description
28312  * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
28313  * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
28314  * as specified in the template.
28315  *
28316  * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
28317  * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
28318  * matches the value obtained from the evaluated expression. In other words, you define a container element
28319  * (where you place the directive), place an expression on the **`on="..."` attribute**
28320  * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
28321  * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
28322  * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
28323  * attribute is displayed.
28324  *
28325  * <div class="alert alert-info">
28326  * Be aware that the attribute values to match against cannot be expressions. They are interpreted
28327  * as literal string values to match against.
28328  * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
28329  * value of the expression `$scope.someVal`.
28330  * </div>
28331
28332  * @animations
28333  * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
28334  * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
28335  *
28336  * @usage
28337  *
28338  * ```
28339  * <ANY ng-switch="expression">
28340  *   <ANY ng-switch-when="matchValue1">...</ANY>
28341  *   <ANY ng-switch-when="matchValue2">...</ANY>
28342  *   <ANY ng-switch-default>...</ANY>
28343  * </ANY>
28344  * ```
28345  *
28346  *
28347  * @scope
28348  * @priority 1200
28349  * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
28350  * On child elements add:
28351  *
28352  * * `ngSwitchWhen`: the case statement to match against. If match then this
28353  *   case will be displayed. If the same match appears multiple times, all the
28354  *   elements will be displayed.
28355  * * `ngSwitchDefault`: the default case when no other case match. If there
28356  *   are multiple default cases, all of them will be displayed when no other
28357  *   case match.
28358  *
28359  *
28360  * @example
28361   <example module="switchExample" deps="angular-animate.js" animations="true">
28362     <file name="index.html">
28363       <div ng-controller="ExampleController">
28364         <select ng-model="selection" ng-options="item for item in items">
28365         </select>
28366         <code>selection={{selection}}</code>
28367         <hr/>
28368         <div class="animate-switch-container"
28369           ng-switch on="selection">
28370             <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
28371             <div class="animate-switch" ng-switch-when="home">Home Span</div>
28372             <div class="animate-switch" ng-switch-default>default</div>
28373         </div>
28374       </div>
28375     </file>
28376     <file name="script.js">
28377       angular.module('switchExample', ['ngAnimate'])
28378         .controller('ExampleController', ['$scope', function($scope) {
28379           $scope.items = ['settings', 'home', 'other'];
28380           $scope.selection = $scope.items[0];
28381         }]);
28382     </file>
28383     <file name="animations.css">
28384       .animate-switch-container {
28385         position:relative;
28386         background:white;
28387         border:1px solid black;
28388         height:40px;
28389         overflow:hidden;
28390       }
28391
28392       .animate-switch {
28393         padding:10px;
28394       }
28395
28396       .animate-switch.ng-animate {
28397         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
28398
28399         position:absolute;
28400         top:0;
28401         left:0;
28402         right:0;
28403         bottom:0;
28404       }
28405
28406       .animate-switch.ng-leave.ng-leave-active,
28407       .animate-switch.ng-enter {
28408         top:-50px;
28409       }
28410       .animate-switch.ng-leave,
28411       .animate-switch.ng-enter.ng-enter-active {
28412         top:0;
28413       }
28414     </file>
28415     <file name="protractor.js" type="protractor">
28416       var switchElem = element(by.css('[ng-switch]'));
28417       var select = element(by.model('selection'));
28418
28419       it('should start in settings', function() {
28420         expect(switchElem.getText()).toMatch(/Settings Div/);
28421       });
28422       it('should change to home', function() {
28423         select.all(by.css('option')).get(1).click();
28424         expect(switchElem.getText()).toMatch(/Home Span/);
28425       });
28426       it('should select default', function() {
28427         select.all(by.css('option')).get(2).click();
28428         expect(switchElem.getText()).toMatch(/default/);
28429       });
28430     </file>
28431   </example>
28432  */
28433 var ngSwitchDirective = ['$animate', function($animate) {
28434   return {
28435     require: 'ngSwitch',
28436
28437     // asks for $scope to fool the BC controller module
28438     controller: ['$scope', function ngSwitchController() {
28439      this.cases = {};
28440     }],
28441     link: function(scope, element, attr, ngSwitchController) {
28442       var watchExpr = attr.ngSwitch || attr.on,
28443           selectedTranscludes = [],
28444           selectedElements = [],
28445           previousLeaveAnimations = [],
28446           selectedScopes = [];
28447
28448       var spliceFactory = function(array, index) {
28449           return function() { array.splice(index, 1); };
28450       };
28451
28452       scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
28453         var i, ii;
28454         for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
28455           $animate.cancel(previousLeaveAnimations[i]);
28456         }
28457         previousLeaveAnimations.length = 0;
28458
28459         for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
28460           var selected = getBlockNodes(selectedElements[i].clone);
28461           selectedScopes[i].$destroy();
28462           var promise = previousLeaveAnimations[i] = $animate.leave(selected);
28463           promise.then(spliceFactory(previousLeaveAnimations, i));
28464         }
28465
28466         selectedElements.length = 0;
28467         selectedScopes.length = 0;
28468
28469         if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
28470           forEach(selectedTranscludes, function(selectedTransclude) {
28471             selectedTransclude.transclude(function(caseElement, selectedScope) {
28472               selectedScopes.push(selectedScope);
28473               var anchor = selectedTransclude.element;
28474               caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
28475               var block = { clone: caseElement };
28476
28477               selectedElements.push(block);
28478               $animate.enter(caseElement, anchor.parent(), anchor);
28479             });
28480           });
28481         }
28482       });
28483     }
28484   };
28485 }];
28486
28487 var ngSwitchWhenDirective = ngDirective({
28488   transclude: 'element',
28489   priority: 1200,
28490   require: '^ngSwitch',
28491   multiElement: true,
28492   link: function(scope, element, attrs, ctrl, $transclude) {
28493     ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
28494     ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
28495   }
28496 });
28497
28498 var ngSwitchDefaultDirective = ngDirective({
28499   transclude: 'element',
28500   priority: 1200,
28501   require: '^ngSwitch',
28502   multiElement: true,
28503   link: function(scope, element, attr, ctrl, $transclude) {
28504     ctrl.cases['?'] = (ctrl.cases['?'] || []);
28505     ctrl.cases['?'].push({ transclude: $transclude, element: element });
28506    }
28507 });
28508
28509 /**
28510  * @ngdoc directive
28511  * @name ngTransclude
28512  * @restrict EAC
28513  *
28514  * @description
28515  * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
28516  *
28517  * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
28518  * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
28519  *
28520  * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
28521  *
28522  * @element ANY
28523  *
28524  * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided or empty then
28525  *                                               the default slot is used.
28526  *
28527  * @example
28528  * ### Default transclusion
28529  * This example demonstrates simple transclusion.
28530    <example name="simpleTranscludeExample" module="transcludeExample">
28531      <file name="index.html">
28532        <script>
28533          angular.module('transcludeExample', [])
28534           .directive('pane', function(){
28535              return {
28536                restrict: 'E',
28537                transclude: true,
28538                scope: { title:'@' },
28539                template: '<div style="border: 1px solid black;">' +
28540                            '<div style="background-color: gray">{{title}}</div>' +
28541                            '<ng-transclude></ng-transclude>' +
28542                          '</div>'
28543              };
28544          })
28545          .controller('ExampleController', ['$scope', function($scope) {
28546            $scope.title = 'Lorem Ipsum';
28547            $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
28548          }]);
28549        </script>
28550        <div ng-controller="ExampleController">
28551          <input ng-model="title" aria-label="title"> <br/>
28552          <textarea ng-model="text" aria-label="text"></textarea> <br/>
28553          <pane title="{{title}}">{{text}}</pane>
28554        </div>
28555      </file>
28556      <file name="protractor.js" type="protractor">
28557         it('should have transcluded', function() {
28558           var titleElement = element(by.model('title'));
28559           titleElement.clear();
28560           titleElement.sendKeys('TITLE');
28561           var textElement = element(by.model('text'));
28562           textElement.clear();
28563           textElement.sendKeys('TEXT');
28564           expect(element(by.binding('title')).getText()).toEqual('TITLE');
28565           expect(element(by.binding('text')).getText()).toEqual('TEXT');
28566         });
28567      </file>
28568    </example>
28569  *
28570  * @example
28571  * ### Multi-slot transclusion
28572    <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
28573      <file name="index.html">
28574       <div ng-controller="ExampleController">
28575         <input ng-model="title" aria-label="title"> <br/>
28576         <textarea ng-model="text" aria-label="text"></textarea> <br/>
28577         <pane>
28578           <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
28579           <pane-body><p>{{text}}</p></pane-body>
28580         </pane>
28581       </div>
28582      </file>
28583      <file name="app.js">
28584       angular.module('multiSlotTranscludeExample', [])
28585        .directive('pane', function(){
28586           return {
28587             restrict: 'E',
28588             transclude: {
28589               'paneTitle': '?title',
28590               'paneBody': 'body'
28591             },
28592             template: '<div style="border: 1px solid black;">' +
28593                         '<div ng-transclude="title" style="background-color: gray"></div>' +
28594                         '<div ng-transclude="body"></div>' +
28595                       '</div>'
28596           };
28597       })
28598       .controller('ExampleController', ['$scope', function($scope) {
28599         $scope.title = 'Lorem Ipsum';
28600         $scope.link = "https://google.com";
28601         $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
28602       }]);
28603      </file>
28604      <file name="protractor.js" type="protractor">
28605         it('should have transcluded the title and the body', function() {
28606           var titleElement = element(by.model('title'));
28607           titleElement.clear();
28608           titleElement.sendKeys('TITLE');
28609           var textElement = element(by.model('text'));
28610           textElement.clear();
28611           textElement.sendKeys('TEXT');
28612           expect(element(by.binding('title')).getText()).toEqual('TITLE');
28613           expect(element(by.binding('text')).getText()).toEqual('TEXT');
28614         });
28615      </file>
28616    </example> */
28617 var ngTranscludeMinErr = minErr('ngTransclude');
28618 var ngTranscludeDirective = ngDirective({
28619   restrict: 'EAC',
28620   link: function($scope, $element, $attrs, controller, $transclude) {
28621
28622     function ngTranscludeCloneAttachFn(clone) {
28623       $element.empty();
28624       $element.append(clone);
28625     }
28626
28627     if (!$transclude) {
28628       throw ngTranscludeMinErr('orphan',
28629        'Illegal use of ngTransclude directive in the template! ' +
28630        'No parent directive that requires a transclusion found. ' +
28631        'Element: {0}',
28632        startingTag($element));
28633     }
28634
28635     $transclude(ngTranscludeCloneAttachFn, null, $attrs.ngTransclude || $attrs.ngTranscludeSlot);
28636   }
28637 });
28638
28639 /**
28640  * @ngdoc directive
28641  * @name script
28642  * @restrict E
28643  *
28644  * @description
28645  * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
28646  * template can be used by {@link ng.directive:ngInclude `ngInclude`},
28647  * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
28648  * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
28649  * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
28650  *
28651  * @param {string} type Must be set to `'text/ng-template'`.
28652  * @param {string} id Cache name of the template.
28653  *
28654  * @example
28655   <example>
28656     <file name="index.html">
28657       <script type="text/ng-template" id="/tpl.html">
28658         Content of the template.
28659       </script>
28660
28661       <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
28662       <div id="tpl-content" ng-include src="currentTpl"></div>
28663     </file>
28664     <file name="protractor.js" type="protractor">
28665       it('should load template defined inside script tag', function() {
28666         element(by.css('#tpl-link')).click();
28667         expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
28668       });
28669     </file>
28670   </example>
28671  */
28672 var scriptDirective = ['$templateCache', function($templateCache) {
28673   return {
28674     restrict: 'E',
28675     terminal: true,
28676     compile: function(element, attr) {
28677       if (attr.type == 'text/ng-template') {
28678         var templateUrl = attr.id,
28679             text = element[0].text;
28680
28681         $templateCache.put(templateUrl, text);
28682       }
28683     }
28684   };
28685 }];
28686
28687 var noopNgModelController = { $setViewValue: noop, $render: noop };
28688
28689 function chromeHack(optionElement) {
28690   // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
28691   // Adding an <option selected="selected"> element to a <select required="required"> should
28692   // automatically select the new element
28693   if (optionElement[0].hasAttribute('selected')) {
28694     optionElement[0].selected = true;
28695   }
28696 }
28697
28698 /**
28699  * @ngdoc type
28700  * @name  select.SelectController
28701  * @description
28702  * The controller for the `<select>` directive. This provides support for reading
28703  * and writing the selected value(s) of the control and also coordinates dynamically
28704  * added `<option>` elements, perhaps by an `ngRepeat` directive.
28705  */
28706 var SelectController =
28707         ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
28708
28709   var self = this,
28710       optionsMap = new HashMap();
28711
28712   // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
28713   self.ngModelCtrl = noopNgModelController;
28714
28715   // The "unknown" option is one that is prepended to the list if the viewValue
28716   // does not match any of the options. When it is rendered the value of the unknown
28717   // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
28718   //
28719   // We can't just jqLite('<option>') since jqLite is not smart enough
28720   // to create it in <select> and IE barfs otherwise.
28721   self.unknownOption = jqLite(document.createElement('option'));
28722   self.renderUnknownOption = function(val) {
28723     var unknownVal = '? ' + hashKey(val) + ' ?';
28724     self.unknownOption.val(unknownVal);
28725     $element.prepend(self.unknownOption);
28726     $element.val(unknownVal);
28727   };
28728
28729   $scope.$on('$destroy', function() {
28730     // disable unknown option so that we don't do work when the whole select is being destroyed
28731     self.renderUnknownOption = noop;
28732   });
28733
28734   self.removeUnknownOption = function() {
28735     if (self.unknownOption.parent()) self.unknownOption.remove();
28736   };
28737
28738
28739   // Read the value of the select control, the implementation of this changes depending
28740   // upon whether the select can have multiple values and whether ngOptions is at work.
28741   self.readValue = function readSingleValue() {
28742     self.removeUnknownOption();
28743     return $element.val();
28744   };
28745
28746
28747   // Write the value to the select control, the implementation of this changes depending
28748   // upon whether the select can have multiple values and whether ngOptions is at work.
28749   self.writeValue = function writeSingleValue(value) {
28750     if (self.hasOption(value)) {
28751       self.removeUnknownOption();
28752       $element.val(value);
28753       if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
28754     } else {
28755       if (value == null && self.emptyOption) {
28756         self.removeUnknownOption();
28757         $element.val('');
28758       } else {
28759         self.renderUnknownOption(value);
28760       }
28761     }
28762   };
28763
28764
28765   // Tell the select control that an option, with the given value, has been added
28766   self.addOption = function(value, element) {
28767     assertNotHasOwnProperty(value, '"option value"');
28768     if (value === '') {
28769       self.emptyOption = element;
28770     }
28771     var count = optionsMap.get(value) || 0;
28772     optionsMap.put(value, count + 1);
28773     self.ngModelCtrl.$render();
28774     chromeHack(element);
28775   };
28776
28777   // Tell the select control that an option, with the given value, has been removed
28778   self.removeOption = function(value) {
28779     var count = optionsMap.get(value);
28780     if (count) {
28781       if (count === 1) {
28782         optionsMap.remove(value);
28783         if (value === '') {
28784           self.emptyOption = undefined;
28785         }
28786       } else {
28787         optionsMap.put(value, count - 1);
28788       }
28789     }
28790   };
28791
28792   // Check whether the select control has an option matching the given value
28793   self.hasOption = function(value) {
28794     return !!optionsMap.get(value);
28795   };
28796
28797
28798   self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
28799
28800     if (interpolateValueFn) {
28801       // The value attribute is interpolated
28802       var oldVal;
28803       optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
28804         if (isDefined(oldVal)) {
28805           self.removeOption(oldVal);
28806         }
28807         oldVal = newVal;
28808         self.addOption(newVal, optionElement);
28809       });
28810     } else if (interpolateTextFn) {
28811       // The text content is interpolated
28812       optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
28813         optionAttrs.$set('value', newVal);
28814         if (oldVal !== newVal) {
28815           self.removeOption(oldVal);
28816         }
28817         self.addOption(newVal, optionElement);
28818       });
28819     } else {
28820       // The value attribute is static
28821       self.addOption(optionAttrs.value, optionElement);
28822     }
28823
28824     optionElement.on('$destroy', function() {
28825       self.removeOption(optionAttrs.value);
28826       self.ngModelCtrl.$render();
28827     });
28828   };
28829 }];
28830
28831 /**
28832  * @ngdoc directive
28833  * @name select
28834  * @restrict E
28835  *
28836  * @description
28837  * HTML `SELECT` element with angular data-binding.
28838  *
28839  * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
28840  * between the scope and the `<select>` control (including setting default values).
28841  * Ìt also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
28842  * {@link ngOptions `ngOptions`} directives.
28843  *
28844  * When an item in the `<select>` menu is selected, the value of the selected option will be bound
28845  * to the model identified by the `ngModel` directive. With static or repeated options, this is
28846  * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
28847  * If you want dynamic value attributes, you can use interpolation inside the value attribute.
28848  *
28849  * <div class="alert alert-warning">
28850  * Note that the value of a `select` directive used without `ngOptions` is always a string.
28851  * When the model needs to be bound to a non-string value, you must either explictly convert it
28852  * using a directive (see example below) or use `ngOptions` to specify the set of options.
28853  * This is because an option element can only be bound to string values at present.
28854  * </div>
28855  *
28856  * If the viewValue of `ngModel` does not match any of the options, then the control
28857  * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
28858  *
28859  * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
28860  * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
28861  * option. See example below for demonstration.
28862  *
28863  * <div class="alert alert-info">
28864  * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
28865  * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
28866  * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
28867  * comprehension expression, and additionally in reducing memory and increasing speed by not creating
28868  * a new scope for each repeated instance.
28869  * </div>
28870  *
28871  *
28872  * @param {string} ngModel Assignable angular expression to data-bind to.
28873  * @param {string=} name Property name of the form under which the control is published.
28874  * @param {string=} multiple Allows multiple options to be selected. The selected values will be
28875  *     bound to the model as an array.
28876  * @param {string=} required Sets `required` validation error key if the value is not entered.
28877  * @param {string=} ngRequired Adds required attribute and required validation constraint to
28878  * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
28879  * when you want to data-bind to the required attribute.
28880  * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
28881  *    interaction with the select element.
28882  * @param {string=} ngOptions sets the options that the select is populated with and defines what is
28883  * set on the model on selection. See {@link ngOptions `ngOptions`}.
28884  *
28885  * @example
28886  * ### Simple `select` elements with static options
28887  *
28888  * <example name="static-select" module="staticSelect">
28889  * <file name="index.html">
28890  * <div ng-controller="ExampleController">
28891  *   <form name="myForm">
28892  *     <label for="singleSelect"> Single select: </label><br>
28893  *     <select name="singleSelect" ng-model="data.singleSelect">
28894  *       <option value="option-1">Option 1</option>
28895  *       <option value="option-2">Option 2</option>
28896  *     </select><br>
28897  *
28898  *     <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
28899  *     <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
28900  *       <option value="">---Please select---</option> <!-- not selected / blank option -->
28901  *       <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
28902  *       <option value="option-2">Option 2</option>
28903  *     </select><br>
28904  *     <button ng-click="forceUnknownOption()">Force unknown option</button><br>
28905  *     <tt>singleSelect = {{data.singleSelect}}</tt>
28906  *
28907  *     <hr>
28908  *     <label for="multipleSelect"> Multiple select: </label><br>
28909  *     <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
28910  *       <option value="option-1">Option 1</option>
28911  *       <option value="option-2">Option 2</option>
28912  *       <option value="option-3">Option 3</option>
28913  *     </select><br>
28914  *     <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
28915  *   </form>
28916  * </div>
28917  * </file>
28918  * <file name="app.js">
28919  *  angular.module('staticSelect', [])
28920  *    .controller('ExampleController', ['$scope', function($scope) {
28921  *      $scope.data = {
28922  *       singleSelect: null,
28923  *       multipleSelect: [],
28924  *       option1: 'option-1',
28925  *      };
28926  *
28927  *      $scope.forceUnknownOption = function() {
28928  *        $scope.data.singleSelect = 'nonsense';
28929  *      };
28930  *   }]);
28931  * </file>
28932  *</example>
28933  *
28934  * ### Using `ngRepeat` to generate `select` options
28935  * <example name="ngrepeat-select" module="ngrepeatSelect">
28936  * <file name="index.html">
28937  * <div ng-controller="ExampleController">
28938  *   <form name="myForm">
28939  *     <label for="repeatSelect"> Repeat select: </label>
28940  *     <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
28941  *       <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
28942  *     </select>
28943  *   </form>
28944  *   <hr>
28945  *   <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
28946  * </div>
28947  * </file>
28948  * <file name="app.js">
28949  *  angular.module('ngrepeatSelect', [])
28950  *    .controller('ExampleController', ['$scope', function($scope) {
28951  *      $scope.data = {
28952  *       repeatSelect: null,
28953  *       availableOptions: [
28954  *         {id: '1', name: 'Option A'},
28955  *         {id: '2', name: 'Option B'},
28956  *         {id: '3', name: 'Option C'}
28957  *       ],
28958  *      };
28959  *   }]);
28960  * </file>
28961  *</example>
28962  *
28963  *
28964  * ### Using `select` with `ngOptions` and setting a default value
28965  * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
28966  *
28967  * <example name="select-with-default-values" module="defaultValueSelect">
28968  * <file name="index.html">
28969  * <div ng-controller="ExampleController">
28970  *   <form name="myForm">
28971  *     <label for="mySelect">Make a choice:</label>
28972  *     <select name="mySelect" id="mySelect"
28973  *       ng-options="option.name for option in data.availableOptions track by option.id"
28974  *       ng-model="data.selectedOption"></select>
28975  *   </form>
28976  *   <hr>
28977  *   <tt>option = {{data.selectedOption}}</tt><br/>
28978  * </div>
28979  * </file>
28980  * <file name="app.js">
28981  *  angular.module('defaultValueSelect', [])
28982  *    .controller('ExampleController', ['$scope', function($scope) {
28983  *      $scope.data = {
28984  *       availableOptions: [
28985  *         {id: '1', name: 'Option A'},
28986  *         {id: '2', name: 'Option B'},
28987  *         {id: '3', name: 'Option C'}
28988  *       ],
28989  *       selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
28990  *       };
28991  *   }]);
28992  * </file>
28993  *</example>
28994  *
28995  *
28996  * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
28997  *
28998  * <example name="select-with-non-string-options" module="nonStringSelect">
28999  *   <file name="index.html">
29000  *     <select ng-model="model.id" convert-to-number>
29001  *       <option value="0">Zero</option>
29002  *       <option value="1">One</option>
29003  *       <option value="2">Two</option>
29004  *     </select>
29005  *     {{ model }}
29006  *   </file>
29007  *   <file name="app.js">
29008  *     angular.module('nonStringSelect', [])
29009  *       .run(function($rootScope) {
29010  *         $rootScope.model = { id: 2 };
29011  *       })
29012  *       .directive('convertToNumber', function() {
29013  *         return {
29014  *           require: 'ngModel',
29015  *           link: function(scope, element, attrs, ngModel) {
29016  *             ngModel.$parsers.push(function(val) {
29017  *               return parseInt(val, 10);
29018  *             });
29019  *             ngModel.$formatters.push(function(val) {
29020  *               return '' + val;
29021  *             });
29022  *           }
29023  *         };
29024  *       });
29025  *   </file>
29026  *   <file name="protractor.js" type="protractor">
29027  *     it('should initialize to model', function() {
29028  *       var select = element(by.css('select'));
29029  *       expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
29030  *     });
29031  *   </file>
29032  * </example>
29033  *
29034  */
29035 var selectDirective = function() {
29036
29037   return {
29038     restrict: 'E',
29039     require: ['select', '?ngModel'],
29040     controller: SelectController,
29041     priority: 1,
29042     link: {
29043       pre: selectPreLink
29044     }
29045   };
29046
29047   function selectPreLink(scope, element, attr, ctrls) {
29048
29049       // if ngModel is not defined, we don't need to do anything
29050       var ngModelCtrl = ctrls[1];
29051       if (!ngModelCtrl) return;
29052
29053       var selectCtrl = ctrls[0];
29054
29055       selectCtrl.ngModelCtrl = ngModelCtrl;
29056
29057       // We delegate rendering to the `writeValue` method, which can be changed
29058       // if the select can have multiple selected values or if the options are being
29059       // generated by `ngOptions`
29060       ngModelCtrl.$render = function() {
29061         selectCtrl.writeValue(ngModelCtrl.$viewValue);
29062       };
29063
29064       // When the selected item(s) changes we delegate getting the value of the select control
29065       // to the `readValue` method, which can be changed if the select can have multiple
29066       // selected values or if the options are being generated by `ngOptions`
29067       element.on('change', function() {
29068         scope.$apply(function() {
29069           ngModelCtrl.$setViewValue(selectCtrl.readValue());
29070         });
29071       });
29072
29073       // If the select allows multiple values then we need to modify how we read and write
29074       // values from and to the control; also what it means for the value to be empty and
29075       // we have to add an extra watch since ngModel doesn't work well with arrays - it
29076       // doesn't trigger rendering if only an item in the array changes.
29077       if (attr.multiple) {
29078
29079         // Read value now needs to check each option to see if it is selected
29080         selectCtrl.readValue = function readMultipleValue() {
29081           var array = [];
29082           forEach(element.find('option'), function(option) {
29083             if (option.selected) {
29084               array.push(option.value);
29085             }
29086           });
29087           return array;
29088         };
29089
29090         // Write value now needs to set the selected property of each matching option
29091         selectCtrl.writeValue = function writeMultipleValue(value) {
29092           var items = new HashMap(value);
29093           forEach(element.find('option'), function(option) {
29094             option.selected = isDefined(items.get(option.value));
29095           });
29096         };
29097
29098         // we have to do it on each watch since ngModel watches reference, but
29099         // we need to work of an array, so we need to see if anything was inserted/removed
29100         var lastView, lastViewRef = NaN;
29101         scope.$watch(function selectMultipleWatch() {
29102           if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
29103             lastView = shallowCopy(ngModelCtrl.$viewValue);
29104             ngModelCtrl.$render();
29105           }
29106           lastViewRef = ngModelCtrl.$viewValue;
29107         });
29108
29109         // If we are a multiple select then value is now a collection
29110         // so the meaning of $isEmpty changes
29111         ngModelCtrl.$isEmpty = function(value) {
29112           return !value || value.length === 0;
29113         };
29114
29115       }
29116     }
29117 };
29118
29119
29120 // The option directive is purely designed to communicate the existence (or lack of)
29121 // of dynamically created (and destroyed) option elements to their containing select
29122 // directive via its controller.
29123 var optionDirective = ['$interpolate', function($interpolate) {
29124   return {
29125     restrict: 'E',
29126     priority: 100,
29127     compile: function(element, attr) {
29128
29129       if (isDefined(attr.value)) {
29130         // If the value attribute is defined, check if it contains an interpolation
29131         var interpolateValueFn = $interpolate(attr.value, true);
29132       } else {
29133         // If the value attribute is not defined then we fall back to the
29134         // text content of the option element, which may be interpolated
29135         var interpolateTextFn = $interpolate(element.text(), true);
29136         if (!interpolateTextFn) {
29137           attr.$set('value', element.text());
29138         }
29139       }
29140
29141       return function(scope, element, attr) {
29142
29143         // This is an optimization over using ^^ since we don't want to have to search
29144         // all the way to the root of the DOM for every single option element
29145         var selectCtrlName = '$selectController',
29146             parent = element.parent(),
29147             selectCtrl = parent.data(selectCtrlName) ||
29148               parent.parent().data(selectCtrlName); // in case we are in optgroup
29149
29150         if (selectCtrl) {
29151           selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
29152         }
29153       };
29154     }
29155   };
29156 }];
29157
29158 var styleDirective = valueFn({
29159   restrict: 'E',
29160   terminal: false
29161 });
29162
29163 var requiredDirective = function() {
29164   return {
29165     restrict: 'A',
29166     require: '?ngModel',
29167     link: function(scope, elm, attr, ctrl) {
29168       if (!ctrl) return;
29169       attr.required = true; // force truthy in case we are on non input element
29170
29171       ctrl.$validators.required = function(modelValue, viewValue) {
29172         return !attr.required || !ctrl.$isEmpty(viewValue);
29173       };
29174
29175       attr.$observe('required', function() {
29176         ctrl.$validate();
29177       });
29178     }
29179   };
29180 };
29181
29182
29183 var patternDirective = function() {
29184   return {
29185     restrict: 'A',
29186     require: '?ngModel',
29187     link: function(scope, elm, attr, ctrl) {
29188       if (!ctrl) return;
29189
29190       var regexp, patternExp = attr.ngPattern || attr.pattern;
29191       attr.$observe('pattern', function(regex) {
29192         if (isString(regex) && regex.length > 0) {
29193           regex = new RegExp('^' + regex + '$');
29194         }
29195
29196         if (regex && !regex.test) {
29197           throw minErr('ngPattern')('noregexp',
29198             'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
29199             regex, startingTag(elm));
29200         }
29201
29202         regexp = regex || undefined;
29203         ctrl.$validate();
29204       });
29205
29206       ctrl.$validators.pattern = function(modelValue, viewValue) {
29207         // HTML5 pattern constraint validates the input value, so we validate the viewValue
29208         return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
29209       };
29210     }
29211   };
29212 };
29213
29214
29215 var maxlengthDirective = function() {
29216   return {
29217     restrict: 'A',
29218     require: '?ngModel',
29219     link: function(scope, elm, attr, ctrl) {
29220       if (!ctrl) return;
29221
29222       var maxlength = -1;
29223       attr.$observe('maxlength', function(value) {
29224         var intVal = toInt(value);
29225         maxlength = isNaN(intVal) ? -1 : intVal;
29226         ctrl.$validate();
29227       });
29228       ctrl.$validators.maxlength = function(modelValue, viewValue) {
29229         return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
29230       };
29231     }
29232   };
29233 };
29234
29235 var minlengthDirective = function() {
29236   return {
29237     restrict: 'A',
29238     require: '?ngModel',
29239     link: function(scope, elm, attr, ctrl) {
29240       if (!ctrl) return;
29241
29242       var minlength = 0;
29243       attr.$observe('minlength', function(value) {
29244         minlength = toInt(value) || 0;
29245         ctrl.$validate();
29246       });
29247       ctrl.$validators.minlength = function(modelValue, viewValue) {
29248         return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
29249       };
29250     }
29251   };
29252 };
29253
29254 if (window.angular.bootstrap) {
29255   //AngularJS is already loaded, so we can return here...
29256   console.log('WARNING: Tried to load angular more than once.');
29257   return;
29258 }
29259
29260 //try to bind to jquery now so that one can write jqLite(document).ready()
29261 //but we will rebind on bootstrap again.
29262 bindJQuery();
29263
29264 publishExternalAPI(angular);
29265
29266 angular.module("ngLocale", [], ["$provide", function($provide) {
29267 var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
29268 function getDecimals(n) {
29269   n = n + '';
29270   var i = n.indexOf('.');
29271   return (i == -1) ? 0 : n.length - i - 1;
29272 }
29273
29274 function getVF(n, opt_precision) {
29275   var v = opt_precision;
29276
29277   if (undefined === v) {
29278     v = Math.min(getDecimals(n), 3);
29279   }
29280
29281   var base = Math.pow(10, v);
29282   var f = ((n * base) | 0) % base;
29283   return {v: v, f: f};
29284 }
29285
29286 $provide.value("$locale", {
29287   "DATETIME_FORMATS": {
29288     "AMPMS": [
29289       "AM",
29290       "PM"
29291     ],
29292     "DAY": [
29293       "Sunday",
29294       "Monday",
29295       "Tuesday",
29296       "Wednesday",
29297       "Thursday",
29298       "Friday",
29299       "Saturday"
29300     ],
29301     "ERANAMES": [
29302       "Before Christ",
29303       "Anno Domini"
29304     ],
29305     "ERAS": [
29306       "BC",
29307       "AD"
29308     ],
29309     "FIRSTDAYOFWEEK": 6,
29310     "MONTH": [
29311       "January",
29312       "February",
29313       "March",
29314       "April",
29315       "May",
29316       "June",
29317       "July",
29318       "August",
29319       "September",
29320       "October",
29321       "November",
29322       "December"
29323     ],
29324     "SHORTDAY": [
29325       "Sun",
29326       "Mon",
29327       "Tue",
29328       "Wed",
29329       "Thu",
29330       "Fri",
29331       "Sat"
29332     ],
29333     "SHORTMONTH": [
29334       "Jan",
29335       "Feb",
29336       "Mar",
29337       "Apr",
29338       "May",
29339       "Jun",
29340       "Jul",
29341       "Aug",
29342       "Sep",
29343       "Oct",
29344       "Nov",
29345       "Dec"
29346     ],
29347     "WEEKENDRANGE": [
29348       5,
29349       6
29350     ],
29351     "fullDate": "EEEE, MMMM d, y",
29352     "longDate": "MMMM d, y",
29353     "medium": "MMM d, y h:mm:ss a",
29354     "mediumDate": "MMM d, y",
29355     "mediumTime": "h:mm:ss a",
29356     "short": "M/d/yy h:mm a",
29357     "shortDate": "M/d/yy",
29358     "shortTime": "h:mm a"
29359   },
29360   "NUMBER_FORMATS": {
29361     "CURRENCY_SYM": "$",
29362     "DECIMAL_SEP": ".",
29363     "GROUP_SEP": ",",
29364     "PATTERNS": [
29365       {
29366         "gSize": 3,
29367         "lgSize": 3,
29368         "maxFrac": 3,
29369         "minFrac": 0,
29370         "minInt": 1,
29371         "negPre": "-",
29372         "negSuf": "",
29373         "posPre": "",
29374         "posSuf": ""
29375       },
29376       {
29377         "gSize": 3,
29378         "lgSize": 3,
29379         "maxFrac": 2,
29380         "minFrac": 2,
29381         "minInt": 1,
29382         "negPre": "-\u00a4",
29383         "negSuf": "",
29384         "posPre": "\u00a4",
29385         "posSuf": ""
29386       }
29387     ]
29388   },
29389   "id": "en-us",
29390   "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;}
29391 });
29392 }]);
29393
29394   jqLite(document).ready(function() {
29395     angularInit(document, bootstrap);
29396   });
29397
29398 })(window, document);
29399
29400 !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');