Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / webapp / app / fusion / external / angular-1.5 / angular.js
1 /**
2  * @license AngularJS v1.5.0
3  * (c) 2010-2016 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/' +
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 var hasOwnProperty = Object.prototype.hasOwnProperty;
192
193 var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
194 var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
195
196
197 var manualLowercase = function(s) {
198   /* jshint bitwise: false */
199   return isString(s)
200       ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
201       : s;
202 };
203 var manualUppercase = function(s) {
204   /* jshint bitwise: false */
205   return isString(s)
206       ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
207       : s;
208 };
209
210
211 // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
212 // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
213 // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
214 if ('i' !== 'I'.toLowerCase()) {
215   lowercase = manualLowercase;
216   uppercase = manualUppercase;
217 }
218
219
220 var
221     msie,             // holds major version number for IE, or NaN if UA is not IE.
222     jqLite,           // delay binding since jQuery could be loaded after us.
223     jQuery,           // delay binding
224     slice             = [].slice,
225     splice            = [].splice,
226     push              = [].push,
227     toString          = Object.prototype.toString,
228     getPrototypeOf    = Object.getPrototypeOf,
229     ngMinErr          = minErr('ng'),
230
231     /** @name angular */
232     angular           = window.angular || (window.angular = {}),
233     angularModule,
234     uid               = 0;
235
236 /**
237  * documentMode is an IE-only property
238  * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
239  */
240 msie = document.documentMode;
241
242
243 /**
244  * @private
245  * @param {*} obj
246  * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
247  *                   String ...)
248  */
249 function isArrayLike(obj) {
250
251   // `null`, `undefined` and `window` are not array-like
252   if (obj == null || isWindow(obj)) return false;
253
254   // arrays, strings and jQuery/jqLite objects are array like
255   // * jqLite is either the jQuery or jqLite constructor function
256   // * we have to check the existence of jqLite first as this method is called
257   //   via the forEach method when constructing the jqLite object in the first place
258   if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
259
260   // Support: iOS 8.2 (not reproducible in simulator)
261   // "length" in obj used to prevent JIT error (gh-11508)
262   var length = "length" in Object(obj) && obj.length;
263
264   // NodeList objects (with `item` method) and
265   // other objects with suitable length characteristics are array-like
266   return isNumber(length) &&
267     (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item == 'function');
268
269 }
270
271 /**
272  * @ngdoc function
273  * @name angular.forEach
274  * @module ng
275  * @kind function
276  *
277  * @description
278  * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
279  * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
280  * is the value of an object property or an array element, `key` is the object property key or
281  * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
282  *
283  * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
284  * using the `hasOwnProperty` method.
285  *
286  * Unlike ES262's
287  * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
288  * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
289  * return the value provided.
290  *
291    ```js
292      var values = {name: 'misko', gender: 'male'};
293      var log = [];
294      angular.forEach(values, function(value, key) {
295        this.push(key + ': ' + value);
296      }, log);
297      expect(log).toEqual(['name: misko', 'gender: male']);
298    ```
299  *
300  * @param {Object|Array} obj Object to iterate over.
301  * @param {Function} iterator Iterator function.
302  * @param {Object=} context Object to become context (`this`) for the iterator function.
303  * @returns {Object|Array} Reference to `obj`.
304  */
305
306 function forEach(obj, iterator, context) {
307   var key, length;
308   if (obj) {
309     if (isFunction(obj)) {
310       for (key in obj) {
311         // Need to check if hasOwnProperty exists,
312         // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
313         if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
314           iterator.call(context, obj[key], key, obj);
315         }
316       }
317     } else if (isArray(obj) || isArrayLike(obj)) {
318       var isPrimitive = typeof obj !== 'object';
319       for (key = 0, length = obj.length; key < length; key++) {
320         if (isPrimitive || key in obj) {
321           iterator.call(context, obj[key], key, obj);
322         }
323       }
324     } else if (obj.forEach && obj.forEach !== forEach) {
325         obj.forEach(iterator, context, obj);
326     } else if (isBlankObject(obj)) {
327       // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
328       for (key in obj) {
329         iterator.call(context, obj[key], key, obj);
330       }
331     } else if (typeof obj.hasOwnProperty === 'function') {
332       // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
333       for (key in obj) {
334         if (obj.hasOwnProperty(key)) {
335           iterator.call(context, obj[key], key, obj);
336         }
337       }
338     } else {
339       // Slow path for objects which do not have a method `hasOwnProperty`
340       for (key in obj) {
341         if (hasOwnProperty.call(obj, key)) {
342           iterator.call(context, obj[key], key, obj);
343         }
344       }
345     }
346   }
347   return obj;
348 }
349
350 function forEachSorted(obj, iterator, context) {
351   var keys = Object.keys(obj).sort();
352   for (var i = 0; i < keys.length; i++) {
353     iterator.call(context, obj[keys[i]], keys[i]);
354   }
355   return keys;
356 }
357
358
359 /**
360  * when using forEach the params are value, key, but it is often useful to have key, value.
361  * @param {function(string, *)} iteratorFn
362  * @returns {function(*, string)}
363  */
364 function reverseParams(iteratorFn) {
365   return function(value, key) {iteratorFn(key, value);};
366 }
367
368 /**
369  * A consistent way of creating unique IDs in angular.
370  *
371  * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
372  * we hit number precision issues in JavaScript.
373  *
374  * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
375  *
376  * @returns {number} an unique alpha-numeric string
377  */
378 function nextUid() {
379   return ++uid;
380 }
381
382
383 /**
384  * Set or clear the hashkey for an object.
385  * @param obj object
386  * @param h the hashkey (!truthy to delete the hashkey)
387  */
388 function setHashKey(obj, h) {
389   if (h) {
390     obj.$$hashKey = h;
391   } else {
392     delete obj.$$hashKey;
393   }
394 }
395
396
397 function baseExtend(dst, objs, deep) {
398   var h = dst.$$hashKey;
399
400   for (var i = 0, ii = objs.length; i < ii; ++i) {
401     var obj = objs[i];
402     if (!isObject(obj) && !isFunction(obj)) continue;
403     var keys = Object.keys(obj);
404     for (var j = 0, jj = keys.length; j < jj; j++) {
405       var key = keys[j];
406       var src = obj[key];
407
408       if (deep && isObject(src)) {
409         if (isDate(src)) {
410           dst[key] = new Date(src.valueOf());
411         } else if (isRegExp(src)) {
412           dst[key] = new RegExp(src);
413         } else if (src.nodeName) {
414           dst[key] = src.cloneNode(true);
415         } else if (isElement(src)) {
416           dst[key] = src.clone();
417         } else {
418           if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
419           baseExtend(dst[key], [src], true);
420         }
421       } else {
422         dst[key] = src;
423       }
424     }
425   }
426
427   setHashKey(dst, h);
428   return dst;
429 }
430
431 /**
432  * @ngdoc function
433  * @name angular.extend
434  * @module ng
435  * @kind function
436  *
437  * @description
438  * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
439  * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
440  * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
441  *
442  * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
443  * {@link angular.merge} for this.
444  *
445  * @param {Object} dst Destination object.
446  * @param {...Object} src Source object(s).
447  * @returns {Object} Reference to `dst`.
448  */
449 function extend(dst) {
450   return baseExtend(dst, slice.call(arguments, 1), false);
451 }
452
453
454 /**
455 * @ngdoc function
456 * @name angular.merge
457 * @module ng
458 * @kind function
459 *
460 * @description
461 * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
462 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
463 * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
464 *
465 * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
466 * objects, performing a deep copy.
467 *
468 * @param {Object} dst Destination object.
469 * @param {...Object} src Source object(s).
470 * @returns {Object} Reference to `dst`.
471 */
472 function merge(dst) {
473   return baseExtend(dst, slice.call(arguments, 1), true);
474 }
475
476
477
478 function toInt(str) {
479   return parseInt(str, 10);
480 }
481
482
483 function inherit(parent, extra) {
484   return extend(Object.create(parent), extra);
485 }
486
487 /**
488  * @ngdoc function
489  * @name angular.noop
490  * @module ng
491  * @kind function
492  *
493  * @description
494  * A function that performs no operations. This function can be useful when writing code in the
495  * functional style.
496    ```js
497      function foo(callback) {
498        var result = calculateResult();
499        (callback || angular.noop)(result);
500      }
501    ```
502  */
503 function noop() {}
504 noop.$inject = [];
505
506
507 /**
508  * @ngdoc function
509  * @name angular.identity
510  * @module ng
511  * @kind function
512  *
513  * @description
514  * A function that returns its first argument. This function is useful when writing code in the
515  * functional style.
516  *
517    ```js
518      function transformer(transformationFn, value) {
519        return (transformationFn || angular.identity)(value);
520      };
521    ```
522   * @param {*} value to be returned.
523   * @returns {*} the value passed in.
524  */
525 function identity($) {return $;}
526 identity.$inject = [];
527
528
529 function valueFn(value) {return function() {return value;};}
530
531 function hasCustomToString(obj) {
532   return isFunction(obj.toString) && obj.toString !== toString;
533 }
534
535
536 /**
537  * @ngdoc function
538  * @name angular.isUndefined
539  * @module ng
540  * @kind function
541  *
542  * @description
543  * Determines if a reference is undefined.
544  *
545  * @param {*} value Reference to check.
546  * @returns {boolean} True if `value` is undefined.
547  */
548 function isUndefined(value) {return typeof value === 'undefined';}
549
550
551 /**
552  * @ngdoc function
553  * @name angular.isDefined
554  * @module ng
555  * @kind function
556  *
557  * @description
558  * Determines if a reference is defined.
559  *
560  * @param {*} value Reference to check.
561  * @returns {boolean} True if `value` is defined.
562  */
563 function isDefined(value) {return typeof value !== 'undefined';}
564
565
566 /**
567  * @ngdoc function
568  * @name angular.isObject
569  * @module ng
570  * @kind function
571  *
572  * @description
573  * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
574  * considered to be objects. Note that JavaScript arrays are objects.
575  *
576  * @param {*} value Reference to check.
577  * @returns {boolean} True if `value` is an `Object` but not `null`.
578  */
579 function isObject(value) {
580   // http://jsperf.com/isobject4
581   return value !== null && typeof value === 'object';
582 }
583
584
585 /**
586  * Determine if a value is an object with a null prototype
587  *
588  * @returns {boolean} True if `value` is an `Object` with a null prototype
589  */
590 function isBlankObject(value) {
591   return value !== null && typeof value === 'object' && !getPrototypeOf(value);
592 }
593
594
595 /**
596  * @ngdoc function
597  * @name angular.isString
598  * @module ng
599  * @kind function
600  *
601  * @description
602  * Determines if a reference is a `String`.
603  *
604  * @param {*} value Reference to check.
605  * @returns {boolean} True if `value` is a `String`.
606  */
607 function isString(value) {return typeof value === 'string';}
608
609
610 /**
611  * @ngdoc function
612  * @name angular.isNumber
613  * @module ng
614  * @kind function
615  *
616  * @description
617  * Determines if a reference is a `Number`.
618  *
619  * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
620  *
621  * If you wish to exclude these then you can use the native
622  * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
623  * method.
624  *
625  * @param {*} value Reference to check.
626  * @returns {boolean} True if `value` is a `Number`.
627  */
628 function isNumber(value) {return typeof value === 'number';}
629
630
631 /**
632  * @ngdoc function
633  * @name angular.isDate
634  * @module ng
635  * @kind function
636  *
637  * @description
638  * Determines if a value is a date.
639  *
640  * @param {*} value Reference to check.
641  * @returns {boolean} True if `value` is a `Date`.
642  */
643 function isDate(value) {
644   return toString.call(value) === '[object Date]';
645 }
646
647
648 /**
649  * @ngdoc function
650  * @name angular.isArray
651  * @module ng
652  * @kind function
653  *
654  * @description
655  * Determines if a reference is an `Array`.
656  *
657  * @param {*} value Reference to check.
658  * @returns {boolean} True if `value` is an `Array`.
659  */
660 var isArray = Array.isArray;
661
662 /**
663  * @ngdoc function
664  * @name angular.isFunction
665  * @module ng
666  * @kind function
667  *
668  * @description
669  * Determines if a reference is a `Function`.
670  *
671  * @param {*} value Reference to check.
672  * @returns {boolean} True if `value` is a `Function`.
673  */
674 function isFunction(value) {return typeof value === 'function';}
675
676
677 /**
678  * Determines if a value is a regular expression object.
679  *
680  * @private
681  * @param {*} value Reference to check.
682  * @returns {boolean} True if `value` is a `RegExp`.
683  */
684 function isRegExp(value) {
685   return toString.call(value) === '[object RegExp]';
686 }
687
688
689 /**
690  * Checks if `obj` is a window object.
691  *
692  * @private
693  * @param {*} obj Object to check
694  * @returns {boolean} True if `obj` is a window obj.
695  */
696 function isWindow(obj) {
697   return obj && obj.window === obj;
698 }
699
700
701 function isScope(obj) {
702   return obj && obj.$evalAsync && obj.$watch;
703 }
704
705
706 function isFile(obj) {
707   return toString.call(obj) === '[object File]';
708 }
709
710
711 function isFormData(obj) {
712   return toString.call(obj) === '[object FormData]';
713 }
714
715
716 function isBlob(obj) {
717   return toString.call(obj) === '[object Blob]';
718 }
719
720
721 function isBoolean(value) {
722   return typeof value === 'boolean';
723 }
724
725
726 function isPromiseLike(obj) {
727   return obj && isFunction(obj.then);
728 }
729
730
731 var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
732 function isTypedArray(value) {
733   return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
734 }
735
736 function isArrayBuffer(obj) {
737   return toString.call(obj) === '[object ArrayBuffer]';
738 }
739
740
741 var trim = function(value) {
742   return isString(value) ? value.trim() : value;
743 };
744
745 // Copied from:
746 // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
747 // Prereq: s is a string.
748 var escapeForRegexp = function(s) {
749   return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
750            replace(/\x08/g, '\\x08');
751 };
752
753
754 /**
755  * @ngdoc function
756  * @name angular.isElement
757  * @module ng
758  * @kind function
759  *
760  * @description
761  * Determines if a reference is a DOM element (or wrapped jQuery element).
762  *
763  * @param {*} value Reference to check.
764  * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
765  */
766 function isElement(node) {
767   return !!(node &&
768     (node.nodeName  // we are a direct element
769     || (node.prop && node.attr && node.find)));  // we have an on and find method part of jQuery API
770 }
771
772 /**
773  * @param str 'key1,key2,...'
774  * @returns {object} in the form of {key1:true, key2:true, ...}
775  */
776 function makeMap(str) {
777   var obj = {}, items = str.split(','), i;
778   for (i = 0; i < items.length; i++) {
779     obj[items[i]] = true;
780   }
781   return obj;
782 }
783
784
785 function nodeName_(element) {
786   return lowercase(element.nodeName || (element[0] && element[0].nodeName));
787 }
788
789 function includes(array, obj) {
790   return Array.prototype.indexOf.call(array, obj) != -1;
791 }
792
793 function arrayRemove(array, value) {
794   var index = array.indexOf(value);
795   if (index >= 0) {
796     array.splice(index, 1);
797   }
798   return index;
799 }
800
801 /**
802  * @ngdoc function
803  * @name angular.copy
804  * @module ng
805  * @kind function
806  *
807  * @description
808  * Creates a deep copy of `source`, which should be an object or an array.
809  *
810  * * If no destination is supplied, a copy of the object or array is created.
811  * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
812  *   are deleted and then all elements/properties from the source are copied to it.
813  * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
814  * * If `source` is identical to 'destination' an exception will be thrown.
815  *
816  * @param {*} source The source that will be used to make a copy.
817  *                   Can be any type, including primitives, `null`, and `undefined`.
818  * @param {(Object|Array)=} destination Destination into which the source is copied. If
819  *     provided, must be of the same type as `source`.
820  * @returns {*} The copy or updated `destination`, if `destination` was specified.
821  *
822  * @example
823  <example module="copyExample">
824  <file name="index.html">
825  <div ng-controller="ExampleController">
826  <form novalidate class="simple-form">
827  Name: <input type="text" ng-model="user.name" /><br />
828  E-mail: <input type="email" ng-model="user.email" /><br />
829  Gender: <input type="radio" ng-model="user.gender" value="male" />male
830  <input type="radio" ng-model="user.gender" value="female" />female<br />
831  <button ng-click="reset()">RESET</button>
832  <button ng-click="update(user)">SAVE</button>
833  </form>
834  <pre>form = {{user | json}}</pre>
835  <pre>master = {{master | json}}</pre>
836  </div>
837
838  <script>
839   angular.module('copyExample', [])
840     .controller('ExampleController', ['$scope', function($scope) {
841       $scope.master= {};
842
843       $scope.update = function(user) {
844         // Example with 1 argument
845         $scope.master= angular.copy(user);
846       };
847
848       $scope.reset = function() {
849         // Example with 2 arguments
850         angular.copy($scope.master, $scope.user);
851       };
852
853       $scope.reset();
854     }]);
855  </script>
856  </file>
857  </example>
858  */
859 function copy(source, destination) {
860   var stackSource = [];
861   var stackDest = [];
862
863   if (destination) {
864     if (isTypedArray(destination) || isArrayBuffer(destination)) {
865       throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
866     }
867     if (source === destination) {
868       throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
869     }
870
871     // Empty the destination object
872     if (isArray(destination)) {
873       destination.length = 0;
874     } else {
875       forEach(destination, function(value, key) {
876         if (key !== '$$hashKey') {
877           delete destination[key];
878         }
879       });
880     }
881
882     stackSource.push(source);
883     stackDest.push(destination);
884     return copyRecurse(source, destination);
885   }
886
887   return copyElement(source);
888
889   function copyRecurse(source, destination) {
890     var h = destination.$$hashKey;
891     var result, key;
892     if (isArray(source)) {
893       for (var i = 0, ii = source.length; i < ii; i++) {
894         destination.push(copyElement(source[i]));
895       }
896     } else if (isBlankObject(source)) {
897       // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
898       for (key in source) {
899         destination[key] = copyElement(source[key]);
900       }
901     } else if (source && typeof source.hasOwnProperty === 'function') {
902       // Slow path, which must rely on hasOwnProperty
903       for (key in source) {
904         if (source.hasOwnProperty(key)) {
905           destination[key] = copyElement(source[key]);
906         }
907       }
908     } else {
909       // Slowest path --- hasOwnProperty can't be called as a method
910       for (key in source) {
911         if (hasOwnProperty.call(source, key)) {
912           destination[key] = copyElement(source[key]);
913         }
914       }
915     }
916     setHashKey(destination, h);
917     return destination;
918   }
919
920   function copyElement(source) {
921     // Simple values
922     if (!isObject(source)) {
923       return source;
924     }
925
926     // Already copied values
927     var index = stackSource.indexOf(source);
928     if (index !== -1) {
929       return stackDest[index];
930     }
931
932     if (isWindow(source) || isScope(source)) {
933       throw ngMinErr('cpws',
934         "Can't copy! Making copies of Window or Scope instances is not supported.");
935     }
936
937     var needsRecurse = false;
938     var destination = copyType(source);
939
940     if (destination === undefined) {
941       destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
942       needsRecurse = true;
943     }
944
945     stackSource.push(source);
946     stackDest.push(destination);
947
948     return needsRecurse
949       ? copyRecurse(source, destination)
950       : destination;
951   }
952
953   function copyType(source) {
954     switch (toString.call(source)) {
955       case '[object Int8Array]':
956       case '[object Int16Array]':
957       case '[object Int32Array]':
958       case '[object Float32Array]':
959       case '[object Float64Array]':
960       case '[object Uint8Array]':
961       case '[object Uint8ClampedArray]':
962       case '[object Uint16Array]':
963       case '[object Uint32Array]':
964         return new source.constructor(copyElement(source.buffer));
965
966       case '[object ArrayBuffer]':
967         //Support: IE10
968         if (!source.slice) {
969           var copied = new ArrayBuffer(source.byteLength);
970           new Uint8Array(copied).set(new Uint8Array(source));
971           return copied;
972         }
973         return source.slice(0);
974
975       case '[object Boolean]':
976       case '[object Number]':
977       case '[object String]':
978       case '[object Date]':
979         return new source.constructor(source.valueOf());
980
981       case '[object RegExp]':
982         var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
983         re.lastIndex = source.lastIndex;
984         return re;
985     }
986
987     if (isFunction(source.cloneNode)) {
988       return source.cloneNode(true);
989     }
990   }
991 }
992
993 /**
994  * Creates a shallow copy of an object, an array or a primitive.
995  *
996  * Assumes that there are no proto properties for objects.
997  */
998 function shallowCopy(src, dst) {
999   if (isArray(src)) {
1000     dst = dst || [];
1001
1002     for (var i = 0, ii = src.length; i < ii; i++) {
1003       dst[i] = src[i];
1004     }
1005   } else if (isObject(src)) {
1006     dst = dst || {};
1007
1008     for (var key in src) {
1009       if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
1010         dst[key] = src[key];
1011       }
1012     }
1013   }
1014
1015   return dst || src;
1016 }
1017
1018
1019 /**
1020  * @ngdoc function
1021  * @name angular.equals
1022  * @module ng
1023  * @kind function
1024  *
1025  * @description
1026  * Determines if two objects or two values are equivalent. Supports value types, regular
1027  * expressions, arrays and objects.
1028  *
1029  * Two objects or values are considered equivalent if at least one of the following is true:
1030  *
1031  * * Both objects or values pass `===` comparison.
1032  * * Both objects or values are of the same type and all of their properties are equal by
1033  *   comparing them with `angular.equals`.
1034  * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
1035  * * Both values represent the same regular expression (In JavaScript,
1036  *   /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
1037  *   representation matches).
1038  *
1039  * During a property comparison, properties of `function` type and properties with names
1040  * that begin with `$` are ignored.
1041  *
1042  * Scope and DOMWindow objects are being compared only by identify (`===`).
1043  *
1044  * @param {*} o1 Object or value to compare.
1045  * @param {*} o2 Object or value to compare.
1046  * @returns {boolean} True if arguments are equal.
1047  */
1048 function equals(o1, o2) {
1049   if (o1 === o2) return true;
1050   if (o1 === null || o2 === null) return false;
1051   if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
1052   var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
1053   if (t1 == t2 && t1 == 'object') {
1054     if (isArray(o1)) {
1055       if (!isArray(o2)) return false;
1056       if ((length = o1.length) == o2.length) {
1057         for (key = 0; key < length; key++) {
1058           if (!equals(o1[key], o2[key])) return false;
1059         }
1060         return true;
1061       }
1062     } else if (isDate(o1)) {
1063       if (!isDate(o2)) return false;
1064       return equals(o1.getTime(), o2.getTime());
1065     } else if (isRegExp(o1)) {
1066       if (!isRegExp(o2)) return false;
1067       return o1.toString() == o2.toString();
1068     } else {
1069       if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
1070         isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
1071       keySet = createMap();
1072       for (key in o1) {
1073         if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
1074         if (!equals(o1[key], o2[key])) return false;
1075         keySet[key] = true;
1076       }
1077       for (key in o2) {
1078         if (!(key in keySet) &&
1079             key.charAt(0) !== '$' &&
1080             isDefined(o2[key]) &&
1081             !isFunction(o2[key])) return false;
1082       }
1083       return true;
1084     }
1085   }
1086   return false;
1087 }
1088
1089 var csp = function() {
1090   if (!isDefined(csp.rules)) {
1091
1092
1093     var ngCspElement = (document.querySelector('[ng-csp]') ||
1094                     document.querySelector('[data-ng-csp]'));
1095
1096     if (ngCspElement) {
1097       var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
1098                     ngCspElement.getAttribute('data-ng-csp');
1099       csp.rules = {
1100         noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
1101         noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
1102       };
1103     } else {
1104       csp.rules = {
1105         noUnsafeEval: noUnsafeEval(),
1106         noInlineStyle: false
1107       };
1108     }
1109   }
1110
1111   return csp.rules;
1112
1113   function noUnsafeEval() {
1114     try {
1115       /* jshint -W031, -W054 */
1116       new Function('');
1117       /* jshint +W031, +W054 */
1118       return false;
1119     } catch (e) {
1120       return true;
1121     }
1122   }
1123 };
1124
1125 /**
1126  * @ngdoc directive
1127  * @module ng
1128  * @name ngJq
1129  *
1130  * @element ANY
1131  * @param {string=} ngJq the name of the library available under `window`
1132  * to be used for angular.element
1133  * @description
1134  * Use this directive to force the angular.element library.  This should be
1135  * used to force either jqLite by leaving ng-jq blank or setting the name of
1136  * the jquery variable under window (eg. jQuery).
1137  *
1138  * Since angular looks for this directive when it is loaded (doesn't wait for the
1139  * DOMContentLoaded event), it must be placed on an element that comes before the script
1140  * which loads angular. Also, only the first instance of `ng-jq` will be used and all
1141  * others ignored.
1142  *
1143  * @example
1144  * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
1145  ```html
1146  <!doctype html>
1147  <html ng-app ng-jq>
1148  ...
1149  ...
1150  </html>
1151  ```
1152  * @example
1153  * This example shows how to use a jQuery based library of a different name.
1154  * The library name must be available at the top most 'window'.
1155  ```html
1156  <!doctype html>
1157  <html ng-app ng-jq="jQueryLib">
1158  ...
1159  ...
1160  </html>
1161  ```
1162  */
1163 var jq = function() {
1164   if (isDefined(jq.name_)) return jq.name_;
1165   var el;
1166   var i, ii = ngAttrPrefixes.length, prefix, name;
1167   for (i = 0; i < ii; ++i) {
1168     prefix = ngAttrPrefixes[i];
1169     if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
1170       name = el.getAttribute(prefix + 'jq');
1171       break;
1172     }
1173   }
1174
1175   return (jq.name_ = name);
1176 };
1177
1178 function concat(array1, array2, index) {
1179   return array1.concat(slice.call(array2, index));
1180 }
1181
1182 function sliceArgs(args, startIndex) {
1183   return slice.call(args, startIndex || 0);
1184 }
1185
1186
1187 /* jshint -W101 */
1188 /**
1189  * @ngdoc function
1190  * @name angular.bind
1191  * @module ng
1192  * @kind function
1193  *
1194  * @description
1195  * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
1196  * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
1197  * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
1198  * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
1199  *
1200  * @param {Object} self Context which `fn` should be evaluated in.
1201  * @param {function()} fn Function to be bound.
1202  * @param {...*} args Optional arguments to be prebound to the `fn` function call.
1203  * @returns {function()} Function that wraps the `fn` with all the specified bindings.
1204  */
1205 /* jshint +W101 */
1206 function bind(self, fn) {
1207   var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
1208   if (isFunction(fn) && !(fn instanceof RegExp)) {
1209     return curryArgs.length
1210       ? function() {
1211           return arguments.length
1212             ? fn.apply(self, concat(curryArgs, arguments, 0))
1213             : fn.apply(self, curryArgs);
1214         }
1215       : function() {
1216           return arguments.length
1217             ? fn.apply(self, arguments)
1218             : fn.call(self);
1219         };
1220   } else {
1221     // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
1222     return fn;
1223   }
1224 }
1225
1226
1227 function toJsonReplacer(key, value) {
1228   var val = value;
1229
1230   if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
1231     val = undefined;
1232   } else if (isWindow(value)) {
1233     val = '$WINDOW';
1234   } else if (value &&  document === value) {
1235     val = '$DOCUMENT';
1236   } else if (isScope(value)) {
1237     val = '$SCOPE';
1238   }
1239
1240   return val;
1241 }
1242
1243
1244 /**
1245  * @ngdoc function
1246  * @name angular.toJson
1247  * @module ng
1248  * @kind function
1249  *
1250  * @description
1251  * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
1252  * stripped since angular uses this notation internally.
1253  *
1254  * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
1255  * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
1256  *    If set to an integer, the JSON output will contain that many spaces per indentation.
1257  * @returns {string|undefined} JSON-ified string representing `obj`.
1258  */
1259 function toJson(obj, pretty) {
1260   if (isUndefined(obj)) return undefined;
1261   if (!isNumber(pretty)) {
1262     pretty = pretty ? 2 : null;
1263   }
1264   return JSON.stringify(obj, toJsonReplacer, pretty);
1265 }
1266
1267
1268 /**
1269  * @ngdoc function
1270  * @name angular.fromJson
1271  * @module ng
1272  * @kind function
1273  *
1274  * @description
1275  * Deserializes a JSON string.
1276  *
1277  * @param {string} json JSON string to deserialize.
1278  * @returns {Object|Array|string|number} Deserialized JSON string.
1279  */
1280 function fromJson(json) {
1281   return isString(json)
1282       ? JSON.parse(json)
1283       : json;
1284 }
1285
1286
1287 var ALL_COLONS = /:/g;
1288 function timezoneToOffset(timezone, fallback) {
1289   // IE/Edge do not "understand" colon (`:`) in timezone
1290   timezone = timezone.replace(ALL_COLONS, '');
1291   var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
1292   return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
1293 }
1294
1295
1296 function addDateMinutes(date, minutes) {
1297   date = new Date(date.getTime());
1298   date.setMinutes(date.getMinutes() + minutes);
1299   return date;
1300 }
1301
1302
1303 function convertTimezoneToLocal(date, timezone, reverse) {
1304   reverse = reverse ? -1 : 1;
1305   var dateTimezoneOffset = date.getTimezoneOffset();
1306   var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
1307   return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
1308 }
1309
1310
1311 /**
1312  * @returns {string} Returns the string representation of the element.
1313  */
1314 function startingTag(element) {
1315   element = jqLite(element).clone();
1316   try {
1317     // turns out IE does not let you set .html() on elements which
1318     // are not allowed to have children. So we just ignore it.
1319     element.empty();
1320   } catch (e) {}
1321   var elemHtml = jqLite('<div>').append(element).html();
1322   try {
1323     return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
1324         elemHtml.
1325           match(/^(<[^>]+>)/)[1].
1326           replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
1327   } catch (e) {
1328     return lowercase(elemHtml);
1329   }
1330
1331 }
1332
1333
1334 /////////////////////////////////////////////////
1335
1336 /**
1337  * Tries to decode the URI component without throwing an exception.
1338  *
1339  * @private
1340  * @param str value potential URI component to check.
1341  * @returns {boolean} True if `value` can be decoded
1342  * with the decodeURIComponent function.
1343  */
1344 function tryDecodeURIComponent(value) {
1345   try {
1346     return decodeURIComponent(value);
1347   } catch (e) {
1348     // Ignore any invalid uri component
1349   }
1350 }
1351
1352
1353 /**
1354  * Parses an escaped url query string into key-value pairs.
1355  * @returns {Object.<string,boolean|Array>}
1356  */
1357 function parseKeyValue(/**string*/keyValue) {
1358   var obj = {};
1359   forEach((keyValue || "").split('&'), function(keyValue) {
1360     var splitPoint, key, val;
1361     if (keyValue) {
1362       key = keyValue = keyValue.replace(/\+/g,'%20');
1363       splitPoint = keyValue.indexOf('=');
1364       if (splitPoint !== -1) {
1365         key = keyValue.substring(0, splitPoint);
1366         val = keyValue.substring(splitPoint + 1);
1367       }
1368       key = tryDecodeURIComponent(key);
1369       if (isDefined(key)) {
1370         val = isDefined(val) ? tryDecodeURIComponent(val) : true;
1371         if (!hasOwnProperty.call(obj, key)) {
1372           obj[key] = val;
1373         } else if (isArray(obj[key])) {
1374           obj[key].push(val);
1375         } else {
1376           obj[key] = [obj[key],val];
1377         }
1378       }
1379     }
1380   });
1381   return obj;
1382 }
1383
1384 function toKeyValue(obj) {
1385   var parts = [];
1386   forEach(obj, function(value, key) {
1387     if (isArray(value)) {
1388       forEach(value, function(arrayValue) {
1389         parts.push(encodeUriQuery(key, true) +
1390                    (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
1391       });
1392     } else {
1393     parts.push(encodeUriQuery(key, true) +
1394                (value === true ? '' : '=' + encodeUriQuery(value, true)));
1395     }
1396   });
1397   return parts.length ? parts.join('&') : '';
1398 }
1399
1400
1401 /**
1402  * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
1403  * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
1404  * segments:
1405  *    segment       = *pchar
1406  *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
1407  *    pct-encoded   = "%" HEXDIG HEXDIG
1408  *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
1409  *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
1410  *                     / "*" / "+" / "," / ";" / "="
1411  */
1412 function encodeUriSegment(val) {
1413   return encodeUriQuery(val, true).
1414              replace(/%26/gi, '&').
1415              replace(/%3D/gi, '=').
1416              replace(/%2B/gi, '+');
1417 }
1418
1419
1420 /**
1421  * This method is intended for encoding *key* or *value* parts of query component. We need a custom
1422  * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
1423  * encoded per http://tools.ietf.org/html/rfc3986:
1424  *    query       = *( pchar / "/" / "?" )
1425  *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
1426  *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
1427  *    pct-encoded   = "%" HEXDIG HEXDIG
1428  *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
1429  *                     / "*" / "+" / "," / ";" / "="
1430  */
1431 function encodeUriQuery(val, pctEncodeSpaces) {
1432   return encodeURIComponent(val).
1433              replace(/%40/gi, '@').
1434              replace(/%3A/gi, ':').
1435              replace(/%24/g, '$').
1436              replace(/%2C/gi, ',').
1437              replace(/%3B/gi, ';').
1438              replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
1439 }
1440
1441 var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
1442
1443 function getNgAttribute(element, ngAttr) {
1444   var attr, i, ii = ngAttrPrefixes.length;
1445   for (i = 0; i < ii; ++i) {
1446     attr = ngAttrPrefixes[i] + ngAttr;
1447     if (isString(attr = element.getAttribute(attr))) {
1448       return attr;
1449     }
1450   }
1451   return null;
1452 }
1453
1454 /**
1455  * @ngdoc directive
1456  * @name ngApp
1457  * @module ng
1458  *
1459  * @element ANY
1460  * @param {angular.Module} ngApp an optional application
1461  *   {@link angular.module module} name to load.
1462  * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
1463  *   created in "strict-di" mode. This means that the application will fail to invoke functions which
1464  *   do not use explicit function annotation (and are thus unsuitable for minification), as described
1465  *   in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
1466  *   tracking down the root of these bugs.
1467  *
1468  * @description
1469  *
1470  * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
1471  * designates the **root element** of the application and is typically placed near the root element
1472  * of the page - e.g. on the `<body>` or `<html>` tags.
1473  *
1474  * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
1475  * found in the document will be used to define the root element to auto-bootstrap as an
1476  * application. To run multiple applications in an HTML document you must manually bootstrap them using
1477  * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
1478  *
1479  * You can specify an **AngularJS module** to be used as the root module for the application.  This
1480  * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
1481  * should contain the application code needed or have dependencies on other modules that will
1482  * contain the code. See {@link angular.module} for more information.
1483  *
1484  * In the example below if the `ngApp` directive were not placed on the `html` element then the
1485  * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
1486  * would not be resolved to `3`.
1487  *
1488  * `ngApp` is the easiest, and most common way to bootstrap an application.
1489  *
1490  <example module="ngAppDemo">
1491    <file name="index.html">
1492    <div ng-controller="ngAppDemoController">
1493      I can add: {{a}} + {{b}} =  {{ a+b }}
1494    </div>
1495    </file>
1496    <file name="script.js">
1497    angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
1498      $scope.a = 1;
1499      $scope.b = 2;
1500    });
1501    </file>
1502  </example>
1503  *
1504  * Using `ngStrictDi`, you would see something like this:
1505  *
1506  <example ng-app-included="true">
1507    <file name="index.html">
1508    <div ng-app="ngAppStrictDemo" ng-strict-di>
1509        <div ng-controller="GoodController1">
1510            I can add: {{a}} + {{b}} =  {{ a+b }}
1511
1512            <p>This renders because the controller does not fail to
1513               instantiate, by using explicit annotation style (see
1514               script.js for details)
1515            </p>
1516        </div>
1517
1518        <div ng-controller="GoodController2">
1519            Name: <input ng-model="name"><br />
1520            Hello, {{name}}!
1521
1522            <p>This renders because the controller does not fail to
1523               instantiate, by using explicit annotation style
1524               (see script.js for details)
1525            </p>
1526        </div>
1527
1528        <div ng-controller="BadController">
1529            I can add: {{a}} + {{b}} =  {{ a+b }}
1530
1531            <p>The controller could not be instantiated, due to relying
1532               on automatic function annotations (which are disabled in
1533               strict mode). As such, the content of this section is not
1534               interpolated, and there should be an error in your web console.
1535            </p>
1536        </div>
1537    </div>
1538    </file>
1539    <file name="script.js">
1540    angular.module('ngAppStrictDemo', [])
1541      // BadController will fail to instantiate, due to relying on automatic function annotation,
1542      // rather than an explicit annotation
1543      .controller('BadController', function($scope) {
1544        $scope.a = 1;
1545        $scope.b = 2;
1546      })
1547      // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
1548      // due to using explicit annotations using the array style and $inject property, respectively.
1549      .controller('GoodController1', ['$scope', function($scope) {
1550        $scope.a = 1;
1551        $scope.b = 2;
1552      }])
1553      .controller('GoodController2', GoodController2);
1554      function GoodController2($scope) {
1555        $scope.name = "World";
1556      }
1557      GoodController2.$inject = ['$scope'];
1558    </file>
1559    <file name="style.css">
1560    div[ng-controller] {
1561        margin-bottom: 1em;
1562        -webkit-border-radius: 4px;
1563        border-radius: 4px;
1564        border: 1px solid;
1565        padding: .5em;
1566    }
1567    div[ng-controller^=Good] {
1568        border-color: #d6e9c6;
1569        background-color: #dff0d8;
1570        color: #3c763d;
1571    }
1572    div[ng-controller^=Bad] {
1573        border-color: #ebccd1;
1574        background-color: #f2dede;
1575        color: #a94442;
1576        margin-bottom: 0;
1577    }
1578    </file>
1579  </example>
1580  */
1581 function angularInit(element, bootstrap) {
1582   var appElement,
1583       module,
1584       config = {};
1585
1586   // The element `element` has priority over any other element
1587   forEach(ngAttrPrefixes, function(prefix) {
1588     var name = prefix + 'app';
1589
1590     if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
1591       appElement = element;
1592       module = element.getAttribute(name);
1593     }
1594   });
1595   forEach(ngAttrPrefixes, function(prefix) {
1596     var name = prefix + 'app';
1597     var candidate;
1598
1599     if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
1600       appElement = candidate;
1601       module = candidate.getAttribute(name);
1602     }
1603   });
1604   if (appElement) {
1605     config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
1606     bootstrap(appElement, module ? [module] : [], config);
1607   }
1608 }
1609
1610 /**
1611  * @ngdoc function
1612  * @name angular.bootstrap
1613  * @module ng
1614  * @description
1615  * Use this function to manually start up angular application.
1616  *
1617  * See: {@link guide/bootstrap Bootstrap}
1618  *
1619  * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
1620  * They must use {@link ng.directive:ngApp ngApp}.
1621  *
1622  * Angular will detect if it has been loaded into the browser more than once and only allow the
1623  * first loaded script to be bootstrapped and will report a warning to the browser console for
1624  * each of the subsequent scripts. This prevents strange results in applications, where otherwise
1625  * multiple instances of Angular try to work on the DOM.
1626  *
1627  * ```html
1628  * <!doctype html>
1629  * <html>
1630  * <body>
1631  * <div ng-controller="WelcomeController">
1632  *   {{greeting}}
1633  * </div>
1634  *
1635  * <script src="angular.js"></script>
1636  * <script>
1637  *   var app = angular.module('demo', [])
1638  *   .controller('WelcomeController', function($scope) {
1639  *       $scope.greeting = 'Welcome!';
1640  *   });
1641  *   angular.bootstrap(document, ['demo']);
1642  * </script>
1643  * </body>
1644  * </html>
1645  * ```
1646  *
1647  * @param {DOMElement} element DOM element which is the root of angular application.
1648  * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
1649  *     Each item in the array should be the name of a predefined module or a (DI annotated)
1650  *     function that will be invoked by the injector as a `config` block.
1651  *     See: {@link angular.module modules}
1652  * @param {Object=} config an object for defining configuration options for the application. The
1653  *     following keys are supported:
1654  *
1655  * * `strictDi` - disable automatic function annotation for the application. This is meant to
1656  *   assist in finding bugs which break minified code. Defaults to `false`.
1657  *
1658  * @returns {auto.$injector} Returns the newly created injector for this app.
1659  */
1660 function bootstrap(element, modules, config) {
1661   if (!isObject(config)) config = {};
1662   var defaultConfig = {
1663     strictDi: false
1664   };
1665   config = extend(defaultConfig, config);
1666   var doBootstrap = function() {
1667     element = jqLite(element);
1668
1669     if (element.injector()) {
1670       var tag = (element[0] === document) ? 'document' : startingTag(element);
1671       //Encode angle brackets to prevent input from being sanitized to empty string #8683
1672       throw ngMinErr(
1673           'btstrpd',
1674           "App Already Bootstrapped with this Element '{0}'",
1675           tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
1676     }
1677
1678     modules = modules || [];
1679     modules.unshift(['$provide', function($provide) {
1680       $provide.value('$rootElement', element);
1681     }]);
1682
1683     if (config.debugInfoEnabled) {
1684       // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
1685       modules.push(['$compileProvider', function($compileProvider) {
1686         $compileProvider.debugInfoEnabled(true);
1687       }]);
1688     }
1689
1690     modules.unshift('ng');
1691     var injector = createInjector(modules, config.strictDi);
1692     injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
1693        function bootstrapApply(scope, element, compile, injector) {
1694         scope.$apply(function() {
1695           element.data('$injector', injector);
1696           compile(element)(scope);
1697         });
1698       }]
1699     );
1700     return injector;
1701   };
1702
1703   var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
1704   var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
1705
1706   if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
1707     config.debugInfoEnabled = true;
1708     window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
1709   }
1710
1711   if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
1712     return doBootstrap();
1713   }
1714
1715   window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
1716   angular.resumeBootstrap = function(extraModules) {
1717     forEach(extraModules, function(module) {
1718       modules.push(module);
1719     });
1720     return doBootstrap();
1721   };
1722
1723   if (isFunction(angular.resumeDeferredBootstrap)) {
1724     angular.resumeDeferredBootstrap();
1725   }
1726 }
1727
1728 /**
1729  * @ngdoc function
1730  * @name angular.reloadWithDebugInfo
1731  * @module ng
1732  * @description
1733  * Use this function to reload the current application with debug information turned on.
1734  * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
1735  *
1736  * See {@link ng.$compileProvider#debugInfoEnabled} for more.
1737  */
1738 function reloadWithDebugInfo() {
1739   window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
1740   window.location.reload();
1741 }
1742
1743 /**
1744  * @name angular.getTestability
1745  * @module ng
1746  * @description
1747  * Get the testability service for the instance of Angular on the given
1748  * element.
1749  * @param {DOMElement} element DOM element which is the root of angular application.
1750  */
1751 function getTestability(rootElement) {
1752   var injector = angular.element(rootElement).injector();
1753   if (!injector) {
1754     throw ngMinErr('test',
1755       'no injector found for element argument to getTestability');
1756   }
1757   return injector.get('$$testability');
1758 }
1759
1760 var SNAKE_CASE_REGEXP = /[A-Z]/g;
1761 function snake_case(name, separator) {
1762   separator = separator || '_';
1763   return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
1764     return (pos ? separator : '') + letter.toLowerCase();
1765   });
1766 }
1767
1768 var bindJQueryFired = false;
1769 function bindJQuery() {
1770   var originalCleanData;
1771
1772   if (bindJQueryFired) {
1773     return;
1774   }
1775
1776   // bind to jQuery if present;
1777   var jqName = jq();
1778   jQuery = isUndefined(jqName) ? window.jQuery :   // use jQuery (if present)
1779            !jqName             ? undefined     :   // use jqLite
1780                                  window[jqName];   // use jQuery specified by `ngJq`
1781
1782   // Use jQuery if it exists with proper functionality, otherwise default to us.
1783   // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
1784   // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
1785   // versions. It will not work for sure with jQuery <1.7, though.
1786   if (jQuery && jQuery.fn.on) {
1787     jqLite = jQuery;
1788     extend(jQuery.fn, {
1789       scope: JQLitePrototype.scope,
1790       isolateScope: JQLitePrototype.isolateScope,
1791       controller: JQLitePrototype.controller,
1792       injector: JQLitePrototype.injector,
1793       inheritedData: JQLitePrototype.inheritedData
1794     });
1795
1796     // All nodes removed from the DOM via various jQuery APIs like .remove()
1797     // are passed through jQuery.cleanData. Monkey-patch this method to fire
1798     // the $destroy event on all removed nodes.
1799     originalCleanData = jQuery.cleanData;
1800     jQuery.cleanData = function(elems) {
1801       var events;
1802       for (var i = 0, elem; (elem = elems[i]) != null; i++) {
1803         events = jQuery._data(elem, "events");
1804         if (events && events.$destroy) {
1805           jQuery(elem).triggerHandler('$destroy');
1806         }
1807       }
1808       originalCleanData(elems);
1809     };
1810   } else {
1811     jqLite = JQLite;
1812   }
1813
1814   angular.element = jqLite;
1815
1816   // Prevent double-proxying.
1817   bindJQueryFired = true;
1818 }
1819
1820 /**
1821  * throw error if the argument is falsy.
1822  */
1823 function assertArg(arg, name, reason) {
1824   if (!arg) {
1825     throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
1826   }
1827   return arg;
1828 }
1829
1830 function assertArgFn(arg, name, acceptArrayAnnotation) {
1831   if (acceptArrayAnnotation && isArray(arg)) {
1832       arg = arg[arg.length - 1];
1833   }
1834
1835   assertArg(isFunction(arg), name, 'not a function, got ' +
1836       (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
1837   return arg;
1838 }
1839
1840 /**
1841  * throw error if the name given is hasOwnProperty
1842  * @param  {String} name    the name to test
1843  * @param  {String} context the context in which the name is used, such as module or directive
1844  */
1845 function assertNotHasOwnProperty(name, context) {
1846   if (name === 'hasOwnProperty') {
1847     throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
1848   }
1849 }
1850
1851 /**
1852  * Return the value accessible from the object by path. Any undefined traversals are ignored
1853  * @param {Object} obj starting object
1854  * @param {String} path path to traverse
1855  * @param {boolean} [bindFnToScope=true]
1856  * @returns {Object} value as accessible by path
1857  */
1858 //TODO(misko): this function needs to be removed
1859 function getter(obj, path, bindFnToScope) {
1860   if (!path) return obj;
1861   var keys = path.split('.');
1862   var key;
1863   var lastInstance = obj;
1864   var len = keys.length;
1865
1866   for (var i = 0; i < len; i++) {
1867     key = keys[i];
1868     if (obj) {
1869       obj = (lastInstance = obj)[key];
1870     }
1871   }
1872   if (!bindFnToScope && isFunction(obj)) {
1873     return bind(lastInstance, obj);
1874   }
1875   return obj;
1876 }
1877
1878 /**
1879  * Return the DOM siblings between the first and last node in the given array.
1880  * @param {Array} array like object
1881  * @returns {Array} the inputted object or a jqLite collection containing the nodes
1882  */
1883 function getBlockNodes(nodes) {
1884   // TODO(perf): update `nodes` instead of creating a new object?
1885   var node = nodes[0];
1886   var endNode = nodes[nodes.length - 1];
1887   var blockNodes;
1888
1889   for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
1890     if (blockNodes || nodes[i] !== node) {
1891       if (!blockNodes) {
1892         blockNodes = jqLite(slice.call(nodes, 0, i));
1893       }
1894       blockNodes.push(node);
1895     }
1896   }
1897
1898   return blockNodes || nodes;
1899 }
1900
1901
1902 /**
1903  * Creates a new object without a prototype. This object is useful for lookup without having to
1904  * guard against prototypically inherited properties via hasOwnProperty.
1905  *
1906  * Related micro-benchmarks:
1907  * - http://jsperf.com/object-create2
1908  * - http://jsperf.com/proto-map-lookup/2
1909  * - http://jsperf.com/for-in-vs-object-keys2
1910  *
1911  * @returns {Object}
1912  */
1913 function createMap() {
1914   return Object.create(null);
1915 }
1916
1917 var NODE_TYPE_ELEMENT = 1;
1918 var NODE_TYPE_ATTRIBUTE = 2;
1919 var NODE_TYPE_TEXT = 3;
1920 var NODE_TYPE_COMMENT = 8;
1921 var NODE_TYPE_DOCUMENT = 9;
1922 var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
1923
1924 /**
1925  * @ngdoc type
1926  * @name angular.Module
1927  * @module ng
1928  * @description
1929  *
1930  * Interface for configuring angular {@link angular.module modules}.
1931  */
1932
1933 function setupModuleLoader(window) {
1934
1935   var $injectorMinErr = minErr('$injector');
1936   var ngMinErr = minErr('ng');
1937
1938   function ensure(obj, name, factory) {
1939     return obj[name] || (obj[name] = factory());
1940   }
1941
1942   var angular = ensure(window, 'angular', Object);
1943
1944   // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
1945   angular.$$minErr = angular.$$minErr || minErr;
1946
1947   return ensure(angular, 'module', function() {
1948     /** @type {Object.<string, angular.Module>} */
1949     var modules = {};
1950
1951     /**
1952      * @ngdoc function
1953      * @name angular.module
1954      * @module ng
1955      * @description
1956      *
1957      * The `angular.module` is a global place for creating, registering and retrieving Angular
1958      * modules.
1959      * All modules (angular core or 3rd party) that should be available to an application must be
1960      * registered using this mechanism.
1961      *
1962      * Passing one argument retrieves an existing {@link angular.Module},
1963      * whereas passing more than one argument creates a new {@link angular.Module}
1964      *
1965      *
1966      * # Module
1967      *
1968      * A module is a collection of services, directives, controllers, filters, and configuration information.
1969      * `angular.module` is used to configure the {@link auto.$injector $injector}.
1970      *
1971      * ```js
1972      * // Create a new module
1973      * var myModule = angular.module('myModule', []);
1974      *
1975      * // register a new service
1976      * myModule.value('appName', 'MyCoolApp');
1977      *
1978      * // configure existing services inside initialization blocks.
1979      * myModule.config(['$locationProvider', function($locationProvider) {
1980      *   // Configure existing providers
1981      *   $locationProvider.hashPrefix('!');
1982      * }]);
1983      * ```
1984      *
1985      * Then you can create an injector and load your modules like this:
1986      *
1987      * ```js
1988      * var injector = angular.injector(['ng', 'myModule'])
1989      * ```
1990      *
1991      * However it's more likely that you'll just use
1992      * {@link ng.directive:ngApp ngApp} or
1993      * {@link angular.bootstrap} to simplify this process for you.
1994      *
1995      * @param {!string} name The name of the module to create or retrieve.
1996      * @param {!Array.<string>=} requires If specified then new module is being created. If
1997      *        unspecified then the module is being retrieved for further configuration.
1998      * @param {Function=} configFn Optional configuration function for the module. Same as
1999      *        {@link angular.Module#config Module#config()}.
2000      * @returns {angular.Module} new module with the {@link angular.Module} api.
2001      */
2002     return function module(name, requires, configFn) {
2003       var assertNotHasOwnProperty = function(name, context) {
2004         if (name === 'hasOwnProperty') {
2005           throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
2006         }
2007       };
2008
2009       assertNotHasOwnProperty(name, 'module');
2010       if (requires && modules.hasOwnProperty(name)) {
2011         modules[name] = null;
2012       }
2013       return ensure(modules, name, function() {
2014         if (!requires) {
2015           throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
2016              "the module name or forgot to load it. If registering a module ensure that you " +
2017              "specify the dependencies as the second argument.", name);
2018         }
2019
2020         /** @type {!Array.<Array.<*>>} */
2021         var invokeQueue = [];
2022
2023         /** @type {!Array.<Function>} */
2024         var configBlocks = [];
2025
2026         /** @type {!Array.<Function>} */
2027         var runBlocks = [];
2028
2029         var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
2030
2031         /** @type {angular.Module} */
2032         var moduleInstance = {
2033           // Private state
2034           _invokeQueue: invokeQueue,
2035           _configBlocks: configBlocks,
2036           _runBlocks: runBlocks,
2037
2038           /**
2039            * @ngdoc property
2040            * @name angular.Module#requires
2041            * @module ng
2042            *
2043            * @description
2044            * Holds the list of modules which the injector will load before the current module is
2045            * loaded.
2046            */
2047           requires: requires,
2048
2049           /**
2050            * @ngdoc property
2051            * @name angular.Module#name
2052            * @module ng
2053            *
2054            * @description
2055            * Name of the module.
2056            */
2057           name: name,
2058
2059
2060           /**
2061            * @ngdoc method
2062            * @name angular.Module#provider
2063            * @module ng
2064            * @param {string} name service name
2065            * @param {Function} providerType Construction function for creating new instance of the
2066            *                                service.
2067            * @description
2068            * See {@link auto.$provide#provider $provide.provider()}.
2069            */
2070           provider: invokeLaterAndSetModuleName('$provide', 'provider'),
2071
2072           /**
2073            * @ngdoc method
2074            * @name angular.Module#factory
2075            * @module ng
2076            * @param {string} name service name
2077            * @param {Function} providerFunction Function for creating new instance of the service.
2078            * @description
2079            * See {@link auto.$provide#factory $provide.factory()}.
2080            */
2081           factory: invokeLaterAndSetModuleName('$provide', 'factory'),
2082
2083           /**
2084            * @ngdoc method
2085            * @name angular.Module#service
2086            * @module ng
2087            * @param {string} name service name
2088            * @param {Function} constructor A constructor function that will be instantiated.
2089            * @description
2090            * See {@link auto.$provide#service $provide.service()}.
2091            */
2092           service: invokeLaterAndSetModuleName('$provide', 'service'),
2093
2094           /**
2095            * @ngdoc method
2096            * @name angular.Module#value
2097            * @module ng
2098            * @param {string} name service name
2099            * @param {*} object Service instance object.
2100            * @description
2101            * See {@link auto.$provide#value $provide.value()}.
2102            */
2103           value: invokeLater('$provide', 'value'),
2104
2105           /**
2106            * @ngdoc method
2107            * @name angular.Module#constant
2108            * @module ng
2109            * @param {string} name constant name
2110            * @param {*} object Constant value.
2111            * @description
2112            * Because the constants are fixed, they get applied before other provide methods.
2113            * See {@link auto.$provide#constant $provide.constant()}.
2114            */
2115           constant: invokeLater('$provide', 'constant', 'unshift'),
2116
2117            /**
2118            * @ngdoc method
2119            * @name angular.Module#decorator
2120            * @module ng
2121            * @param {string} The name of the service to decorate.
2122            * @param {Function} This function will be invoked when the service needs to be
2123            *                                    instantiated and should return the decorated service instance.
2124            * @description
2125            * See {@link auto.$provide#decorator $provide.decorator()}.
2126            */
2127           decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
2128
2129           /**
2130            * @ngdoc method
2131            * @name angular.Module#animation
2132            * @module ng
2133            * @param {string} name animation name
2134            * @param {Function} animationFactory Factory function for creating new instance of an
2135            *                                    animation.
2136            * @description
2137            *
2138            * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
2139            *
2140            *
2141            * Defines an animation hook that can be later used with
2142            * {@link $animate $animate} service and directives that use this service.
2143            *
2144            * ```js
2145            * module.animation('.animation-name', function($inject1, $inject2) {
2146            *   return {
2147            *     eventName : function(element, done) {
2148            *       //code to run the animation
2149            *       //once complete, then run done()
2150            *       return function cancellationFunction(element) {
2151            *         //code to cancel the animation
2152            *       }
2153            *     }
2154            *   }
2155            * })
2156            * ```
2157            *
2158            * See {@link ng.$animateProvider#register $animateProvider.register()} and
2159            * {@link ngAnimate ngAnimate module} for more information.
2160            */
2161           animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
2162
2163           /**
2164            * @ngdoc method
2165            * @name angular.Module#filter
2166            * @module ng
2167            * @param {string} name Filter name - this must be a valid angular expression identifier
2168            * @param {Function} filterFactory Factory function for creating new instance of filter.
2169            * @description
2170            * See {@link ng.$filterProvider#register $filterProvider.register()}.
2171            *
2172            * <div class="alert alert-warning">
2173            * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
2174            * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
2175            * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
2176            * (`myapp_subsection_filterx`).
2177            * </div>
2178            */
2179           filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
2180
2181           /**
2182            * @ngdoc method
2183            * @name angular.Module#controller
2184            * @module ng
2185            * @param {string|Object} name Controller name, or an object map of controllers where the
2186            *    keys are the names and the values are the constructors.
2187            * @param {Function} constructor Controller constructor function.
2188            * @description
2189            * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
2190            */
2191           controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
2192
2193           /**
2194            * @ngdoc method
2195            * @name angular.Module#directive
2196            * @module ng
2197            * @param {string|Object} name Directive name, or an object map of directives where the
2198            *    keys are the names and the values are the factories.
2199            * @param {Function} directiveFactory Factory function for creating new instance of
2200            * directives.
2201            * @description
2202            * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
2203            */
2204           directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
2205
2206           /**
2207            * @ngdoc method
2208            * @name angular.Module#component
2209            * @module ng
2210            * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
2211            * @param {Object} options Component definition object (a simplified
2212            *    {@link ng.$compile#directive-definition-object directive definition object})
2213            *
2214            * @description
2215            * See {@link ng.$compileProvider#component $compileProvider.component()}.
2216            */
2217           component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
2218
2219           /**
2220            * @ngdoc method
2221            * @name angular.Module#config
2222            * @module ng
2223            * @param {Function} configFn Execute this function on module load. Useful for service
2224            *    configuration.
2225            * @description
2226            * Use this method to register work which needs to be performed on module loading.
2227            * For more about how to configure services, see
2228            * {@link providers#provider-recipe Provider Recipe}.
2229            */
2230           config: config,
2231
2232           /**
2233            * @ngdoc method
2234            * @name angular.Module#run
2235            * @module ng
2236            * @param {Function} initializationFn Execute this function after injector creation.
2237            *    Useful for application initialization.
2238            * @description
2239            * Use this method to register work which should be performed when the injector is done
2240            * loading all modules.
2241            */
2242           run: function(block) {
2243             runBlocks.push(block);
2244             return this;
2245           }
2246         };
2247
2248         if (configFn) {
2249           config(configFn);
2250         }
2251
2252         return moduleInstance;
2253
2254         /**
2255          * @param {string} provider
2256          * @param {string} method
2257          * @param {String=} insertMethod
2258          * @returns {angular.Module}
2259          */
2260         function invokeLater(provider, method, insertMethod, queue) {
2261           if (!queue) queue = invokeQueue;
2262           return function() {
2263             queue[insertMethod || 'push']([provider, method, arguments]);
2264             return moduleInstance;
2265           };
2266         }
2267
2268         /**
2269          * @param {string} provider
2270          * @param {string} method
2271          * @returns {angular.Module}
2272          */
2273         function invokeLaterAndSetModuleName(provider, method) {
2274           return function(recipeName, factoryFunction) {
2275             if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
2276             invokeQueue.push([provider, method, arguments]);
2277             return moduleInstance;
2278           };
2279         }
2280       });
2281     };
2282   });
2283
2284 }
2285
2286 /* global: toDebugString: true */
2287
2288 function serializeObject(obj) {
2289   var seen = [];
2290
2291   return JSON.stringify(obj, function(key, val) {
2292     val = toJsonReplacer(key, val);
2293     if (isObject(val)) {
2294
2295       if (seen.indexOf(val) >= 0) return '...';
2296
2297       seen.push(val);
2298     }
2299     return val;
2300   });
2301 }
2302
2303 function toDebugString(obj) {
2304   if (typeof obj === 'function') {
2305     return obj.toString().replace(/ \{[\s\S]*$/, '');
2306   } else if (isUndefined(obj)) {
2307     return 'undefined';
2308   } else if (typeof obj !== 'string') {
2309     return serializeObject(obj);
2310   }
2311   return obj;
2312 }
2313
2314 /* global angularModule: true,
2315   version: true,
2316
2317   $CompileProvider,
2318
2319   htmlAnchorDirective,
2320   inputDirective,
2321   inputDirective,
2322   formDirective,
2323   scriptDirective,
2324   selectDirective,
2325   styleDirective,
2326   optionDirective,
2327   ngBindDirective,
2328   ngBindHtmlDirective,
2329   ngBindTemplateDirective,
2330   ngClassDirective,
2331   ngClassEvenDirective,
2332   ngClassOddDirective,
2333   ngCloakDirective,
2334   ngControllerDirective,
2335   ngFormDirective,
2336   ngHideDirective,
2337   ngIfDirective,
2338   ngIncludeDirective,
2339   ngIncludeFillContentDirective,
2340   ngInitDirective,
2341   ngNonBindableDirective,
2342   ngPluralizeDirective,
2343   ngRepeatDirective,
2344   ngShowDirective,
2345   ngStyleDirective,
2346   ngSwitchDirective,
2347   ngSwitchWhenDirective,
2348   ngSwitchDefaultDirective,
2349   ngOptionsDirective,
2350   ngTranscludeDirective,
2351   ngModelDirective,
2352   ngListDirective,
2353   ngChangeDirective,
2354   patternDirective,
2355   patternDirective,
2356   requiredDirective,
2357   requiredDirective,
2358   minlengthDirective,
2359   minlengthDirective,
2360   maxlengthDirective,
2361   maxlengthDirective,
2362   ngValueDirective,
2363   ngModelOptionsDirective,
2364   ngAttributeAliasDirectives,
2365   ngEventDirectives,
2366
2367   $AnchorScrollProvider,
2368   $AnimateProvider,
2369   $CoreAnimateCssProvider,
2370   $$CoreAnimateJsProvider,
2371   $$CoreAnimateQueueProvider,
2372   $$AnimateRunnerFactoryProvider,
2373   $$AnimateAsyncRunFactoryProvider,
2374   $BrowserProvider,
2375   $CacheFactoryProvider,
2376   $ControllerProvider,
2377   $DateProvider,
2378   $DocumentProvider,
2379   $ExceptionHandlerProvider,
2380   $FilterProvider,
2381   $$ForceReflowProvider,
2382   $InterpolateProvider,
2383   $IntervalProvider,
2384   $$HashMapProvider,
2385   $HttpProvider,
2386   $HttpParamSerializerProvider,
2387   $HttpParamSerializerJQLikeProvider,
2388   $HttpBackendProvider,
2389   $xhrFactoryProvider,
2390   $LocationProvider,
2391   $LogProvider,
2392   $ParseProvider,
2393   $RootScopeProvider,
2394   $QProvider,
2395   $$QProvider,
2396   $$SanitizeUriProvider,
2397   $SceProvider,
2398   $SceDelegateProvider,
2399   $SnifferProvider,
2400   $TemplateCacheProvider,
2401   $TemplateRequestProvider,
2402   $$TestabilityProvider,
2403   $TimeoutProvider,
2404   $$RAFProvider,
2405   $WindowProvider,
2406   $$jqLiteProvider,
2407   $$CookieReaderProvider
2408 */
2409
2410
2411 /**
2412  * @ngdoc object
2413  * @name angular.version
2414  * @module ng
2415  * @description
2416  * An object that contains information about the current AngularJS version.
2417  *
2418  * This object has the following properties:
2419  *
2420  * - `full` – `{string}` – Full version string, such as "0.9.18".
2421  * - `major` – `{number}` – Major version number, such as "0".
2422  * - `minor` – `{number}` – Minor version number, such as "9".
2423  * - `dot` – `{number}` – Dot version number, such as "18".
2424  * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
2425  */
2426 var version = {
2427   full: '1.5.0',    // all of these placeholder strings will be replaced by grunt's
2428   major: 1,    // package task
2429   minor: 5,
2430   dot: 0,
2431   codeName: 'ennoblement-facilitation'
2432 };
2433
2434
2435 function publishExternalAPI(angular) {
2436   extend(angular, {
2437     'bootstrap': bootstrap,
2438     'copy': copy,
2439     'extend': extend,
2440     'merge': merge,
2441     'equals': equals,
2442     'element': jqLite,
2443     'forEach': forEach,
2444     'injector': createInjector,
2445     'noop': noop,
2446     'bind': bind,
2447     'toJson': toJson,
2448     'fromJson': fromJson,
2449     'identity': identity,
2450     'isUndefined': isUndefined,
2451     'isDefined': isDefined,
2452     'isString': isString,
2453     'isFunction': isFunction,
2454     'isObject': isObject,
2455     'isNumber': isNumber,
2456     'isElement': isElement,
2457     'isArray': isArray,
2458     'version': version,
2459     'isDate': isDate,
2460     'lowercase': lowercase,
2461     'uppercase': uppercase,
2462     'callbacks': {counter: 0},
2463     'getTestability': getTestability,
2464     '$$minErr': minErr,
2465     '$$csp': csp,
2466     'reloadWithDebugInfo': reloadWithDebugInfo
2467   });
2468
2469   angularModule = setupModuleLoader(window);
2470
2471   angularModule('ng', ['ngLocale'], ['$provide',
2472     function ngModule($provide) {
2473       // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
2474       $provide.provider({
2475         $$sanitizeUri: $$SanitizeUriProvider
2476       });
2477       $provide.provider('$compile', $CompileProvider).
2478         directive({
2479             a: htmlAnchorDirective,
2480             input: inputDirective,
2481             textarea: inputDirective,
2482             form: formDirective,
2483             script: scriptDirective,
2484             select: selectDirective,
2485             style: styleDirective,
2486             option: optionDirective,
2487             ngBind: ngBindDirective,
2488             ngBindHtml: ngBindHtmlDirective,
2489             ngBindTemplate: ngBindTemplateDirective,
2490             ngClass: ngClassDirective,
2491             ngClassEven: ngClassEvenDirective,
2492             ngClassOdd: ngClassOddDirective,
2493             ngCloak: ngCloakDirective,
2494             ngController: ngControllerDirective,
2495             ngForm: ngFormDirective,
2496             ngHide: ngHideDirective,
2497             ngIf: ngIfDirective,
2498             ngInclude: ngIncludeDirective,
2499             ngInit: ngInitDirective,
2500             ngNonBindable: ngNonBindableDirective,
2501             ngPluralize: ngPluralizeDirective,
2502             ngRepeat: ngRepeatDirective,
2503             ngShow: ngShowDirective,
2504             ngStyle: ngStyleDirective,
2505             ngSwitch: ngSwitchDirective,
2506             ngSwitchWhen: ngSwitchWhenDirective,
2507             ngSwitchDefault: ngSwitchDefaultDirective,
2508             ngOptions: ngOptionsDirective,
2509             ngTransclude: ngTranscludeDirective,
2510             ngModel: ngModelDirective,
2511             ngList: ngListDirective,
2512             ngChange: ngChangeDirective,
2513             pattern: patternDirective,
2514             ngPattern: patternDirective,
2515             required: requiredDirective,
2516             ngRequired: requiredDirective,
2517             minlength: minlengthDirective,
2518             ngMinlength: minlengthDirective,
2519             maxlength: maxlengthDirective,
2520             ngMaxlength: maxlengthDirective,
2521             ngValue: ngValueDirective,
2522             ngModelOptions: ngModelOptionsDirective
2523         }).
2524         directive({
2525           ngInclude: ngIncludeFillContentDirective
2526         }).
2527         directive(ngAttributeAliasDirectives).
2528         directive(ngEventDirectives);
2529       $provide.provider({
2530         $anchorScroll: $AnchorScrollProvider,
2531         $animate: $AnimateProvider,
2532         $animateCss: $CoreAnimateCssProvider,
2533         $$animateJs: $$CoreAnimateJsProvider,
2534         $$animateQueue: $$CoreAnimateQueueProvider,
2535         $$AnimateRunner: $$AnimateRunnerFactoryProvider,
2536         $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
2537         $browser: $BrowserProvider,
2538         $cacheFactory: $CacheFactoryProvider,
2539         $controller: $ControllerProvider,
2540         $document: $DocumentProvider,
2541         $exceptionHandler: $ExceptionHandlerProvider,
2542         $filter: $FilterProvider,
2543         $$forceReflow: $$ForceReflowProvider,
2544         $interpolate: $InterpolateProvider,
2545         $interval: $IntervalProvider,
2546         $http: $HttpProvider,
2547         $httpParamSerializer: $HttpParamSerializerProvider,
2548         $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
2549         $httpBackend: $HttpBackendProvider,
2550         $xhrFactory: $xhrFactoryProvider,
2551         $location: $LocationProvider,
2552         $log: $LogProvider,
2553         $parse: $ParseProvider,
2554         $rootScope: $RootScopeProvider,
2555         $q: $QProvider,
2556         $$q: $$QProvider,
2557         $sce: $SceProvider,
2558         $sceDelegate: $SceDelegateProvider,
2559         $sniffer: $SnifferProvider,
2560         $templateCache: $TemplateCacheProvider,
2561         $templateRequest: $TemplateRequestProvider,
2562         $$testability: $$TestabilityProvider,
2563         $timeout: $TimeoutProvider,
2564         $window: $WindowProvider,
2565         $$rAF: $$RAFProvider,
2566         $$jqLite: $$jqLiteProvider,
2567         $$HashMap: $$HashMapProvider,
2568         $$cookieReader: $$CookieReaderProvider
2569       });
2570     }
2571   ]);
2572 }
2573
2574 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2575  *     Any commits to this file should be reviewed with security in mind.  *
2576  *   Changes to this file can potentially create security vulnerabilities. *
2577  *          An approval from 2 Core members with history of modifying      *
2578  *                         this file is required.                          *
2579  *                                                                         *
2580  *  Does the change somehow allow for arbitrary javascript to be executed? *
2581  *    Or allows for someone to change the prototype of built-in objects?   *
2582  *     Or gives undesired access to variables likes document or window?    *
2583  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2584
2585 /* global JQLitePrototype: true,
2586   addEventListenerFn: true,
2587   removeEventListenerFn: true,
2588   BOOLEAN_ATTR: true,
2589   ALIASED_ATTR: true,
2590 */
2591
2592 //////////////////////////////////
2593 //JQLite
2594 //////////////////////////////////
2595
2596 /**
2597  * @ngdoc function
2598  * @name angular.element
2599  * @module ng
2600  * @kind function
2601  *
2602  * @description
2603  * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
2604  *
2605  * If jQuery is available, `angular.element` is an alias for the
2606  * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
2607  * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
2608  *
2609  * jqLite is a tiny, API-compatible subset of jQuery that allows
2610  * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
2611  * commonly needed functionality with the goal of having a very small footprint.
2612  *
2613  * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
2614  * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
2615  * specific version of jQuery if multiple versions exist on the page.
2616  *
2617  * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
2618  * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
2619  *
2620  * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
2621  * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
2622  * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
2623  *
2624  * ## Angular's jqLite
2625  * jqLite provides only the following jQuery methods:
2626  *
2627  * - [`addClass()`](http://api.jquery.com/addClass/)
2628  * - [`after()`](http://api.jquery.com/after/)
2629  * - [`append()`](http://api.jquery.com/append/)
2630  * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
2631  * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
2632  * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
2633  * - [`clone()`](http://api.jquery.com/clone/)
2634  * - [`contents()`](http://api.jquery.com/contents/)
2635  * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
2636  *   As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
2637  * - [`data()`](http://api.jquery.com/data/)
2638  * - [`detach()`](http://api.jquery.com/detach/)
2639  * - [`empty()`](http://api.jquery.com/empty/)
2640  * - [`eq()`](http://api.jquery.com/eq/)
2641  * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
2642  * - [`hasClass()`](http://api.jquery.com/hasClass/)
2643  * - [`html()`](http://api.jquery.com/html/)
2644  * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
2645  * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
2646  * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
2647  * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
2648  * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
2649  * - [`prepend()`](http://api.jquery.com/prepend/)
2650  * - [`prop()`](http://api.jquery.com/prop/)
2651  * - [`ready()`](http://api.jquery.com/ready/)
2652  * - [`remove()`](http://api.jquery.com/remove/)
2653  * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
2654  * - [`removeClass()`](http://api.jquery.com/removeClass/)
2655  * - [`removeData()`](http://api.jquery.com/removeData/)
2656  * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
2657  * - [`text()`](http://api.jquery.com/text/)
2658  * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
2659  * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
2660  * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
2661  * - [`val()`](http://api.jquery.com/val/)
2662  * - [`wrap()`](http://api.jquery.com/wrap/)
2663  *
2664  * ## jQuery/jqLite Extras
2665  * Angular also provides the following additional methods and events to both jQuery and jqLite:
2666  *
2667  * ### Events
2668  * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
2669  *    on all DOM nodes being removed.  This can be used to clean up any 3rd party bindings to the DOM
2670  *    element before it is removed.
2671  *
2672  * ### Methods
2673  * - `controller(name)` - retrieves the controller of the current element or its parent. By default
2674  *   retrieves controller associated with the `ngController` directive. If `name` is provided as
2675  *   camelCase directive name, then the controller for this directive will be retrieved (e.g.
2676  *   `'ngModel'`).
2677  * - `injector()` - retrieves the injector of the current element or its parent.
2678  * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
2679  *   element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
2680  *   be enabled.
2681  * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
2682  *   current element. This getter should be used only on elements that contain a directive which starts a new isolate
2683  *   scope. Calling `scope()` on this element always returns the original non-isolate scope.
2684  *   Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
2685  * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
2686  *   parent element is reached.
2687  *
2688  * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
2689  * @returns {Object} jQuery object.
2690  */
2691
2692 JQLite.expando = 'ng339';
2693
2694 var jqCache = JQLite.cache = {},
2695     jqId = 1,
2696     addEventListenerFn = function(element, type, fn) {
2697       element.addEventListener(type, fn, false);
2698     },
2699     removeEventListenerFn = function(element, type, fn) {
2700       element.removeEventListener(type, fn, false);
2701     };
2702
2703 /*
2704  * !!! This is an undocumented "private" function !!!
2705  */
2706 JQLite._data = function(node) {
2707   //jQuery always returns an object on cache miss
2708   return this.cache[node[this.expando]] || {};
2709 };
2710
2711 function jqNextId() { return ++jqId; }
2712
2713
2714 var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
2715 var MOZ_HACK_REGEXP = /^moz([A-Z])/;
2716 var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
2717 var jqLiteMinErr = minErr('jqLite');
2718
2719 /**
2720  * Converts snake_case to camelCase.
2721  * Also there is special case for Moz prefix starting with upper case letter.
2722  * @param name Name to normalize
2723  */
2724 function camelCase(name) {
2725   return name.
2726     replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
2727       return offset ? letter.toUpperCase() : letter;
2728     }).
2729     replace(MOZ_HACK_REGEXP, 'Moz$1');
2730 }
2731
2732 var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
2733 var HTML_REGEXP = /<|&#?\w+;/;
2734 var TAG_NAME_REGEXP = /<([\w:-]+)/;
2735 var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
2736
2737 var wrapMap = {
2738   'option': [1, '<select multiple="multiple">', '</select>'],
2739
2740   'thead': [1, '<table>', '</table>'],
2741   'col': [2, '<table><colgroup>', '</colgroup></table>'],
2742   'tr': [2, '<table><tbody>', '</tbody></table>'],
2743   'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
2744   '_default': [0, "", ""]
2745 };
2746
2747 wrapMap.optgroup = wrapMap.option;
2748 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
2749 wrapMap.th = wrapMap.td;
2750
2751
2752 function jqLiteIsTextNode(html) {
2753   return !HTML_REGEXP.test(html);
2754 }
2755
2756 function jqLiteAcceptsData(node) {
2757   // The window object can accept data but has no nodeType
2758   // Otherwise we are only interested in elements (1) and documents (9)
2759   var nodeType = node.nodeType;
2760   return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
2761 }
2762
2763 function jqLiteHasData(node) {
2764   for (var key in jqCache[node.ng339]) {
2765     return true;
2766   }
2767   return false;
2768 }
2769
2770 function jqLiteCleanData(nodes) {
2771   for (var i = 0, ii = nodes.length; i < ii; i++) {
2772     jqLiteRemoveData(nodes[i]);
2773   }
2774 }
2775
2776 function jqLiteBuildFragment(html, context) {
2777   var tmp, tag, wrap,
2778       fragment = context.createDocumentFragment(),
2779       nodes = [], i;
2780
2781   if (jqLiteIsTextNode(html)) {
2782     // Convert non-html into a text node
2783     nodes.push(context.createTextNode(html));
2784   } else {
2785     // Convert html into DOM nodes
2786     tmp = tmp || fragment.appendChild(context.createElement("div"));
2787     tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
2788     wrap = wrapMap[tag] || wrapMap._default;
2789     tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
2790
2791     // Descend through wrappers to the right content
2792     i = wrap[0];
2793     while (i--) {
2794       tmp = tmp.lastChild;
2795     }
2796
2797     nodes = concat(nodes, tmp.childNodes);
2798
2799     tmp = fragment.firstChild;
2800     tmp.textContent = "";
2801   }
2802
2803   // Remove wrapper from fragment
2804   fragment.textContent = "";
2805   fragment.innerHTML = ""; // Clear inner HTML
2806   forEach(nodes, function(node) {
2807     fragment.appendChild(node);
2808   });
2809
2810   return fragment;
2811 }
2812
2813 function jqLiteParseHTML(html, context) {
2814   context = context || document;
2815   var parsed;
2816
2817   if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
2818     return [context.createElement(parsed[1])];
2819   }
2820
2821   if ((parsed = jqLiteBuildFragment(html, context))) {
2822     return parsed.childNodes;
2823   }
2824
2825   return [];
2826 }
2827
2828 function jqLiteWrapNode(node, wrapper) {
2829   var parent = node.parentNode;
2830
2831   if (parent) {
2832     parent.replaceChild(wrapper, node);
2833   }
2834
2835   wrapper.appendChild(node);
2836 }
2837
2838
2839 // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
2840 var jqLiteContains = Node.prototype.contains || function(arg) {
2841   // jshint bitwise: false
2842   return !!(this.compareDocumentPosition(arg) & 16);
2843   // jshint bitwise: true
2844 };
2845
2846 /////////////////////////////////////////////
2847 function JQLite(element) {
2848   if (element instanceof JQLite) {
2849     return element;
2850   }
2851
2852   var argIsString;
2853
2854   if (isString(element)) {
2855     element = trim(element);
2856     argIsString = true;
2857   }
2858   if (!(this instanceof JQLite)) {
2859     if (argIsString && element.charAt(0) != '<') {
2860       throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
2861     }
2862     return new JQLite(element);
2863   }
2864
2865   if (argIsString) {
2866     jqLiteAddNodes(this, jqLiteParseHTML(element));
2867   } else {
2868     jqLiteAddNodes(this, element);
2869   }
2870 }
2871
2872 function jqLiteClone(element) {
2873   return element.cloneNode(true);
2874 }
2875
2876 function jqLiteDealoc(element, onlyDescendants) {
2877   if (!onlyDescendants) jqLiteRemoveData(element);
2878
2879   if (element.querySelectorAll) {
2880     var descendants = element.querySelectorAll('*');
2881     for (var i = 0, l = descendants.length; i < l; i++) {
2882       jqLiteRemoveData(descendants[i]);
2883     }
2884   }
2885 }
2886
2887 function jqLiteOff(element, type, fn, unsupported) {
2888   if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
2889
2890   var expandoStore = jqLiteExpandoStore(element);
2891   var events = expandoStore && expandoStore.events;
2892   var handle = expandoStore && expandoStore.handle;
2893
2894   if (!handle) return; //no listeners registered
2895
2896   if (!type) {
2897     for (type in events) {
2898       if (type !== '$destroy') {
2899         removeEventListenerFn(element, type, handle);
2900       }
2901       delete events[type];
2902     }
2903   } else {
2904
2905     var removeHandler = function(type) {
2906       var listenerFns = events[type];
2907       if (isDefined(fn)) {
2908         arrayRemove(listenerFns || [], fn);
2909       }
2910       if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
2911         removeEventListenerFn(element, type, handle);
2912         delete events[type];
2913       }
2914     };
2915
2916     forEach(type.split(' '), function(type) {
2917       removeHandler(type);
2918       if (MOUSE_EVENT_MAP[type]) {
2919         removeHandler(MOUSE_EVENT_MAP[type]);
2920       }
2921     });
2922   }
2923 }
2924
2925 function jqLiteRemoveData(element, name) {
2926   var expandoId = element.ng339;
2927   var expandoStore = expandoId && jqCache[expandoId];
2928
2929   if (expandoStore) {
2930     if (name) {
2931       delete expandoStore.data[name];
2932       return;
2933     }
2934
2935     if (expandoStore.handle) {
2936       if (expandoStore.events.$destroy) {
2937         expandoStore.handle({}, '$destroy');
2938       }
2939       jqLiteOff(element);
2940     }
2941     delete jqCache[expandoId];
2942     element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
2943   }
2944 }
2945
2946
2947 function jqLiteExpandoStore(element, createIfNecessary) {
2948   var expandoId = element.ng339,
2949       expandoStore = expandoId && jqCache[expandoId];
2950
2951   if (createIfNecessary && !expandoStore) {
2952     element.ng339 = expandoId = jqNextId();
2953     expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
2954   }
2955
2956   return expandoStore;
2957 }
2958
2959
2960 function jqLiteData(element, key, value) {
2961   if (jqLiteAcceptsData(element)) {
2962
2963     var isSimpleSetter = isDefined(value);
2964     var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
2965     var massGetter = !key;
2966     var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
2967     var data = expandoStore && expandoStore.data;
2968
2969     if (isSimpleSetter) { // data('key', value)
2970       data[key] = value;
2971     } else {
2972       if (massGetter) {  // data()
2973         return data;
2974       } else {
2975         if (isSimpleGetter) { // data('key')
2976           // don't force creation of expandoStore if it doesn't exist yet
2977           return data && data[key];
2978         } else { // mass-setter: data({key1: val1, key2: val2})
2979           extend(data, key);
2980         }
2981       }
2982     }
2983   }
2984 }
2985
2986 function jqLiteHasClass(element, selector) {
2987   if (!element.getAttribute) return false;
2988   return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
2989       indexOf(" " + selector + " ") > -1);
2990 }
2991
2992 function jqLiteRemoveClass(element, cssClasses) {
2993   if (cssClasses && element.setAttribute) {
2994     forEach(cssClasses.split(' '), function(cssClass) {
2995       element.setAttribute('class', trim(
2996           (" " + (element.getAttribute('class') || '') + " ")
2997           .replace(/[\n\t]/g, " ")
2998           .replace(" " + trim(cssClass) + " ", " "))
2999       );
3000     });
3001   }
3002 }
3003
3004 function jqLiteAddClass(element, cssClasses) {
3005   if (cssClasses && element.setAttribute) {
3006     var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
3007                             .replace(/[\n\t]/g, " ");
3008
3009     forEach(cssClasses.split(' '), function(cssClass) {
3010       cssClass = trim(cssClass);
3011       if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
3012         existingClasses += cssClass + ' ';
3013       }
3014     });
3015
3016     element.setAttribute('class', trim(existingClasses));
3017   }
3018 }
3019
3020
3021 function jqLiteAddNodes(root, elements) {
3022   // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
3023
3024   if (elements) {
3025
3026     // if a Node (the most common case)
3027     if (elements.nodeType) {
3028       root[root.length++] = elements;
3029     } else {
3030       var length = elements.length;
3031
3032       // if an Array or NodeList and not a Window
3033       if (typeof length === 'number' && elements.window !== elements) {
3034         if (length) {
3035           for (var i = 0; i < length; i++) {
3036             root[root.length++] = elements[i];
3037           }
3038         }
3039       } else {
3040         root[root.length++] = elements;
3041       }
3042     }
3043   }
3044 }
3045
3046
3047 function jqLiteController(element, name) {
3048   return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
3049 }
3050
3051 function jqLiteInheritedData(element, name, value) {
3052   // if element is the document object work with the html element instead
3053   // this makes $(document).scope() possible
3054   if (element.nodeType == NODE_TYPE_DOCUMENT) {
3055     element = element.documentElement;
3056   }
3057   var names = isArray(name) ? name : [name];
3058
3059   while (element) {
3060     for (var i = 0, ii = names.length; i < ii; i++) {
3061       if (isDefined(value = jqLite.data(element, names[i]))) return value;
3062     }
3063
3064     // If dealing with a document fragment node with a host element, and no parent, use the host
3065     // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
3066     // to lookup parent controllers.
3067     element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
3068   }
3069 }
3070
3071 function jqLiteEmpty(element) {
3072   jqLiteDealoc(element, true);
3073   while (element.firstChild) {
3074     element.removeChild(element.firstChild);
3075   }
3076 }
3077
3078 function jqLiteRemove(element, keepData) {
3079   if (!keepData) jqLiteDealoc(element);
3080   var parent = element.parentNode;
3081   if (parent) parent.removeChild(element);
3082 }
3083
3084
3085 function jqLiteDocumentLoaded(action, win) {
3086   win = win || window;
3087   if (win.document.readyState === 'complete') {
3088     // Force the action to be run async for consistent behavior
3089     // from the action's point of view
3090     // i.e. it will definitely not be in a $apply
3091     win.setTimeout(action);
3092   } else {
3093     // No need to unbind this handler as load is only ever called once
3094     jqLite(win).on('load', action);
3095   }
3096 }
3097
3098 //////////////////////////////////////////
3099 // Functions which are declared directly.
3100 //////////////////////////////////////////
3101 var JQLitePrototype = JQLite.prototype = {
3102   ready: function(fn) {
3103     var fired = false;
3104
3105     function trigger() {
3106       if (fired) return;
3107       fired = true;
3108       fn();
3109     }
3110
3111     // check if document is already loaded
3112     if (document.readyState === 'complete') {
3113       setTimeout(trigger);
3114     } else {
3115       this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
3116       // we can not use jqLite since we are not done loading and jQuery could be loaded later.
3117       // jshint -W064
3118       JQLite(window).on('load', trigger); // fallback to window.onload for others
3119       // jshint +W064
3120     }
3121   },
3122   toString: function() {
3123     var value = [];
3124     forEach(this, function(e) { value.push('' + e);});
3125     return '[' + value.join(', ') + ']';
3126   },
3127
3128   eq: function(index) {
3129       return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
3130   },
3131
3132   length: 0,
3133   push: push,
3134   sort: [].sort,
3135   splice: [].splice
3136 };
3137
3138 //////////////////////////////////////////
3139 // Functions iterating getter/setters.
3140 // these functions return self on setter and
3141 // value on get.
3142 //////////////////////////////////////////
3143 var BOOLEAN_ATTR = {};
3144 forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
3145   BOOLEAN_ATTR[lowercase(value)] = value;
3146 });
3147 var BOOLEAN_ELEMENTS = {};
3148 forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
3149   BOOLEAN_ELEMENTS[value] = true;
3150 });
3151 var ALIASED_ATTR = {
3152   'ngMinlength': 'minlength',
3153   'ngMaxlength': 'maxlength',
3154   'ngMin': 'min',
3155   'ngMax': 'max',
3156   'ngPattern': 'pattern'
3157 };
3158
3159 function getBooleanAttrName(element, name) {
3160   // check dom last since we will most likely fail on name
3161   var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
3162
3163   // booleanAttr is here twice to minimize DOM access
3164   return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
3165 }
3166
3167 function getAliasedAttrName(name) {
3168   return ALIASED_ATTR[name];
3169 }
3170
3171 forEach({
3172   data: jqLiteData,
3173   removeData: jqLiteRemoveData,
3174   hasData: jqLiteHasData,
3175   cleanData: jqLiteCleanData
3176 }, function(fn, name) {
3177   JQLite[name] = fn;
3178 });
3179
3180 forEach({
3181   data: jqLiteData,
3182   inheritedData: jqLiteInheritedData,
3183
3184   scope: function(element) {
3185     // Can't use jqLiteData here directly so we stay compatible with jQuery!
3186     return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
3187   },
3188
3189   isolateScope: function(element) {
3190     // Can't use jqLiteData here directly so we stay compatible with jQuery!
3191     return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
3192   },
3193
3194   controller: jqLiteController,
3195
3196   injector: function(element) {
3197     return jqLiteInheritedData(element, '$injector');
3198   },
3199
3200   removeAttr: function(element, name) {
3201     element.removeAttribute(name);
3202   },
3203
3204   hasClass: jqLiteHasClass,
3205
3206   css: function(element, name, value) {
3207     name = camelCase(name);
3208
3209     if (isDefined(value)) {
3210       element.style[name] = value;
3211     } else {
3212       return element.style[name];
3213     }
3214   },
3215
3216   attr: function(element, name, value) {
3217     var nodeType = element.nodeType;
3218     if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
3219       return;
3220     }
3221     var lowercasedName = lowercase(name);
3222     if (BOOLEAN_ATTR[lowercasedName]) {
3223       if (isDefined(value)) {
3224         if (!!value) {
3225           element[name] = true;
3226           element.setAttribute(name, lowercasedName);
3227         } else {
3228           element[name] = false;
3229           element.removeAttribute(lowercasedName);
3230         }
3231       } else {
3232         return (element[name] ||
3233                  (element.attributes.getNamedItem(name) || noop).specified)
3234                ? lowercasedName
3235                : undefined;
3236       }
3237     } else if (isDefined(value)) {
3238       element.setAttribute(name, value);
3239     } else if (element.getAttribute) {
3240       // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
3241       // some elements (e.g. Document) don't have get attribute, so return undefined
3242       var ret = element.getAttribute(name, 2);
3243       // normalize non-existing attributes to undefined (as jQuery)
3244       return ret === null ? undefined : ret;
3245     }
3246   },
3247
3248   prop: function(element, name, value) {
3249     if (isDefined(value)) {
3250       element[name] = value;
3251     } else {
3252       return element[name];
3253     }
3254   },
3255
3256   text: (function() {
3257     getText.$dv = '';
3258     return getText;
3259
3260     function getText(element, value) {
3261       if (isUndefined(value)) {
3262         var nodeType = element.nodeType;
3263         return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
3264       }
3265       element.textContent = value;
3266     }
3267   })(),
3268
3269   val: function(element, value) {
3270     if (isUndefined(value)) {
3271       if (element.multiple && nodeName_(element) === 'select') {
3272         var result = [];
3273         forEach(element.options, function(option) {
3274           if (option.selected) {
3275             result.push(option.value || option.text);
3276           }
3277         });
3278         return result.length === 0 ? null : result;
3279       }
3280       return element.value;
3281     }
3282     element.value = value;
3283   },
3284
3285   html: function(element, value) {
3286     if (isUndefined(value)) {
3287       return element.innerHTML;
3288     }
3289     jqLiteDealoc(element, true);
3290     element.innerHTML = value;
3291   },
3292
3293   empty: jqLiteEmpty
3294 }, function(fn, name) {
3295   /**
3296    * Properties: writes return selection, reads return first value
3297    */
3298   JQLite.prototype[name] = function(arg1, arg2) {
3299     var i, key;
3300     var nodeCount = this.length;
3301
3302     // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
3303     // in a way that survives minification.
3304     // jqLiteEmpty takes no arguments but is a setter.
3305     if (fn !== jqLiteEmpty &&
3306         (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
3307       if (isObject(arg1)) {
3308
3309         // we are a write, but the object properties are the key/values
3310         for (i = 0; i < nodeCount; i++) {
3311           if (fn === jqLiteData) {
3312             // data() takes the whole object in jQuery
3313             fn(this[i], arg1);
3314           } else {
3315             for (key in arg1) {
3316               fn(this[i], key, arg1[key]);
3317             }
3318           }
3319         }
3320         // return self for chaining
3321         return this;
3322       } else {
3323         // we are a read, so read the first child.
3324         // TODO: do we still need this?
3325         var value = fn.$dv;
3326         // Only if we have $dv do we iterate over all, otherwise it is just the first element.
3327         var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
3328         for (var j = 0; j < jj; j++) {
3329           var nodeValue = fn(this[j], arg1, arg2);
3330           value = value ? value + nodeValue : nodeValue;
3331         }
3332         return value;
3333       }
3334     } else {
3335       // we are a write, so apply to all children
3336       for (i = 0; i < nodeCount; i++) {
3337         fn(this[i], arg1, arg2);
3338       }
3339       // return self for chaining
3340       return this;
3341     }
3342   };
3343 });
3344
3345 function createEventHandler(element, events) {
3346   var eventHandler = function(event, type) {
3347     // jQuery specific api
3348     event.isDefaultPrevented = function() {
3349       return event.defaultPrevented;
3350     };
3351
3352     var eventFns = events[type || event.type];
3353     var eventFnsLength = eventFns ? eventFns.length : 0;
3354
3355     if (!eventFnsLength) return;
3356
3357     if (isUndefined(event.immediatePropagationStopped)) {
3358       var originalStopImmediatePropagation = event.stopImmediatePropagation;
3359       event.stopImmediatePropagation = function() {
3360         event.immediatePropagationStopped = true;
3361
3362         if (event.stopPropagation) {
3363           event.stopPropagation();
3364         }
3365
3366         if (originalStopImmediatePropagation) {
3367           originalStopImmediatePropagation.call(event);
3368         }
3369       };
3370     }
3371
3372     event.isImmediatePropagationStopped = function() {
3373       return event.immediatePropagationStopped === true;
3374     };
3375
3376     // Some events have special handlers that wrap the real handler
3377     var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
3378
3379     // Copy event handlers in case event handlers array is modified during execution.
3380     if ((eventFnsLength > 1)) {
3381       eventFns = shallowCopy(eventFns);
3382     }
3383
3384     for (var i = 0; i < eventFnsLength; i++) {
3385       if (!event.isImmediatePropagationStopped()) {
3386         handlerWrapper(element, event, eventFns[i]);
3387       }
3388     }
3389   };
3390
3391   // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
3392   //       events on `element`
3393   eventHandler.elem = element;
3394   return eventHandler;
3395 }
3396
3397 function defaultHandlerWrapper(element, event, handler) {
3398   handler.call(element, event);
3399 }
3400
3401 function specialMouseHandlerWrapper(target, event, handler) {
3402   // Refer to jQuery's implementation of mouseenter & mouseleave
3403   // Read about mouseenter and mouseleave:
3404   // http://www.quirksmode.org/js/events_mouse.html#link8
3405   var related = event.relatedTarget;
3406   // For mousenter/leave call the handler if related is outside the target.
3407   // NB: No relatedTarget if the mouse left/entered the browser window
3408   if (!related || (related !== target && !jqLiteContains.call(target, related))) {
3409     handler.call(target, event);
3410   }
3411 }
3412
3413 //////////////////////////////////////////
3414 // Functions iterating traversal.
3415 // These functions chain results into a single
3416 // selector.
3417 //////////////////////////////////////////
3418 forEach({
3419   removeData: jqLiteRemoveData,
3420
3421   on: function jqLiteOn(element, type, fn, unsupported) {
3422     if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
3423
3424     // Do not add event handlers to non-elements because they will not be cleaned up.
3425     if (!jqLiteAcceptsData(element)) {
3426       return;
3427     }
3428
3429     var expandoStore = jqLiteExpandoStore(element, true);
3430     var events = expandoStore.events;
3431     var handle = expandoStore.handle;
3432
3433     if (!handle) {
3434       handle = expandoStore.handle = createEventHandler(element, events);
3435     }
3436
3437     // http://jsperf.com/string-indexof-vs-split
3438     var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
3439     var i = types.length;
3440
3441     var addHandler = function(type, specialHandlerWrapper, noEventListener) {
3442       var eventFns = events[type];
3443
3444       if (!eventFns) {
3445         eventFns = events[type] = [];
3446         eventFns.specialHandlerWrapper = specialHandlerWrapper;
3447         if (type !== '$destroy' && !noEventListener) {
3448           addEventListenerFn(element, type, handle);
3449         }
3450       }
3451
3452       eventFns.push(fn);
3453     };
3454
3455     while (i--) {
3456       type = types[i];
3457       if (MOUSE_EVENT_MAP[type]) {
3458         addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
3459         addHandler(type, undefined, true);
3460       } else {
3461         addHandler(type);
3462       }
3463     }
3464   },
3465
3466   off: jqLiteOff,
3467
3468   one: function(element, type, fn) {
3469     element = jqLite(element);
3470
3471     //add the listener twice so that when it is called
3472     //you can remove the original function and still be
3473     //able to call element.off(ev, fn) normally
3474     element.on(type, function onFn() {
3475       element.off(type, fn);
3476       element.off(type, onFn);
3477     });
3478     element.on(type, fn);
3479   },
3480
3481   replaceWith: function(element, replaceNode) {
3482     var index, parent = element.parentNode;
3483     jqLiteDealoc(element);
3484     forEach(new JQLite(replaceNode), function(node) {
3485       if (index) {
3486         parent.insertBefore(node, index.nextSibling);
3487       } else {
3488         parent.replaceChild(node, element);
3489       }
3490       index = node;
3491     });
3492   },
3493
3494   children: function(element) {
3495     var children = [];
3496     forEach(element.childNodes, function(element) {
3497       if (element.nodeType === NODE_TYPE_ELEMENT) {
3498         children.push(element);
3499       }
3500     });
3501     return children;
3502   },
3503
3504   contents: function(element) {
3505     return element.contentDocument || element.childNodes || [];
3506   },
3507
3508   append: function(element, node) {
3509     var nodeType = element.nodeType;
3510     if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
3511
3512     node = new JQLite(node);
3513
3514     for (var i = 0, ii = node.length; i < ii; i++) {
3515       var child = node[i];
3516       element.appendChild(child);
3517     }
3518   },
3519
3520   prepend: function(element, node) {
3521     if (element.nodeType === NODE_TYPE_ELEMENT) {
3522       var index = element.firstChild;
3523       forEach(new JQLite(node), function(child) {
3524         element.insertBefore(child, index);
3525       });
3526     }
3527   },
3528
3529   wrap: function(element, wrapNode) {
3530     jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
3531   },
3532
3533   remove: jqLiteRemove,
3534
3535   detach: function(element) {
3536     jqLiteRemove(element, true);
3537   },
3538
3539   after: function(element, newElement) {
3540     var index = element, parent = element.parentNode;
3541     newElement = new JQLite(newElement);
3542
3543     for (var i = 0, ii = newElement.length; i < ii; i++) {
3544       var node = newElement[i];
3545       parent.insertBefore(node, index.nextSibling);
3546       index = node;
3547     }
3548   },
3549
3550   addClass: jqLiteAddClass,
3551   removeClass: jqLiteRemoveClass,
3552
3553   toggleClass: function(element, selector, condition) {
3554     if (selector) {
3555       forEach(selector.split(' '), function(className) {
3556         var classCondition = condition;
3557         if (isUndefined(classCondition)) {
3558           classCondition = !jqLiteHasClass(element, className);
3559         }
3560         (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
3561       });
3562     }
3563   },
3564
3565   parent: function(element) {
3566     var parent = element.parentNode;
3567     return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
3568   },
3569
3570   next: function(element) {
3571     return element.nextElementSibling;
3572   },
3573
3574   find: function(element, selector) {
3575     if (element.getElementsByTagName) {
3576       return element.getElementsByTagName(selector);
3577     } else {
3578       return [];
3579     }
3580   },
3581
3582   clone: jqLiteClone,
3583
3584   triggerHandler: function(element, event, extraParameters) {
3585
3586     var dummyEvent, eventFnsCopy, handlerArgs;
3587     var eventName = event.type || event;
3588     var expandoStore = jqLiteExpandoStore(element);
3589     var events = expandoStore && expandoStore.events;
3590     var eventFns = events && events[eventName];
3591
3592     if (eventFns) {
3593       // Create a dummy event to pass to the handlers
3594       dummyEvent = {
3595         preventDefault: function() { this.defaultPrevented = true; },
3596         isDefaultPrevented: function() { return this.defaultPrevented === true; },
3597         stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
3598         isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
3599         stopPropagation: noop,
3600         type: eventName,
3601         target: element
3602       };
3603
3604       // If a custom event was provided then extend our dummy event with it
3605       if (event.type) {
3606         dummyEvent = extend(dummyEvent, event);
3607       }
3608
3609       // Copy event handlers in case event handlers array is modified during execution.
3610       eventFnsCopy = shallowCopy(eventFns);
3611       handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
3612
3613       forEach(eventFnsCopy, function(fn) {
3614         if (!dummyEvent.isImmediatePropagationStopped()) {
3615           fn.apply(element, handlerArgs);
3616         }
3617       });
3618     }
3619   }
3620 }, function(fn, name) {
3621   /**
3622    * chaining functions
3623    */
3624   JQLite.prototype[name] = function(arg1, arg2, arg3) {
3625     var value;
3626
3627     for (var i = 0, ii = this.length; i < ii; i++) {
3628       if (isUndefined(value)) {
3629         value = fn(this[i], arg1, arg2, arg3);
3630         if (isDefined(value)) {
3631           // any function which returns a value needs to be wrapped
3632           value = jqLite(value);
3633         }
3634       } else {
3635         jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
3636       }
3637     }
3638     return isDefined(value) ? value : this;
3639   };
3640
3641   // bind legacy bind/unbind to on/off
3642   JQLite.prototype.bind = JQLite.prototype.on;
3643   JQLite.prototype.unbind = JQLite.prototype.off;
3644 });
3645
3646
3647 // Provider for private $$jqLite service
3648 function $$jqLiteProvider() {
3649   this.$get = function $$jqLite() {
3650     return extend(JQLite, {
3651       hasClass: function(node, classes) {
3652         if (node.attr) node = node[0];
3653         return jqLiteHasClass(node, classes);
3654       },
3655       addClass: function(node, classes) {
3656         if (node.attr) node = node[0];
3657         return jqLiteAddClass(node, classes);
3658       },
3659       removeClass: function(node, classes) {
3660         if (node.attr) node = node[0];
3661         return jqLiteRemoveClass(node, classes);
3662       }
3663     });
3664   };
3665 }
3666
3667 /**
3668  * Computes a hash of an 'obj'.
3669  * Hash of a:
3670  *  string is string
3671  *  number is number as string
3672  *  object is either result of calling $$hashKey function on the object or uniquely generated id,
3673  *         that is also assigned to the $$hashKey property of the object.
3674  *
3675  * @param obj
3676  * @returns {string} hash string such that the same input will have the same hash string.
3677  *         The resulting string key is in 'type:hashKey' format.
3678  */
3679 function hashKey(obj, nextUidFn) {
3680   var key = obj && obj.$$hashKey;
3681
3682   if (key) {
3683     if (typeof key === 'function') {
3684       key = obj.$$hashKey();
3685     }
3686     return key;
3687   }
3688
3689   var objType = typeof obj;
3690   if (objType == 'function' || (objType == 'object' && obj !== null)) {
3691     key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
3692   } else {
3693     key = objType + ':' + obj;
3694   }
3695
3696   return key;
3697 }
3698
3699 /**
3700  * HashMap which can use objects as keys
3701  */
3702 function HashMap(array, isolatedUid) {
3703   if (isolatedUid) {
3704     var uid = 0;
3705     this.nextUid = function() {
3706       return ++uid;
3707     };
3708   }
3709   forEach(array, this.put, this);
3710 }
3711 HashMap.prototype = {
3712   /**
3713    * Store key value pair
3714    * @param key key to store can be any type
3715    * @param value value to store can be any type
3716    */
3717   put: function(key, value) {
3718     this[hashKey(key, this.nextUid)] = value;
3719   },
3720
3721   /**
3722    * @param key
3723    * @returns {Object} the value for the key
3724    */
3725   get: function(key) {
3726     return this[hashKey(key, this.nextUid)];
3727   },
3728
3729   /**
3730    * Remove the key/value pair
3731    * @param key
3732    */
3733   remove: function(key) {
3734     var value = this[key = hashKey(key, this.nextUid)];
3735     delete this[key];
3736     return value;
3737   }
3738 };
3739
3740 var $$HashMapProvider = [function() {
3741   this.$get = [function() {
3742     return HashMap;
3743   }];
3744 }];
3745
3746 /**
3747  * @ngdoc function
3748  * @module ng
3749  * @name angular.injector
3750  * @kind function
3751  *
3752  * @description
3753  * Creates an injector object that can be used for retrieving services as well as for
3754  * dependency injection (see {@link guide/di dependency injection}).
3755  *
3756  * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
3757  *     {@link angular.module}. The `ng` module must be explicitly added.
3758  * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
3759  *     disallows argument name annotation inference.
3760  * @returns {injector} Injector object. See {@link auto.$injector $injector}.
3761  *
3762  * @example
3763  * Typical usage
3764  * ```js
3765  *   // create an injector
3766  *   var $injector = angular.injector(['ng']);
3767  *
3768  *   // use the injector to kick off your application
3769  *   // use the type inference to auto inject arguments, or use implicit injection
3770  *   $injector.invoke(function($rootScope, $compile, $document) {
3771  *     $compile($document)($rootScope);
3772  *     $rootScope.$digest();
3773  *   });
3774  * ```
3775  *
3776  * Sometimes you want to get access to the injector of a currently running Angular app
3777  * from outside Angular. Perhaps, you want to inject and compile some markup after the
3778  * application has been bootstrapped. You can do this using the extra `injector()` added
3779  * to JQuery/jqLite elements. See {@link angular.element}.
3780  *
3781  * *This is fairly rare but could be the case if a third party library is injecting the
3782  * markup.*
3783  *
3784  * In the following example a new block of HTML containing a `ng-controller`
3785  * directive is added to the end of the document body by JQuery. We then compile and link
3786  * it into the current AngularJS scope.
3787  *
3788  * ```js
3789  * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
3790  * $(document.body).append($div);
3791  *
3792  * angular.element(document).injector().invoke(function($compile) {
3793  *   var scope = angular.element($div).scope();
3794  *   $compile($div)(scope);
3795  * });
3796  * ```
3797  */
3798
3799
3800 /**
3801  * @ngdoc module
3802  * @name auto
3803  * @description
3804  *
3805  * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
3806  */
3807
3808 var ARROW_ARG = /^([^\(]+?)=>/;
3809 var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
3810 var FN_ARG_SPLIT = /,/;
3811 var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
3812 var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
3813 var $injectorMinErr = minErr('$injector');
3814
3815 function extractArgs(fn) {
3816   var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
3817       args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
3818   return args;
3819 }
3820
3821 function anonFn(fn) {
3822   // For anonymous functions, showing at the very least the function signature can help in
3823   // debugging.
3824   var args = extractArgs(fn);
3825   if (args) {
3826     return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
3827   }
3828   return 'fn';
3829 }
3830
3831 function annotate(fn, strictDi, name) {
3832   var $inject,
3833       argDecl,
3834       last;
3835
3836   if (typeof fn === 'function') {
3837     if (!($inject = fn.$inject)) {
3838       $inject = [];
3839       if (fn.length) {
3840         if (strictDi) {
3841           if (!isString(name) || !name) {
3842             name = fn.name || anonFn(fn);
3843           }
3844           throw $injectorMinErr('strictdi',
3845             '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
3846         }
3847         argDecl = extractArgs(fn);
3848         forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
3849           arg.replace(FN_ARG, function(all, underscore, name) {
3850             $inject.push(name);
3851           });
3852         });
3853       }
3854       fn.$inject = $inject;
3855     }
3856   } else if (isArray(fn)) {
3857     last = fn.length - 1;
3858     assertArgFn(fn[last], 'fn');
3859     $inject = fn.slice(0, last);
3860   } else {
3861     assertArgFn(fn, 'fn', true);
3862   }
3863   return $inject;
3864 }
3865
3866 ///////////////////////////////////////
3867
3868 /**
3869  * @ngdoc service
3870  * @name $injector
3871  *
3872  * @description
3873  *
3874  * `$injector` is used to retrieve object instances as defined by
3875  * {@link auto.$provide provider}, instantiate types, invoke methods,
3876  * and load modules.
3877  *
3878  * The following always holds true:
3879  *
3880  * ```js
3881  *   var $injector = angular.injector();
3882  *   expect($injector.get('$injector')).toBe($injector);
3883  *   expect($injector.invoke(function($injector) {
3884  *     return $injector;
3885  *   })).toBe($injector);
3886  * ```
3887  *
3888  * # Injection Function Annotation
3889  *
3890  * JavaScript does not have annotations, and annotations are needed for dependency injection. The
3891  * following are all valid ways of annotating function with injection arguments and are equivalent.
3892  *
3893  * ```js
3894  *   // inferred (only works if code not minified/obfuscated)
3895  *   $injector.invoke(function(serviceA){});
3896  *
3897  *   // annotated
3898  *   function explicit(serviceA) {};
3899  *   explicit.$inject = ['serviceA'];
3900  *   $injector.invoke(explicit);
3901  *
3902  *   // inline
3903  *   $injector.invoke(['serviceA', function(serviceA){}]);
3904  * ```
3905  *
3906  * ## Inference
3907  *
3908  * In JavaScript calling `toString()` on a function returns the function definition. The definition
3909  * can then be parsed and the function arguments can be extracted. This method of discovering
3910  * annotations is disallowed when the injector is in strict mode.
3911  * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
3912  * argument names.
3913  *
3914  * ## `$inject` Annotation
3915  * By adding an `$inject` property onto a function the injection parameters can be specified.
3916  *
3917  * ## Inline
3918  * As an array of injection names, where the last item in the array is the function to call.
3919  */
3920
3921 /**
3922  * @ngdoc method
3923  * @name $injector#get
3924  *
3925  * @description
3926  * Return an instance of the service.
3927  *
3928  * @param {string} name The name of the instance to retrieve.
3929  * @param {string=} caller An optional string to provide the origin of the function call for error messages.
3930  * @return {*} The instance.
3931  */
3932
3933 /**
3934  * @ngdoc method
3935  * @name $injector#invoke
3936  *
3937  * @description
3938  * Invoke the method and supply the method arguments from the `$injector`.
3939  *
3940  * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
3941  *   injected according to the {@link guide/di $inject Annotation} rules.
3942  * @param {Object=} self The `this` for the invoked method.
3943  * @param {Object=} locals Optional object. If preset then any argument names are read from this
3944  *                         object first, before the `$injector` is consulted.
3945  * @returns {*} the value returned by the invoked `fn` function.
3946  */
3947
3948 /**
3949  * @ngdoc method
3950  * @name $injector#has
3951  *
3952  * @description
3953  * Allows the user to query if the particular service exists.
3954  *
3955  * @param {string} name Name of the service to query.
3956  * @returns {boolean} `true` if injector has given service.
3957  */
3958
3959 /**
3960  * @ngdoc method
3961  * @name $injector#instantiate
3962  * @description
3963  * Create a new instance of JS type. The method takes a constructor function, invokes the new
3964  * operator, and supplies all of the arguments to the constructor function as specified by the
3965  * constructor annotation.
3966  *
3967  * @param {Function} Type Annotated constructor function.
3968  * @param {Object=} locals Optional object. If preset then any argument names are read from this
3969  * object first, before the `$injector` is consulted.
3970  * @returns {Object} new instance of `Type`.
3971  */
3972
3973 /**
3974  * @ngdoc method
3975  * @name $injector#annotate
3976  *
3977  * @description
3978  * Returns an array of service names which the function is requesting for injection. This API is
3979  * used by the injector to determine which services need to be injected into the function when the
3980  * function is invoked. There are three ways in which the function can be annotated with the needed
3981  * dependencies.
3982  *
3983  * # Argument names
3984  *
3985  * The simplest form is to extract the dependencies from the arguments of the function. This is done
3986  * by converting the function into a string using `toString()` method and extracting the argument
3987  * names.
3988  * ```js
3989  *   // Given
3990  *   function MyController($scope, $route) {
3991  *     // ...
3992  *   }
3993  *
3994  *   // Then
3995  *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
3996  * ```
3997  *
3998  * You can disallow this method by using strict injection mode.
3999  *
4000  * This method does not work with code minification / obfuscation. For this reason the following
4001  * annotation strategies are supported.
4002  *
4003  * # The `$inject` property
4004  *
4005  * If a function has an `$inject` property and its value is an array of strings, then the strings
4006  * represent names of services to be injected into the function.
4007  * ```js
4008  *   // Given
4009  *   var MyController = function(obfuscatedScope, obfuscatedRoute) {
4010  *     // ...
4011  *   }
4012  *   // Define function dependencies
4013  *   MyController['$inject'] = ['$scope', '$route'];
4014  *
4015  *   // Then
4016  *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
4017  * ```
4018  *
4019  * # The array notation
4020  *
4021  * It is often desirable to inline Injected functions and that's when setting the `$inject` property
4022  * is very inconvenient. In these situations using the array notation to specify the dependencies in
4023  * a way that survives minification is a better choice:
4024  *
4025  * ```js
4026  *   // We wish to write this (not minification / obfuscation safe)
4027  *   injector.invoke(function($compile, $rootScope) {
4028  *     // ...
4029  *   });
4030  *
4031  *   // We are forced to write break inlining
4032  *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
4033  *     // ...
4034  *   };
4035  *   tmpFn.$inject = ['$compile', '$rootScope'];
4036  *   injector.invoke(tmpFn);
4037  *
4038  *   // To better support inline function the inline annotation is supported
4039  *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
4040  *     // ...
4041  *   }]);
4042  *
4043  *   // Therefore
4044  *   expect(injector.annotate(
4045  *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
4046  *    ).toEqual(['$compile', '$rootScope']);
4047  * ```
4048  *
4049  * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
4050  * be retrieved as described above.
4051  *
4052  * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
4053  *
4054  * @returns {Array.<string>} The names of the services which the function requires.
4055  */
4056
4057
4058
4059
4060 /**
4061  * @ngdoc service
4062  * @name $provide
4063  *
4064  * @description
4065  *
4066  * The {@link auto.$provide $provide} service has a number of methods for registering components
4067  * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
4068  * {@link angular.Module}.
4069  *
4070  * An Angular **service** is a singleton object created by a **service factory**.  These **service
4071  * factories** are functions which, in turn, are created by a **service provider**.
4072  * The **service providers** are constructor functions. When instantiated they must contain a
4073  * property called `$get`, which holds the **service factory** function.
4074  *
4075  * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
4076  * correct **service provider**, instantiating it and then calling its `$get` **service factory**
4077  * function to get the instance of the **service**.
4078  *
4079  * Often services have no configuration options and there is no need to add methods to the service
4080  * provider.  The provider will be no more than a constructor function with a `$get` property. For
4081  * these cases the {@link auto.$provide $provide} service has additional helper methods to register
4082  * services without specifying a provider.
4083  *
4084  * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
4085  *     {@link auto.$injector $injector}
4086  * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
4087  *     providers and services.
4088  * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
4089  *     services, not providers.
4090  * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
4091  *     that will be wrapped in a **service provider** object, whose `$get` property will contain the
4092  *     given factory function.
4093  * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
4094  *     that will be wrapped in a **service provider** object, whose `$get` property will instantiate
4095  *      a new object using the given constructor function.
4096  *
4097  * See the individual methods for more information and examples.
4098  */
4099
4100 /**
4101  * @ngdoc method
4102  * @name $provide#provider
4103  * @description
4104  *
4105  * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
4106  * are constructor functions, whose instances are responsible for "providing" a factory for a
4107  * service.
4108  *
4109  * Service provider names start with the name of the service they provide followed by `Provider`.
4110  * For example, the {@link ng.$log $log} service has a provider called
4111  * {@link ng.$logProvider $logProvider}.
4112  *
4113  * Service provider objects can have additional methods which allow configuration of the provider
4114  * and its service. Importantly, you can configure what kind of service is created by the `$get`
4115  * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
4116  * method {@link ng.$logProvider#debugEnabled debugEnabled}
4117  * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
4118  * console or not.
4119  *
4120  * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
4121                         'Provider'` key.
4122  * @param {(Object|function())} provider If the provider is:
4123  *
4124  *   - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
4125  *     {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
4126  *   - `Constructor`: a new instance of the provider will be created using
4127  *     {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
4128  *
4129  * @returns {Object} registered provider instance
4130
4131  * @example
4132  *
4133  * The following example shows how to create a simple event tracking service and register it using
4134  * {@link auto.$provide#provider $provide.provider()}.
4135  *
4136  * ```js
4137  *  // Define the eventTracker provider
4138  *  function EventTrackerProvider() {
4139  *    var trackingUrl = '/track';
4140  *
4141  *    // A provider method for configuring where the tracked events should been saved
4142  *    this.setTrackingUrl = function(url) {
4143  *      trackingUrl = url;
4144  *    };
4145  *
4146  *    // The service factory function
4147  *    this.$get = ['$http', function($http) {
4148  *      var trackedEvents = {};
4149  *      return {
4150  *        // Call this to track an event
4151  *        event: function(event) {
4152  *          var count = trackedEvents[event] || 0;
4153  *          count += 1;
4154  *          trackedEvents[event] = count;
4155  *          return count;
4156  *        },
4157  *        // Call this to save the tracked events to the trackingUrl
4158  *        save: function() {
4159  *          $http.post(trackingUrl, trackedEvents);
4160  *        }
4161  *      };
4162  *    }];
4163  *  }
4164  *
4165  *  describe('eventTracker', function() {
4166  *    var postSpy;
4167  *
4168  *    beforeEach(module(function($provide) {
4169  *      // Register the eventTracker provider
4170  *      $provide.provider('eventTracker', EventTrackerProvider);
4171  *    }));
4172  *
4173  *    beforeEach(module(function(eventTrackerProvider) {
4174  *      // Configure eventTracker provider
4175  *      eventTrackerProvider.setTrackingUrl('/custom-track');
4176  *    }));
4177  *
4178  *    it('tracks events', inject(function(eventTracker) {
4179  *      expect(eventTracker.event('login')).toEqual(1);
4180  *      expect(eventTracker.event('login')).toEqual(2);
4181  *    }));
4182  *
4183  *    it('saves to the tracking url', inject(function(eventTracker, $http) {
4184  *      postSpy = spyOn($http, 'post');
4185  *      eventTracker.event('login');
4186  *      eventTracker.save();
4187  *      expect(postSpy).toHaveBeenCalled();
4188  *      expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
4189  *      expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
4190  *      expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
4191  *    }));
4192  *  });
4193  * ```
4194  */
4195
4196 /**
4197  * @ngdoc method
4198  * @name $provide#factory
4199  * @description
4200  *
4201  * Register a **service factory**, which will be called to return the service instance.
4202  * This is short for registering a service where its provider consists of only a `$get` property,
4203  * which is the given service factory function.
4204  * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
4205  * configure your service in a provider.
4206  *
4207  * @param {string} name The name of the instance.
4208  * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
4209  *                      Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
4210  * @returns {Object} registered provider instance
4211  *
4212  * @example
4213  * Here is an example of registering a service
4214  * ```js
4215  *   $provide.factory('ping', ['$http', function($http) {
4216  *     return function ping() {
4217  *       return $http.send('/ping');
4218  *     };
4219  *   }]);
4220  * ```
4221  * You would then inject and use this service like this:
4222  * ```js
4223  *   someModule.controller('Ctrl', ['ping', function(ping) {
4224  *     ping();
4225  *   }]);
4226  * ```
4227  */
4228
4229
4230 /**
4231  * @ngdoc method
4232  * @name $provide#service
4233  * @description
4234  *
4235  * Register a **service constructor**, which will be invoked with `new` to create the service
4236  * instance.
4237  * This is short for registering a service where its provider's `$get` property is a factory
4238  * function that returns an instance instantiated by the injector from the service constructor
4239  * function.
4240  *
4241  * Internally it looks a bit like this:
4242  *
4243  * ```
4244  * {
4245  *   $get: function() {
4246  *     return $injector.instantiate(constructor);
4247  *   }
4248  * }
4249  * ```
4250  *
4251  *
4252  * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
4253  * as a type/class.
4254  *
4255  * @param {string} name The name of the instance.
4256  * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
4257  *     that will be instantiated.
4258  * @returns {Object} registered provider instance
4259  *
4260  * @example
4261  * Here is an example of registering a service using
4262  * {@link auto.$provide#service $provide.service(class)}.
4263  * ```js
4264  *   var Ping = function($http) {
4265  *     this.$http = $http;
4266  *   };
4267  *
4268  *   Ping.$inject = ['$http'];
4269  *
4270  *   Ping.prototype.send = function() {
4271  *     return this.$http.get('/ping');
4272  *   };
4273  *   $provide.service('ping', Ping);
4274  * ```
4275  * You would then inject and use this service like this:
4276  * ```js
4277  *   someModule.controller('Ctrl', ['ping', function(ping) {
4278  *     ping.send();
4279  *   }]);
4280  * ```
4281  */
4282
4283
4284 /**
4285  * @ngdoc method
4286  * @name $provide#value
4287  * @description
4288  *
4289  * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
4290  * number, an array, an object or a function.  This is short for registering a service where its
4291  * provider's `$get` property is a factory function that takes no arguments and returns the **value
4292  * service**.
4293  *
4294  * Value services are similar to constant services, except that they cannot be injected into a
4295  * module configuration function (see {@link angular.Module#config}) but they can be overridden by
4296  * an Angular
4297  * {@link auto.$provide#decorator decorator}.
4298  *
4299  * @param {string} name The name of the instance.
4300  * @param {*} value The value.
4301  * @returns {Object} registered provider instance
4302  *
4303  * @example
4304  * Here are some examples of creating value services.
4305  * ```js
4306  *   $provide.value('ADMIN_USER', 'admin');
4307  *
4308  *   $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
4309  *
4310  *   $provide.value('halfOf', function(value) {
4311  *     return value / 2;
4312  *   });
4313  * ```
4314  */
4315
4316
4317 /**
4318  * @ngdoc method
4319  * @name $provide#constant
4320  * @description
4321  *
4322  * Register a **constant service**, such as a string, a number, an array, an object or a function,
4323  * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
4324  * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
4325  * be overridden by an Angular {@link auto.$provide#decorator decorator}.
4326  *
4327  * @param {string} name The name of the constant.
4328  * @param {*} value The constant value.
4329  * @returns {Object} registered instance
4330  *
4331  * @example
4332  * Here a some examples of creating constants:
4333  * ```js
4334  *   $provide.constant('SHARD_HEIGHT', 306);
4335  *
4336  *   $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
4337  *
4338  *   $provide.constant('double', function(value) {
4339  *     return value * 2;
4340  *   });
4341  * ```
4342  */
4343
4344
4345 /**
4346  * @ngdoc method
4347  * @name $provide#decorator
4348  * @description
4349  *
4350  * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
4351  * intercepts the creation of a service, allowing it to override or modify the behavior of the
4352  * service. The object returned by the decorator may be the original service, or a new service
4353  * object which replaces or wraps and delegates to the original service.
4354  *
4355  * @param {string} name The name of the service to decorate.
4356  * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
4357  *    instantiated and should return the decorated service instance. The function is called using
4358  *    the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
4359  *    Local injection arguments:
4360  *
4361  *    * `$delegate` - The original service instance, which can be monkey patched, configured,
4362  *      decorated or delegated to.
4363  *
4364  * @example
4365  * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
4366  * calls to {@link ng.$log#error $log.warn()}.
4367  * ```js
4368  *   $provide.decorator('$log', ['$delegate', function($delegate) {
4369  *     $delegate.warn = $delegate.error;
4370  *     return $delegate;
4371  *   }]);
4372  * ```
4373  */
4374
4375
4376 function createInjector(modulesToLoad, strictDi) {
4377   strictDi = (strictDi === true);
4378   var INSTANTIATING = {},
4379       providerSuffix = 'Provider',
4380       path = [],
4381       loadedModules = new HashMap([], true),
4382       providerCache = {
4383         $provide: {
4384             provider: supportObject(provider),
4385             factory: supportObject(factory),
4386             service: supportObject(service),
4387             value: supportObject(value),
4388             constant: supportObject(constant),
4389             decorator: decorator
4390           }
4391       },
4392       providerInjector = (providerCache.$injector =
4393           createInternalInjector(providerCache, function(serviceName, caller) {
4394             if (angular.isString(caller)) {
4395               path.push(caller);
4396             }
4397             throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
4398           })),
4399       instanceCache = {},
4400       protoInstanceInjector =
4401           createInternalInjector(instanceCache, function(serviceName, caller) {
4402             var provider = providerInjector.get(serviceName + providerSuffix, caller);
4403             return instanceInjector.invoke(
4404                 provider.$get, provider, undefined, serviceName);
4405           }),
4406       instanceInjector = protoInstanceInjector;
4407
4408   providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
4409   var runBlocks = loadModules(modulesToLoad);
4410   instanceInjector = protoInstanceInjector.get('$injector');
4411   instanceInjector.strictDi = strictDi;
4412   forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
4413
4414   return instanceInjector;
4415
4416   ////////////////////////////////////
4417   // $provider
4418   ////////////////////////////////////
4419
4420   function supportObject(delegate) {
4421     return function(key, value) {
4422       if (isObject(key)) {
4423         forEach(key, reverseParams(delegate));
4424       } else {
4425         return delegate(key, value);
4426       }
4427     };
4428   }
4429
4430   function provider(name, provider_) {
4431     assertNotHasOwnProperty(name, 'service');
4432     if (isFunction(provider_) || isArray(provider_)) {
4433       provider_ = providerInjector.instantiate(provider_);
4434     }
4435     if (!provider_.$get) {
4436       throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
4437     }
4438     return providerCache[name + providerSuffix] = provider_;
4439   }
4440
4441   function enforceReturnValue(name, factory) {
4442     return function enforcedReturnValue() {
4443       var result = instanceInjector.invoke(factory, this);
4444       if (isUndefined(result)) {
4445         throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
4446       }
4447       return result;
4448     };
4449   }
4450
4451   function factory(name, factoryFn, enforce) {
4452     return provider(name, {
4453       $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
4454     });
4455   }
4456
4457   function service(name, constructor) {
4458     return factory(name, ['$injector', function($injector) {
4459       return $injector.instantiate(constructor);
4460     }]);
4461   }
4462
4463   function value(name, val) { return factory(name, valueFn(val), false); }
4464
4465   function constant(name, value) {
4466     assertNotHasOwnProperty(name, 'constant');
4467     providerCache[name] = value;
4468     instanceCache[name] = value;
4469   }
4470
4471   function decorator(serviceName, decorFn) {
4472     var origProvider = providerInjector.get(serviceName + providerSuffix),
4473         orig$get = origProvider.$get;
4474
4475     origProvider.$get = function() {
4476       var origInstance = instanceInjector.invoke(orig$get, origProvider);
4477       return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
4478     };
4479   }
4480
4481   ////////////////////////////////////
4482   // Module Loading
4483   ////////////////////////////////////
4484   function loadModules(modulesToLoad) {
4485     assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
4486     var runBlocks = [], moduleFn;
4487     forEach(modulesToLoad, function(module) {
4488       if (loadedModules.get(module)) return;
4489       loadedModules.put(module, true);
4490
4491       function runInvokeQueue(queue) {
4492         var i, ii;
4493         for (i = 0, ii = queue.length; i < ii; i++) {
4494           var invokeArgs = queue[i],
4495               provider = providerInjector.get(invokeArgs[0]);
4496
4497           provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
4498         }
4499       }
4500
4501       try {
4502         if (isString(module)) {
4503           moduleFn = angularModule(module);
4504           runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
4505           runInvokeQueue(moduleFn._invokeQueue);
4506           runInvokeQueue(moduleFn._configBlocks);
4507         } else if (isFunction(module)) {
4508             runBlocks.push(providerInjector.invoke(module));
4509         } else if (isArray(module)) {
4510             runBlocks.push(providerInjector.invoke(module));
4511         } else {
4512           assertArgFn(module, 'module');
4513         }
4514       } catch (e) {
4515         if (isArray(module)) {
4516           module = module[module.length - 1];
4517         }
4518         if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
4519           // Safari & FF's stack traces don't contain error.message content
4520           // unlike those of Chrome and IE
4521           // So if stack doesn't contain message, we create a new string that contains both.
4522           // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
4523           /* jshint -W022 */
4524           e = e.message + '\n' + e.stack;
4525         }
4526         throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
4527                   module, e.stack || e.message || e);
4528       }
4529     });
4530     return runBlocks;
4531   }
4532
4533   ////////////////////////////////////
4534   // internal Injector
4535   ////////////////////////////////////
4536
4537   function createInternalInjector(cache, factory) {
4538
4539     function getService(serviceName, caller) {
4540       if (cache.hasOwnProperty(serviceName)) {
4541         if (cache[serviceName] === INSTANTIATING) {
4542           throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
4543                     serviceName + ' <- ' + path.join(' <- '));
4544         }
4545         return cache[serviceName];
4546       } else {
4547         try {
4548           path.unshift(serviceName);
4549           cache[serviceName] = INSTANTIATING;
4550           return cache[serviceName] = factory(serviceName, caller);
4551         } catch (err) {
4552           if (cache[serviceName] === INSTANTIATING) {
4553             delete cache[serviceName];
4554           }
4555           throw err;
4556         } finally {
4557           path.shift();
4558         }
4559       }
4560     }
4561
4562
4563     function injectionArgs(fn, locals, serviceName) {
4564       var args = [],
4565           $inject = createInjector.$$annotate(fn, strictDi, serviceName);
4566
4567       for (var i = 0, length = $inject.length; i < length; i++) {
4568         var key = $inject[i];
4569         if (typeof key !== 'string') {
4570           throw $injectorMinErr('itkn',
4571                   'Incorrect injection token! Expected service name as string, got {0}', key);
4572         }
4573         args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
4574                                                          getService(key, serviceName));
4575       }
4576       return args;
4577     }
4578
4579     function isClass(func) {
4580       // IE 9-11 do not support classes and IE9 leaks with the code below.
4581       if (msie <= 11) {
4582         return false;
4583       }
4584       // Workaround for MS Edge.
4585       // Check https://connect.microsoft.com/IE/Feedback/Details/2211653
4586       return typeof func === 'function'
4587         && /^(?:class\s|constructor\()/.test(Function.prototype.toString.call(func));
4588     }
4589
4590     function invoke(fn, self, locals, serviceName) {
4591       if (typeof locals === 'string') {
4592         serviceName = locals;
4593         locals = null;
4594       }
4595
4596       var args = injectionArgs(fn, locals, serviceName);
4597       if (isArray(fn)) {
4598         fn = fn[fn.length - 1];
4599       }
4600
4601       if (!isClass(fn)) {
4602         // http://jsperf.com/angularjs-invoke-apply-vs-switch
4603         // #5388
4604         return fn.apply(self, args);
4605       } else {
4606         args.unshift(null);
4607         return new (Function.prototype.bind.apply(fn, args))();
4608       }
4609     }
4610
4611
4612     function instantiate(Type, locals, serviceName) {
4613       // Check if Type is annotated and use just the given function at n-1 as parameter
4614       // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
4615       var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
4616       var args = injectionArgs(Type, locals, serviceName);
4617       // Empty object at position 0 is ignored for invocation with `new`, but required.
4618       args.unshift(null);
4619       return new (Function.prototype.bind.apply(ctor, args))();
4620     }
4621
4622
4623     return {
4624       invoke: invoke,
4625       instantiate: instantiate,
4626       get: getService,
4627       annotate: createInjector.$$annotate,
4628       has: function(name) {
4629         return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
4630       }
4631     };
4632   }
4633 }
4634
4635 createInjector.$$annotate = annotate;
4636
4637 /**
4638  * @ngdoc provider
4639  * @name $anchorScrollProvider
4640  *
4641  * @description
4642  * Use `$anchorScrollProvider` to disable automatic scrolling whenever
4643  * {@link ng.$location#hash $location.hash()} changes.
4644  */
4645 function $AnchorScrollProvider() {
4646
4647   var autoScrollingEnabled = true;
4648
4649   /**
4650    * @ngdoc method
4651    * @name $anchorScrollProvider#disableAutoScrolling
4652    *
4653    * @description
4654    * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
4655    * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
4656    * Use this method to disable automatic scrolling.
4657    *
4658    * If automatic scrolling is disabled, one must explicitly call
4659    * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
4660    * current hash.
4661    */
4662   this.disableAutoScrolling = function() {
4663     autoScrollingEnabled = false;
4664   };
4665
4666   /**
4667    * @ngdoc service
4668    * @name $anchorScroll
4669    * @kind function
4670    * @requires $window
4671    * @requires $location
4672    * @requires $rootScope
4673    *
4674    * @description
4675    * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
4676    * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
4677    * in the
4678    * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
4679    *
4680    * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
4681    * match any anchor whenever it changes. This can be disabled by calling
4682    * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
4683    *
4684    * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
4685    * vertical scroll-offset (either fixed or dynamic).
4686    *
4687    * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
4688    *                       {@link ng.$location#hash $location.hash()} will be used.
4689    *
4690    * @property {(number|function|jqLite)} yOffset
4691    * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
4692    * positioned elements at the top of the page, such as navbars, headers etc.
4693    *
4694    * `yOffset` can be specified in various ways:
4695    * - **number**: A fixed number of pixels to be used as offset.<br /><br />
4696    * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
4697    *   a number representing the offset (in pixels).<br /><br />
4698    * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
4699    *   the top of the page to the element's bottom will be used as offset.<br />
4700    *   **Note**: The element will be taken into account only as long as its `position` is set to
4701    *   `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
4702    *   their height and/or positioning according to the viewport's size.
4703    *
4704    * <br />
4705    * <div class="alert alert-warning">
4706    * In order for `yOffset` to work properly, scrolling should take place on the document's root and
4707    * not some child element.
4708    * </div>
4709    *
4710    * @example
4711      <example module="anchorScrollExample">
4712        <file name="index.html">
4713          <div id="scrollArea" ng-controller="ScrollController">
4714            <a ng-click="gotoBottom()">Go to bottom</a>
4715            <a id="bottom"></a> You're at the bottom!
4716          </div>
4717        </file>
4718        <file name="script.js">
4719          angular.module('anchorScrollExample', [])
4720            .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
4721              function ($scope, $location, $anchorScroll) {
4722                $scope.gotoBottom = function() {
4723                  // set the location.hash to the id of
4724                  // the element you wish to scroll to.
4725                  $location.hash('bottom');
4726
4727                  // call $anchorScroll()
4728                  $anchorScroll();
4729                };
4730              }]);
4731        </file>
4732        <file name="style.css">
4733          #scrollArea {
4734            height: 280px;
4735            overflow: auto;
4736          }
4737
4738          #bottom {
4739            display: block;
4740            margin-top: 2000px;
4741          }
4742        </file>
4743      </example>
4744    *
4745    * <hr />
4746    * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
4747    * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
4748    *
4749    * @example
4750      <example module="anchorScrollOffsetExample">
4751        <file name="index.html">
4752          <div class="fixed-header" ng-controller="headerCtrl">
4753            <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
4754              Go to anchor {{x}}
4755            </a>
4756          </div>
4757          <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
4758            Anchor {{x}} of 5
4759          </div>
4760        </file>
4761        <file name="script.js">
4762          angular.module('anchorScrollOffsetExample', [])
4763            .run(['$anchorScroll', function($anchorScroll) {
4764              $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels
4765            }])
4766            .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
4767              function ($anchorScroll, $location, $scope) {
4768                $scope.gotoAnchor = function(x) {
4769                  var newHash = 'anchor' + x;
4770                  if ($location.hash() !== newHash) {
4771                    // set the $location.hash to `newHash` and
4772                    // $anchorScroll will automatically scroll to it
4773                    $location.hash('anchor' + x);
4774                  } else {
4775                    // call $anchorScroll() explicitly,
4776                    // since $location.hash hasn't changed
4777                    $anchorScroll();
4778                  }
4779                };
4780              }
4781            ]);
4782        </file>
4783        <file name="style.css">
4784          body {
4785            padding-top: 50px;
4786          }
4787
4788          .anchor {
4789            border: 2px dashed DarkOrchid;
4790            padding: 10px 10px 200px 10px;
4791          }
4792
4793          .fixed-header {
4794            background-color: rgba(0, 0, 0, 0.2);
4795            height: 50px;
4796            position: fixed;
4797            top: 0; left: 0; right: 0;
4798          }
4799
4800          .fixed-header > a {
4801            display: inline-block;
4802            margin: 5px 15px;
4803          }
4804        </file>
4805      </example>
4806    */
4807   this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
4808     var document = $window.document;
4809
4810     // Helper function to get first anchor from a NodeList
4811     // (using `Array#some()` instead of `angular#forEach()` since it's more performant
4812     //  and working in all supported browsers.)
4813     function getFirstAnchor(list) {
4814       var result = null;
4815       Array.prototype.some.call(list, function(element) {
4816         if (nodeName_(element) === 'a') {
4817           result = element;
4818           return true;
4819         }
4820       });
4821       return result;
4822     }
4823
4824     function getYOffset() {
4825
4826       var offset = scroll.yOffset;
4827
4828       if (isFunction(offset)) {
4829         offset = offset();
4830       } else if (isElement(offset)) {
4831         var elem = offset[0];
4832         var style = $window.getComputedStyle(elem);
4833         if (style.position !== 'fixed') {
4834           offset = 0;
4835         } else {
4836           offset = elem.getBoundingClientRect().bottom;
4837         }
4838       } else if (!isNumber(offset)) {
4839         offset = 0;
4840       }
4841
4842       return offset;
4843     }
4844
4845     function scrollTo(elem) {
4846       if (elem) {
4847         elem.scrollIntoView();
4848
4849         var offset = getYOffset();
4850
4851         if (offset) {
4852           // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
4853           // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
4854           // top of the viewport.
4855           //
4856           // IF the number of pixels from the top of `elem` to the end of the page's content is less
4857           // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
4858           // way down the page.
4859           //
4860           // This is often the case for elements near the bottom of the page.
4861           //
4862           // In such cases we do not need to scroll the whole `offset` up, just the difference between
4863           // the top of the element and the offset, which is enough to align the top of `elem` at the
4864           // desired position.
4865           var elemTop = elem.getBoundingClientRect().top;
4866           $window.scrollBy(0, elemTop - offset);
4867         }
4868       } else {
4869         $window.scrollTo(0, 0);
4870       }
4871     }
4872
4873     function scroll(hash) {
4874       hash = isString(hash) ? hash : $location.hash();
4875       var elm;
4876
4877       // empty hash, scroll to the top of the page
4878       if (!hash) scrollTo(null);
4879
4880       // element with given id
4881       else if ((elm = document.getElementById(hash))) scrollTo(elm);
4882
4883       // first anchor with given name :-D
4884       else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
4885
4886       // no element and hash == 'top', scroll to the top of the page
4887       else if (hash === 'top') scrollTo(null);
4888     }
4889
4890     // does not scroll when user clicks on anchor link that is currently on
4891     // (no url change, no $location.hash() change), browser native does scroll
4892     if (autoScrollingEnabled) {
4893       $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
4894         function autoScrollWatchAction(newVal, oldVal) {
4895           // skip the initial scroll if $location.hash is empty
4896           if (newVal === oldVal && newVal === '') return;
4897
4898           jqLiteDocumentLoaded(function() {
4899             $rootScope.$evalAsync(scroll);
4900           });
4901         });
4902     }
4903
4904     return scroll;
4905   }];
4906 }
4907
4908 var $animateMinErr = minErr('$animate');
4909 var ELEMENT_NODE = 1;
4910 var NG_ANIMATE_CLASSNAME = 'ng-animate';
4911
4912 function mergeClasses(a,b) {
4913   if (!a && !b) return '';
4914   if (!a) return b;
4915   if (!b) return a;
4916   if (isArray(a)) a = a.join(' ');
4917   if (isArray(b)) b = b.join(' ');
4918   return a + ' ' + b;
4919 }
4920
4921 function extractElementNode(element) {
4922   for (var i = 0; i < element.length; i++) {
4923     var elm = element[i];
4924     if (elm.nodeType === ELEMENT_NODE) {
4925       return elm;
4926     }
4927   }
4928 }
4929
4930 function splitClasses(classes) {
4931   if (isString(classes)) {
4932     classes = classes.split(' ');
4933   }
4934
4935   // Use createMap() to prevent class assumptions involving property names in
4936   // Object.prototype
4937   var obj = createMap();
4938   forEach(classes, function(klass) {
4939     // sometimes the split leaves empty string values
4940     // incase extra spaces were applied to the options
4941     if (klass.length) {
4942       obj[klass] = true;
4943     }
4944   });
4945   return obj;
4946 }
4947
4948 // if any other type of options value besides an Object value is
4949 // passed into the $animate.method() animation then this helper code
4950 // will be run which will ignore it. While this patch is not the
4951 // greatest solution to this, a lot of existing plugins depend on
4952 // $animate to either call the callback (< 1.2) or return a promise
4953 // that can be changed. This helper function ensures that the options
4954 // are wiped clean incase a callback function is provided.
4955 function prepareAnimateOptions(options) {
4956   return isObject(options)
4957       ? options
4958       : {};
4959 }
4960
4961 var $$CoreAnimateJsProvider = function() {
4962   this.$get = function() {};
4963 };
4964
4965 // this is prefixed with Core since it conflicts with
4966 // the animateQueueProvider defined in ngAnimate/animateQueue.js
4967 var $$CoreAnimateQueueProvider = function() {
4968   var postDigestQueue = new HashMap();
4969   var postDigestElements = [];
4970
4971   this.$get = ['$$AnimateRunner', '$rootScope',
4972        function($$AnimateRunner,   $rootScope) {
4973     return {
4974       enabled: noop,
4975       on: noop,
4976       off: noop,
4977       pin: noop,
4978
4979       push: function(element, event, options, domOperation) {
4980         domOperation        && domOperation();
4981
4982         options = options || {};
4983         options.from        && element.css(options.from);
4984         options.to          && element.css(options.to);
4985
4986         if (options.addClass || options.removeClass) {
4987           addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
4988         }
4989
4990         var runner = new $$AnimateRunner(); // jshint ignore:line
4991
4992         // since there are no animations to run the runner needs to be
4993         // notified that the animation call is complete.
4994         runner.complete();
4995         return runner;
4996       }
4997     };
4998
4999
5000     function updateData(data, classes, value) {
5001       var changed = false;
5002       if (classes) {
5003         classes = isString(classes) ? classes.split(' ') :
5004                   isArray(classes) ? classes : [];
5005         forEach(classes, function(className) {
5006           if (className) {
5007             changed = true;
5008             data[className] = value;
5009           }
5010         });
5011       }
5012       return changed;
5013     }
5014
5015     function handleCSSClassChanges() {
5016       forEach(postDigestElements, function(element) {
5017         var data = postDigestQueue.get(element);
5018         if (data) {
5019           var existing = splitClasses(element.attr('class'));
5020           var toAdd = '';
5021           var toRemove = '';
5022           forEach(data, function(status, className) {
5023             var hasClass = !!existing[className];
5024             if (status !== hasClass) {
5025               if (status) {
5026                 toAdd += (toAdd.length ? ' ' : '') + className;
5027               } else {
5028                 toRemove += (toRemove.length ? ' ' : '') + className;
5029               }
5030             }
5031           });
5032
5033           forEach(element, function(elm) {
5034             toAdd    && jqLiteAddClass(elm, toAdd);
5035             toRemove && jqLiteRemoveClass(elm, toRemove);
5036           });
5037           postDigestQueue.remove(element);
5038         }
5039       });
5040       postDigestElements.length = 0;
5041     }
5042
5043
5044     function addRemoveClassesPostDigest(element, add, remove) {
5045       var data = postDigestQueue.get(element) || {};
5046
5047       var classesAdded = updateData(data, add, true);
5048       var classesRemoved = updateData(data, remove, false);
5049
5050       if (classesAdded || classesRemoved) {
5051
5052         postDigestQueue.put(element, data);
5053         postDigestElements.push(element);
5054
5055         if (postDigestElements.length === 1) {
5056           $rootScope.$$postDigest(handleCSSClassChanges);
5057         }
5058       }
5059     }
5060   }];
5061 };
5062
5063 /**
5064  * @ngdoc provider
5065  * @name $animateProvider
5066  *
5067  * @description
5068  * Default implementation of $animate that doesn't perform any animations, instead just
5069  * synchronously performs DOM updates and resolves the returned runner promise.
5070  *
5071  * In order to enable animations the `ngAnimate` module has to be loaded.
5072  *
5073  * To see the functional implementation check out `src/ngAnimate/animate.js`.
5074  */
5075 var $AnimateProvider = ['$provide', function($provide) {
5076   var provider = this;
5077
5078   this.$$registeredAnimations = Object.create(null);
5079
5080    /**
5081    * @ngdoc method
5082    * @name $animateProvider#register
5083    *
5084    * @description
5085    * Registers a new injectable animation factory function. The factory function produces the
5086    * animation object which contains callback functions for each event that is expected to be
5087    * animated.
5088    *
5089    *   * `eventFn`: `function(element, ... , doneFunction, options)`
5090    *   The element to animate, the `doneFunction` and the options fed into the animation. Depending
5091    *   on the type of animation additional arguments will be injected into the animation function. The
5092    *   list below explains the function signatures for the different animation methods:
5093    *
5094    *   - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
5095    *   - addClass: function(element, addedClasses, doneFunction, options)
5096    *   - removeClass: function(element, removedClasses, doneFunction, options)
5097    *   - enter, leave, move: function(element, doneFunction, options)
5098    *   - animate: function(element, fromStyles, toStyles, doneFunction, options)
5099    *
5100    *   Make sure to trigger the `doneFunction` once the animation is fully complete.
5101    *
5102    * ```js
5103    *   return {
5104    *     //enter, leave, move signature
5105    *     eventFn : function(element, done, options) {
5106    *       //code to run the animation
5107    *       //once complete, then run done()
5108    *       return function endFunction(wasCancelled) {
5109    *         //code to cancel the animation
5110    *       }
5111    *     }
5112    *   }
5113    * ```
5114    *
5115    * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
5116    * @param {Function} factory The factory function that will be executed to return the animation
5117    *                           object.
5118    */
5119   this.register = function(name, factory) {
5120     if (name && name.charAt(0) !== '.') {
5121       throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
5122     }
5123
5124     var key = name + '-animation';
5125     provider.$$registeredAnimations[name.substr(1)] = key;
5126     $provide.factory(key, factory);
5127   };
5128
5129   /**
5130    * @ngdoc method
5131    * @name $animateProvider#classNameFilter
5132    *
5133    * @description
5134    * Sets and/or returns the CSS class regular expression that is checked when performing
5135    * an animation. Upon bootstrap the classNameFilter value is not set at all and will
5136    * therefore enable $animate to attempt to perform an animation on any element that is triggered.
5137    * When setting the `classNameFilter` value, animations will only be performed on elements
5138    * that successfully match the filter expression. This in turn can boost performance
5139    * for low-powered devices as well as applications containing a lot of structural operations.
5140    * @param {RegExp=} expression The className expression which will be checked against all animations
5141    * @return {RegExp} The current CSS className expression value. If null then there is no expression value
5142    */
5143   this.classNameFilter = function(expression) {
5144     if (arguments.length === 1) {
5145       this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
5146       if (this.$$classNameFilter) {
5147         var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
5148         if (reservedRegex.test(this.$$classNameFilter.toString())) {
5149           throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
5150
5151         }
5152       }
5153     }
5154     return this.$$classNameFilter;
5155   };
5156
5157   this.$get = ['$$animateQueue', function($$animateQueue) {
5158     function domInsert(element, parentElement, afterElement) {
5159       // if for some reason the previous element was removed
5160       // from the dom sometime before this code runs then let's
5161       // just stick to using the parent element as the anchor
5162       if (afterElement) {
5163         var afterNode = extractElementNode(afterElement);
5164         if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
5165           afterElement = null;
5166         }
5167       }
5168       afterElement ? afterElement.after(element) : parentElement.prepend(element);
5169     }
5170
5171     /**
5172      * @ngdoc service
5173      * @name $animate
5174      * @description The $animate service exposes a series of DOM utility methods that provide support
5175      * for animation hooks. The default behavior is the application of DOM operations, however,
5176      * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
5177      * to ensure that animation runs with the triggered DOM operation.
5178      *
5179      * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
5180      * included and only when it is active then the animation hooks that `$animate` triggers will be
5181      * functional. Once active then all structural `ng-` directives will trigger animations as they perform
5182      * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
5183      * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
5184      *
5185      * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
5186      *
5187      * To learn more about enabling animation support, click here to visit the
5188      * {@link ngAnimate ngAnimate module page}.
5189      */
5190     return {
5191       // we don't call it directly since non-existant arguments may
5192       // be interpreted as null within the sub enabled function
5193
5194       /**
5195        *
5196        * @ngdoc method
5197        * @name $animate#on
5198        * @kind function
5199        * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
5200        *    has fired on the given element or among any of its children. Once the listener is fired, the provided callback
5201        *    is fired with the following params:
5202        *
5203        * ```js
5204        * $animate.on('enter', container,
5205        *    function callback(element, phase) {
5206        *      // cool we detected an enter animation within the container
5207        *    }
5208        * );
5209        * ```
5210        *
5211        * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
5212        * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
5213        *     as well as among its children
5214        * @param {Function} callback the callback function that will be fired when the listener is triggered
5215        *
5216        * The arguments present in the callback function are:
5217        * * `element` - The captured DOM element that the animation was fired on.
5218        * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
5219        */
5220       on: $$animateQueue.on,
5221
5222       /**
5223        *
5224        * @ngdoc method
5225        * @name $animate#off
5226        * @kind function
5227        * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
5228        * can be used in three different ways depending on the arguments:
5229        *
5230        * ```js
5231        * // remove all the animation event listeners listening for `enter`
5232        * $animate.off('enter');
5233        *
5234        * // remove all the animation event listeners listening for `enter` on the given element and its children
5235        * $animate.off('enter', container);
5236        *
5237        * // remove the event listener function provided by `callback` that is set
5238        * // to listen for `enter` on the given `container` as well as its children
5239        * $animate.off('enter', container, callback);
5240        * ```
5241        *
5242        * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
5243        * @param {DOMElement=} container the container element the event listener was placed on
5244        * @param {Function=} callback the callback function that was registered as the listener
5245        */
5246       off: $$animateQueue.off,
5247
5248       /**
5249        * @ngdoc method
5250        * @name $animate#pin
5251        * @kind function
5252        * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
5253        *    outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
5254        *    element despite being outside the realm of the application or within another application. Say for example if the application
5255        *    was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
5256        *    as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
5257        *    that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
5258        *
5259        *    Note that this feature is only active when the `ngAnimate` module is used.
5260        *
5261        * @param {DOMElement} element the external element that will be pinned
5262        * @param {DOMElement} parentElement the host parent element that will be associated with the external element
5263        */
5264       pin: $$animateQueue.pin,
5265
5266       /**
5267        *
5268        * @ngdoc method
5269        * @name $animate#enabled
5270        * @kind function
5271        * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
5272        * function can be called in four ways:
5273        *
5274        * ```js
5275        * // returns true or false
5276        * $animate.enabled();
5277        *
5278        * // changes the enabled state for all animations
5279        * $animate.enabled(false);
5280        * $animate.enabled(true);
5281        *
5282        * // returns true or false if animations are enabled for an element
5283        * $animate.enabled(element);
5284        *
5285        * // changes the enabled state for an element and its children
5286        * $animate.enabled(element, true);
5287        * $animate.enabled(element, false);
5288        * ```
5289        *
5290        * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
5291        * @param {boolean=} enabled whether or not the animations will be enabled for the element
5292        *
5293        * @return {boolean} whether or not animations are enabled
5294        */
5295       enabled: $$animateQueue.enabled,
5296
5297       /**
5298        * @ngdoc method
5299        * @name $animate#cancel
5300        * @kind function
5301        * @description Cancels the provided animation.
5302        *
5303        * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
5304        */
5305       cancel: function(runner) {
5306         runner.end && runner.end();
5307       },
5308
5309       /**
5310        *
5311        * @ngdoc method
5312        * @name $animate#enter
5313        * @kind function
5314        * @description Inserts the element into the DOM either after the `after` element (if provided) or
5315        *   as the first child within the `parent` element and then triggers an animation.
5316        *   A promise is returned that will be resolved during the next digest once the animation
5317        *   has completed.
5318        *
5319        * @param {DOMElement} element the element which will be inserted into the DOM
5320        * @param {DOMElement} parent the parent element which will append the element as
5321        *   a child (so long as the after element is not present)
5322        * @param {DOMElement=} after the sibling element after which the element will be appended
5323        * @param {object=} options an optional collection of options/styles that will be applied to the element
5324        *
5325        * @return {Promise} the animation callback promise
5326        */
5327       enter: function(element, parent, after, options) {
5328         parent = parent && jqLite(parent);
5329         after = after && jqLite(after);
5330         parent = parent || after.parent();
5331         domInsert(element, parent, after);
5332         return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
5333       },
5334
5335       /**
5336        *
5337        * @ngdoc method
5338        * @name $animate#move
5339        * @kind function
5340        * @description Inserts (moves) the element into its new position in the DOM either after
5341        *   the `after` element (if provided) or as the first child within the `parent` element
5342        *   and then triggers an animation. A promise is returned that will be resolved
5343        *   during the next digest once the animation has completed.
5344        *
5345        * @param {DOMElement} element the element which will be moved into the new DOM position
5346        * @param {DOMElement} parent the parent element which will append the element as
5347        *   a child (so long as the after element is not present)
5348        * @param {DOMElement=} after the sibling element after which the element will be appended
5349        * @param {object=} options an optional collection of options/styles that will be applied to the element
5350        *
5351        * @return {Promise} the animation callback promise
5352        */
5353       move: function(element, parent, after, options) {
5354         parent = parent && jqLite(parent);
5355         after = after && jqLite(after);
5356         parent = parent || after.parent();
5357         domInsert(element, parent, after);
5358         return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
5359       },
5360
5361       /**
5362        * @ngdoc method
5363        * @name $animate#leave
5364        * @kind function
5365        * @description Triggers an animation and then removes the element from the DOM.
5366        * When the function is called a promise is returned that will be resolved during the next
5367        * digest once the animation has completed.
5368        *
5369        * @param {DOMElement} element the element which will be removed from the DOM
5370        * @param {object=} options an optional collection of options/styles that will be applied to the element
5371        *
5372        * @return {Promise} the animation callback promise
5373        */
5374       leave: function(element, options) {
5375         return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
5376           element.remove();
5377         });
5378       },
5379
5380       /**
5381        * @ngdoc method
5382        * @name $animate#addClass
5383        * @kind function
5384        *
5385        * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
5386        *   execution, the addClass operation will only be handled after the next digest and it will not trigger an
5387        *   animation if element already contains the CSS class or if the class is removed at a later step.
5388        *   Note that class-based animations are treated differently compared to structural animations
5389        *   (like enter, move and leave) since the CSS classes may be added/removed at different points
5390        *   depending if CSS or JavaScript animations are used.
5391        *
5392        * @param {DOMElement} element the element which the CSS classes will be applied to
5393        * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
5394        * @param {object=} options an optional collection of options/styles that will be applied to the element
5395        *
5396        * @return {Promise} the animation callback promise
5397        */
5398       addClass: function(element, className, options) {
5399         options = prepareAnimateOptions(options);
5400         options.addClass = mergeClasses(options.addclass, className);
5401         return $$animateQueue.push(element, 'addClass', options);
5402       },
5403
5404       /**
5405        * @ngdoc method
5406        * @name $animate#removeClass
5407        * @kind function
5408        *
5409        * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
5410        *   execution, the removeClass operation will only be handled after the next digest and it will not trigger an
5411        *   animation if element does not contain the CSS class or if the class is added at a later step.
5412        *   Note that class-based animations are treated differently compared to structural animations
5413        *   (like enter, move and leave) since the CSS classes may be added/removed at different points
5414        *   depending if CSS or JavaScript animations are used.
5415        *
5416        * @param {DOMElement} element the element which the CSS classes will be applied to
5417        * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
5418        * @param {object=} options an optional collection of options/styles that will be applied to the element
5419        *
5420        * @return {Promise} the animation callback promise
5421        */
5422       removeClass: function(element, className, options) {
5423         options = prepareAnimateOptions(options);
5424         options.removeClass = mergeClasses(options.removeClass, className);
5425         return $$animateQueue.push(element, 'removeClass', options);
5426       },
5427
5428       /**
5429        * @ngdoc method
5430        * @name $animate#setClass
5431        * @kind function
5432        *
5433        * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
5434        *    triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
5435        *    `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
5436        *    passed. Note that class-based animations are treated differently compared to structural animations
5437        *    (like enter, move and leave) since the CSS classes may be added/removed at different points
5438        *    depending if CSS or JavaScript animations are used.
5439        *
5440        * @param {DOMElement} element the element which the CSS classes will be applied to
5441        * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
5442        * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
5443        * @param {object=} options an optional collection of options/styles that will be applied to the element
5444        *
5445        * @return {Promise} the animation callback promise
5446        */
5447       setClass: function(element, add, remove, options) {
5448         options = prepareAnimateOptions(options);
5449         options.addClass = mergeClasses(options.addClass, add);
5450         options.removeClass = mergeClasses(options.removeClass, remove);
5451         return $$animateQueue.push(element, 'setClass', options);
5452       },
5453
5454       /**
5455        * @ngdoc method
5456        * @name $animate#animate
5457        * @kind function
5458        *
5459        * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
5460        * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
5461        * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
5462        * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
5463        * style in `to`, the style in `from` is applied immediately, and no animation is run.
5464        * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
5465        * method (or as part of the `options` parameter):
5466        *
5467        * ```js
5468        * ngModule.animation('.my-inline-animation', function() {
5469        *   return {
5470        *     animate : function(element, from, to, done, options) {
5471        *       //animation
5472        *       done();
5473        *     }
5474        *   }
5475        * });
5476        * ```
5477        *
5478        * @param {DOMElement} element the element which the CSS styles will be applied to
5479        * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
5480        * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
5481        * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
5482        *    this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
5483        *    (Note that if no animation is detected then this value will not be applied to the element.)
5484        * @param {object=} options an optional collection of options/styles that will be applied to the element
5485        *
5486        * @return {Promise} the animation callback promise
5487        */
5488       animate: function(element, from, to, className, options) {
5489         options = prepareAnimateOptions(options);
5490         options.from = options.from ? extend(options.from, from) : from;
5491         options.to   = options.to   ? extend(options.to, to)     : to;
5492
5493         className = className || 'ng-inline-animate';
5494         options.tempClasses = mergeClasses(options.tempClasses, className);
5495         return $$animateQueue.push(element, 'animate', options);
5496       }
5497     };
5498   }];
5499 }];
5500
5501 var $$AnimateAsyncRunFactoryProvider = function() {
5502   this.$get = ['$$rAF', function($$rAF) {
5503     var waitQueue = [];
5504
5505     function waitForTick(fn) {
5506       waitQueue.push(fn);
5507       if (waitQueue.length > 1) return;
5508       $$rAF(function() {
5509         for (var i = 0; i < waitQueue.length; i++) {
5510           waitQueue[i]();
5511         }
5512         waitQueue = [];
5513       });
5514     }
5515
5516     return function() {
5517       var passed = false;
5518       waitForTick(function() {
5519         passed = true;
5520       });
5521       return function(callback) {
5522         passed ? callback() : waitForTick(callback);
5523       };
5524     };
5525   }];
5526 };
5527
5528 var $$AnimateRunnerFactoryProvider = function() {
5529   this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
5530        function($q,   $sniffer,   $$animateAsyncRun,   $document,   $timeout) {
5531
5532     var INITIAL_STATE = 0;
5533     var DONE_PENDING_STATE = 1;
5534     var DONE_COMPLETE_STATE = 2;
5535
5536     AnimateRunner.chain = function(chain, callback) {
5537       var index = 0;
5538
5539       next();
5540       function next() {
5541         if (index === chain.length) {
5542           callback(true);
5543           return;
5544         }
5545
5546         chain[index](function(response) {
5547           if (response === false) {
5548             callback(false);
5549             return;
5550           }
5551           index++;
5552           next();
5553         });
5554       }
5555     };
5556
5557     AnimateRunner.all = function(runners, callback) {
5558       var count = 0;
5559       var status = true;
5560       forEach(runners, function(runner) {
5561         runner.done(onProgress);
5562       });
5563
5564       function onProgress(response) {
5565         status = status && response;
5566         if (++count === runners.length) {
5567           callback(status);
5568         }
5569       }
5570     };
5571
5572     function AnimateRunner(host) {
5573       this.setHost(host);
5574
5575       var rafTick = $$animateAsyncRun();
5576       var timeoutTick = function(fn) {
5577         $timeout(fn, 0, false);
5578       };
5579
5580       this._doneCallbacks = [];
5581       this._tick = function(fn) {
5582         var doc = $document[0];
5583
5584         // the document may not be ready or attached
5585         // to the module for some internal tests
5586         if (doc && doc.hidden) {
5587           timeoutTick(fn);
5588         } else {
5589           rafTick(fn);
5590         }
5591       };
5592       this._state = 0;
5593     }
5594
5595     AnimateRunner.prototype = {
5596       setHost: function(host) {
5597         this.host = host || {};
5598       },
5599
5600       done: function(fn) {
5601         if (this._state === DONE_COMPLETE_STATE) {
5602           fn();
5603         } else {
5604           this._doneCallbacks.push(fn);
5605         }
5606       },
5607
5608       progress: noop,
5609
5610       getPromise: function() {
5611         if (!this.promise) {
5612           var self = this;
5613           this.promise = $q(function(resolve, reject) {
5614             self.done(function(status) {
5615               status === false ? reject() : resolve();
5616             });
5617           });
5618         }
5619         return this.promise;
5620       },
5621
5622       then: function(resolveHandler, rejectHandler) {
5623         return this.getPromise().then(resolveHandler, rejectHandler);
5624       },
5625
5626       'catch': function(handler) {
5627         return this.getPromise()['catch'](handler);
5628       },
5629
5630       'finally': function(handler) {
5631         return this.getPromise()['finally'](handler);
5632       },
5633
5634       pause: function() {
5635         if (this.host.pause) {
5636           this.host.pause();
5637         }
5638       },
5639
5640       resume: function() {
5641         if (this.host.resume) {
5642           this.host.resume();
5643         }
5644       },
5645
5646       end: function() {
5647         if (this.host.end) {
5648           this.host.end();
5649         }
5650         this._resolve(true);
5651       },
5652
5653       cancel: function() {
5654         if (this.host.cancel) {
5655           this.host.cancel();
5656         }
5657         this._resolve(false);
5658       },
5659
5660       complete: function(response) {
5661         var self = this;
5662         if (self._state === INITIAL_STATE) {
5663           self._state = DONE_PENDING_STATE;
5664           self._tick(function() {
5665             self._resolve(response);
5666           });
5667         }
5668       },
5669
5670       _resolve: function(response) {
5671         if (this._state !== DONE_COMPLETE_STATE) {
5672           forEach(this._doneCallbacks, function(fn) {
5673             fn(response);
5674           });
5675           this._doneCallbacks.length = 0;
5676           this._state = DONE_COMPLETE_STATE;
5677         }
5678       }
5679     };
5680
5681     return AnimateRunner;
5682   }];
5683 };
5684
5685 /**
5686  * @ngdoc service
5687  * @name $animateCss
5688  * @kind object
5689  *
5690  * @description
5691  * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
5692  * then the `$animateCss` service will actually perform animations.
5693  *
5694  * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
5695  */
5696 var $CoreAnimateCssProvider = function() {
5697   this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
5698
5699     return function(element, initialOptions) {
5700       // all of the animation functions should create
5701       // a copy of the options data, however, if a
5702       // parent service has already created a copy then
5703       // we should stick to using that
5704       var options = initialOptions || {};
5705       if (!options.$$prepared) {
5706         options = copy(options);
5707       }
5708
5709       // there is no point in applying the styles since
5710       // there is no animation that goes on at all in
5711       // this version of $animateCss.
5712       if (options.cleanupStyles) {
5713         options.from = options.to = null;
5714       }
5715
5716       if (options.from) {
5717         element.css(options.from);
5718         options.from = null;
5719       }
5720
5721       /* jshint newcap: false */
5722       var closed, runner = new $$AnimateRunner();
5723       return {
5724         start: run,
5725         end: run
5726       };
5727
5728       function run() {
5729         $$rAF(function() {
5730           applyAnimationContents();
5731           if (!closed) {
5732             runner.complete();
5733           }
5734           closed = true;
5735         });
5736         return runner;
5737       }
5738
5739       function applyAnimationContents() {
5740         if (options.addClass) {
5741           element.addClass(options.addClass);
5742           options.addClass = null;
5743         }
5744         if (options.removeClass) {
5745           element.removeClass(options.removeClass);
5746           options.removeClass = null;
5747         }
5748         if (options.to) {
5749           element.css(options.to);
5750           options.to = null;
5751         }
5752       }
5753     };
5754   }];
5755 };
5756
5757 /* global stripHash: true */
5758
5759 /**
5760  * ! This is a private undocumented service !
5761  *
5762  * @name $browser
5763  * @requires $log
5764  * @description
5765  * This object has two goals:
5766  *
5767  * - hide all the global state in the browser caused by the window object
5768  * - abstract away all the browser specific features and inconsistencies
5769  *
5770  * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
5771  * service, which can be used for convenient testing of the application without the interaction with
5772  * the real browser apis.
5773  */
5774 /**
5775  * @param {object} window The global window object.
5776  * @param {object} document jQuery wrapped document.
5777  * @param {object} $log window.console or an object with the same interface.
5778  * @param {object} $sniffer $sniffer service
5779  */
5780 function Browser(window, document, $log, $sniffer) {
5781   var self = this,
5782       rawDocument = document[0],
5783       location = window.location,
5784       history = window.history,
5785       setTimeout = window.setTimeout,
5786       clearTimeout = window.clearTimeout,
5787       pendingDeferIds = {};
5788
5789   self.isMock = false;
5790
5791   var outstandingRequestCount = 0;
5792   var outstandingRequestCallbacks = [];
5793
5794   // TODO(vojta): remove this temporary api
5795   self.$$completeOutstandingRequest = completeOutstandingRequest;
5796   self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
5797
5798   /**
5799    * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
5800    * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
5801    */
5802   function completeOutstandingRequest(fn) {
5803     try {
5804       fn.apply(null, sliceArgs(arguments, 1));
5805     } finally {
5806       outstandingRequestCount--;
5807       if (outstandingRequestCount === 0) {
5808         while (outstandingRequestCallbacks.length) {
5809           try {
5810             outstandingRequestCallbacks.pop()();
5811           } catch (e) {
5812             $log.error(e);
5813           }
5814         }
5815       }
5816     }
5817   }
5818
5819   function getHash(url) {
5820     var index = url.indexOf('#');
5821     return index === -1 ? '' : url.substr(index);
5822   }
5823
5824   /**
5825    * @private
5826    * Note: this method is used only by scenario runner
5827    * TODO(vojta): prefix this method with $$ ?
5828    * @param {function()} callback Function that will be called when no outstanding request
5829    */
5830   self.notifyWhenNoOutstandingRequests = function(callback) {
5831     if (outstandingRequestCount === 0) {
5832       callback();
5833     } else {
5834       outstandingRequestCallbacks.push(callback);
5835     }
5836   };
5837
5838   //////////////////////////////////////////////////////////////
5839   // URL API
5840   //////////////////////////////////////////////////////////////
5841
5842   var cachedState, lastHistoryState,
5843       lastBrowserUrl = location.href,
5844       baseElement = document.find('base'),
5845       pendingLocation = null;
5846
5847   cacheState();
5848   lastHistoryState = cachedState;
5849
5850   /**
5851    * @name $browser#url
5852    *
5853    * @description
5854    * GETTER:
5855    * Without any argument, this method just returns current value of location.href.
5856    *
5857    * SETTER:
5858    * With at least one argument, this method sets url to new value.
5859    * If html5 history api supported, pushState/replaceState is used, otherwise
5860    * location.href/location.replace is used.
5861    * Returns its own instance to allow chaining
5862    *
5863    * NOTE: this api is intended for use only by the $location service. Please use the
5864    * {@link ng.$location $location service} to change url.
5865    *
5866    * @param {string} url New url (when used as setter)
5867    * @param {boolean=} replace Should new url replace current history record?
5868    * @param {object=} state object to use with pushState/replaceState
5869    */
5870   self.url = function(url, replace, state) {
5871     // In modern browsers `history.state` is `null` by default; treating it separately
5872     // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
5873     // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
5874     if (isUndefined(state)) {
5875       state = null;
5876     }
5877
5878     // Android Browser BFCache causes location, history reference to become stale.
5879     if (location !== window.location) location = window.location;
5880     if (history !== window.history) history = window.history;
5881
5882     // setter
5883     if (url) {
5884       var sameState = lastHistoryState === state;
5885
5886       // Don't change anything if previous and current URLs and states match. This also prevents
5887       // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
5888       // See https://github.com/angular/angular.js/commit/ffb2701
5889       if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
5890         return self;
5891       }
5892       var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
5893       lastBrowserUrl = url;
5894       lastHistoryState = state;
5895       // Don't use history API if only the hash changed
5896       // due to a bug in IE10/IE11 which leads
5897       // to not firing a `hashchange` nor `popstate` event
5898       // in some cases (see #9143).
5899       if ($sniffer.history && (!sameBase || !sameState)) {
5900         history[replace ? 'replaceState' : 'pushState'](state, '', url);
5901         cacheState();
5902         // Do the assignment again so that those two variables are referentially identical.
5903         lastHistoryState = cachedState;
5904       } else {
5905         if (!sameBase || pendingLocation) {
5906           pendingLocation = url;
5907         }
5908         if (replace) {
5909           location.replace(url);
5910         } else if (!sameBase) {
5911           location.href = url;
5912         } else {
5913           location.hash = getHash(url);
5914         }
5915         if (location.href !== url) {
5916           pendingLocation = url;
5917         }
5918       }
5919       return self;
5920     // getter
5921     } else {
5922       // - pendingLocation is needed as browsers don't allow to read out
5923       //   the new location.href if a reload happened or if there is a bug like in iOS 9 (see
5924       //   https://openradar.appspot.com/22186109).
5925       // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
5926       return pendingLocation || location.href.replace(/%27/g,"'");
5927     }
5928   };
5929
5930   /**
5931    * @name $browser#state
5932    *
5933    * @description
5934    * This method is a getter.
5935    *
5936    * Return history.state or null if history.state is undefined.
5937    *
5938    * @returns {object} state
5939    */
5940   self.state = function() {
5941     return cachedState;
5942   };
5943
5944   var urlChangeListeners = [],
5945       urlChangeInit = false;
5946
5947   function cacheStateAndFireUrlChange() {
5948     pendingLocation = null;
5949     cacheState();
5950     fireUrlChange();
5951   }
5952
5953   function getCurrentState() {
5954     try {
5955       return history.state;
5956     } catch (e) {
5957       // MSIE can reportedly throw when there is no state (UNCONFIRMED).
5958     }
5959   }
5960
5961   // This variable should be used *only* inside the cacheState function.
5962   var lastCachedState = null;
5963   function cacheState() {
5964     // This should be the only place in $browser where `history.state` is read.
5965     cachedState = getCurrentState();
5966     cachedState = isUndefined(cachedState) ? null : cachedState;
5967
5968     // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
5969     if (equals(cachedState, lastCachedState)) {
5970       cachedState = lastCachedState;
5971     }
5972     lastCachedState = cachedState;
5973   }
5974
5975   function fireUrlChange() {
5976     if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
5977       return;
5978     }
5979
5980     lastBrowserUrl = self.url();
5981     lastHistoryState = cachedState;
5982     forEach(urlChangeListeners, function(listener) {
5983       listener(self.url(), cachedState);
5984     });
5985   }
5986
5987   /**
5988    * @name $browser#onUrlChange
5989    *
5990    * @description
5991    * Register callback function that will be called, when url changes.
5992    *
5993    * It's only called when the url is changed from outside of angular:
5994    * - user types different url into address bar
5995    * - user clicks on history (forward/back) button
5996    * - user clicks on a link
5997    *
5998    * It's not called when url is changed by $browser.url() method
5999    *
6000    * The listener gets called with new url as parameter.
6001    *
6002    * NOTE: this api is intended for use only by the $location service. Please use the
6003    * {@link ng.$location $location service} to monitor url changes in angular apps.
6004    *
6005    * @param {function(string)} listener Listener function to be called when url changes.
6006    * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
6007    */
6008   self.onUrlChange = function(callback) {
6009     // TODO(vojta): refactor to use node's syntax for events
6010     if (!urlChangeInit) {
6011       // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
6012       // don't fire popstate when user change the address bar and don't fire hashchange when url
6013       // changed by push/replaceState
6014
6015       // html5 history api - popstate event
6016       if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
6017       // hashchange event
6018       jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
6019
6020       urlChangeInit = true;
6021     }
6022
6023     urlChangeListeners.push(callback);
6024     return callback;
6025   };
6026
6027   /**
6028    * @private
6029    * Remove popstate and hashchange handler from window.
6030    *
6031    * NOTE: this api is intended for use only by $rootScope.
6032    */
6033   self.$$applicationDestroyed = function() {
6034     jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
6035   };
6036
6037   /**
6038    * Checks whether the url has changed outside of Angular.
6039    * Needs to be exported to be able to check for changes that have been done in sync,
6040    * as hashchange/popstate events fire in async.
6041    */
6042   self.$$checkUrlChange = fireUrlChange;
6043
6044   //////////////////////////////////////////////////////////////
6045   // Misc API
6046   //////////////////////////////////////////////////////////////
6047
6048   /**
6049    * @name $browser#baseHref
6050    *
6051    * @description
6052    * Returns current <base href>
6053    * (always relative - without domain)
6054    *
6055    * @returns {string} The current base href
6056    */
6057   self.baseHref = function() {
6058     var href = baseElement.attr('href');
6059     return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
6060   };
6061
6062   /**
6063    * @name $browser#defer
6064    * @param {function()} fn A function, who's execution should be deferred.
6065    * @param {number=} [delay=0] of milliseconds to defer the function execution.
6066    * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
6067    *
6068    * @description
6069    * Executes a fn asynchronously via `setTimeout(fn, delay)`.
6070    *
6071    * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
6072    * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
6073    * via `$browser.defer.flush()`.
6074    *
6075    */
6076   self.defer = function(fn, delay) {
6077     var timeoutId;
6078     outstandingRequestCount++;
6079     timeoutId = setTimeout(function() {
6080       delete pendingDeferIds[timeoutId];
6081       completeOutstandingRequest(fn);
6082     }, delay || 0);
6083     pendingDeferIds[timeoutId] = true;
6084     return timeoutId;
6085   };
6086
6087
6088   /**
6089    * @name $browser#defer.cancel
6090    *
6091    * @description
6092    * Cancels a deferred task identified with `deferId`.
6093    *
6094    * @param {*} deferId Token returned by the `$browser.defer` function.
6095    * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
6096    *                    canceled.
6097    */
6098   self.defer.cancel = function(deferId) {
6099     if (pendingDeferIds[deferId]) {
6100       delete pendingDeferIds[deferId];
6101       clearTimeout(deferId);
6102       completeOutstandingRequest(noop);
6103       return true;
6104     }
6105     return false;
6106   };
6107
6108 }
6109
6110 function $BrowserProvider() {
6111   this.$get = ['$window', '$log', '$sniffer', '$document',
6112       function($window, $log, $sniffer, $document) {
6113         return new Browser($window, $document, $log, $sniffer);
6114       }];
6115 }
6116
6117 /**
6118  * @ngdoc service
6119  * @name $cacheFactory
6120  *
6121  * @description
6122  * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
6123  * them.
6124  *
6125  * ```js
6126  *
6127  *  var cache = $cacheFactory('cacheId');
6128  *  expect($cacheFactory.get('cacheId')).toBe(cache);
6129  *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
6130  *
6131  *  cache.put("key", "value");
6132  *  cache.put("another key", "another value");
6133  *
6134  *  // We've specified no options on creation
6135  *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});
6136  *
6137  * ```
6138  *
6139  *
6140  * @param {string} cacheId Name or id of the newly created cache.
6141  * @param {object=} options Options object that specifies the cache behavior. Properties:
6142  *
6143  *   - `{number=}` `capacity` — turns the cache into LRU cache.
6144  *
6145  * @returns {object} Newly created cache object with the following set of methods:
6146  *
6147  * - `{object}` `info()` — Returns id, size, and options of cache.
6148  * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
6149  *   it.
6150  * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
6151  * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
6152  * - `{void}` `removeAll()` — Removes all cached values.
6153  * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
6154  *
6155  * @example
6156    <example module="cacheExampleApp">
6157      <file name="index.html">
6158        <div ng-controller="CacheController">
6159          <input ng-model="newCacheKey" placeholder="Key">
6160          <input ng-model="newCacheValue" placeholder="Value">
6161          <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
6162
6163          <p ng-if="keys.length">Cached Values</p>
6164          <div ng-repeat="key in keys">
6165            <span ng-bind="key"></span>
6166            <span>: </span>
6167            <b ng-bind="cache.get(key)"></b>
6168          </div>
6169
6170          <p>Cache Info</p>
6171          <div ng-repeat="(key, value) in cache.info()">
6172            <span ng-bind="key"></span>
6173            <span>: </span>
6174            <b ng-bind="value"></b>
6175          </div>
6176        </div>
6177      </file>
6178      <file name="script.js">
6179        angular.module('cacheExampleApp', []).
6180          controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
6181            $scope.keys = [];
6182            $scope.cache = $cacheFactory('cacheId');
6183            $scope.put = function(key, value) {
6184              if (angular.isUndefined($scope.cache.get(key))) {
6185                $scope.keys.push(key);
6186              }
6187              $scope.cache.put(key, angular.isUndefined(value) ? null : value);
6188            };
6189          }]);
6190      </file>
6191      <file name="style.css">
6192        p {
6193          margin: 10px 0 3px;
6194        }
6195      </file>
6196    </example>
6197  */
6198 function $CacheFactoryProvider() {
6199
6200   this.$get = function() {
6201     var caches = {};
6202
6203     function cacheFactory(cacheId, options) {
6204       if (cacheId in caches) {
6205         throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
6206       }
6207
6208       var size = 0,
6209           stats = extend({}, options, {id: cacheId}),
6210           data = createMap(),
6211           capacity = (options && options.capacity) || Number.MAX_VALUE,
6212           lruHash = createMap(),
6213           freshEnd = null,
6214           staleEnd = null;
6215
6216       /**
6217        * @ngdoc type
6218        * @name $cacheFactory.Cache
6219        *
6220        * @description
6221        * A cache object used to store and retrieve data, primarily used by
6222        * {@link $http $http} and the {@link ng.directive:script script} directive to cache
6223        * templates and other data.
6224        *
6225        * ```js
6226        *  angular.module('superCache')
6227        *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {
6228        *      return $cacheFactory('super-cache');
6229        *    }]);
6230        * ```
6231        *
6232        * Example test:
6233        *
6234        * ```js
6235        *  it('should behave like a cache', inject(function(superCache) {
6236        *    superCache.put('key', 'value');
6237        *    superCache.put('another key', 'another value');
6238        *
6239        *    expect(superCache.info()).toEqual({
6240        *      id: 'super-cache',
6241        *      size: 2
6242        *    });
6243        *
6244        *    superCache.remove('another key');
6245        *    expect(superCache.get('another key')).toBeUndefined();
6246        *
6247        *    superCache.removeAll();
6248        *    expect(superCache.info()).toEqual({
6249        *      id: 'super-cache',
6250        *      size: 0
6251        *    });
6252        *  }));
6253        * ```
6254        */
6255       return caches[cacheId] = {
6256
6257         /**
6258          * @ngdoc method
6259          * @name $cacheFactory.Cache#put
6260          * @kind function
6261          *
6262          * @description
6263          * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
6264          * retrieved later, and incrementing the size of the cache if the key was not already
6265          * present in the cache. If behaving like an LRU cache, it will also remove stale
6266          * entries from the set.
6267          *
6268          * It will not insert undefined values into the cache.
6269          *
6270          * @param {string} key the key under which the cached data is stored.
6271          * @param {*} value the value to store alongside the key. If it is undefined, the key
6272          *    will not be stored.
6273          * @returns {*} the value stored.
6274          */
6275         put: function(key, value) {
6276           if (isUndefined(value)) return;
6277           if (capacity < Number.MAX_VALUE) {
6278             var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
6279
6280             refresh(lruEntry);
6281           }
6282
6283           if (!(key in data)) size++;
6284           data[key] = value;
6285
6286           if (size > capacity) {
6287             this.remove(staleEnd.key);
6288           }
6289
6290           return value;
6291         },
6292
6293         /**
6294          * @ngdoc method
6295          * @name $cacheFactory.Cache#get
6296          * @kind function
6297          *
6298          * @description
6299          * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
6300          *
6301          * @param {string} key the key of the data to be retrieved
6302          * @returns {*} the value stored.
6303          */
6304         get: function(key) {
6305           if (capacity < Number.MAX_VALUE) {
6306             var lruEntry = lruHash[key];
6307
6308             if (!lruEntry) return;
6309
6310             refresh(lruEntry);
6311           }
6312
6313           return data[key];
6314         },
6315
6316
6317         /**
6318          * @ngdoc method
6319          * @name $cacheFactory.Cache#remove
6320          * @kind function
6321          *
6322          * @description
6323          * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
6324          *
6325          * @param {string} key the key of the entry to be removed
6326          */
6327         remove: function(key) {
6328           if (capacity < Number.MAX_VALUE) {
6329             var lruEntry = lruHash[key];
6330
6331             if (!lruEntry) return;
6332
6333             if (lruEntry == freshEnd) freshEnd = lruEntry.p;
6334             if (lruEntry == staleEnd) staleEnd = lruEntry.n;
6335             link(lruEntry.n,lruEntry.p);
6336
6337             delete lruHash[key];
6338           }
6339
6340           if (!(key in data)) return;
6341
6342           delete data[key];
6343           size--;
6344         },
6345
6346
6347         /**
6348          * @ngdoc method
6349          * @name $cacheFactory.Cache#removeAll
6350          * @kind function
6351          *
6352          * @description
6353          * Clears the cache object of any entries.
6354          */
6355         removeAll: function() {
6356           data = createMap();
6357           size = 0;
6358           lruHash = createMap();
6359           freshEnd = staleEnd = null;
6360         },
6361
6362
6363         /**
6364          * @ngdoc method
6365          * @name $cacheFactory.Cache#destroy
6366          * @kind function
6367          *
6368          * @description
6369          * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
6370          * removing it from the {@link $cacheFactory $cacheFactory} set.
6371          */
6372         destroy: function() {
6373           data = null;
6374           stats = null;
6375           lruHash = null;
6376           delete caches[cacheId];
6377         },
6378
6379
6380         /**
6381          * @ngdoc method
6382          * @name $cacheFactory.Cache#info
6383          * @kind function
6384          *
6385          * @description
6386          * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
6387          *
6388          * @returns {object} an object with the following properties:
6389          *   <ul>
6390          *     <li>**id**: the id of the cache instance</li>
6391          *     <li>**size**: the number of entries kept in the cache instance</li>
6392          *     <li>**...**: any additional properties from the options object when creating the
6393          *       cache.</li>
6394          *   </ul>
6395          */
6396         info: function() {
6397           return extend({}, stats, {size: size});
6398         }
6399       };
6400
6401
6402       /**
6403        * makes the `entry` the freshEnd of the LRU linked list
6404        */
6405       function refresh(entry) {
6406         if (entry != freshEnd) {
6407           if (!staleEnd) {
6408             staleEnd = entry;
6409           } else if (staleEnd == entry) {
6410             staleEnd = entry.n;
6411           }
6412
6413           link(entry.n, entry.p);
6414           link(entry, freshEnd);
6415           freshEnd = entry;
6416           freshEnd.n = null;
6417         }
6418       }
6419
6420
6421       /**
6422        * bidirectionally links two entries of the LRU linked list
6423        */
6424       function link(nextEntry, prevEntry) {
6425         if (nextEntry != prevEntry) {
6426           if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
6427           if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
6428         }
6429       }
6430     }
6431
6432
6433   /**
6434    * @ngdoc method
6435    * @name $cacheFactory#info
6436    *
6437    * @description
6438    * Get information about all the caches that have been created
6439    *
6440    * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
6441    */
6442     cacheFactory.info = function() {
6443       var info = {};
6444       forEach(caches, function(cache, cacheId) {
6445         info[cacheId] = cache.info();
6446       });
6447       return info;
6448     };
6449
6450
6451   /**
6452    * @ngdoc method
6453    * @name $cacheFactory#get
6454    *
6455    * @description
6456    * Get access to a cache object by the `cacheId` used when it was created.
6457    *
6458    * @param {string} cacheId Name or id of a cache to access.
6459    * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
6460    */
6461     cacheFactory.get = function(cacheId) {
6462       return caches[cacheId];
6463     };
6464
6465
6466     return cacheFactory;
6467   };
6468 }
6469
6470 /**
6471  * @ngdoc service
6472  * @name $templateCache
6473  *
6474  * @description
6475  * The first time a template is used, it is loaded in the template cache for quick retrieval. You
6476  * can load templates directly into the cache in a `script` tag, or by consuming the
6477  * `$templateCache` service directly.
6478  *
6479  * Adding via the `script` tag:
6480  *
6481  * ```html
6482  *   <script type="text/ng-template" id="templateId.html">
6483  *     <p>This is the content of the template</p>
6484  *   </script>
6485  * ```
6486  *
6487  * **Note:** the `script` tag containing the template does not need to be included in the `head` of
6488  * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
6489  * element with ng-app attribute), otherwise the template will be ignored.
6490  *
6491  * Adding via the `$templateCache` service:
6492  *
6493  * ```js
6494  * var myApp = angular.module('myApp', []);
6495  * myApp.run(function($templateCache) {
6496  *   $templateCache.put('templateId.html', 'This is the content of the template');
6497  * });
6498  * ```
6499  *
6500  * To retrieve the template later, simply use it in your HTML:
6501  * ```html
6502  * <div ng-include=" 'templateId.html' "></div>
6503  * ```
6504  *
6505  * or get it via Javascript:
6506  * ```js
6507  * $templateCache.get('templateId.html')
6508  * ```
6509  *
6510  * See {@link ng.$cacheFactory $cacheFactory}.
6511  *
6512  */
6513 function $TemplateCacheProvider() {
6514   this.$get = ['$cacheFactory', function($cacheFactory) {
6515     return $cacheFactory('templates');
6516   }];
6517 }
6518
6519 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
6520  *     Any commits to this file should be reviewed with security in mind.  *
6521  *   Changes to this file can potentially create security vulnerabilities. *
6522  *          An approval from 2 Core members with history of modifying      *
6523  *                         this file is required.                          *
6524  *                                                                         *
6525  *  Does the change somehow allow for arbitrary javascript to be executed? *
6526  *    Or allows for someone to change the prototype of built-in objects?   *
6527  *     Or gives undesired access to variables likes document or window?    *
6528  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
6529
6530 /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
6531  *
6532  * DOM-related variables:
6533  *
6534  * - "node" - DOM Node
6535  * - "element" - DOM Element or Node
6536  * - "$node" or "$element" - jqLite-wrapped node or element
6537  *
6538  *
6539  * Compiler related stuff:
6540  *
6541  * - "linkFn" - linking fn of a single directive
6542  * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
6543  * - "childLinkFn" -  function that aggregates all linking fns for child nodes of a particular node
6544  * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
6545  */
6546
6547
6548 /**
6549  * @ngdoc service
6550  * @name $compile
6551  * @kind function
6552  *
6553  * @description
6554  * Compiles an HTML string or DOM into a template and produces a template function, which
6555  * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
6556  *
6557  * The compilation is a process of walking the DOM tree and matching DOM elements to
6558  * {@link ng.$compileProvider#directive directives}.
6559  *
6560  * <div class="alert alert-warning">
6561  * **Note:** This document is an in-depth reference of all directive options.
6562  * For a gentle introduction to directives with examples of common use cases,
6563  * see the {@link guide/directive directive guide}.
6564  * </div>
6565  *
6566  * ## Comprehensive Directive API
6567  *
6568  * There are many different options for a directive.
6569  *
6570  * The difference resides in the return value of the factory function.
6571  * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
6572  * or just the `postLink` function (all other properties will have the default values).
6573  *
6574  * <div class="alert alert-success">
6575  * **Best Practice:** It's recommended to use the "directive definition object" form.
6576  * </div>
6577  *
6578  * Here's an example directive declared with a Directive Definition Object:
6579  *
6580  * ```js
6581  *   var myModule = angular.module(...);
6582  *
6583  *   myModule.directive('directiveName', function factory(injectables) {
6584  *     var directiveDefinitionObject = {
6585  *       priority: 0,
6586  *       template: '<div></div>', // or // function(tElement, tAttrs) { ... },
6587  *       // or
6588  *       // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
6589  *       transclude: false,
6590  *       restrict: 'A',
6591  *       templateNamespace: 'html',
6592  *       scope: false,
6593  *       controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
6594  *       controllerAs: 'stringIdentifier',
6595  *       bindToController: false,
6596  *       require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
6597  *       compile: function compile(tElement, tAttrs, transclude) {
6598  *         return {
6599  *           pre: function preLink(scope, iElement, iAttrs, controller) { ... },
6600  *           post: function postLink(scope, iElement, iAttrs, controller) { ... }
6601  *         }
6602  *         // or
6603  *         // return function postLink( ... ) { ... }
6604  *       },
6605  *       // or
6606  *       // link: {
6607  *       //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },
6608  *       //  post: function postLink(scope, iElement, iAttrs, controller) { ... }
6609  *       // }
6610  *       // or
6611  *       // link: function postLink( ... ) { ... }
6612  *     };
6613  *     return directiveDefinitionObject;
6614  *   });
6615  * ```
6616  *
6617  * <div class="alert alert-warning">
6618  * **Note:** Any unspecified options will use the default value. You can see the default values below.
6619  * </div>
6620  *
6621  * Therefore the above can be simplified as:
6622  *
6623  * ```js
6624  *   var myModule = angular.module(...);
6625  *
6626  *   myModule.directive('directiveName', function factory(injectables) {
6627  *     var directiveDefinitionObject = {
6628  *       link: function postLink(scope, iElement, iAttrs) { ... }
6629  *     };
6630  *     return directiveDefinitionObject;
6631  *     // or
6632  *     // return function postLink(scope, iElement, iAttrs) { ... }
6633  *   });
6634  * ```
6635  *
6636  *
6637  *
6638  * ### Directive Definition Object
6639  *
6640  * The directive definition object provides instructions to the {@link ng.$compile
6641  * compiler}. The attributes are:
6642  *
6643  * #### `multiElement`
6644  * When this property is set to true, the HTML compiler will collect DOM nodes between
6645  * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
6646  * together as the directive elements. It is recommended that this feature be used on directives
6647  * which are not strictly behavioral (such as {@link ngClick}), and which
6648  * do not manipulate or replace child nodes (such as {@link ngInclude}).
6649  *
6650  * #### `priority`
6651  * When there are multiple directives defined on a single DOM element, sometimes it
6652  * is necessary to specify the order in which the directives are applied. The `priority` is used
6653  * to sort the directives before their `compile` functions get called. Priority is defined as a
6654  * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
6655  * are also run in priority order, but post-link functions are run in reverse order. The order
6656  * of directives with the same priority is undefined. The default priority is `0`.
6657  *
6658  * #### `terminal`
6659  * If set to true then the current `priority` will be the last set of directives
6660  * which will execute (any directives at the current priority will still execute
6661  * as the order of execution on same `priority` is undefined). Note that expressions
6662  * and other directives used in the directive's template will also be excluded from execution.
6663  *
6664  * #### `scope`
6665  * The scope property can be `true`, an object or a falsy value:
6666  *
6667  * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
6668  *
6669  * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
6670  * the directive's element. If multiple directives on the same element request a new scope,
6671  * only one new scope is created. The new scope rule does not apply for the root of the template
6672  * since the root of the template always gets a new scope.
6673  *
6674  * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
6675  * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
6676  * scope. This is useful when creating reusable components, which should not accidentally read or modify
6677  * data in the parent scope.
6678  *
6679  * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
6680  * directive's element. These local properties are useful for aliasing values for templates. The keys in
6681  * the object hash map to the name of the property on the isolate scope; the values define how the property
6682  * is bound to the parent scope, via matching attributes on the directive's element:
6683  *
6684  * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
6685  *   always a string since DOM attributes are strings. If no `attr` name is specified then the
6686  *   attribute name is assumed to be the same as the local name. Given `<my-component
6687  *   my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
6688  *   the directive's scope property `localName` will reflect the interpolated value of `hello
6689  *   {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
6690  *   scope. The `name` is read from the parent scope (not the directive's scope).
6691  *
6692  * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
6693  *   passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
6694  *   If no `attr` name is specified then the attribute name is assumed to be the same as the local
6695  *   name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
6696  *   localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
6697  *   value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
6698  *   `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
6699  *   `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
6700  *   optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
6701  *   will be thrown upon discovering changes to the local value, since it will be impossible to sync
6702  *   them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
6703  *   method is used for tracking changes, and the equality check is based on object identity.
6704  *   However, if an object literal or an array literal is passed as the binding expression, the
6705  *   equality check is done by value (using the {@link angular.equals} function). It's also possible
6706  *   to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
6707  *   `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
6708  *
6709   * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
6710  *   expression passed via the attribute `attr`. The expression is evaluated in the context of the
6711  *   parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
6712  *   local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
6713  *
6714  *   For example, given `<my-component my-attr="parentModel">` and directive definition of
6715  *   `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
6716  *   value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
6717  *   in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
6718  *   two caveats:
6719  *     1. one-way binding does not copy the value from the parent to the isolate scope, it simply
6720  *     sets the same value. That means if your bound value is an object, changes to its properties
6721  *     in the isolated scope will be reflected in the parent scope (because both reference the same object).
6722  *     2. one-way binding watches changes to the **identity** of the parent value. That means the
6723  *     {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
6724  *     to the value has changed. In most cases, this should not be of concern, but can be important
6725  *     to know if you one-way bind to an object, and then replace that object in the isolated scope.
6726  *     If you now change a property of the object in your parent scope, the change will not be
6727  *     propagated to the isolated scope, because the identity of the object on the parent scope
6728  *     has not changed. Instead you must assign a new object.
6729  *
6730  *   One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
6731  *   back to the parent. However, it does not make this completely impossible.
6732  *
6733  * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
6734  *   no `attr` name is specified then the attribute name is assumed to be the same as the local name.
6735  *   Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
6736  *   localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
6737  *   the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
6738  *   via an expression to the parent scope. This can be done by passing a map of local variable names
6739  *   and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
6740  *   then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
6741  *
6742  * In general it's possible to apply more than one directive to one element, but there might be limitations
6743  * depending on the type of scope required by the directives. The following points will help explain these limitations.
6744  * For simplicity only two directives are taken into account, but it is also applicable for several directives:
6745  *
6746  * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
6747  * * **child scope** + **no scope** =>  Both directives will share one single child scope
6748  * * **child scope** + **child scope** =>  Both directives will share one single child scope
6749  * * **isolated scope** + **no scope** =>  The isolated directive will use it's own created isolated scope. The other directive will use
6750  * its parent's scope
6751  * * **isolated scope** + **child scope** =>  **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
6752  * be applied to the same element.
6753  * * **isolated scope** + **isolated scope**  =>  **Won't work!** Only one scope can be related to one element. Therefore these directives
6754  * cannot be applied to the same element.
6755  *
6756  *
6757  * #### `bindToController`
6758  * This property is used to bind scope properties directly to the controller. It can be either
6759  * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
6760  * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
6761  * definition: `controller: 'myCtrl as myAlias'`.
6762  *
6763  * When an isolate scope is used for a directive (see above), `bindToController: true` will
6764  * allow a component to have its properties bound to the controller, rather than to scope.
6765  *
6766  * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
6767  * properties. You can access these bindings once they have been initialized by providing a controller method called
6768  * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
6769  * initialized.
6770  *
6771  * <div class="alert alert-warning">
6772  * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
6773  * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
6774  * code that relies upon bindings inside a `$onInit` method on the controller, instead.
6775  * </div>
6776  *
6777  * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
6778  * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
6779  * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
6780  * scope (useful for component directives).
6781  *
6782  * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
6783  *
6784  *
6785  * #### `controller`
6786  * Controller constructor function. The controller is instantiated before the
6787  * pre-linking phase and can be accessed by other directives (see
6788  * `require` attribute). This allows the directives to communicate with each other and augment
6789  * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
6790  *
6791  * * `$scope` - Current scope associated with the element
6792  * * `$element` - Current element
6793  * * `$attrs` - Current attributes object for the element
6794  * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
6795  *   `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
6796  *    * `scope`: (optional) override the scope.
6797  *    * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
6798  *    * `futureParentElement` (optional):
6799  *        * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
6800  *        * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
6801  *        * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
6802  *          and when the `cloneLinkinFn` is passed,
6803  *          as those elements need to created and cloned in a special way when they are defined outside their
6804  *          usual containers (e.g. like `<svg>`).
6805  *        * See also the `directive.templateNamespace` property.
6806  *    * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
6807  *      then the default translusion is provided.
6808  *    The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
6809  *    `true` if the specified slot contains content (i.e. one or more DOM nodes).
6810  *
6811  * The controller can provide the following methods that act as life-cycle hooks:
6812  * * `$onInit` - Called on each controller after all the controllers on an element have been constructed and
6813  *   had their bindings initialized (and before the pre &amp; post linking functions for the directives on
6814  *   this element). This is a good place to put initialization code for your controller.
6815  *
6816  * #### `require`
6817  * Require another directive and inject its controller as the fourth argument to the linking function. The
6818  * `require` property can be a string, an array or an object:
6819  * * a **string** containing the name of the directive to pass to the linking function
6820  * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
6821  * linking function will be an array of controllers in the same order as the names in the `require` property
6822  * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
6823  * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
6824  * controllers.
6825  *
6826  * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
6827  * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
6828  * have been constructed but before `$onInit` is called.
6829  * See the {@link $compileProvider#component} helper for an example of how this can be used.
6830  *
6831  * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
6832  * raised (unless no link function is specified and the required controllers are not being bound to the directive
6833  * controller, in which case error checking is skipped). The name can be prefixed with:
6834  *
6835  * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
6836  * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
6837  * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
6838  * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
6839  * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
6840  *   `null` to the `link` fn if not found.
6841  * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
6842  *   `null` to the `link` fn if not found.
6843  *
6844  *
6845  * #### `controllerAs`
6846  * Identifier name for a reference to the controller in the directive's scope.
6847  * This allows the controller to be referenced from the directive template. This is especially
6848  * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
6849  * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
6850  * `controllerAs` reference might overwrite a property that already exists on the parent scope.
6851  *
6852  *
6853  * #### `restrict`
6854  * String of subset of `EACM` which restricts the directive to a specific directive
6855  * declaration style. If omitted, the defaults (elements and attributes) are used.
6856  *
6857  * * `E` - Element name (default): `<my-directive></my-directive>`
6858  * * `A` - Attribute (default): `<div my-directive="exp"></div>`
6859  * * `C` - Class: `<div class="my-directive: exp;"></div>`
6860  * * `M` - Comment: `<!-- directive: my-directive exp -->`
6861  *
6862  *
6863  * #### `templateNamespace`
6864  * String representing the document type used by the markup in the template.
6865  * AngularJS needs this information as those elements need to be created and cloned
6866  * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
6867  *
6868  * * `html` - All root nodes in the template are HTML. Root nodes may also be
6869  *   top-level elements such as `<svg>` or `<math>`.
6870  * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
6871  * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
6872  *
6873  * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
6874  *
6875  * #### `template`
6876  * HTML markup that may:
6877  * * Replace the contents of the directive's element (default).
6878  * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
6879  * * Wrap the contents of the directive's element (if `transclude` is true).
6880  *
6881  * Value may be:
6882  *
6883  * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
6884  * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
6885  *   function api below) and returns a string value.
6886  *
6887  *
6888  * #### `templateUrl`
6889  * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
6890  *
6891  * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
6892  * for later when the template has been resolved.  In the meantime it will continue to compile and link
6893  * sibling and parent elements as though this element had not contained any directives.
6894  *
6895  * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
6896  * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
6897  * case when only one deeply nested directive has `templateUrl`.
6898  *
6899  * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
6900  *
6901  * You can specify `templateUrl` as a string representing the URL or as a function which takes two
6902  * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
6903  * a string value representing the url.  In either case, the template URL is passed through {@link
6904  * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
6905  *
6906  *
6907  * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
6908  * specify what the template should replace. Defaults to `false`.
6909  *
6910  * * `true` - the template will replace the directive's element.
6911  * * `false` - the template will replace the contents of the directive's element.
6912  *
6913  * The replacement process migrates all of the attributes / classes from the old element to the new
6914  * one. See the {@link guide/directive#template-expanding-directive
6915  * Directives Guide} for an example.
6916  *
6917  * There are very few scenarios where element replacement is required for the application function,
6918  * the main one being reusable custom components that are used within SVG contexts
6919  * (because SVG doesn't work with custom elements in the DOM tree).
6920  *
6921  * #### `transclude`
6922  * Extract the contents of the element where the directive appears and make it available to the directive.
6923  * The contents are compiled and provided to the directive as a **transclusion function**. See the
6924  * {@link $compile#transclusion Transclusion} section below.
6925  *
6926  *
6927  * #### `compile`
6928  *
6929  * ```js
6930  *   function compile(tElement, tAttrs, transclude) { ... }
6931  * ```
6932  *
6933  * The compile function deals with transforming the template DOM. Since most directives do not do
6934  * template transformation, it is not used often. The compile function takes the following arguments:
6935  *
6936  *   * `tElement` - template element - The element where the directive has been declared. It is
6937  *     safe to do template transformation on the element and child elements only.
6938  *
6939  *   * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
6940  *     between all directive compile functions.
6941  *
6942  *   * `transclude` -  [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
6943  *
6944  * <div class="alert alert-warning">
6945  * **Note:** The template instance and the link instance may be different objects if the template has
6946  * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
6947  * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
6948  * should be done in a linking function rather than in a compile function.
6949  * </div>
6950
6951  * <div class="alert alert-warning">
6952  * **Note:** The compile function cannot handle directives that recursively use themselves in their
6953  * own templates or compile functions. Compiling these directives results in an infinite loop and
6954  * stack overflow errors.
6955  *
6956  * This can be avoided by manually using $compile in the postLink function to imperatively compile
6957  * a directive's template instead of relying on automatic template compilation via `template` or
6958  * `templateUrl` declaration or manual compilation inside the compile function.
6959  * </div>
6960  *
6961  * <div class="alert alert-danger">
6962  * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
6963  *   e.g. does not know about the right outer scope. Please use the transclude function that is passed
6964  *   to the link function instead.
6965  * </div>
6966
6967  * A compile function can have a return value which can be either a function or an object.
6968  *
6969  * * returning a (post-link) function - is equivalent to registering the linking function via the
6970  *   `link` property of the config object when the compile function is empty.
6971  *
6972  * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
6973  *   control when a linking function should be called during the linking phase. See info about
6974  *   pre-linking and post-linking functions below.
6975  *
6976  *
6977  * #### `link`
6978  * This property is used only if the `compile` property is not defined.
6979  *
6980  * ```js
6981  *   function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
6982  * ```
6983  *
6984  * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
6985  * executed after the template has been cloned. This is where most of the directive logic will be
6986  * put.
6987  *
6988  *   * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
6989  *     directive for registering {@link ng.$rootScope.Scope#$watch watches}.
6990  *
6991  *   * `iElement` - instance element - The element where the directive is to be used. It is safe to
6992  *     manipulate the children of the element only in `postLink` function since the children have
6993  *     already been linked.
6994  *
6995  *   * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
6996  *     between all directive linking functions.
6997  *
6998  *   * `controller` - the directive's required controller instance(s) - Instances are shared
6999  *     among all directives, which allows the directives to use the controllers as a communication
7000  *     channel. The exact value depends on the directive's `require` property:
7001  *       * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
7002  *       * `string`: the controller instance
7003  *       * `array`: array of controller instances
7004  *
7005  *     If a required controller cannot be found, and it is optional, the instance is `null`,
7006  *     otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
7007  *
7008  *     Note that you can also require the directive's own controller - it will be made available like
7009  *     any other controller.
7010  *
7011  *   * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
7012  *     This is the same as the `$transclude`
7013  *     parameter of directive controllers, see there for details.
7014  *     `function([scope], cloneLinkingFn, futureParentElement)`.
7015  *
7016  * #### Pre-linking function
7017  *
7018  * Executed before the child elements are linked. Not safe to do DOM transformation since the
7019  * compiler linking function will fail to locate the correct elements for linking.
7020  *
7021  * #### Post-linking function
7022  *
7023  * Executed after the child elements are linked.
7024  *
7025  * Note that child elements that contain `templateUrl` directives will not have been compiled
7026  * and linked since they are waiting for their template to load asynchronously and their own
7027  * compilation and linking has been suspended until that occurs.
7028  *
7029  * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
7030  * for their async templates to be resolved.
7031  *
7032  *
7033  * ### Transclusion
7034  *
7035  * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
7036  * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
7037  * scope from where they were taken.
7038  *
7039  * Transclusion is used (often with {@link ngTransclude}) to insert the
7040  * original contents of a directive's element into a specified place in the template of the directive.
7041  * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
7042  * content has access to the properties on the scope from which it was taken, even if the directive
7043  * has isolated scope.
7044  * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
7045  *
7046  * This makes it possible for the widget to have private state for its template, while the transcluded
7047  * content has access to its originating scope.
7048  *
7049  * <div class="alert alert-warning">
7050  * **Note:** When testing an element transclude directive you must not place the directive at the root of the
7051  * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
7052  * Testing Transclusion Directives}.
7053  * </div>
7054  *
7055  * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
7056  * directive's element, the entire element or multiple parts of the element contents:
7057  *
7058  * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
7059  * * `'element'` - transclude the whole of the directive's element including any directives on this
7060  *   element that defined at a lower priority than this directive. When used, the `template`
7061  *   property is ignored.
7062  * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
7063  *
7064  * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
7065  *
7066  * This object is a map where the keys are the name of the slot to fill and the value is an element selector
7067  * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
7068  * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
7069  *
7070  * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
7071  *
7072  * If the element selector is prefixed with a `?` then that slot is optional.
7073  *
7074  * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
7075  * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
7076  *
7077  * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
7078  * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
7079  * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
7080  * injectable into the directive's controller.
7081  *
7082  *
7083  * #### Transclusion Functions
7084  *
7085  * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
7086  * function** to the directive's `link` function and `controller`. This transclusion function is a special
7087  * **linking function** that will return the compiled contents linked to a new transclusion scope.
7088  *
7089  * <div class="alert alert-info">
7090  * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
7091  * ngTransclude will deal with it for us.
7092  * </div>
7093  *
7094  * If you want to manually control the insertion and removal of the transcluded content in your directive
7095  * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
7096  * object that contains the compiled DOM, which is linked to the correct transclusion scope.
7097  *
7098  * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
7099  * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
7100  * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
7101  *
7102  * <div class="alert alert-info">
7103  * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
7104  * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
7105  * </div>
7106  *
7107  * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
7108  * attach function**:
7109  *
7110  * ```js
7111  * var transcludedContent, transclusionScope;
7112  *
7113  * $transclude(function(clone, scope) {
7114  *   element.append(clone);
7115  *   transcludedContent = clone;
7116  *   transclusionScope = scope;
7117  * });
7118  * ```
7119  *
7120  * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
7121  * associated transclusion scope:
7122  *
7123  * ```js
7124  * transcludedContent.remove();
7125  * transclusionScope.$destroy();
7126  * ```
7127  *
7128  * <div class="alert alert-info">
7129  * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
7130  * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
7131  * then you are also responsible for calling `$destroy` on the transclusion scope.
7132  * </div>
7133  *
7134  * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
7135  * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
7136  * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
7137  *
7138  *
7139  * #### Transclusion Scopes
7140  *
7141  * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
7142  * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
7143  * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
7144  * was taken.
7145  *
7146  * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
7147  * like this:
7148  *
7149  * ```html
7150  * <div ng-app>
7151  *   <div isolate>
7152  *     <div transclusion>
7153  *     </div>
7154  *   </div>
7155  * </div>
7156  * ```
7157  *
7158  * The `$parent` scope hierarchy will look like this:
7159  *
7160    ```
7161    - $rootScope
7162      - isolate
7163        - transclusion
7164    ```
7165  *
7166  * but the scopes will inherit prototypically from different scopes to their `$parent`.
7167  *
7168    ```
7169    - $rootScope
7170      - transclusion
7171    - isolate
7172    ```
7173  *
7174  *
7175  * ### Attributes
7176  *
7177  * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
7178  * `link()` or `compile()` functions. It has a variety of uses.
7179  *
7180  * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
7181  *   'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
7182  *   to the attributes.
7183  *
7184  * * *Directive inter-communication:* All directives share the same instance of the attributes
7185  *   object which allows the directives to use the attributes object as inter directive
7186  *   communication.
7187  *
7188  * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
7189  *   allowing other directives to read the interpolated value.
7190  *
7191  * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
7192  *   that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
7193  *   the only way to easily get the actual value because during the linking phase the interpolation
7194  *   hasn't been evaluated yet and so the value is at this time set to `undefined`.
7195  *
7196  * ```js
7197  * function linkingFn(scope, elm, attrs, ctrl) {
7198  *   // get the attribute value
7199  *   console.log(attrs.ngModel);
7200  *
7201  *   // change the attribute
7202  *   attrs.$set('ngModel', 'new value');
7203  *
7204  *   // observe changes to interpolated attribute
7205  *   attrs.$observe('ngModel', function(value) {
7206  *     console.log('ngModel has changed value to ' + value);
7207  *   });
7208  * }
7209  * ```
7210  *
7211  * ## Example
7212  *
7213  * <div class="alert alert-warning">
7214  * **Note**: Typically directives are registered with `module.directive`. The example below is
7215  * to illustrate how `$compile` works.
7216  * </div>
7217  *
7218  <example module="compileExample">
7219    <file name="index.html">
7220     <script>
7221       angular.module('compileExample', [], function($compileProvider) {
7222         // configure new 'compile' directive by passing a directive
7223         // factory function. The factory function injects the '$compile'
7224         $compileProvider.directive('compile', function($compile) {
7225           // directive factory creates a link function
7226           return function(scope, element, attrs) {
7227             scope.$watch(
7228               function(scope) {
7229                  // watch the 'compile' expression for changes
7230                 return scope.$eval(attrs.compile);
7231               },
7232               function(value) {
7233                 // when the 'compile' expression changes
7234                 // assign it into the current DOM
7235                 element.html(value);
7236
7237                 // compile the new DOM and link it to the current
7238                 // scope.
7239                 // NOTE: we only compile .childNodes so that
7240                 // we don't get into infinite loop compiling ourselves
7241                 $compile(element.contents())(scope);
7242               }
7243             );
7244           };
7245         });
7246       })
7247       .controller('GreeterController', ['$scope', function($scope) {
7248         $scope.name = 'Angular';
7249         $scope.html = 'Hello {{name}}';
7250       }]);
7251     </script>
7252     <div ng-controller="GreeterController">
7253       <input ng-model="name"> <br/>
7254       <textarea ng-model="html"></textarea> <br/>
7255       <div compile="html"></div>
7256     </div>
7257    </file>
7258    <file name="protractor.js" type="protractor">
7259      it('should auto compile', function() {
7260        var textarea = $('textarea');
7261        var output = $('div[compile]');
7262        // The initial state reads 'Hello Angular'.
7263        expect(output.getText()).toBe('Hello Angular');
7264        textarea.clear();
7265        textarea.sendKeys('{{name}}!');
7266        expect(output.getText()).toBe('Angular!');
7267      });
7268    </file>
7269  </example>
7270
7271  *
7272  *
7273  * @param {string|DOMElement} element Element or HTML string to compile into a template function.
7274  * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
7275  *
7276  * <div class="alert alert-danger">
7277  * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
7278  *   e.g. will not use the right outer scope. Please pass the transclude function as a
7279  *   `parentBoundTranscludeFn` to the link function instead.
7280  * </div>
7281  *
7282  * @param {number} maxPriority only apply directives lower than given priority (Only effects the
7283  *                 root element(s), not their children)
7284  * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
7285  * (a DOM element/tree) to a scope. Where:
7286  *
7287  *  * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
7288  *  * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
7289  *  `template` and call the `cloneAttachFn` function allowing the caller to attach the
7290  *  cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
7291  *  called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
7292  *
7293  *      * `clonedElement` - is a clone of the original `element` passed into the compiler.
7294  *      * `scope` - is the current scope with which the linking function is working with.
7295  *
7296  *  * `options` - An optional object hash with linking options. If `options` is provided, then the following
7297  *  keys may be used to control linking behavior:
7298  *
7299  *      * `parentBoundTranscludeFn` - the transclude function made available to
7300  *        directives; if given, it will be passed through to the link functions of
7301  *        directives found in `element` during compilation.
7302  *      * `transcludeControllers` - an object hash with keys that map controller names
7303  *        to a hash with the key `instance`, which maps to the controller instance;
7304  *        if given, it will make the controllers available to directives on the compileNode:
7305  *        ```
7306  *        {
7307  *          parent: {
7308  *            instance: parentControllerInstance
7309  *          }
7310  *        }
7311  *        ```
7312  *      * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
7313  *        the cloned elements; only needed for transcludes that are allowed to contain non html
7314  *        elements (e.g. SVG elements). See also the directive.controller property.
7315  *
7316  * Calling the linking function returns the element of the template. It is either the original
7317  * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
7318  *
7319  * After linking the view is not updated until after a call to $digest which typically is done by
7320  * Angular automatically.
7321  *
7322  * If you need access to the bound view, there are two ways to do it:
7323  *
7324  * - If you are not asking the linking function to clone the template, create the DOM element(s)
7325  *   before you send them to the compiler and keep this reference around.
7326  *   ```js
7327  *     var element = $compile('<p>{{total}}</p>')(scope);
7328  *   ```
7329  *
7330  * - if on the other hand, you need the element to be cloned, the view reference from the original
7331  *   example would not point to the clone, but rather to the original template that was cloned. In
7332  *   this case, you can access the clone via the cloneAttachFn:
7333  *   ```js
7334  *     var templateElement = angular.element('<p>{{total}}</p>'),
7335  *         scope = ....;
7336  *
7337  *     var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
7338  *       //attach the clone to DOM document at the right place
7339  *     });
7340  *
7341  *     //now we have reference to the cloned DOM via `clonedElement`
7342  *   ```
7343  *
7344  *
7345  * For information on how the compiler works, see the
7346  * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
7347  */
7348
7349 var $compileMinErr = minErr('$compile');
7350
7351 /**
7352  * @ngdoc provider
7353  * @name $compileProvider
7354  *
7355  * @description
7356  */
7357 $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
7358 function $CompileProvider($provide, $$sanitizeUriProvider) {
7359   var hasDirectives = {},
7360       Suffix = 'Directive',
7361       COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
7362       CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
7363       ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
7364       REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
7365
7366   // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
7367   // The assumption is that future DOM event attribute names will begin with
7368   // 'on' and be composed of only English letters.
7369   var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
7370
7371   function parseIsolateBindings(scope, directiveName, isController) {
7372     var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
7373
7374     var bindings = {};
7375
7376     forEach(scope, function(definition, scopeName) {
7377       var match = definition.match(LOCAL_REGEXP);
7378
7379       if (!match) {
7380         throw $compileMinErr('iscp',
7381             "Invalid {3} for directive '{0}'." +
7382             " Definition: {... {1}: '{2}' ...}",
7383             directiveName, scopeName, definition,
7384             (isController ? "controller bindings definition" :
7385             "isolate scope definition"));
7386       }
7387
7388       bindings[scopeName] = {
7389         mode: match[1][0],
7390         collection: match[2] === '*',
7391         optional: match[3] === '?',
7392         attrName: match[4] || scopeName
7393       };
7394     });
7395
7396     return bindings;
7397   }
7398
7399   function parseDirectiveBindings(directive, directiveName) {
7400     var bindings = {
7401       isolateScope: null,
7402       bindToController: null
7403     };
7404     if (isObject(directive.scope)) {
7405       if (directive.bindToController === true) {
7406         bindings.bindToController = parseIsolateBindings(directive.scope,
7407                                                          directiveName, true);
7408         bindings.isolateScope = {};
7409       } else {
7410         bindings.isolateScope = parseIsolateBindings(directive.scope,
7411                                                      directiveName, false);
7412       }
7413     }
7414     if (isObject(directive.bindToController)) {
7415       bindings.bindToController =
7416           parseIsolateBindings(directive.bindToController, directiveName, true);
7417     }
7418     if (isObject(bindings.bindToController)) {
7419       var controller = directive.controller;
7420       var controllerAs = directive.controllerAs;
7421       if (!controller) {
7422         // There is no controller, there may or may not be a controllerAs property
7423         throw $compileMinErr('noctrl',
7424               "Cannot bind to controller without directive '{0}'s controller.",
7425               directiveName);
7426       } else if (!identifierForController(controller, controllerAs)) {
7427         // There is a controller, but no identifier or controllerAs property
7428         throw $compileMinErr('noident',
7429               "Cannot bind to controller without identifier for directive '{0}'.",
7430               directiveName);
7431       }
7432     }
7433     return bindings;
7434   }
7435
7436   function assertValidDirectiveName(name) {
7437     var letter = name.charAt(0);
7438     if (!letter || letter !== lowercase(letter)) {
7439       throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
7440     }
7441     if (name !== name.trim()) {
7442       throw $compileMinErr('baddir',
7443             "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
7444             name);
7445     }
7446   }
7447
7448   /**
7449    * @ngdoc method
7450    * @name $compileProvider#directive
7451    * @kind function
7452    *
7453    * @description
7454    * Register a new directive with the compiler.
7455    *
7456    * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
7457    *    will match as <code>ng-bind</code>), or an object map of directives where the keys are the
7458    *    names and the values are the factories.
7459    * @param {Function|Array} directiveFactory An injectable directive factory function. See the
7460    *    {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
7461    * @returns {ng.$compileProvider} Self for chaining.
7462    */
7463    this.directive = function registerDirective(name, directiveFactory) {
7464     assertNotHasOwnProperty(name, 'directive');
7465     if (isString(name)) {
7466       assertValidDirectiveName(name);
7467       assertArg(directiveFactory, 'directiveFactory');
7468       if (!hasDirectives.hasOwnProperty(name)) {
7469         hasDirectives[name] = [];
7470         $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
7471           function($injector, $exceptionHandler) {
7472             var directives = [];
7473             forEach(hasDirectives[name], function(directiveFactory, index) {
7474               try {
7475                 var directive = $injector.invoke(directiveFactory);
7476                 if (isFunction(directive)) {
7477                   directive = { compile: valueFn(directive) };
7478                 } else if (!directive.compile && directive.link) {
7479                   directive.compile = valueFn(directive.link);
7480                 }
7481                 directive.priority = directive.priority || 0;
7482                 directive.index = index;
7483                 directive.name = directive.name || name;
7484                 directive.require = directive.require || (directive.controller && directive.name);
7485                 directive.restrict = directive.restrict || 'EA';
7486                 var bindings = directive.$$bindings =
7487                     parseDirectiveBindings(directive, directive.name);
7488                 if (isObject(bindings.isolateScope)) {
7489                   directive.$$isolateBindings = bindings.isolateScope;
7490                 }
7491                 directive.$$moduleName = directiveFactory.$$moduleName;
7492                 directives.push(directive);
7493               } catch (e) {
7494                 $exceptionHandler(e);
7495               }
7496             });
7497             return directives;
7498           }]);
7499       }
7500       hasDirectives[name].push(directiveFactory);
7501     } else {
7502       forEach(name, reverseParams(registerDirective));
7503     }
7504     return this;
7505   };
7506
7507   /**
7508    * @ngdoc method
7509    * @name $compileProvider#component
7510    * @module ng
7511    * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
7512    * @param {Object} options Component definition object (a simplified
7513    *    {@link ng.$compile#directive-definition-object directive definition object}),
7514    *    with the following properties (all optional):
7515    *
7516    *    - `controller` – `{(string|function()=}` – controller constructor function that should be
7517    *      associated with newly created scope or the name of a {@link ng.$compile#-controller-
7518    *      registered controller} if passed as a string. An empty `noop` function by default.
7519    *    - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
7520    *      If present, the controller will be published to scope under the `controllerAs` name.
7521    *      If not present, this will default to be `$ctrl`.
7522    *    - `template` – `{string=|function()=}` – html template as a string or a function that
7523    *      returns an html template as a string which should be used as the contents of this component.
7524    *      Empty string by default.
7525    *
7526    *      If `template` is a function, then it is {@link auto.$injector#invoke injected} with
7527    *      the following locals:
7528    *
7529    *      - `$element` - Current element
7530    *      - `$attrs` - Current attributes object for the element
7531    *
7532    *    - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
7533    *      template that should be used  as the contents of this component.
7534    *
7535    *      If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
7536    *      the following locals:
7537    *
7538    *      - `$element` - Current element
7539    *      - `$attrs` - Current attributes object for the element
7540    *
7541    *    - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
7542    *      Component properties are always bound to the component controller and not to the scope.
7543    *      See {@link ng.$compile#-bindtocontroller- `bindToController`}.
7544    *    - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
7545    *      Disabled by default.
7546    *    - `$...` – `{function()=}` – additional annotations to provide to the directive factory function.
7547    *
7548    * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
7549    * @description
7550    * Register a **component definition** with the compiler. This is a shorthand for registering a special
7551    * type of directive, which represents a self-contained UI component in your application. Such components
7552    * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
7553    *
7554    * Component definitions are very simple and do not require as much configuration as defining general
7555    * directives. Component definitions usually consist only of a template and a controller backing it.
7556    *
7557    * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
7558    * `bindToController`. They always have **isolate scope** and are restricted to elements.
7559    *
7560    * Here are a few examples of how you would usually define components:
7561    *
7562    * ```js
7563    *   var myMod = angular.module(...);
7564    *   myMod.component('myComp', {
7565    *     template: '<div>My name is {{$ctrl.name}}</div>',
7566    *     controller: function() {
7567    *       this.name = 'shahar';
7568    *     }
7569    *   });
7570    *
7571    *   myMod.component('myComp', {
7572    *     template: '<div>My name is {{$ctrl.name}}</div>',
7573    *     bindings: {name: '@'}
7574    *   });
7575    *
7576    *   myMod.component('myComp', {
7577    *     templateUrl: 'views/my-comp.html',
7578    *     controller: 'MyCtrl as ctrl',
7579    *     bindings: {name: '@'}
7580    *   });
7581    *
7582    * ```
7583    * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
7584    *
7585    * <br />
7586    * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
7587    */
7588   this.component = function registerComponent(name, options) {
7589     var controller = options.controller || function() {};
7590
7591     function factory($injector) {
7592       function makeInjectable(fn) {
7593         if (isFunction(fn) || isArray(fn)) {
7594           return function(tElement, tAttrs) {
7595             return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
7596           };
7597         } else {
7598           return fn;
7599         }
7600       }
7601
7602       var template = (!options.template && !options.templateUrl ? '' : options.template);
7603       return {
7604         controller: controller,
7605         controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
7606         template: makeInjectable(template),
7607         templateUrl: makeInjectable(options.templateUrl),
7608         transclude: options.transclude,
7609         scope: {},
7610         bindToController: options.bindings || {},
7611         restrict: 'E',
7612         require: options.require
7613       };
7614     }
7615
7616     // Copy any annotation properties (starting with $) over to the factory function
7617     // These could be used by libraries such as the new component router
7618     forEach(options, function(val, key) {
7619       if (key.charAt(0) === '$') {
7620         factory[key] = val;
7621       }
7622     });
7623
7624     factory.$inject = ['$injector'];
7625
7626     return this.directive(name, factory);
7627   };
7628
7629
7630   /**
7631    * @ngdoc method
7632    * @name $compileProvider#aHrefSanitizationWhitelist
7633    * @kind function
7634    *
7635    * @description
7636    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
7637    * urls during a[href] sanitization.
7638    *
7639    * The sanitization is a security measure aimed at preventing XSS attacks via html links.
7640    *
7641    * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
7642    * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
7643    * regular expression. If a match is found, the original url is written into the dom. Otherwise,
7644    * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
7645    *
7646    * @param {RegExp=} regexp New regexp to whitelist urls with.
7647    * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
7648    *    chaining otherwise.
7649    */
7650   this.aHrefSanitizationWhitelist = function(regexp) {
7651     if (isDefined(regexp)) {
7652       $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
7653       return this;
7654     } else {
7655       return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
7656     }
7657   };
7658
7659
7660   /**
7661    * @ngdoc method
7662    * @name $compileProvider#imgSrcSanitizationWhitelist
7663    * @kind function
7664    *
7665    * @description
7666    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
7667    * urls during img[src] sanitization.
7668    *
7669    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
7670    *
7671    * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
7672    * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
7673    * regular expression. If a match is found, the original url is written into the dom. Otherwise,
7674    * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
7675    *
7676    * @param {RegExp=} regexp New regexp to whitelist urls with.
7677    * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
7678    *    chaining otherwise.
7679    */
7680   this.imgSrcSanitizationWhitelist = function(regexp) {
7681     if (isDefined(regexp)) {
7682       $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
7683       return this;
7684     } else {
7685       return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
7686     }
7687   };
7688
7689   /**
7690    * @ngdoc method
7691    * @name  $compileProvider#debugInfoEnabled
7692    *
7693    * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
7694    * current debugInfoEnabled state
7695    * @returns {*} current value if used as getter or itself (chaining) if used as setter
7696    *
7697    * @kind function
7698    *
7699    * @description
7700    * Call this method to enable/disable various debug runtime information in the compiler such as adding
7701    * binding information and a reference to the current scope on to DOM elements.
7702    * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
7703    * * `ng-binding` CSS class
7704    * * `$binding` data property containing an array of the binding expressions
7705    *
7706    * You may want to disable this in production for a significant performance boost. See
7707    * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
7708    *
7709    * The default value is true.
7710    */
7711   var debugInfoEnabled = true;
7712   this.debugInfoEnabled = function(enabled) {
7713     if (isDefined(enabled)) {
7714       debugInfoEnabled = enabled;
7715       return this;
7716     }
7717     return debugInfoEnabled;
7718   };
7719
7720   this.$get = [
7721             '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
7722             '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
7723     function($injector,   $interpolate,   $exceptionHandler,   $templateRequest,   $parse,
7724              $controller,   $rootScope,   $sce,   $animate,   $$sanitizeUri) {
7725
7726     var SIMPLE_ATTR_NAME = /^\w/;
7727     var specialAttrHolder = document.createElement('div');
7728     var Attributes = function(element, attributesToCopy) {
7729       if (attributesToCopy) {
7730         var keys = Object.keys(attributesToCopy);
7731         var i, l, key;
7732
7733         for (i = 0, l = keys.length; i < l; i++) {
7734           key = keys[i];
7735           this[key] = attributesToCopy[key];
7736         }
7737       } else {
7738         this.$attr = {};
7739       }
7740
7741       this.$$element = element;
7742     };
7743
7744     Attributes.prototype = {
7745       /**
7746        * @ngdoc method
7747        * @name $compile.directive.Attributes#$normalize
7748        * @kind function
7749        *
7750        * @description
7751        * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
7752        * `data-`) to its normalized, camelCase form.
7753        *
7754        * Also there is special case for Moz prefix starting with upper case letter.
7755        *
7756        * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
7757        *
7758        * @param {string} name Name to normalize
7759        */
7760       $normalize: directiveNormalize,
7761
7762
7763       /**
7764        * @ngdoc method
7765        * @name $compile.directive.Attributes#$addClass
7766        * @kind function
7767        *
7768        * @description
7769        * Adds the CSS class value specified by the classVal parameter to the element. If animations
7770        * are enabled then an animation will be triggered for the class addition.
7771        *
7772        * @param {string} classVal The className value that will be added to the element
7773        */
7774       $addClass: function(classVal) {
7775         if (classVal && classVal.length > 0) {
7776           $animate.addClass(this.$$element, classVal);
7777         }
7778       },
7779
7780       /**
7781        * @ngdoc method
7782        * @name $compile.directive.Attributes#$removeClass
7783        * @kind function
7784        *
7785        * @description
7786        * Removes the CSS class value specified by the classVal parameter from the element. If
7787        * animations are enabled then an animation will be triggered for the class removal.
7788        *
7789        * @param {string} classVal The className value that will be removed from the element
7790        */
7791       $removeClass: function(classVal) {
7792         if (classVal && classVal.length > 0) {
7793           $animate.removeClass(this.$$element, classVal);
7794         }
7795       },
7796
7797       /**
7798        * @ngdoc method
7799        * @name $compile.directive.Attributes#$updateClass
7800        * @kind function
7801        *
7802        * @description
7803        * Adds and removes the appropriate CSS class values to the element based on the difference
7804        * between the new and old CSS class values (specified as newClasses and oldClasses).
7805        *
7806        * @param {string} newClasses The current CSS className value
7807        * @param {string} oldClasses The former CSS className value
7808        */
7809       $updateClass: function(newClasses, oldClasses) {
7810         var toAdd = tokenDifference(newClasses, oldClasses);
7811         if (toAdd && toAdd.length) {
7812           $animate.addClass(this.$$element, toAdd);
7813         }
7814
7815         var toRemove = tokenDifference(oldClasses, newClasses);
7816         if (toRemove && toRemove.length) {
7817           $animate.removeClass(this.$$element, toRemove);
7818         }
7819       },
7820
7821       /**
7822        * Set a normalized attribute on the element in a way such that all directives
7823        * can share the attribute. This function properly handles boolean attributes.
7824        * @param {string} key Normalized key. (ie ngAttribute)
7825        * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
7826        * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
7827        *     Defaults to true.
7828        * @param {string=} attrName Optional none normalized name. Defaults to key.
7829        */
7830       $set: function(key, value, writeAttr, attrName) {
7831         // TODO: decide whether or not to throw an error if "class"
7832         //is set through this function since it may cause $updateClass to
7833         //become unstable.
7834
7835         var node = this.$$element[0],
7836             booleanKey = getBooleanAttrName(node, key),
7837             aliasedKey = getAliasedAttrName(key),
7838             observer = key,
7839             nodeName;
7840
7841         if (booleanKey) {
7842           this.$$element.prop(key, value);
7843           attrName = booleanKey;
7844         } else if (aliasedKey) {
7845           this[aliasedKey] = value;
7846           observer = aliasedKey;
7847         }
7848
7849         this[key] = value;
7850
7851         // translate normalized key to actual key
7852         if (attrName) {
7853           this.$attr[key] = attrName;
7854         } else {
7855           attrName = this.$attr[key];
7856           if (!attrName) {
7857             this.$attr[key] = attrName = snake_case(key, '-');
7858           }
7859         }
7860
7861         nodeName = nodeName_(this.$$element);
7862
7863         if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
7864             (nodeName === 'img' && key === 'src')) {
7865           // sanitize a[href] and img[src] values
7866           this[key] = value = $$sanitizeUri(value, key === 'src');
7867         } else if (nodeName === 'img' && key === 'srcset') {
7868           // sanitize img[srcset] values
7869           var result = "";
7870
7871           // first check if there are spaces because it's not the same pattern
7872           var trimmedSrcset = trim(value);
7873           //                (   999x   ,|   999w   ,|   ,|,   )
7874           var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
7875           var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
7876
7877           // split srcset into tuple of uri and descriptor except for the last item
7878           var rawUris = trimmedSrcset.split(pattern);
7879
7880           // for each tuples
7881           var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
7882           for (var i = 0; i < nbrUrisWith2parts; i++) {
7883             var innerIdx = i * 2;
7884             // sanitize the uri
7885             result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
7886             // add the descriptor
7887             result += (" " + trim(rawUris[innerIdx + 1]));
7888           }
7889
7890           // split the last item into uri and descriptor
7891           var lastTuple = trim(rawUris[i * 2]).split(/\s/);
7892
7893           // sanitize the last uri
7894           result += $$sanitizeUri(trim(lastTuple[0]), true);
7895
7896           // and add the last descriptor if any
7897           if (lastTuple.length === 2) {
7898             result += (" " + trim(lastTuple[1]));
7899           }
7900           this[key] = value = result;
7901         }
7902
7903         if (writeAttr !== false) {
7904           if (value === null || isUndefined(value)) {
7905             this.$$element.removeAttr(attrName);
7906           } else {
7907             if (SIMPLE_ATTR_NAME.test(attrName)) {
7908               this.$$element.attr(attrName, value);
7909             } else {
7910               setSpecialAttr(this.$$element[0], attrName, value);
7911             }
7912           }
7913         }
7914
7915         // fire observers
7916         var $$observers = this.$$observers;
7917         $$observers && forEach($$observers[observer], function(fn) {
7918           try {
7919             fn(value);
7920           } catch (e) {
7921             $exceptionHandler(e);
7922           }
7923         });
7924       },
7925
7926
7927       /**
7928        * @ngdoc method
7929        * @name $compile.directive.Attributes#$observe
7930        * @kind function
7931        *
7932        * @description
7933        * Observes an interpolated attribute.
7934        *
7935        * The observer function will be invoked once during the next `$digest` following
7936        * compilation. The observer is then invoked whenever the interpolated value
7937        * changes.
7938        *
7939        * @param {string} key Normalized key. (ie ngAttribute) .
7940        * @param {function(interpolatedValue)} fn Function that will be called whenever
7941                 the interpolated value of the attribute changes.
7942        *        See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
7943        *        guide} for more info.
7944        * @returns {function()} Returns a deregistration function for this observer.
7945        */
7946       $observe: function(key, fn) {
7947         var attrs = this,
7948             $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
7949             listeners = ($$observers[key] || ($$observers[key] = []));
7950
7951         listeners.push(fn);
7952         $rootScope.$evalAsync(function() {
7953           if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
7954             // no one registered attribute interpolation function, so lets call it manually
7955             fn(attrs[key]);
7956           }
7957         });
7958
7959         return function() {
7960           arrayRemove(listeners, fn);
7961         };
7962       }
7963     };
7964
7965     function setSpecialAttr(element, attrName, value) {
7966       // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
7967       // so we have to jump through some hoops to get such an attribute
7968       // https://github.com/angular/angular.js/pull/13318
7969       specialAttrHolder.innerHTML = "<span " + attrName + ">";
7970       var attributes = specialAttrHolder.firstChild.attributes;
7971       var attribute = attributes[0];
7972       // We have to remove the attribute from its container element before we can add it to the destination element
7973       attributes.removeNamedItem(attribute.name);
7974       attribute.value = value;
7975       element.attributes.setNamedItem(attribute);
7976     }
7977
7978     function safeAddClass($element, className) {
7979       try {
7980         $element.addClass(className);
7981       } catch (e) {
7982         // ignore, since it means that we are trying to set class on
7983         // SVG element, where class name is read-only.
7984       }
7985     }
7986
7987
7988     var startSymbol = $interpolate.startSymbol(),
7989         endSymbol = $interpolate.endSymbol(),
7990         denormalizeTemplate = (startSymbol == '{{' && endSymbol  == '}}')
7991             ? identity
7992             : function denormalizeTemplate(template) {
7993               return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
7994         },
7995         NG_ATTR_BINDING = /^ngAttr[A-Z]/;
7996     var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
7997
7998     compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
7999       var bindings = $element.data('$binding') || [];
8000
8001       if (isArray(binding)) {
8002         bindings = bindings.concat(binding);
8003       } else {
8004         bindings.push(binding);
8005       }
8006
8007       $element.data('$binding', bindings);
8008     } : noop;
8009
8010     compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
8011       safeAddClass($element, 'ng-binding');
8012     } : noop;
8013
8014     compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
8015       var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
8016       $element.data(dataName, scope);
8017     } : noop;
8018
8019     compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
8020       safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
8021     } : noop;
8022
8023     return compile;
8024
8025     //================================
8026
8027     function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
8028                         previousCompileContext) {
8029       if (!($compileNodes instanceof jqLite)) {
8030         // jquery always rewraps, whereas we need to preserve the original selector so that we can
8031         // modify it.
8032         $compileNodes = jqLite($compileNodes);
8033       }
8034
8035       var NOT_EMPTY = /\S+/;
8036
8037       // We can not compile top level text elements since text nodes can be merged and we will
8038       // not be able to attach scope data to them, so we will wrap them in <span>
8039       for (var i = 0, len = $compileNodes.length; i < len; i++) {
8040         var domNode = $compileNodes[i];
8041
8042         if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
8043           jqLiteWrapNode(domNode, $compileNodes[i] = document.createElement('span'));
8044         }
8045       }
8046
8047       var compositeLinkFn =
8048               compileNodes($compileNodes, transcludeFn, $compileNodes,
8049                            maxPriority, ignoreDirective, previousCompileContext);
8050       compile.$$addScopeClass($compileNodes);
8051       var namespace = null;
8052       return function publicLinkFn(scope, cloneConnectFn, options) {
8053         assertArg(scope, 'scope');
8054
8055         if (previousCompileContext && previousCompileContext.needsNewScope) {
8056           // A parent directive did a replace and a directive on this element asked
8057           // for transclusion, which caused us to lose a layer of element on which
8058           // we could hold the new transclusion scope, so we will create it manually
8059           // here.
8060           scope = scope.$parent.$new();
8061         }
8062
8063         options = options || {};
8064         var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
8065           transcludeControllers = options.transcludeControllers,
8066           futureParentElement = options.futureParentElement;
8067
8068         // When `parentBoundTranscludeFn` is passed, it is a
8069         // `controllersBoundTransclude` function (it was previously passed
8070         // as `transclude` to directive.link) so we must unwrap it to get
8071         // its `boundTranscludeFn`
8072         if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
8073           parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
8074         }
8075
8076         if (!namespace) {
8077           namespace = detectNamespaceForChildElements(futureParentElement);
8078         }
8079         var $linkNode;
8080         if (namespace !== 'html') {
8081           // When using a directive with replace:true and templateUrl the $compileNodes
8082           // (or a child element inside of them)
8083           // might change, so we need to recreate the namespace adapted compileNodes
8084           // for call to the link function.
8085           // Note: This will already clone the nodes...
8086           $linkNode = jqLite(
8087             wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
8088           );
8089         } else if (cloneConnectFn) {
8090           // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
8091           // and sometimes changes the structure of the DOM.
8092           $linkNode = JQLitePrototype.clone.call($compileNodes);
8093         } else {
8094           $linkNode = $compileNodes;
8095         }
8096
8097         if (transcludeControllers) {
8098           for (var controllerName in transcludeControllers) {
8099             $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
8100           }
8101         }
8102
8103         compile.$$addScopeInfo($linkNode, scope);
8104
8105         if (cloneConnectFn) cloneConnectFn($linkNode, scope);
8106         if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
8107         return $linkNode;
8108       };
8109     }
8110
8111     function detectNamespaceForChildElements(parentElement) {
8112       // TODO: Make this detect MathML as well...
8113       var node = parentElement && parentElement[0];
8114       if (!node) {
8115         return 'html';
8116       } else {
8117         return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
8118       }
8119     }
8120
8121     /**
8122      * Compile function matches each node in nodeList against the directives. Once all directives
8123      * for a particular node are collected their compile functions are executed. The compile
8124      * functions return values - the linking functions - are combined into a composite linking
8125      * function, which is the a linking function for the node.
8126      *
8127      * @param {NodeList} nodeList an array of nodes or NodeList to compile
8128      * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
8129      *        scope argument is auto-generated to the new child of the transcluded parent scope.
8130      * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
8131      *        the rootElement must be set the jqLite collection of the compile root. This is
8132      *        needed so that the jqLite collection items can be replaced with widgets.
8133      * @param {number=} maxPriority Max directive priority.
8134      * @returns {Function} A composite linking function of all of the matched directives or null.
8135      */
8136     function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
8137                             previousCompileContext) {
8138       var linkFns = [],
8139           attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
8140
8141       for (var i = 0; i < nodeList.length; i++) {
8142         attrs = new Attributes();
8143
8144         // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
8145         directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
8146                                         ignoreDirective);
8147
8148         nodeLinkFn = (directives.length)
8149             ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
8150                                       null, [], [], previousCompileContext)
8151             : null;
8152
8153         if (nodeLinkFn && nodeLinkFn.scope) {
8154           compile.$$addScopeClass(attrs.$$element);
8155         }
8156
8157         childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
8158                       !(childNodes = nodeList[i].childNodes) ||
8159                       !childNodes.length)
8160             ? null
8161             : compileNodes(childNodes,
8162                  nodeLinkFn ? (
8163                   (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
8164                      && nodeLinkFn.transclude) : transcludeFn);
8165
8166         if (nodeLinkFn || childLinkFn) {
8167           linkFns.push(i, nodeLinkFn, childLinkFn);
8168           linkFnFound = true;
8169           nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
8170         }
8171
8172         //use the previous context only for the first element in the virtual group
8173         previousCompileContext = null;
8174       }
8175
8176       // return a linking function if we have found anything, null otherwise
8177       return linkFnFound ? compositeLinkFn : null;
8178
8179       function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
8180         var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
8181         var stableNodeList;
8182
8183
8184         if (nodeLinkFnFound) {
8185           // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
8186           // offsets don't get screwed up
8187           var nodeListLength = nodeList.length;
8188           stableNodeList = new Array(nodeListLength);
8189
8190           // create a sparse array by only copying the elements which have a linkFn
8191           for (i = 0; i < linkFns.length; i+=3) {
8192             idx = linkFns[i];
8193             stableNodeList[idx] = nodeList[idx];
8194           }
8195         } else {
8196           stableNodeList = nodeList;
8197         }
8198
8199         for (i = 0, ii = linkFns.length; i < ii;) {
8200           node = stableNodeList[linkFns[i++]];
8201           nodeLinkFn = linkFns[i++];
8202           childLinkFn = linkFns[i++];
8203
8204           if (nodeLinkFn) {
8205             if (nodeLinkFn.scope) {
8206               childScope = scope.$new();
8207               compile.$$addScopeInfo(jqLite(node), childScope);
8208             } else {
8209               childScope = scope;
8210             }
8211
8212             if (nodeLinkFn.transcludeOnThisElement) {
8213               childBoundTranscludeFn = createBoundTranscludeFn(
8214                   scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
8215
8216             } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
8217               childBoundTranscludeFn = parentBoundTranscludeFn;
8218
8219             } else if (!parentBoundTranscludeFn && transcludeFn) {
8220               childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
8221
8222             } else {
8223               childBoundTranscludeFn = null;
8224             }
8225
8226             nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
8227
8228           } else if (childLinkFn) {
8229             childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
8230           }
8231         }
8232       }
8233     }
8234
8235     function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
8236
8237       var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
8238
8239         if (!transcludedScope) {
8240           transcludedScope = scope.$new(false, containingScope);
8241           transcludedScope.$$transcluded = true;
8242         }
8243
8244         return transcludeFn(transcludedScope, cloneFn, {
8245           parentBoundTranscludeFn: previousBoundTranscludeFn,
8246           transcludeControllers: controllers,
8247           futureParentElement: futureParentElement
8248         });
8249       };
8250
8251       // We need  to attach the transclusion slots onto the `boundTranscludeFn`
8252       // so that they are available inside the `controllersBoundTransclude` function
8253       var boundSlots = boundTranscludeFn.$$slots = createMap();
8254       for (var slotName in transcludeFn.$$slots) {
8255         if (transcludeFn.$$slots[slotName]) {
8256           boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
8257         } else {
8258           boundSlots[slotName] = null;
8259         }
8260       }
8261
8262       return boundTranscludeFn;
8263     }
8264
8265     /**
8266      * Looks for directives on the given node and adds them to the directive collection which is
8267      * sorted.
8268      *
8269      * @param node Node to search.
8270      * @param directives An array to which the directives are added to. This array is sorted before
8271      *        the function returns.
8272      * @param attrs The shared attrs object which is used to populate the normalized attributes.
8273      * @param {number=} maxPriority Max directive priority.
8274      */
8275     function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
8276       var nodeType = node.nodeType,
8277           attrsMap = attrs.$attr,
8278           match,
8279           className;
8280
8281       switch (nodeType) {
8282         case NODE_TYPE_ELEMENT: /* Element */
8283           // use the node name: <directive>
8284           addDirective(directives,
8285               directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
8286
8287           // iterate over the attributes
8288           for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
8289                    j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
8290             var attrStartName = false;
8291             var attrEndName = false;
8292
8293             attr = nAttrs[j];
8294             name = attr.name;
8295             value = trim(attr.value);
8296
8297             // support ngAttr attribute binding
8298             ngAttrName = directiveNormalize(name);
8299             if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
8300               name = name.replace(PREFIX_REGEXP, '')
8301                 .substr(8).replace(/_(.)/g, function(match, letter) {
8302                   return letter.toUpperCase();
8303                 });
8304             }
8305
8306             var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
8307             if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
8308               attrStartName = name;
8309               attrEndName = name.substr(0, name.length - 5) + 'end';
8310               name = name.substr(0, name.length - 6);
8311             }
8312
8313             nName = directiveNormalize(name.toLowerCase());
8314             attrsMap[nName] = name;
8315             if (isNgAttr || !attrs.hasOwnProperty(nName)) {
8316                 attrs[nName] = value;
8317                 if (getBooleanAttrName(node, nName)) {
8318                   attrs[nName] = true; // presence means true
8319                 }
8320             }
8321             addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
8322             addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
8323                           attrEndName);
8324           }
8325
8326           // use class as directive
8327           className = node.className;
8328           if (isObject(className)) {
8329               // Maybe SVGAnimatedString
8330               className = className.animVal;
8331           }
8332           if (isString(className) && className !== '') {
8333             while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
8334               nName = directiveNormalize(match[2]);
8335               if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
8336                 attrs[nName] = trim(match[3]);
8337               }
8338               className = className.substr(match.index + match[0].length);
8339             }
8340           }
8341           break;
8342         case NODE_TYPE_TEXT: /* Text Node */
8343           if (msie === 11) {
8344             // Workaround for #11781
8345             while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
8346               node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
8347               node.parentNode.removeChild(node.nextSibling);
8348             }
8349           }
8350           addTextInterpolateDirective(directives, node.nodeValue);
8351           break;
8352         case NODE_TYPE_COMMENT: /* Comment */
8353           try {
8354             match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
8355             if (match) {
8356               nName = directiveNormalize(match[1]);
8357               if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
8358                 attrs[nName] = trim(match[2]);
8359               }
8360             }
8361           } catch (e) {
8362             // turns out that under some circumstances IE9 throws errors when one attempts to read
8363             // comment's node value.
8364             // Just ignore it and continue. (Can't seem to reproduce in test case.)
8365           }
8366           break;
8367       }
8368
8369       directives.sort(byPriority);
8370       return directives;
8371     }
8372
8373     /**
8374      * Given a node with an directive-start it collects all of the siblings until it finds
8375      * directive-end.
8376      * @param node
8377      * @param attrStart
8378      * @param attrEnd
8379      * @returns {*}
8380      */
8381     function groupScan(node, attrStart, attrEnd) {
8382       var nodes = [];
8383       var depth = 0;
8384       if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
8385         do {
8386           if (!node) {
8387             throw $compileMinErr('uterdir',
8388                       "Unterminated attribute, found '{0}' but no matching '{1}' found.",
8389                       attrStart, attrEnd);
8390           }
8391           if (node.nodeType == NODE_TYPE_ELEMENT) {
8392             if (node.hasAttribute(attrStart)) depth++;
8393             if (node.hasAttribute(attrEnd)) depth--;
8394           }
8395           nodes.push(node);
8396           node = node.nextSibling;
8397         } while (depth > 0);
8398       } else {
8399         nodes.push(node);
8400       }
8401
8402       return jqLite(nodes);
8403     }
8404
8405     /**
8406      * Wrapper for linking function which converts normal linking function into a grouped
8407      * linking function.
8408      * @param linkFn
8409      * @param attrStart
8410      * @param attrEnd
8411      * @returns {Function}
8412      */
8413     function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
8414       return function(scope, element, attrs, controllers, transcludeFn) {
8415         element = groupScan(element[0], attrStart, attrEnd);
8416         return linkFn(scope, element, attrs, controllers, transcludeFn);
8417       };
8418     }
8419
8420     /**
8421      * A function generator that is used to support both eager and lazy compilation
8422      * linking function.
8423      * @param eager
8424      * @param $compileNodes
8425      * @param transcludeFn
8426      * @param maxPriority
8427      * @param ignoreDirective
8428      * @param previousCompileContext
8429      * @returns {Function}
8430      */
8431     function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
8432         if (eager) {
8433             return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
8434         }
8435
8436         var compiled;
8437
8438         return function() {
8439             if (!compiled) {
8440                 compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
8441
8442                 // Null out all of these references in order to make them eligible for garbage collection
8443                 // since this is a potentially long lived closure
8444                 $compileNodes = transcludeFn = previousCompileContext = null;
8445             }
8446
8447             return compiled.apply(this, arguments);
8448         };
8449     }
8450
8451     /**
8452      * Once the directives have been collected, their compile functions are executed. This method
8453      * is responsible for inlining directive templates as well as terminating the application
8454      * of the directives if the terminal directive has been reached.
8455      *
8456      * @param {Array} directives Array of collected directives to execute their compile function.
8457      *        this needs to be pre-sorted by priority order.
8458      * @param {Node} compileNode The raw DOM node to apply the compile functions to
8459      * @param {Object} templateAttrs The shared attribute function
8460      * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
8461      *                                                  scope argument is auto-generated to the new
8462      *                                                  child of the transcluded parent scope.
8463      * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
8464      *                              argument has the root jqLite array so that we can replace nodes
8465      *                              on it.
8466      * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
8467      *                                           compiling the transclusion.
8468      * @param {Array.<Function>} preLinkFns
8469      * @param {Array.<Function>} postLinkFns
8470      * @param {Object} previousCompileContext Context used for previous compilation of the current
8471      *                                        node
8472      * @returns {Function} linkFn
8473      */
8474     function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
8475                                    jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
8476                                    previousCompileContext) {
8477       previousCompileContext = previousCompileContext || {};
8478
8479       var terminalPriority = -Number.MAX_VALUE,
8480           newScopeDirective = previousCompileContext.newScopeDirective,
8481           controllerDirectives = previousCompileContext.controllerDirectives,
8482           newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
8483           templateDirective = previousCompileContext.templateDirective,
8484           nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
8485           hasTranscludeDirective = false,
8486           hasTemplate = false,
8487           hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
8488           $compileNode = templateAttrs.$$element = jqLite(compileNode),
8489           directive,
8490           directiveName,
8491           $template,
8492           replaceDirective = originalReplaceDirective,
8493           childTranscludeFn = transcludeFn,
8494           linkFn,
8495           didScanForMultipleTransclusion = false,
8496           mightHaveMultipleTransclusionError = false,
8497           directiveValue;
8498
8499       // executes all directives on the current element
8500       for (var i = 0, ii = directives.length; i < ii; i++) {
8501         directive = directives[i];
8502         var attrStart = directive.$$start;
8503         var attrEnd = directive.$$end;
8504
8505         // collect multiblock sections
8506         if (attrStart) {
8507           $compileNode = groupScan(compileNode, attrStart, attrEnd);
8508         }
8509         $template = undefined;
8510
8511         if (terminalPriority > directive.priority) {
8512           break; // prevent further processing of directives
8513         }
8514
8515         if (directiveValue = directive.scope) {
8516
8517           // skip the check for directives with async templates, we'll check the derived sync
8518           // directive when the template arrives
8519           if (!directive.templateUrl) {
8520             if (isObject(directiveValue)) {
8521               // This directive is trying to add an isolated scope.
8522               // Check that there is no scope of any kind already
8523               assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
8524                                 directive, $compileNode);
8525               newIsolateScopeDirective = directive;
8526             } else {
8527               // This directive is trying to add a child scope.
8528               // Check that there is no isolated scope already
8529               assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
8530                                 $compileNode);
8531             }
8532           }
8533
8534           newScopeDirective = newScopeDirective || directive;
8535         }
8536
8537         directiveName = directive.name;
8538
8539         // If we encounter a condition that can result in transclusion on the directive,
8540         // then scan ahead in the remaining directives for others that may cause a multiple
8541         // transclusion error to be thrown during the compilation process.  If a matching directive
8542         // is found, then we know that when we encounter a transcluded directive, we need to eagerly
8543         // compile the `transclude` function rather than doing it lazily in order to throw
8544         // exceptions at the correct time
8545         if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
8546             || (directive.transclude && !directive.$$tlb))) {
8547                 var candidateDirective;
8548
8549                 for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
8550                     if ((candidateDirective.transclude && !candidateDirective.$$tlb)
8551                         || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
8552                         mightHaveMultipleTransclusionError = true;
8553                         break;
8554                     }
8555                 }
8556
8557                 didScanForMultipleTransclusion = true;
8558         }
8559
8560         if (!directive.templateUrl && directive.controller) {
8561           directiveValue = directive.controller;
8562           controllerDirectives = controllerDirectives || createMap();
8563           assertNoDuplicate("'" + directiveName + "' controller",
8564               controllerDirectives[directiveName], directive, $compileNode);
8565           controllerDirectives[directiveName] = directive;
8566         }
8567
8568         if (directiveValue = directive.transclude) {
8569           hasTranscludeDirective = true;
8570
8571           // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
8572           // This option should only be used by directives that know how to safely handle element transclusion,
8573           // where the transcluded nodes are added or replaced after linking.
8574           if (!directive.$$tlb) {
8575             assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
8576             nonTlbTranscludeDirective = directive;
8577           }
8578
8579           if (directiveValue == 'element') {
8580             hasElementTranscludeDirective = true;
8581             terminalPriority = directive.priority;
8582             $template = $compileNode;
8583             $compileNode = templateAttrs.$$element =
8584                 jqLite(document.createComment(' ' + directiveName + ': ' +
8585                                               templateAttrs[directiveName] + ' '));
8586             compileNode = $compileNode[0];
8587             replaceWith(jqCollection, sliceArgs($template), compileNode);
8588
8589             childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
8590                                         replaceDirective && replaceDirective.name, {
8591                                           // Don't pass in:
8592                                           // - controllerDirectives - otherwise we'll create duplicates controllers
8593                                           // - newIsolateScopeDirective or templateDirective - combining templates with
8594                                           //   element transclusion doesn't make sense.
8595                                           //
8596                                           // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
8597                                           // on the same element more than once.
8598                                           nonTlbTranscludeDirective: nonTlbTranscludeDirective
8599                                         });
8600           } else {
8601
8602             var slots = createMap();
8603
8604             $template = jqLite(jqLiteClone(compileNode)).contents();
8605
8606             if (isObject(directiveValue)) {
8607
8608               // We have transclusion slots,
8609               // collect them up, compile them and store their transclusion functions
8610               $template = [];
8611
8612               var slotMap = createMap();
8613               var filledSlots = createMap();
8614
8615               // Parse the element selectors
8616               forEach(directiveValue, function(elementSelector, slotName) {
8617                 // If an element selector starts with a ? then it is optional
8618                 var optional = (elementSelector.charAt(0) === '?');
8619                 elementSelector = optional ? elementSelector.substring(1) : elementSelector;
8620
8621                 slotMap[elementSelector] = slotName;
8622
8623                 // We explicitly assign `null` since this implies that a slot was defined but not filled.
8624                 // Later when calling boundTransclusion functions with a slot name we only error if the
8625                 // slot is `undefined`
8626                 slots[slotName] = null;
8627
8628                 // filledSlots contains `true` for all slots that are either optional or have been
8629                 // filled. This is used to check that we have not missed any required slots
8630                 filledSlots[slotName] = optional;
8631               });
8632
8633               // Add the matching elements into their slot
8634               forEach($compileNode.contents(), function(node) {
8635                 var slotName = slotMap[directiveNormalize(nodeName_(node))];
8636                 if (slotName) {
8637                   filledSlots[slotName] = true;
8638                   slots[slotName] = slots[slotName] || [];
8639                   slots[slotName].push(node);
8640                 } else {
8641                   $template.push(node);
8642                 }
8643               });
8644
8645               // Check for required slots that were not filled
8646               forEach(filledSlots, function(filled, slotName) {
8647                 if (!filled) {
8648                   throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
8649                 }
8650               });
8651
8652               for (var slotName in slots) {
8653                 if (slots[slotName]) {
8654                   // Only define a transclusion function if the slot was filled
8655                   slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
8656                 }
8657               }
8658             }
8659
8660             $compileNode.empty(); // clear contents
8661             childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
8662                 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
8663             childTranscludeFn.$$slots = slots;
8664           }
8665         }
8666
8667         if (directive.template) {
8668           hasTemplate = true;
8669           assertNoDuplicate('template', templateDirective, directive, $compileNode);
8670           templateDirective = directive;
8671
8672           directiveValue = (isFunction(directive.template))
8673               ? directive.template($compileNode, templateAttrs)
8674               : directive.template;
8675
8676           directiveValue = denormalizeTemplate(directiveValue);
8677
8678           if (directive.replace) {
8679             replaceDirective = directive;
8680             if (jqLiteIsTextNode(directiveValue)) {
8681               $template = [];
8682             } else {
8683               $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
8684             }
8685             compileNode = $template[0];
8686
8687             if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
8688               throw $compileMinErr('tplrt',
8689                   "Template for directive '{0}' must have exactly one root element. {1}",
8690                   directiveName, '');
8691             }
8692
8693             replaceWith(jqCollection, $compileNode, compileNode);
8694
8695             var newTemplateAttrs = {$attr: {}};
8696
8697             // combine directives from the original node and from the template:
8698             // - take the array of directives for this element
8699             // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
8700             // - collect directives from the template and sort them by priority
8701             // - combine directives as: processed + template + unprocessed
8702             var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
8703             var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
8704
8705             if (newIsolateScopeDirective || newScopeDirective) {
8706               // The original directive caused the current element to be replaced but this element
8707               // also needs to have a new scope, so we need to tell the template directives
8708               // that they would need to get their scope from further up, if they require transclusion
8709               markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
8710             }
8711             directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
8712             mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
8713
8714             ii = directives.length;
8715           } else {
8716             $compileNode.html(directiveValue);
8717           }
8718         }
8719
8720         if (directive.templateUrl) {
8721           hasTemplate = true;
8722           assertNoDuplicate('template', templateDirective, directive, $compileNode);
8723           templateDirective = directive;
8724
8725           if (directive.replace) {
8726             replaceDirective = directive;
8727           }
8728
8729           nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
8730               templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
8731                 controllerDirectives: controllerDirectives,
8732                 newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
8733                 newIsolateScopeDirective: newIsolateScopeDirective,
8734                 templateDirective: templateDirective,
8735                 nonTlbTranscludeDirective: nonTlbTranscludeDirective
8736               });
8737           ii = directives.length;
8738         } else if (directive.compile) {
8739           try {
8740             linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
8741             if (isFunction(linkFn)) {
8742               addLinkFns(null, linkFn, attrStart, attrEnd);
8743             } else if (linkFn) {
8744               addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
8745             }
8746           } catch (e) {
8747             $exceptionHandler(e, startingTag($compileNode));
8748           }
8749         }
8750
8751         if (directive.terminal) {
8752           nodeLinkFn.terminal = true;
8753           terminalPriority = Math.max(terminalPriority, directive.priority);
8754         }
8755
8756       }
8757
8758       nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
8759       nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
8760       nodeLinkFn.templateOnThisElement = hasTemplate;
8761       nodeLinkFn.transclude = childTranscludeFn;
8762
8763       previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
8764
8765       // might be normal or delayed nodeLinkFn depending on if templateUrl is present
8766       return nodeLinkFn;
8767
8768       ////////////////////
8769
8770       function addLinkFns(pre, post, attrStart, attrEnd) {
8771         if (pre) {
8772           if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
8773           pre.require = directive.require;
8774           pre.directiveName = directiveName;
8775           if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
8776             pre = cloneAndAnnotateFn(pre, {isolateScope: true});
8777           }
8778           preLinkFns.push(pre);
8779         }
8780         if (post) {
8781           if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
8782           post.require = directive.require;
8783           post.directiveName = directiveName;
8784           if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
8785             post = cloneAndAnnotateFn(post, {isolateScope: true});
8786           }
8787           postLinkFns.push(post);
8788         }
8789       }
8790
8791
8792       function getControllers(directiveName, require, $element, elementControllers) {
8793         var value;
8794
8795         if (isString(require)) {
8796           var match = require.match(REQUIRE_PREFIX_REGEXP);
8797           var name = require.substring(match[0].length);
8798           var inheritType = match[1] || match[3];
8799           var optional = match[2] === '?';
8800
8801           //If only parents then start at the parent element
8802           if (inheritType === '^^') {
8803             $element = $element.parent();
8804           //Otherwise attempt getting the controller from elementControllers in case
8805           //the element is transcluded (and has no data) and to avoid .data if possible
8806           } else {
8807             value = elementControllers && elementControllers[name];
8808             value = value && value.instance;
8809           }
8810
8811           if (!value) {
8812             var dataName = '$' + name + 'Controller';
8813             value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
8814           }
8815
8816           if (!value && !optional) {
8817             throw $compileMinErr('ctreq',
8818                 "Controller '{0}', required by directive '{1}', can't be found!",
8819                 name, directiveName);
8820           }
8821         } else if (isArray(require)) {
8822           value = [];
8823           for (var i = 0, ii = require.length; i < ii; i++) {
8824             value[i] = getControllers(directiveName, require[i], $element, elementControllers);
8825           }
8826         } else if (isObject(require)) {
8827           value = {};
8828           forEach(require, function(controller, property) {
8829             value[property] = getControllers(directiveName, controller, $element, elementControllers);
8830           });
8831         }
8832
8833         return value || null;
8834       }
8835
8836       function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
8837         var elementControllers = createMap();
8838         for (var controllerKey in controllerDirectives) {
8839           var directive = controllerDirectives[controllerKey];
8840           var locals = {
8841             $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
8842             $element: $element,
8843             $attrs: attrs,
8844             $transclude: transcludeFn
8845           };
8846
8847           var controller = directive.controller;
8848           if (controller == '@') {
8849             controller = attrs[directive.name];
8850           }
8851
8852           var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
8853
8854           // For directives with element transclusion the element is a comment,
8855           // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
8856           // clean up (http://bugs.jquery.com/ticket/8335).
8857           // Instead, we save the controllers for the element in a local hash and attach to .data
8858           // later, once we have the actual element.
8859           elementControllers[directive.name] = controllerInstance;
8860           if (!hasElementTranscludeDirective) {
8861             $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
8862           }
8863         }
8864         return elementControllers;
8865       }
8866
8867       function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
8868         var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
8869             attrs, removeScopeBindingWatches, removeControllerBindingWatches;
8870
8871         if (compileNode === linkNode) {
8872           attrs = templateAttrs;
8873           $element = templateAttrs.$$element;
8874         } else {
8875           $element = jqLite(linkNode);
8876           attrs = new Attributes($element, templateAttrs);
8877         }
8878
8879         controllerScope = scope;
8880         if (newIsolateScopeDirective) {
8881           isolateScope = scope.$new(true);
8882         } else if (newScopeDirective) {
8883           controllerScope = scope.$parent;
8884         }
8885
8886         if (boundTranscludeFn) {
8887           // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
8888           // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
8889           transcludeFn = controllersBoundTransclude;
8890           transcludeFn.$$boundTransclude = boundTranscludeFn;
8891           // expose the slots on the `$transclude` function
8892           transcludeFn.isSlotFilled = function(slotName) {
8893             return !!boundTranscludeFn.$$slots[slotName];
8894           };
8895         }
8896
8897         if (controllerDirectives) {
8898           elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
8899         }
8900
8901         if (newIsolateScopeDirective) {
8902           // Initialize isolate scope bindings for new isolate scope directive.
8903           compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
8904               templateDirective === newIsolateScopeDirective.$$originalDirective)));
8905           compile.$$addScopeClass($element, true);
8906           isolateScope.$$isolateBindings =
8907               newIsolateScopeDirective.$$isolateBindings;
8908           removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
8909                                         isolateScope.$$isolateBindings,
8910                                         newIsolateScopeDirective);
8911           if (removeScopeBindingWatches) {
8912             isolateScope.$on('$destroy', removeScopeBindingWatches);
8913           }
8914         }
8915
8916         // Initialize bindToController bindings
8917         for (var name in elementControllers) {
8918           var controllerDirective = controllerDirectives[name];
8919           var controller = elementControllers[name];
8920           var bindings = controllerDirective.$$bindings.bindToController;
8921
8922           if (controller.identifier && bindings) {
8923             removeControllerBindingWatches =
8924               initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
8925           }
8926
8927           var controllerResult = controller();
8928           if (controllerResult !== controller.instance) {
8929             // If the controller constructor has a return value, overwrite the instance
8930             // from setupControllers
8931             controller.instance = controllerResult;
8932             $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
8933             removeControllerBindingWatches && removeControllerBindingWatches();
8934             removeControllerBindingWatches =
8935               initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
8936           }
8937         }
8938
8939         // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
8940         forEach(controllerDirectives, function(controllerDirective, name) {
8941           var require = controllerDirective.require;
8942           if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
8943             extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
8944           }
8945         });
8946
8947         // Trigger the `$onInit` method on all controllers that have one
8948         forEach(elementControllers, function(controller) {
8949           if (isFunction(controller.instance.$onInit)) {
8950             controller.instance.$onInit();
8951           }
8952         });
8953
8954         // PRELINKING
8955         for (i = 0, ii = preLinkFns.length; i < ii; i++) {
8956           linkFn = preLinkFns[i];
8957           invokeLinkFn(linkFn,
8958               linkFn.isolateScope ? isolateScope : scope,
8959               $element,
8960               attrs,
8961               linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
8962               transcludeFn
8963           );
8964         }
8965
8966         // RECURSION
8967         // We only pass the isolate scope, if the isolate directive has a template,
8968         // otherwise the child elements do not belong to the isolate directive.
8969         var scopeToChild = scope;
8970         if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
8971           scopeToChild = isolateScope;
8972         }
8973         childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
8974
8975         // POSTLINKING
8976         for (i = postLinkFns.length - 1; i >= 0; i--) {
8977           linkFn = postLinkFns[i];
8978           invokeLinkFn(linkFn,
8979               linkFn.isolateScope ? isolateScope : scope,
8980               $element,
8981               attrs,
8982               linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
8983               transcludeFn
8984           );
8985         }
8986
8987         // This is the function that is injected as `$transclude`.
8988         // Note: all arguments are optional!
8989         function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
8990           var transcludeControllers;
8991           // No scope passed in:
8992           if (!isScope(scope)) {
8993             slotName = futureParentElement;
8994             futureParentElement = cloneAttachFn;
8995             cloneAttachFn = scope;
8996             scope = undefined;
8997           }
8998
8999           if (hasElementTranscludeDirective) {
9000             transcludeControllers = elementControllers;
9001           }
9002           if (!futureParentElement) {
9003             futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
9004           }
9005           if (slotName) {
9006             // slotTranscludeFn can be one of three things:
9007             //  * a transclude function - a filled slot
9008             //  * `null` - an optional slot that was not filled
9009             //  * `undefined` - a slot that was not declared (i.e. invalid)
9010             var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
9011             if (slotTranscludeFn) {
9012               return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
9013             } else if (isUndefined(slotTranscludeFn)) {
9014               throw $compileMinErr('noslot',
9015                'No parent directive that requires a transclusion with slot name "{0}". ' +
9016                'Element: {1}',
9017                slotName, startingTag($element));
9018             }
9019           } else {
9020             return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
9021           }
9022         }
9023       }
9024     }
9025
9026     // Depending upon the context in which a directive finds itself it might need to have a new isolated
9027     // or child scope created. For instance:
9028     // * if the directive has been pulled into a template because another directive with a higher priority
9029     // asked for element transclusion
9030     // * if the directive itself asks for transclusion but it is at the root of a template and the original
9031     // element was replaced. See https://github.com/angular/angular.js/issues/12936
9032     function markDirectiveScope(directives, isolateScope, newScope) {
9033       for (var j = 0, jj = directives.length; j < jj; j++) {
9034         directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
9035       }
9036     }
9037
9038     /**
9039      * looks up the directive and decorates it with exception handling and proper parameters. We
9040      * call this the boundDirective.
9041      *
9042      * @param {string} name name of the directive to look up.
9043      * @param {string} location The directive must be found in specific format.
9044      *   String containing any of theses characters:
9045      *
9046      *   * `E`: element name
9047      *   * `A': attribute
9048      *   * `C`: class
9049      *   * `M`: comment
9050      * @returns {boolean} true if directive was added.
9051      */
9052     function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
9053                           endAttrName) {
9054       if (name === ignoreDirective) return null;
9055       var match = null;
9056       if (hasDirectives.hasOwnProperty(name)) {
9057         for (var directive, directives = $injector.get(name + Suffix),
9058             i = 0, ii = directives.length; i < ii; i++) {
9059           try {
9060             directive = directives[i];
9061             if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
9062                  directive.restrict.indexOf(location) != -1) {
9063               if (startAttrName) {
9064                 directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
9065               }
9066               tDirectives.push(directive);
9067               match = directive;
9068             }
9069           } catch (e) { $exceptionHandler(e); }
9070         }
9071       }
9072       return match;
9073     }
9074
9075
9076     /**
9077      * looks up the directive and returns true if it is a multi-element directive,
9078      * and therefore requires DOM nodes between -start and -end markers to be grouped
9079      * together.
9080      *
9081      * @param {string} name name of the directive to look up.
9082      * @returns true if directive was registered as multi-element.
9083      */
9084     function directiveIsMultiElement(name) {
9085       if (hasDirectives.hasOwnProperty(name)) {
9086         for (var directive, directives = $injector.get(name + Suffix),
9087             i = 0, ii = directives.length; i < ii; i++) {
9088           directive = directives[i];
9089           if (directive.multiElement) {
9090             return true;
9091           }
9092         }
9093       }
9094       return false;
9095     }
9096
9097     /**
9098      * When the element is replaced with HTML template then the new attributes
9099      * on the template need to be merged with the existing attributes in the DOM.
9100      * The desired effect is to have both of the attributes present.
9101      *
9102      * @param {object} dst destination attributes (original DOM)
9103      * @param {object} src source attributes (from the directive template)
9104      */
9105     function mergeTemplateAttributes(dst, src) {
9106       var srcAttr = src.$attr,
9107           dstAttr = dst.$attr,
9108           $element = dst.$$element;
9109
9110       // reapply the old attributes to the new element
9111       forEach(dst, function(value, key) {
9112         if (key.charAt(0) != '$') {
9113           if (src[key] && src[key] !== value) {
9114             value += (key === 'style' ? ';' : ' ') + src[key];
9115           }
9116           dst.$set(key, value, true, srcAttr[key]);
9117         }
9118       });
9119
9120       // copy the new attributes on the old attrs object
9121       forEach(src, function(value, key) {
9122         if (key == 'class') {
9123           safeAddClass($element, value);
9124           dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
9125         } else if (key == 'style') {
9126           $element.attr('style', $element.attr('style') + ';' + value);
9127           dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
9128           // `dst` will never contain hasOwnProperty as DOM parser won't let it.
9129           // You will get an "InvalidCharacterError: DOM Exception 5" error if you
9130           // have an attribute like "has-own-property" or "data-has-own-property", etc.
9131         } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
9132           dst[key] = value;
9133           dstAttr[key] = srcAttr[key];
9134         }
9135       });
9136     }
9137
9138
9139     function compileTemplateUrl(directives, $compileNode, tAttrs,
9140         $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
9141       var linkQueue = [],
9142           afterTemplateNodeLinkFn,
9143           afterTemplateChildLinkFn,
9144           beforeTemplateCompileNode = $compileNode[0],
9145           origAsyncDirective = directives.shift(),
9146           derivedSyncDirective = inherit(origAsyncDirective, {
9147             templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
9148           }),
9149           templateUrl = (isFunction(origAsyncDirective.templateUrl))
9150               ? origAsyncDirective.templateUrl($compileNode, tAttrs)
9151               : origAsyncDirective.templateUrl,
9152           templateNamespace = origAsyncDirective.templateNamespace;
9153
9154       $compileNode.empty();
9155
9156       $templateRequest(templateUrl)
9157         .then(function(content) {
9158           var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
9159
9160           content = denormalizeTemplate(content);
9161
9162           if (origAsyncDirective.replace) {
9163             if (jqLiteIsTextNode(content)) {
9164               $template = [];
9165             } else {
9166               $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
9167             }
9168             compileNode = $template[0];
9169
9170             if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
9171               throw $compileMinErr('tplrt',
9172                   "Template for directive '{0}' must have exactly one root element. {1}",
9173                   origAsyncDirective.name, templateUrl);
9174             }
9175
9176             tempTemplateAttrs = {$attr: {}};
9177             replaceWith($rootElement, $compileNode, compileNode);
9178             var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
9179
9180             if (isObject(origAsyncDirective.scope)) {
9181               // the original directive that caused the template to be loaded async required
9182               // an isolate scope
9183               markDirectiveScope(templateDirectives, true);
9184             }
9185             directives = templateDirectives.concat(directives);
9186             mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
9187           } else {
9188             compileNode = beforeTemplateCompileNode;
9189             $compileNode.html(content);
9190           }
9191
9192           directives.unshift(derivedSyncDirective);
9193
9194           afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
9195               childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
9196               previousCompileContext);
9197           forEach($rootElement, function(node, i) {
9198             if (node == compileNode) {
9199               $rootElement[i] = $compileNode[0];
9200             }
9201           });
9202           afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
9203
9204           while (linkQueue.length) {
9205             var scope = linkQueue.shift(),
9206                 beforeTemplateLinkNode = linkQueue.shift(),
9207                 linkRootElement = linkQueue.shift(),
9208                 boundTranscludeFn = linkQueue.shift(),
9209                 linkNode = $compileNode[0];
9210
9211             if (scope.$$destroyed) continue;
9212
9213             if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
9214               var oldClasses = beforeTemplateLinkNode.className;
9215
9216               if (!(previousCompileContext.hasElementTranscludeDirective &&
9217                   origAsyncDirective.replace)) {
9218                 // it was cloned therefore we have to clone as well.
9219                 linkNode = jqLiteClone(compileNode);
9220               }
9221               replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
9222
9223               // Copy in CSS classes from original node
9224               safeAddClass(jqLite(linkNode), oldClasses);
9225             }
9226             if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
9227               childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
9228             } else {
9229               childBoundTranscludeFn = boundTranscludeFn;
9230             }
9231             afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
9232               childBoundTranscludeFn);
9233           }
9234           linkQueue = null;
9235         });
9236
9237       return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
9238         var childBoundTranscludeFn = boundTranscludeFn;
9239         if (scope.$$destroyed) return;
9240         if (linkQueue) {
9241           linkQueue.push(scope,
9242                          node,
9243                          rootElement,
9244                          childBoundTranscludeFn);
9245         } else {
9246           if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
9247             childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
9248           }
9249           afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
9250         }
9251       };
9252     }
9253
9254
9255     /**
9256      * Sorting function for bound directives.
9257      */
9258     function byPriority(a, b) {
9259       var diff = b.priority - a.priority;
9260       if (diff !== 0) return diff;
9261       if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
9262       return a.index - b.index;
9263     }
9264
9265     function assertNoDuplicate(what, previousDirective, directive, element) {
9266
9267       function wrapModuleNameIfDefined(moduleName) {
9268         return moduleName ?
9269           (' (module: ' + moduleName + ')') :
9270           '';
9271       }
9272
9273       if (previousDirective) {
9274         throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
9275             previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
9276             directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
9277       }
9278     }
9279
9280
9281     function addTextInterpolateDirective(directives, text) {
9282       var interpolateFn = $interpolate(text, true);
9283       if (interpolateFn) {
9284         directives.push({
9285           priority: 0,
9286           compile: function textInterpolateCompileFn(templateNode) {
9287             var templateNodeParent = templateNode.parent(),
9288                 hasCompileParent = !!templateNodeParent.length;
9289
9290             // When transcluding a template that has bindings in the root
9291             // we don't have a parent and thus need to add the class during linking fn.
9292             if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
9293
9294             return function textInterpolateLinkFn(scope, node) {
9295               var parent = node.parent();
9296               if (!hasCompileParent) compile.$$addBindingClass(parent);
9297               compile.$$addBindingInfo(parent, interpolateFn.expressions);
9298               scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
9299                 node[0].nodeValue = value;
9300               });
9301             };
9302           }
9303         });
9304       }
9305     }
9306
9307
9308     function wrapTemplate(type, template) {
9309       type = lowercase(type || 'html');
9310       switch (type) {
9311       case 'svg':
9312       case 'math':
9313         var wrapper = document.createElement('div');
9314         wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
9315         return wrapper.childNodes[0].childNodes;
9316       default:
9317         return template;
9318       }
9319     }
9320
9321
9322     function getTrustedContext(node, attrNormalizedName) {
9323       if (attrNormalizedName == "srcdoc") {
9324         return $sce.HTML;
9325       }
9326       var tag = nodeName_(node);
9327       // maction[xlink:href] can source SVG.  It's not limited to <maction>.
9328       if (attrNormalizedName == "xlinkHref" ||
9329           (tag == "form" && attrNormalizedName == "action") ||
9330           (tag != "img" && (attrNormalizedName == "src" ||
9331                             attrNormalizedName == "ngSrc"))) {
9332         return $sce.RESOURCE_URL;
9333       }
9334     }
9335
9336
9337     function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
9338       var trustedContext = getTrustedContext(node, name);
9339       allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
9340
9341       var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
9342
9343       // no interpolation found -> ignore
9344       if (!interpolateFn) return;
9345
9346
9347       if (name === "multiple" && nodeName_(node) === "select") {
9348         throw $compileMinErr("selmulti",
9349             "Binding to the 'multiple' attribute is not supported. Element: {0}",
9350             startingTag(node));
9351       }
9352
9353       directives.push({
9354         priority: 100,
9355         compile: function() {
9356             return {
9357               pre: function attrInterpolatePreLinkFn(scope, element, attr) {
9358                 var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
9359
9360                 if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
9361                   throw $compileMinErr('nodomevents',
9362                       "Interpolations for HTML DOM event attributes are disallowed.  Please use the " +
9363                           "ng- versions (such as ng-click instead of onclick) instead.");
9364                 }
9365
9366                 // If the attribute has changed since last $interpolate()ed
9367                 var newValue = attr[name];
9368                 if (newValue !== value) {
9369                   // we need to interpolate again since the attribute value has been updated
9370                   // (e.g. by another directive's compile function)
9371                   // ensure unset/empty values make interpolateFn falsy
9372                   interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
9373                   value = newValue;
9374                 }
9375
9376                 // if attribute was updated so that there is no interpolation going on we don't want to
9377                 // register any observers
9378                 if (!interpolateFn) return;
9379
9380                 // initialize attr object so that it's ready in case we need the value for isolate
9381                 // scope initialization, otherwise the value would not be available from isolate
9382                 // directive's linking fn during linking phase
9383                 attr[name] = interpolateFn(scope);
9384
9385                 ($$observers[name] || ($$observers[name] = [])).$$inter = true;
9386                 (attr.$$observers && attr.$$observers[name].$$scope || scope).
9387                   $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
9388                     //special case for class attribute addition + removal
9389                     //so that class changes can tap into the animation
9390                     //hooks provided by the $animate service. Be sure to
9391                     //skip animations when the first digest occurs (when
9392                     //both the new and the old values are the same) since
9393                     //the CSS classes are the non-interpolated values
9394                     if (name === 'class' && newValue != oldValue) {
9395                       attr.$updateClass(newValue, oldValue);
9396                     } else {
9397                       attr.$set(name, newValue);
9398                     }
9399                   });
9400               }
9401             };
9402           }
9403       });
9404     }
9405
9406
9407     /**
9408      * This is a special jqLite.replaceWith, which can replace items which
9409      * have no parents, provided that the containing jqLite collection is provided.
9410      *
9411      * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
9412      *                               in the root of the tree.
9413      * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
9414      *                                  the shell, but replace its DOM node reference.
9415      * @param {Node} newNode The new DOM node.
9416      */
9417     function replaceWith($rootElement, elementsToRemove, newNode) {
9418       var firstElementToRemove = elementsToRemove[0],
9419           removeCount = elementsToRemove.length,
9420           parent = firstElementToRemove.parentNode,
9421           i, ii;
9422
9423       if ($rootElement) {
9424         for (i = 0, ii = $rootElement.length; i < ii; i++) {
9425           if ($rootElement[i] == firstElementToRemove) {
9426             $rootElement[i++] = newNode;
9427             for (var j = i, j2 = j + removeCount - 1,
9428                      jj = $rootElement.length;
9429                  j < jj; j++, j2++) {
9430               if (j2 < jj) {
9431                 $rootElement[j] = $rootElement[j2];
9432               } else {
9433                 delete $rootElement[j];
9434               }
9435             }
9436             $rootElement.length -= removeCount - 1;
9437
9438             // If the replaced element is also the jQuery .context then replace it
9439             // .context is a deprecated jQuery api, so we should set it only when jQuery set it
9440             // http://api.jquery.com/context/
9441             if ($rootElement.context === firstElementToRemove) {
9442               $rootElement.context = newNode;
9443             }
9444             break;
9445           }
9446         }
9447       }
9448
9449       if (parent) {
9450         parent.replaceChild(newNode, firstElementToRemove);
9451       }
9452
9453       // Append all the `elementsToRemove` to a fragment. This will...
9454       // - remove them from the DOM
9455       // - allow them to still be traversed with .nextSibling
9456       // - allow a single fragment.qSA to fetch all elements being removed
9457       var fragment = document.createDocumentFragment();
9458       for (i = 0; i < removeCount; i++) {
9459         fragment.appendChild(elementsToRemove[i]);
9460       }
9461
9462       if (jqLite.hasData(firstElementToRemove)) {
9463         // Copy over user data (that includes Angular's $scope etc.). Don't copy private
9464         // data here because there's no public interface in jQuery to do that and copying over
9465         // event listeners (which is the main use of private data) wouldn't work anyway.
9466         jqLite.data(newNode, jqLite.data(firstElementToRemove));
9467
9468         // Remove $destroy event listeners from `firstElementToRemove`
9469         jqLite(firstElementToRemove).off('$destroy');
9470       }
9471
9472       // Cleanup any data/listeners on the elements and children.
9473       // This includes invoking the $destroy event on any elements with listeners.
9474       jqLite.cleanData(fragment.querySelectorAll('*'));
9475
9476       // Update the jqLite collection to only contain the `newNode`
9477       for (i = 1; i < removeCount; i++) {
9478         delete elementsToRemove[i];
9479       }
9480       elementsToRemove[0] = newNode;
9481       elementsToRemove.length = 1;
9482     }
9483
9484
9485     function cloneAndAnnotateFn(fn, annotation) {
9486       return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
9487     }
9488
9489
9490     function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
9491       try {
9492         linkFn(scope, $element, attrs, controllers, transcludeFn);
9493       } catch (e) {
9494         $exceptionHandler(e, startingTag($element));
9495       }
9496     }
9497
9498
9499     // Set up $watches for isolate scope and controller bindings. This process
9500     // only occurs for isolate scopes and new scopes with controllerAs.
9501     function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
9502       var removeWatchCollection = [];
9503       forEach(bindings, function(definition, scopeName) {
9504         var attrName = definition.attrName,
9505         optional = definition.optional,
9506         mode = definition.mode, // @, =, or &
9507         lastValue,
9508         parentGet, parentSet, compare, removeWatch;
9509
9510         switch (mode) {
9511
9512           case '@':
9513             if (!optional && !hasOwnProperty.call(attrs, attrName)) {
9514               destination[scopeName] = attrs[attrName] = void 0;
9515             }
9516             attrs.$observe(attrName, function(value) {
9517               if (isString(value)) {
9518                 destination[scopeName] = value;
9519               }
9520             });
9521             attrs.$$observers[attrName].$$scope = scope;
9522             lastValue = attrs[attrName];
9523             if (isString(lastValue)) {
9524               // If the attribute has been provided then we trigger an interpolation to ensure
9525               // the value is there for use in the link fn
9526               destination[scopeName] = $interpolate(lastValue)(scope);
9527             } else if (isBoolean(lastValue)) {
9528               // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
9529               // the value to boolean rather than a string, so we special case this situation
9530               destination[scopeName] = lastValue;
9531             }
9532             break;
9533
9534           case '=':
9535             if (!hasOwnProperty.call(attrs, attrName)) {
9536               if (optional) break;
9537               attrs[attrName] = void 0;
9538             }
9539             if (optional && !attrs[attrName]) break;
9540
9541             parentGet = $parse(attrs[attrName]);
9542             if (parentGet.literal) {
9543               compare = equals;
9544             } else {
9545               compare = function(a, b) { return a === b || (a !== a && b !== b); };
9546             }
9547             parentSet = parentGet.assign || function() {
9548               // reset the change, or we will throw this exception on every $digest
9549               lastValue = destination[scopeName] = parentGet(scope);
9550               throw $compileMinErr('nonassign',
9551                   "Expression '{0}' in attribute '{1}' used with directive '{2}' is non-assignable!",
9552                   attrs[attrName], attrName, directive.name);
9553             };
9554             lastValue = destination[scopeName] = parentGet(scope);
9555             var parentValueWatch = function parentValueWatch(parentValue) {
9556               if (!compare(parentValue, destination[scopeName])) {
9557                 // we are out of sync and need to copy
9558                 if (!compare(parentValue, lastValue)) {
9559                   // parent changed and it has precedence
9560                   destination[scopeName] = parentValue;
9561                 } else {
9562                   // if the parent can be assigned then do so
9563                   parentSet(scope, parentValue = destination[scopeName]);
9564                 }
9565               }
9566               return lastValue = parentValue;
9567             };
9568             parentValueWatch.$stateful = true;
9569             if (definition.collection) {
9570               removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
9571             } else {
9572               removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
9573             }
9574             removeWatchCollection.push(removeWatch);
9575             break;
9576
9577           case '<':
9578             if (!hasOwnProperty.call(attrs, attrName)) {
9579               if (optional) break;
9580               attrs[attrName] = void 0;
9581             }
9582             if (optional && !attrs[attrName]) break;
9583
9584             parentGet = $parse(attrs[attrName]);
9585
9586             destination[scopeName] = parentGet(scope);
9587
9588             removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
9589               destination[scopeName] = newParentValue;
9590             }, parentGet.literal);
9591
9592             removeWatchCollection.push(removeWatch);
9593             break;
9594
9595           case '&':
9596             // Don't assign Object.prototype method to scope
9597             parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
9598
9599             // Don't assign noop to destination if expression is not valid
9600             if (parentGet === noop && optional) break;
9601
9602             destination[scopeName] = function(locals) {
9603               return parentGet(scope, locals);
9604             };
9605             break;
9606         }
9607       });
9608
9609       return removeWatchCollection.length && function removeWatches() {
9610         for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
9611           removeWatchCollection[i]();
9612         }
9613       };
9614     }
9615   }];
9616 }
9617
9618 var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
9619 /**
9620  * Converts all accepted directives format into proper directive name.
9621  * @param name Name to normalize
9622  */
9623 function directiveNormalize(name) {
9624   return camelCase(name.replace(PREFIX_REGEXP, ''));
9625 }
9626
9627 /**
9628  * @ngdoc type
9629  * @name $compile.directive.Attributes
9630  *
9631  * @description
9632  * A shared object between directive compile / linking functions which contains normalized DOM
9633  * element attributes. The values reflect current binding state `{{ }}`. The normalization is
9634  * needed since all of these are treated as equivalent in Angular:
9635  *
9636  * ```
9637  *    <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
9638  * ```
9639  */
9640
9641 /**
9642  * @ngdoc property
9643  * @name $compile.directive.Attributes#$attr
9644  *
9645  * @description
9646  * A map of DOM element attribute names to the normalized name. This is
9647  * needed to do reverse lookup from normalized name back to actual name.
9648  */
9649
9650
9651 /**
9652  * @ngdoc method
9653  * @name $compile.directive.Attributes#$set
9654  * @kind function
9655  *
9656  * @description
9657  * Set DOM element attribute value.
9658  *
9659  *
9660  * @param {string} name Normalized element attribute name of the property to modify. The name is
9661  *          reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
9662  *          property to the original name.
9663  * @param {string} value Value to set the attribute to. The value can be an interpolated string.
9664  */
9665
9666
9667
9668 /**
9669  * Closure compiler type information
9670  */
9671
9672 function nodesetLinkingFn(
9673   /* angular.Scope */ scope,
9674   /* NodeList */ nodeList,
9675   /* Element */ rootElement,
9676   /* function(Function) */ boundTranscludeFn
9677 ) {}
9678
9679 function directiveLinkingFn(
9680   /* nodesetLinkingFn */ nodesetLinkingFn,
9681   /* angular.Scope */ scope,
9682   /* Node */ node,
9683   /* Element */ rootElement,
9684   /* function(Function) */ boundTranscludeFn
9685 ) {}
9686
9687 function tokenDifference(str1, str2) {
9688   var values = '',
9689       tokens1 = str1.split(/\s+/),
9690       tokens2 = str2.split(/\s+/);
9691
9692   outer:
9693   for (var i = 0; i < tokens1.length; i++) {
9694     var token = tokens1[i];
9695     for (var j = 0; j < tokens2.length; j++) {
9696       if (token == tokens2[j]) continue outer;
9697     }
9698     values += (values.length > 0 ? ' ' : '') + token;
9699   }
9700   return values;
9701 }
9702
9703 function removeComments(jqNodes) {
9704   jqNodes = jqLite(jqNodes);
9705   var i = jqNodes.length;
9706
9707   if (i <= 1) {
9708     return jqNodes;
9709   }
9710
9711   while (i--) {
9712     var node = jqNodes[i];
9713     if (node.nodeType === NODE_TYPE_COMMENT) {
9714       splice.call(jqNodes, i, 1);
9715     }
9716   }
9717   return jqNodes;
9718 }
9719
9720 var $controllerMinErr = minErr('$controller');
9721
9722
9723 var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
9724 function identifierForController(controller, ident) {
9725   if (ident && isString(ident)) return ident;
9726   if (isString(controller)) {
9727     var match = CNTRL_REG.exec(controller);
9728     if (match) return match[3];
9729   }
9730 }
9731
9732
9733 /**
9734  * @ngdoc provider
9735  * @name $controllerProvider
9736  * @description
9737  * The {@link ng.$controller $controller service} is used by Angular to create new
9738  * controllers.
9739  *
9740  * This provider allows controller registration via the
9741  * {@link ng.$controllerProvider#register register} method.
9742  */
9743 function $ControllerProvider() {
9744   var controllers = {},
9745       globals = false;
9746
9747   /**
9748    * @ngdoc method
9749    * @name $controllerProvider#register
9750    * @param {string|Object} name Controller name, or an object map of controllers where the keys are
9751    *    the names and the values are the constructors.
9752    * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
9753    *    annotations in the array notation).
9754    */
9755   this.register = function(name, constructor) {
9756     assertNotHasOwnProperty(name, 'controller');
9757     if (isObject(name)) {
9758       extend(controllers, name);
9759     } else {
9760       controllers[name] = constructor;
9761     }
9762   };
9763
9764   /**
9765    * @ngdoc method
9766    * @name $controllerProvider#allowGlobals
9767    * @description If called, allows `$controller` to find controller constructors on `window`
9768    */
9769   this.allowGlobals = function() {
9770     globals = true;
9771   };
9772
9773
9774   this.$get = ['$injector', '$window', function($injector, $window) {
9775
9776     /**
9777      * @ngdoc service
9778      * @name $controller
9779      * @requires $injector
9780      *
9781      * @param {Function|string} constructor If called with a function then it's considered to be the
9782      *    controller constructor function. Otherwise it's considered to be a string which is used
9783      *    to retrieve the controller constructor using the following steps:
9784      *
9785      *    * check if a controller with given name is registered via `$controllerProvider`
9786      *    * check if evaluating the string on the current scope returns a constructor
9787      *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
9788      *      `window` object (not recommended)
9789      *
9790      *    The string can use the `controller as property` syntax, where the controller instance is published
9791      *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
9792      *    to work correctly.
9793      *
9794      * @param {Object} locals Injection locals for Controller.
9795      * @return {Object} Instance of given controller.
9796      *
9797      * @description
9798      * `$controller` service is responsible for instantiating controllers.
9799      *
9800      * It's just a simple call to {@link auto.$injector $injector}, but extracted into
9801      * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
9802      */
9803     return function(expression, locals, later, ident) {
9804       // PRIVATE API:
9805       //   param `later` --- indicates that the controller's constructor is invoked at a later time.
9806       //                     If true, $controller will allocate the object with the correct
9807       //                     prototype chain, but will not invoke the controller until a returned
9808       //                     callback is invoked.
9809       //   param `ident` --- An optional label which overrides the label parsed from the controller
9810       //                     expression, if any.
9811       var instance, match, constructor, identifier;
9812       later = later === true;
9813       if (ident && isString(ident)) {
9814         identifier = ident;
9815       }
9816
9817       if (isString(expression)) {
9818         match = expression.match(CNTRL_REG);
9819         if (!match) {
9820           throw $controllerMinErr('ctrlfmt',
9821             "Badly formed controller string '{0}'. " +
9822             "Must match `__name__ as __id__` or `__name__`.", expression);
9823         }
9824         constructor = match[1],
9825         identifier = identifier || match[3];
9826         expression = controllers.hasOwnProperty(constructor)
9827             ? controllers[constructor]
9828             : getter(locals.$scope, constructor, true) ||
9829                 (globals ? getter($window, constructor, true) : undefined);
9830
9831         assertArgFn(expression, constructor, true);
9832       }
9833
9834       if (later) {
9835         // Instantiate controller later:
9836         // This machinery is used to create an instance of the object before calling the
9837         // controller's constructor itself.
9838         //
9839         // This allows properties to be added to the controller before the constructor is
9840         // invoked. Primarily, this is used for isolate scope bindings in $compile.
9841         //
9842         // This feature is not intended for use by applications, and is thus not documented
9843         // publicly.
9844         // Object creation: http://jsperf.com/create-constructor/2
9845         var controllerPrototype = (isArray(expression) ?
9846           expression[expression.length - 1] : expression).prototype;
9847         instance = Object.create(controllerPrototype || null);
9848
9849         if (identifier) {
9850           addIdentifier(locals, identifier, instance, constructor || expression.name);
9851         }
9852
9853         var instantiate;
9854         return instantiate = extend(function() {
9855           var result = $injector.invoke(expression, instance, locals, constructor);
9856           if (result !== instance && (isObject(result) || isFunction(result))) {
9857             instance = result;
9858             if (identifier) {
9859               // If result changed, re-assign controllerAs value to scope.
9860               addIdentifier(locals, identifier, instance, constructor || expression.name);
9861             }
9862           }
9863           return instance;
9864         }, {
9865           instance: instance,
9866           identifier: identifier
9867         });
9868       }
9869
9870       instance = $injector.instantiate(expression, locals, constructor);
9871
9872       if (identifier) {
9873         addIdentifier(locals, identifier, instance, constructor || expression.name);
9874       }
9875
9876       return instance;
9877     };
9878
9879     function addIdentifier(locals, identifier, instance, name) {
9880       if (!(locals && isObject(locals.$scope))) {
9881         throw minErr('$controller')('noscp',
9882           "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
9883           name, identifier);
9884       }
9885
9886       locals.$scope[identifier] = instance;
9887     }
9888   }];
9889 }
9890
9891 /**
9892  * @ngdoc service
9893  * @name $document
9894  * @requires $window
9895  *
9896  * @description
9897  * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
9898  *
9899  * @example
9900    <example module="documentExample">
9901      <file name="index.html">
9902        <div ng-controller="ExampleController">
9903          <p>$document title: <b ng-bind="title"></b></p>
9904          <p>window.document title: <b ng-bind="windowTitle"></b></p>
9905        </div>
9906      </file>
9907      <file name="script.js">
9908        angular.module('documentExample', [])
9909          .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
9910            $scope.title = $document[0].title;
9911            $scope.windowTitle = angular.element(window.document)[0].title;
9912          }]);
9913      </file>
9914    </example>
9915  */
9916 function $DocumentProvider() {
9917   this.$get = ['$window', function(window) {
9918     return jqLite(window.document);
9919   }];
9920 }
9921
9922 /**
9923  * @ngdoc service
9924  * @name $exceptionHandler
9925  * @requires ng.$log
9926  *
9927  * @description
9928  * Any uncaught exception in angular expressions is delegated to this service.
9929  * The default implementation simply delegates to `$log.error` which logs it into
9930  * the browser console.
9931  *
9932  * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
9933  * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
9934  *
9935  * ## Example:
9936  *
9937  * ```js
9938  *   angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
9939  *     return function(exception, cause) {
9940  *       exception.message += ' (caused by "' + cause + '")';
9941  *       throw exception;
9942  *     };
9943  *   });
9944  * ```
9945  *
9946  * This example will override the normal action of `$exceptionHandler`, to make angular
9947  * exceptions fail hard when they happen, instead of just logging to the console.
9948  *
9949  * <hr />
9950  * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
9951  * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
9952  * (unless executed during a digest).
9953  *
9954  * If you wish, you can manually delegate exceptions, e.g.
9955  * `try { ... } catch(e) { $exceptionHandler(e); }`
9956  *
9957  * @param {Error} exception Exception associated with the error.
9958  * @param {string=} cause optional information about the context in which
9959  *       the error was thrown.
9960  *
9961  */
9962 function $ExceptionHandlerProvider() {
9963   this.$get = ['$log', function($log) {
9964     return function(exception, cause) {
9965       $log.error.apply($log, arguments);
9966     };
9967   }];
9968 }
9969
9970 var $$ForceReflowProvider = function() {
9971   this.$get = ['$document', function($document) {
9972     return function(domNode) {
9973       //the line below will force the browser to perform a repaint so
9974       //that all the animated elements within the animation frame will
9975       //be properly updated and drawn on screen. This is required to
9976       //ensure that the preparation animation is properly flushed so that
9977       //the active state picks up from there. DO NOT REMOVE THIS LINE.
9978       //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
9979       //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
9980       //WILL TAKE YEARS AWAY FROM YOUR LIFE.
9981       if (domNode) {
9982         if (!domNode.nodeType && domNode instanceof jqLite) {
9983           domNode = domNode[0];
9984         }
9985       } else {
9986         domNode = $document[0].body;
9987       }
9988       return domNode.offsetWidth + 1;
9989     };
9990   }];
9991 };
9992
9993 var APPLICATION_JSON = 'application/json';
9994 var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
9995 var JSON_START = /^\[|^\{(?!\{)/;
9996 var JSON_ENDS = {
9997   '[': /]$/,
9998   '{': /}$/
9999 };
10000 var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
10001 var $httpMinErr = minErr('$http');
10002 var $httpMinErrLegacyFn = function(method) {
10003   return function() {
10004     throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
10005   };
10006 };
10007
10008 function serializeValue(v) {
10009   if (isObject(v)) {
10010     return isDate(v) ? v.toISOString() : toJson(v);
10011   }
10012   return v;
10013 }
10014
10015
10016 function $HttpParamSerializerProvider() {
10017   /**
10018    * @ngdoc service
10019    * @name $httpParamSerializer
10020    * @description
10021    *
10022    * Default {@link $http `$http`} params serializer that converts objects to strings
10023    * according to the following rules:
10024    *
10025    * * `{'foo': 'bar'}` results in `foo=bar`
10026    * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
10027    * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
10028    * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
10029    *
10030    * Note that serializer will sort the request parameters alphabetically.
10031    * */
10032
10033   this.$get = function() {
10034     return function ngParamSerializer(params) {
10035       if (!params) return '';
10036       var parts = [];
10037       forEachSorted(params, function(value, key) {
10038         if (value === null || isUndefined(value)) return;
10039         if (isArray(value)) {
10040           forEach(value, function(v, k) {
10041             parts.push(encodeUriQuery(key)  + '=' + encodeUriQuery(serializeValue(v)));
10042           });
10043         } else {
10044           parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
10045         }
10046       });
10047
10048       return parts.join('&');
10049     };
10050   };
10051 }
10052
10053 function $HttpParamSerializerJQLikeProvider() {
10054   /**
10055    * @ngdoc service
10056    * @name $httpParamSerializerJQLike
10057    * @description
10058    *
10059    * Alternative {@link $http `$http`} params serializer that follows
10060    * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
10061    * The serializer will also sort the params alphabetically.
10062    *
10063    * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
10064    *
10065    * ```js
10066    * $http({
10067    *   url: myUrl,
10068    *   method: 'GET',
10069    *   params: myParams,
10070    *   paramSerializer: '$httpParamSerializerJQLike'
10071    * });
10072    * ```
10073    *
10074    * It is also possible to set it as the default `paramSerializer` in the
10075    * {@link $httpProvider#defaults `$httpProvider`}.
10076    *
10077    * Additionally, you can inject the serializer and use it explicitly, for example to serialize
10078    * form data for submission:
10079    *
10080    * ```js
10081    * .controller(function($http, $httpParamSerializerJQLike) {
10082    *   //...
10083    *
10084    *   $http({
10085    *     url: myUrl,
10086    *     method: 'POST',
10087    *     data: $httpParamSerializerJQLike(myData),
10088    *     headers: {
10089    *       'Content-Type': 'application/x-www-form-urlencoded'
10090    *     }
10091    *   });
10092    *
10093    * });
10094    * ```
10095    *
10096    * */
10097   this.$get = function() {
10098     return function jQueryLikeParamSerializer(params) {
10099       if (!params) return '';
10100       var parts = [];
10101       serialize(params, '', true);
10102       return parts.join('&');
10103
10104       function serialize(toSerialize, prefix, topLevel) {
10105         if (toSerialize === null || isUndefined(toSerialize)) return;
10106         if (isArray(toSerialize)) {
10107           forEach(toSerialize, function(value, index) {
10108             serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
10109           });
10110         } else if (isObject(toSerialize) && !isDate(toSerialize)) {
10111           forEachSorted(toSerialize, function(value, key) {
10112             serialize(value, prefix +
10113                 (topLevel ? '' : '[') +
10114                 key +
10115                 (topLevel ? '' : ']'));
10116           });
10117         } else {
10118           parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
10119         }
10120       }
10121     };
10122   };
10123 }
10124
10125 function defaultHttpResponseTransform(data, headers) {
10126   if (isString(data)) {
10127     // Strip json vulnerability protection prefix and trim whitespace
10128     var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
10129
10130     if (tempData) {
10131       var contentType = headers('Content-Type');
10132       if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
10133         data = fromJson(tempData);
10134       }
10135     }
10136   }
10137
10138   return data;
10139 }
10140
10141 function isJsonLike(str) {
10142     var jsonStart = str.match(JSON_START);
10143     return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
10144 }
10145
10146 /**
10147  * Parse headers into key value object
10148  *
10149  * @param {string} headers Raw headers as a string
10150  * @returns {Object} Parsed headers as key value object
10151  */
10152 function parseHeaders(headers) {
10153   var parsed = createMap(), i;
10154
10155   function fillInParsed(key, val) {
10156     if (key) {
10157       parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
10158     }
10159   }
10160
10161   if (isString(headers)) {
10162     forEach(headers.split('\n'), function(line) {
10163       i = line.indexOf(':');
10164       fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
10165     });
10166   } else if (isObject(headers)) {
10167     forEach(headers, function(headerVal, headerKey) {
10168       fillInParsed(lowercase(headerKey), trim(headerVal));
10169     });
10170   }
10171
10172   return parsed;
10173 }
10174
10175
10176 /**
10177  * Returns a function that provides access to parsed headers.
10178  *
10179  * Headers are lazy parsed when first requested.
10180  * @see parseHeaders
10181  *
10182  * @param {(string|Object)} headers Headers to provide access to.
10183  * @returns {function(string=)} Returns a getter function which if called with:
10184  *
10185  *   - if called with single an argument returns a single header value or null
10186  *   - if called with no arguments returns an object containing all headers.
10187  */
10188 function headersGetter(headers) {
10189   var headersObj;
10190
10191   return function(name) {
10192     if (!headersObj) headersObj =  parseHeaders(headers);
10193
10194     if (name) {
10195       var value = headersObj[lowercase(name)];
10196       if (value === void 0) {
10197         value = null;
10198       }
10199       return value;
10200     }
10201
10202     return headersObj;
10203   };
10204 }
10205
10206
10207 /**
10208  * Chain all given functions
10209  *
10210  * This function is used for both request and response transforming
10211  *
10212  * @param {*} data Data to transform.
10213  * @param {function(string=)} headers HTTP headers getter fn.
10214  * @param {number} status HTTP status code of the response.
10215  * @param {(Function|Array.<Function>)} fns Function or an array of functions.
10216  * @returns {*} Transformed data.
10217  */
10218 function transformData(data, headers, status, fns) {
10219   if (isFunction(fns)) {
10220     return fns(data, headers, status);
10221   }
10222
10223   forEach(fns, function(fn) {
10224     data = fn(data, headers, status);
10225   });
10226
10227   return data;
10228 }
10229
10230
10231 function isSuccess(status) {
10232   return 200 <= status && status < 300;
10233 }
10234
10235
10236 /**
10237  * @ngdoc provider
10238  * @name $httpProvider
10239  * @description
10240  * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
10241  * */
10242 function $HttpProvider() {
10243   /**
10244    * @ngdoc property
10245    * @name $httpProvider#defaults
10246    * @description
10247    *
10248    * Object containing default values for all {@link ng.$http $http} requests.
10249    *
10250    * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
10251    * that will provide the cache for all requests who set their `cache` property to `true`.
10252    * If you set the `defaults.cache = false` then only requests that specify their own custom
10253    * cache object will be cached. See {@link $http#caching $http Caching} for more information.
10254    *
10255    * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
10256    * Defaults value is `'XSRF-TOKEN'`.
10257    *
10258    * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
10259    * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
10260    *
10261    * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
10262    * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
10263    * setting default headers.
10264    *     - **`defaults.headers.common`**
10265    *     - **`defaults.headers.post`**
10266    *     - **`defaults.headers.put`**
10267    *     - **`defaults.headers.patch`**
10268    *
10269    *
10270    * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
10271    *  used to the prepare string representation of request parameters (specified as an object).
10272    *  If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
10273    *  Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
10274    *
10275    **/
10276   var defaults = this.defaults = {
10277     // transform incoming response data
10278     transformResponse: [defaultHttpResponseTransform],
10279
10280     // transform outgoing request data
10281     transformRequest: [function(d) {
10282       return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
10283     }],
10284
10285     // default headers
10286     headers: {
10287       common: {
10288         'Accept': 'application/json, text/plain, */*'
10289       },
10290       post:   shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
10291       put:    shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
10292       patch:  shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
10293     },
10294
10295     xsrfCookieName: 'XSRF-TOKEN',
10296     xsrfHeaderName: 'X-XSRF-TOKEN',
10297
10298     paramSerializer: '$httpParamSerializer'
10299   };
10300
10301   var useApplyAsync = false;
10302   /**
10303    * @ngdoc method
10304    * @name $httpProvider#useApplyAsync
10305    * @description
10306    *
10307    * Configure $http service to combine processing of multiple http responses received at around
10308    * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
10309    * significant performance improvement for bigger applications that make many HTTP requests
10310    * concurrently (common during application bootstrap).
10311    *
10312    * Defaults to false. If no value is specified, returns the current configured value.
10313    *
10314    * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
10315    *    "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
10316    *    to load and share the same digest cycle.
10317    *
10318    * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
10319    *    otherwise, returns the current configured value.
10320    **/
10321   this.useApplyAsync = function(value) {
10322     if (isDefined(value)) {
10323       useApplyAsync = !!value;
10324       return this;
10325     }
10326     return useApplyAsync;
10327   };
10328
10329   var useLegacyPromise = true;
10330   /**
10331    * @ngdoc method
10332    * @name $httpProvider#useLegacyPromiseExtensions
10333    * @description
10334    *
10335    * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
10336    * This should be used to make sure that applications work without these methods.
10337    *
10338    * Defaults to true. If no value is specified, returns the current configured value.
10339    *
10340    * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
10341    *
10342    * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
10343    *    otherwise, returns the current configured value.
10344    **/
10345   this.useLegacyPromiseExtensions = function(value) {
10346     if (isDefined(value)) {
10347       useLegacyPromise = !!value;
10348       return this;
10349     }
10350     return useLegacyPromise;
10351   };
10352
10353   /**
10354    * @ngdoc property
10355    * @name $httpProvider#interceptors
10356    * @description
10357    *
10358    * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
10359    * pre-processing of request or postprocessing of responses.
10360    *
10361    * These service factories are ordered by request, i.e. they are applied in the same order as the
10362    * array, on request, but reverse order, on response.
10363    *
10364    * {@link ng.$http#interceptors Interceptors detailed info}
10365    **/
10366   var interceptorFactories = this.interceptors = [];
10367
10368   this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
10369       function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
10370
10371     var defaultCache = $cacheFactory('$http');
10372
10373     /**
10374      * Make sure that default param serializer is exposed as a function
10375      */
10376     defaults.paramSerializer = isString(defaults.paramSerializer) ?
10377       $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
10378
10379     /**
10380      * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
10381      * The reversal is needed so that we can build up the interception chain around the
10382      * server request.
10383      */
10384     var reversedInterceptors = [];
10385
10386     forEach(interceptorFactories, function(interceptorFactory) {
10387       reversedInterceptors.unshift(isString(interceptorFactory)
10388           ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
10389     });
10390
10391     /**
10392      * @ngdoc service
10393      * @kind function
10394      * @name $http
10395      * @requires ng.$httpBackend
10396      * @requires $cacheFactory
10397      * @requires $rootScope
10398      * @requires $q
10399      * @requires $injector
10400      *
10401      * @description
10402      * The `$http` service is a core Angular service that facilitates communication with the remote
10403      * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
10404      * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
10405      *
10406      * For unit testing applications that use `$http` service, see
10407      * {@link ngMock.$httpBackend $httpBackend mock}.
10408      *
10409      * For a higher level of abstraction, please check out the {@link ngResource.$resource
10410      * $resource} service.
10411      *
10412      * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
10413      * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
10414      * it is important to familiarize yourself with these APIs and the guarantees they provide.
10415      *
10416      *
10417      * ## General usage
10418      * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
10419      * that is used to generate an HTTP request and returns  a {@link ng.$q promise}.
10420      *
10421      * ```js
10422      *   // Simple GET request example:
10423      *   $http({
10424      *     method: 'GET',
10425      *     url: '/someUrl'
10426      *   }).then(function successCallback(response) {
10427      *       // this callback will be called asynchronously
10428      *       // when the response is available
10429      *     }, function errorCallback(response) {
10430      *       // called asynchronously if an error occurs
10431      *       // or server returns response with an error status.
10432      *     });
10433      * ```
10434      *
10435      * The response object has these properties:
10436      *
10437      *   - **data** – `{string|Object}` – The response body transformed with the transform
10438      *     functions.
10439      *   - **status** – `{number}` – HTTP status code of the response.
10440      *   - **headers** – `{function([headerName])}` – Header getter function.
10441      *   - **config** – `{Object}` – The configuration object that was used to generate the request.
10442      *   - **statusText** – `{string}` – HTTP status text of the response.
10443      *
10444      * A response status code between 200 and 299 is considered a success status and
10445      * will result in the success callback being called. Note that if the response is a redirect,
10446      * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
10447      * called for such responses.
10448      *
10449      *
10450      * ## Shortcut methods
10451      *
10452      * Shortcut methods are also available. All shortcut methods require passing in the URL, and
10453      * request data must be passed in for POST/PUT requests. An optional config can be passed as the
10454      * last argument.
10455      *
10456      * ```js
10457      *   $http.get('/someUrl', config).then(successCallback, errorCallback);
10458      *   $http.post('/someUrl', data, config).then(successCallback, errorCallback);
10459      * ```
10460      *
10461      * Complete list of shortcut methods:
10462      *
10463      * - {@link ng.$http#get $http.get}
10464      * - {@link ng.$http#head $http.head}
10465      * - {@link ng.$http#post $http.post}
10466      * - {@link ng.$http#put $http.put}
10467      * - {@link ng.$http#delete $http.delete}
10468      * - {@link ng.$http#jsonp $http.jsonp}
10469      * - {@link ng.$http#patch $http.patch}
10470      *
10471      *
10472      * ## Writing Unit Tests that use $http
10473      * When unit testing (using {@link ngMock ngMock}), it is necessary to call
10474      * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
10475      * request using trained responses.
10476      *
10477      * ```
10478      * $httpBackend.expectGET(...);
10479      * $http.get(...);
10480      * $httpBackend.flush();
10481      * ```
10482      *
10483      * ## Deprecation Notice
10484      * <div class="alert alert-danger">
10485      *   The `$http` legacy promise methods `success` and `error` have been deprecated.
10486      *   Use the standard `then` method instead.
10487      *   If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
10488      *   `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
10489      * </div>
10490      *
10491      * ## Setting HTTP Headers
10492      *
10493      * The $http service will automatically add certain HTTP headers to all requests. These defaults
10494      * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
10495      * object, which currently contains this default configuration:
10496      *
10497      * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
10498      *   - `Accept: application/json, text/plain, * / *`
10499      * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
10500      *   - `Content-Type: application/json`
10501      * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
10502      *   - `Content-Type: application/json`
10503      *
10504      * To add or overwrite these defaults, simply add or remove a property from these configuration
10505      * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
10506      * with the lowercased HTTP method name as the key, e.g.
10507      * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
10508      *
10509      * The defaults can also be set at runtime via the `$http.defaults` object in the same
10510      * fashion. For example:
10511      *
10512      * ```
10513      * module.run(function($http) {
10514      *   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
10515      * });
10516      * ```
10517      *
10518      * In addition, you can supply a `headers` property in the config object passed when
10519      * calling `$http(config)`, which overrides the defaults without changing them globally.
10520      *
10521      * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
10522      * Use the `headers` property, setting the desired header to `undefined`. For example:
10523      *
10524      * ```js
10525      * var req = {
10526      *  method: 'POST',
10527      *  url: 'http://example.com',
10528      *  headers: {
10529      *    'Content-Type': undefined
10530      *  },
10531      *  data: { test: 'test' }
10532      * }
10533      *
10534      * $http(req).then(function(){...}, function(){...});
10535      * ```
10536      *
10537      * ## Transforming Requests and Responses
10538      *
10539      * Both requests and responses can be transformed using transformation functions: `transformRequest`
10540      * and `transformResponse`. These properties can be a single function that returns
10541      * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
10542      * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
10543      *
10544      * ### Default Transformations
10545      *
10546      * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
10547      * `defaults.transformResponse` properties. If a request does not provide its own transformations
10548      * then these will be applied.
10549      *
10550      * You can augment or replace the default transformations by modifying these properties by adding to or
10551      * replacing the array.
10552      *
10553      * Angular provides the following default transformations:
10554      *
10555      * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
10556      *
10557      * - If the `data` property of the request configuration object contains an object, serialize it
10558      *   into JSON format.
10559      *
10560      * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
10561      *
10562      *  - If XSRF prefix is detected, strip it (see Security Considerations section below).
10563      *  - If JSON response is detected, deserialize it using a JSON parser.
10564      *
10565      *
10566      * ### Overriding the Default Transformations Per Request
10567      *
10568      * If you wish override the request/response transformations only for a single request then provide
10569      * `transformRequest` and/or `transformResponse` properties on the configuration object passed
10570      * into `$http`.
10571      *
10572      * Note that if you provide these properties on the config object the default transformations will be
10573      * overwritten. If you wish to augment the default transformations then you must include them in your
10574      * local transformation array.
10575      *
10576      * The following code demonstrates adding a new response transformation to be run after the default response
10577      * transformations have been run.
10578      *
10579      * ```js
10580      * function appendTransform(defaults, transform) {
10581      *
10582      *   // We can't guarantee that the default transformation is an array
10583      *   defaults = angular.isArray(defaults) ? defaults : [defaults];
10584      *
10585      *   // Append the new transformation to the defaults
10586      *   return defaults.concat(transform);
10587      * }
10588      *
10589      * $http({
10590      *   url: '...',
10591      *   method: 'GET',
10592      *   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
10593      *     return doTransform(value);
10594      *   })
10595      * });
10596      * ```
10597      *
10598      *
10599      * ## Caching
10600      *
10601      * To enable caching, set the request configuration `cache` property to `true` (to use default
10602      * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
10603      * When the cache is enabled, `$http` stores the response from the server in the specified
10604      * cache. The next time the same request is made, the response is served from the cache without
10605      * sending a request to the server.
10606      *
10607      * Note that even if the response is served from cache, delivery of the data is asynchronous in
10608      * the same way that real requests are.
10609      *
10610      * If there are multiple GET requests for the same URL that should be cached using the same
10611      * cache, but the cache is not populated yet, only one request to the server will be made and
10612      * the remaining requests will be fulfilled using the response from the first request.
10613      *
10614      * You can change the default cache to a new object (built with
10615      * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
10616      * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
10617      * their `cache` property to `true` will now use this cache object.
10618      *
10619      * If you set the default cache to `false` then only requests that specify their own custom
10620      * cache object will be cached.
10621      *
10622      * ## Interceptors
10623      *
10624      * Before you start creating interceptors, be sure to understand the
10625      * {@link ng.$q $q and deferred/promise APIs}.
10626      *
10627      * For purposes of global error handling, authentication, or any kind of synchronous or
10628      * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
10629      * able to intercept requests before they are handed to the server and
10630      * responses before they are handed over to the application code that
10631      * initiated these requests. The interceptors leverage the {@link ng.$q
10632      * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
10633      *
10634      * The interceptors are service factories that are registered with the `$httpProvider` by
10635      * adding them to the `$httpProvider.interceptors` array. The factory is called and
10636      * injected with dependencies (if specified) and returns the interceptor.
10637      *
10638      * There are two kinds of interceptors (and two kinds of rejection interceptors):
10639      *
10640      *   * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
10641      *     modify the `config` object or create a new one. The function needs to return the `config`
10642      *     object directly, or a promise containing the `config` or a new `config` object.
10643      *   * `requestError`: interceptor gets called when a previous interceptor threw an error or
10644      *     resolved with a rejection.
10645      *   * `response`: interceptors get called with http `response` object. The function is free to
10646      *     modify the `response` object or create a new one. The function needs to return the `response`
10647      *     object directly, or as a promise containing the `response` or a new `response` object.
10648      *   * `responseError`: interceptor gets called when a previous interceptor threw an error or
10649      *     resolved with a rejection.
10650      *
10651      *
10652      * ```js
10653      *   // register the interceptor as a service
10654      *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
10655      *     return {
10656      *       // optional method
10657      *       'request': function(config) {
10658      *         // do something on success
10659      *         return config;
10660      *       },
10661      *
10662      *       // optional method
10663      *      'requestError': function(rejection) {
10664      *         // do something on error
10665      *         if (canRecover(rejection)) {
10666      *           return responseOrNewPromise
10667      *         }
10668      *         return $q.reject(rejection);
10669      *       },
10670      *
10671      *
10672      *
10673      *       // optional method
10674      *       'response': function(response) {
10675      *         // do something on success
10676      *         return response;
10677      *       },
10678      *
10679      *       // optional method
10680      *      'responseError': function(rejection) {
10681      *         // do something on error
10682      *         if (canRecover(rejection)) {
10683      *           return responseOrNewPromise
10684      *         }
10685      *         return $q.reject(rejection);
10686      *       }
10687      *     };
10688      *   });
10689      *
10690      *   $httpProvider.interceptors.push('myHttpInterceptor');
10691      *
10692      *
10693      *   // alternatively, register the interceptor via an anonymous factory
10694      *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
10695      *     return {
10696      *      'request': function(config) {
10697      *          // same as above
10698      *       },
10699      *
10700      *       'response': function(response) {
10701      *          // same as above
10702      *       }
10703      *     };
10704      *   });
10705      * ```
10706      *
10707      * ## Security Considerations
10708      *
10709      * When designing web applications, consider security threats from:
10710      *
10711      * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
10712      * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
10713      *
10714      * Both server and the client must cooperate in order to eliminate these threats. Angular comes
10715      * pre-configured with strategies that address these issues, but for this to work backend server
10716      * cooperation is required.
10717      *
10718      * ### JSON Vulnerability Protection
10719      *
10720      * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
10721      * allows third party website to turn your JSON resource URL into
10722      * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
10723      * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
10724      * Angular will automatically strip the prefix before processing it as JSON.
10725      *
10726      * For example if your server needs to return:
10727      * ```js
10728      * ['one','two']
10729      * ```
10730      *
10731      * which is vulnerable to attack, your server can return:
10732      * ```js
10733      * )]}',
10734      * ['one','two']
10735      * ```
10736      *
10737      * Angular will strip the prefix, before processing the JSON.
10738      *
10739      *
10740      * ### Cross Site Request Forgery (XSRF) Protection
10741      *
10742      * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
10743      * which the attacker can trick an authenticated user into unknowingly executing actions on your
10744      * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
10745      * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
10746      * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
10747      * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
10748      * The header will not be set for cross-domain requests.
10749      *
10750      * To take advantage of this, your server needs to set a token in a JavaScript readable session
10751      * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
10752      * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
10753      * that only JavaScript running on your domain could have sent the request. The token must be
10754      * unique for each user and must be verifiable by the server (to prevent the JavaScript from
10755      * making up its own tokens). We recommend that the token is a digest of your site's
10756      * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
10757      * for added security.
10758      *
10759      * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
10760      * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
10761      * or the per-request config object.
10762      *
10763      * In order to prevent collisions in environments where multiple Angular apps share the
10764      * same domain or subdomain, we recommend that each application uses unique cookie name.
10765      *
10766      * @param {object} config Object describing the request to be made and how it should be
10767      *    processed. The object has following properties:
10768      *
10769      *    - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
10770      *    - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
10771      *    - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
10772      *      with the `paramSerializer` and appended as GET parameters.
10773      *    - **data** – `{string|Object}` – Data to be sent as the request message data.
10774      *    - **headers** – `{Object}` – Map of strings or functions which return strings representing
10775      *      HTTP headers to send to the server. If the return value of a function is null, the
10776      *      header will not be sent. Functions accept a config object as an argument.
10777      *    - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
10778      *    - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
10779      *    - **transformRequest** –
10780      *      `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
10781      *      transform function or an array of such functions. The transform function takes the http
10782      *      request body and headers and returns its transformed (typically serialized) version.
10783      *      See {@link ng.$http#overriding-the-default-transformations-per-request
10784      *      Overriding the Default Transformations}
10785      *    - **transformResponse** –
10786      *      `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
10787      *      transform function or an array of such functions. The transform function takes the http
10788      *      response body, headers and status and returns its transformed (typically deserialized) version.
10789      *      See {@link ng.$http#overriding-the-default-transformations-per-request
10790      *      Overriding the Default TransformationjqLiks}
10791      *    - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
10792      *      prepare the string representation of request parameters (specified as an object).
10793      *      If specified as string, it is interpreted as function registered with the
10794      *      {@link $injector $injector}, which means you can create your own serializer
10795      *      by registering it as a {@link auto.$provide#service service}.
10796      *      The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
10797      *      alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
10798      *    - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
10799      *      GET request, otherwise if a cache instance built with
10800      *      {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
10801      *      caching.
10802      *    - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
10803      *      that should abort the request when resolved.
10804      *    - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
10805      *      XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
10806      *      for more information.
10807      *    - **responseType** - `{string}` - see
10808      *      [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
10809      *
10810      * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
10811      *                        when the request succeeds or fails.
10812      *
10813      *
10814      * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
10815      *   requests. This is primarily meant to be used for debugging purposes.
10816      *
10817      *
10818      * @example
10819 <example module="httpExample">
10820 <file name="index.html">
10821   <div ng-controller="FetchController">
10822     <select ng-model="method" aria-label="Request method">
10823       <option>GET</option>
10824       <option>JSONP</option>
10825     </select>
10826     <input type="text" ng-model="url" size="80" aria-label="URL" />
10827     <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
10828     <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
10829     <button id="samplejsonpbtn"
10830       ng-click="updateModel('JSONP',
10831                     'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
10832       Sample JSONP
10833     </button>
10834     <button id="invalidjsonpbtn"
10835       ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
10836         Invalid JSONP
10837       </button>
10838     <pre>http status code: {{status}}</pre>
10839     <pre>http response data: {{data}}</pre>
10840   </div>
10841 </file>
10842 <file name="script.js">
10843   angular.module('httpExample', [])
10844     .controller('FetchController', ['$scope', '$http', '$templateCache',
10845       function($scope, $http, $templateCache) {
10846         $scope.method = 'GET';
10847         $scope.url = 'http-hello.html';
10848
10849         $scope.fetch = function() {
10850           $scope.code = null;
10851           $scope.response = null;
10852
10853           $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
10854             then(function(response) {
10855               $scope.status = response.status;
10856               $scope.data = response.data;
10857             }, function(response) {
10858               $scope.data = response.data || "Request failed";
10859               $scope.status = response.status;
10860           });
10861         };
10862
10863         $scope.updateModel = function(method, url) {
10864           $scope.method = method;
10865           $scope.url = url;
10866         };
10867       }]);
10868 </file>
10869 <file name="http-hello.html">
10870   Hello, $http!
10871 </file>
10872 <file name="protractor.js" type="protractor">
10873   var status = element(by.binding('status'));
10874   var data = element(by.binding('data'));
10875   var fetchBtn = element(by.id('fetchbtn'));
10876   var sampleGetBtn = element(by.id('samplegetbtn'));
10877   var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
10878   var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
10879
10880   it('should make an xhr GET request', function() {
10881     sampleGetBtn.click();
10882     fetchBtn.click();
10883     expect(status.getText()).toMatch('200');
10884     expect(data.getText()).toMatch(/Hello, \$http!/);
10885   });
10886
10887 // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
10888 // it('should make a JSONP request to angularjs.org', function() {
10889 //   sampleJsonpBtn.click();
10890 //   fetchBtn.click();
10891 //   expect(status.getText()).toMatch('200');
10892 //   expect(data.getText()).toMatch(/Super Hero!/);
10893 // });
10894
10895   it('should make JSONP request to invalid URL and invoke the error handler',
10896       function() {
10897     invalidJsonpBtn.click();
10898     fetchBtn.click();
10899     expect(status.getText()).toMatch('0');
10900     expect(data.getText()).toMatch('Request failed');
10901   });
10902 </file>
10903 </example>
10904      */
10905     function $http(requestConfig) {
10906
10907       if (!isObject(requestConfig)) {
10908         throw minErr('$http')('badreq', 'Http request configuration must be an object.  Received: {0}', requestConfig);
10909       }
10910
10911       if (!isString(requestConfig.url)) {
10912         throw minErr('$http')('badreq', 'Http request configuration url must be a string.  Received: {0}', requestConfig.url);
10913       }
10914
10915       var config = extend({
10916         method: 'get',
10917         transformRequest: defaults.transformRequest,
10918         transformResponse: defaults.transformResponse,
10919         paramSerializer: defaults.paramSerializer
10920       }, requestConfig);
10921
10922       config.headers = mergeHeaders(requestConfig);
10923       config.method = uppercase(config.method);
10924       config.paramSerializer = isString(config.paramSerializer) ?
10925         $injector.get(config.paramSerializer) : config.paramSerializer;
10926
10927       var serverRequest = function(config) {
10928         var headers = config.headers;
10929         var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
10930
10931         // strip content-type if data is undefined
10932         if (isUndefined(reqData)) {
10933           forEach(headers, function(value, header) {
10934             if (lowercase(header) === 'content-type') {
10935                 delete headers[header];
10936             }
10937           });
10938         }
10939
10940         if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
10941           config.withCredentials = defaults.withCredentials;
10942         }
10943
10944         // send request
10945         return sendReq(config, reqData).then(transformResponse, transformResponse);
10946       };
10947
10948       var chain = [serverRequest, undefined];
10949       var promise = $q.when(config);
10950
10951       // apply interceptors
10952       forEach(reversedInterceptors, function(interceptor) {
10953         if (interceptor.request || interceptor.requestError) {
10954           chain.unshift(interceptor.request, interceptor.requestError);
10955         }
10956         if (interceptor.response || interceptor.responseError) {
10957           chain.push(interceptor.response, interceptor.responseError);
10958         }
10959       });
10960
10961       while (chain.length) {
10962         var thenFn = chain.shift();
10963         var rejectFn = chain.shift();
10964
10965         promise = promise.then(thenFn, rejectFn);
10966       }
10967
10968       if (useLegacyPromise) {
10969         promise.success = function(fn) {
10970           assertArgFn(fn, 'fn');
10971
10972           promise.then(function(response) {
10973             fn(response.data, response.status, response.headers, config);
10974           });
10975           return promise;
10976         };
10977
10978         promise.error = function(fn) {
10979           assertArgFn(fn, 'fn');
10980
10981           promise.then(null, function(response) {
10982             fn(response.data, response.status, response.headers, config);
10983           });
10984           return promise;
10985         };
10986       } else {
10987         promise.success = $httpMinErrLegacyFn('success');
10988         promise.error = $httpMinErrLegacyFn('error');
10989       }
10990
10991       return promise;
10992
10993       function transformResponse(response) {
10994         // make a copy since the response must be cacheable
10995         var resp = extend({}, response);
10996         resp.data = transformData(response.data, response.headers, response.status,
10997                                   config.transformResponse);
10998         return (isSuccess(response.status))
10999           ? resp
11000           : $q.reject(resp);
11001       }
11002
11003       function executeHeaderFns(headers, config) {
11004         var headerContent, processedHeaders = {};
11005
11006         forEach(headers, function(headerFn, header) {
11007           if (isFunction(headerFn)) {
11008             headerContent = headerFn(config);
11009             if (headerContent != null) {
11010               processedHeaders[header] = headerContent;
11011             }
11012           } else {
11013             processedHeaders[header] = headerFn;
11014           }
11015         });
11016
11017         return processedHeaders;
11018       }
11019
11020       function mergeHeaders(config) {
11021         var defHeaders = defaults.headers,
11022             reqHeaders = extend({}, config.headers),
11023             defHeaderName, lowercaseDefHeaderName, reqHeaderName;
11024
11025         defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
11026
11027         // using for-in instead of forEach to avoid unnecessary iteration after header has been found
11028         defaultHeadersIteration:
11029         for (defHeaderName in defHeaders) {
11030           lowercaseDefHeaderName = lowercase(defHeaderName);
11031
11032           for (reqHeaderName in reqHeaders) {
11033             if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
11034               continue defaultHeadersIteration;
11035             }
11036           }
11037
11038           reqHeaders[defHeaderName] = defHeaders[defHeaderName];
11039         }
11040
11041         // execute if header value is a function for merged headers
11042         return executeHeaderFns(reqHeaders, shallowCopy(config));
11043       }
11044     }
11045
11046     $http.pendingRequests = [];
11047
11048     /**
11049      * @ngdoc method
11050      * @name $http#get
11051      *
11052      * @description
11053      * Shortcut method to perform `GET` request.
11054      *
11055      * @param {string} url Relative or absolute URL specifying the destination of the request
11056      * @param {Object=} config Optional configuration object
11057      * @returns {HttpPromise} Future object
11058      */
11059
11060     /**
11061      * @ngdoc method
11062      * @name $http#delete
11063      *
11064      * @description
11065      * Shortcut method to perform `DELETE` request.
11066      *
11067      * @param {string} url Relative or absolute URL specifying the destination of the request
11068      * @param {Object=} config Optional configuration object
11069      * @returns {HttpPromise} Future object
11070      */
11071
11072     /**
11073      * @ngdoc method
11074      * @name $http#head
11075      *
11076      * @description
11077      * Shortcut method to perform `HEAD` request.
11078      *
11079      * @param {string} url Relative or absolute URL specifying the destination of the request
11080      * @param {Object=} config Optional configuration object
11081      * @returns {HttpPromise} Future object
11082      */
11083
11084     /**
11085      * @ngdoc method
11086      * @name $http#jsonp
11087      *
11088      * @description
11089      * Shortcut method to perform `JSONP` request.
11090      *
11091      * @param {string} url Relative or absolute URL specifying the destination of the request.
11092      *                     The name of the callback should be the string `JSON_CALLBACK`.
11093      * @param {Object=} config Optional configuration object
11094      * @returns {HttpPromise} Future object
11095      */
11096     createShortMethods('get', 'delete', 'head', 'jsonp');
11097
11098     /**
11099      * @ngdoc method
11100      * @name $http#post
11101      *
11102      * @description
11103      * Shortcut method to perform `POST` request.
11104      *
11105      * @param {string} url Relative or absolute URL specifying the destination of the request
11106      * @param {*} data Request content
11107      * @param {Object=} config Optional configuration object
11108      * @returns {HttpPromise} Future object
11109      */
11110
11111     /**
11112      * @ngdoc method
11113      * @name $http#put
11114      *
11115      * @description
11116      * Shortcut method to perform `PUT` request.
11117      *
11118      * @param {string} url Relative or absolute URL specifying the destination of the request
11119      * @param {*} data Request content
11120      * @param {Object=} config Optional configuration object
11121      * @returns {HttpPromise} Future object
11122      */
11123
11124      /**
11125       * @ngdoc method
11126       * @name $http#patch
11127       *
11128       * @description
11129       * Shortcut method to perform `PATCH` request.
11130       *
11131       * @param {string} url Relative or absolute URL specifying the destination of the request
11132       * @param {*} data Request content
11133       * @param {Object=} config Optional configuration object
11134       * @returns {HttpPromise} Future object
11135       */
11136     createShortMethodsWithData('post', 'put', 'patch');
11137
11138         /**
11139          * @ngdoc property
11140          * @name $http#defaults
11141          *
11142          * @description
11143          * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
11144          * default headers, withCredentials as well as request and response transformations.
11145          *
11146          * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
11147          */
11148     $http.defaults = defaults;
11149
11150
11151     return $http;
11152
11153
11154     function createShortMethods(names) {
11155       forEach(arguments, function(name) {
11156         $http[name] = function(url, config) {
11157           return $http(extend({}, config || {}, {
11158             method: name,
11159             url: url
11160           }));
11161         };
11162       });
11163     }
11164
11165
11166     function createShortMethodsWithData(name) {
11167       forEach(arguments, function(name) {
11168         $http[name] = function(url, data, config) {
11169           return $http(extend({}, config || {}, {
11170             method: name,
11171             url: url,
11172             data: data
11173           }));
11174         };
11175       });
11176     }
11177
11178
11179     /**
11180      * Makes the request.
11181      *
11182      * !!! ACCESSES CLOSURE VARS:
11183      * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
11184      */
11185     function sendReq(config, reqData) {
11186       var deferred = $q.defer(),
11187           promise = deferred.promise,
11188           cache,
11189           cachedResp,
11190           reqHeaders = config.headers,
11191           url = buildUrl(config.url, config.paramSerializer(config.params));
11192
11193       $http.pendingRequests.push(config);
11194       promise.then(removePendingReq, removePendingReq);
11195
11196
11197       if ((config.cache || defaults.cache) && config.cache !== false &&
11198           (config.method === 'GET' || config.method === 'JSONP')) {
11199         cache = isObject(config.cache) ? config.cache
11200               : isObject(defaults.cache) ? defaults.cache
11201               : defaultCache;
11202       }
11203
11204       if (cache) {
11205         cachedResp = cache.get(url);
11206         if (isDefined(cachedResp)) {
11207           if (isPromiseLike(cachedResp)) {
11208             // cached request has already been sent, but there is no response yet
11209             cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
11210           } else {
11211             // serving from cache
11212             if (isArray(cachedResp)) {
11213               resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
11214             } else {
11215               resolvePromise(cachedResp, 200, {}, 'OK');
11216             }
11217           }
11218         } else {
11219           // put the promise for the non-transformed response into cache as a placeholder
11220           cache.put(url, promise);
11221         }
11222       }
11223
11224
11225       // if we won't have the response in cache, set the xsrf headers and
11226       // send the request to the backend
11227       if (isUndefined(cachedResp)) {
11228         var xsrfValue = urlIsSameOrigin(config.url)
11229             ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
11230             : undefined;
11231         if (xsrfValue) {
11232           reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
11233         }
11234
11235         $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
11236             config.withCredentials, config.responseType);
11237       }
11238
11239       return promise;
11240
11241
11242       /**
11243        * Callback registered to $httpBackend():
11244        *  - caches the response if desired
11245        *  - resolves the raw $http promise
11246        *  - calls $apply
11247        */
11248       function done(status, response, headersString, statusText) {
11249         if (cache) {
11250           if (isSuccess(status)) {
11251             cache.put(url, [status, response, parseHeaders(headersString), statusText]);
11252           } else {
11253             // remove promise from the cache
11254             cache.remove(url);
11255           }
11256         }
11257
11258         function resolveHttpPromise() {
11259           resolvePromise(response, status, headersString, statusText);
11260         }
11261
11262         if (useApplyAsync) {
11263           $rootScope.$applyAsync(resolveHttpPromise);
11264         } else {
11265           resolveHttpPromise();
11266           if (!$rootScope.$$phase) $rootScope.$apply();
11267         }
11268       }
11269
11270
11271       /**
11272        * Resolves the raw $http promise.
11273        */
11274       function resolvePromise(response, status, headers, statusText) {
11275         //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
11276         status = status >= -1 ? status : 0;
11277
11278         (isSuccess(status) ? deferred.resolve : deferred.reject)({
11279           data: response,
11280           status: status,
11281           headers: headersGetter(headers),
11282           config: config,
11283           statusText: statusText
11284         });
11285       }
11286
11287       function resolvePromiseWithResult(result) {
11288         resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
11289       }
11290
11291       function removePendingReq() {
11292         var idx = $http.pendingRequests.indexOf(config);
11293         if (idx !== -1) $http.pendingRequests.splice(idx, 1);
11294       }
11295     }
11296
11297
11298     function buildUrl(url, serializedParams) {
11299       if (serializedParams.length > 0) {
11300         url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
11301       }
11302       return url;
11303     }
11304   }];
11305 }
11306
11307 /**
11308  * @ngdoc service
11309  * @name $xhrFactory
11310  *
11311  * @description
11312  * Factory function used to create XMLHttpRequest objects.
11313  *
11314  * Replace or decorate this service to create your own custom XMLHttpRequest objects.
11315  *
11316  * ```
11317  * angular.module('myApp', [])
11318  * .factory('$xhrFactory', function() {
11319  *   return function createXhr(method, url) {
11320  *     return new window.XMLHttpRequest({mozSystem: true});
11321  *   };
11322  * });
11323  * ```
11324  *
11325  * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
11326  * @param {string} url URL of the request.
11327  */
11328 function $xhrFactoryProvider() {
11329   this.$get = function() {
11330     return function createXhr() {
11331       return new window.XMLHttpRequest();
11332     };
11333   };
11334 }
11335
11336 /**
11337  * @ngdoc service
11338  * @name $httpBackend
11339  * @requires $window
11340  * @requires $document
11341  * @requires $xhrFactory
11342  *
11343  * @description
11344  * HTTP backend used by the {@link ng.$http service} that delegates to
11345  * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
11346  *
11347  * You should never need to use this service directly, instead use the higher-level abstractions:
11348  * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
11349  *
11350  * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
11351  * $httpBackend} which can be trained with responses.
11352  */
11353 function $HttpBackendProvider() {
11354   this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
11355     return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
11356   }];
11357 }
11358
11359 function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
11360   // TODO(vojta): fix the signature
11361   return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
11362     $browser.$$incOutstandingRequestCount();
11363     url = url || $browser.url();
11364
11365     if (lowercase(method) == 'jsonp') {
11366       var callbackId = '_' + (callbacks.counter++).toString(36);
11367       callbacks[callbackId] = function(data) {
11368         callbacks[callbackId].data = data;
11369         callbacks[callbackId].called = true;
11370       };
11371
11372       var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
11373           callbackId, function(status, text) {
11374         completeRequest(callback, status, callbacks[callbackId].data, "", text);
11375         callbacks[callbackId] = noop;
11376       });
11377     } else {
11378
11379       var xhr = createXhr(method, url);
11380
11381       xhr.open(method, url, true);
11382       forEach(headers, function(value, key) {
11383         if (isDefined(value)) {
11384             xhr.setRequestHeader(key, value);
11385         }
11386       });
11387
11388       xhr.onload = function requestLoaded() {
11389         var statusText = xhr.statusText || '';
11390
11391         // responseText is the old-school way of retrieving response (supported by IE9)
11392         // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
11393         var response = ('response' in xhr) ? xhr.response : xhr.responseText;
11394
11395         // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
11396         var status = xhr.status === 1223 ? 204 : xhr.status;
11397
11398         // fix status code when it is 0 (0 status is undocumented).
11399         // Occurs when accessing file resources or on Android 4.1 stock browser
11400         // while retrieving files from application cache.
11401         if (status === 0) {
11402           status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
11403         }
11404
11405         completeRequest(callback,
11406             status,
11407             response,
11408             xhr.getAllResponseHeaders(),
11409             statusText);
11410       };
11411
11412       var requestError = function() {
11413         // The response is always empty
11414         // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
11415         completeRequest(callback, -1, null, null, '');
11416       };
11417
11418       xhr.onerror = requestError;
11419       xhr.onabort = requestError;
11420
11421       if (withCredentials) {
11422         xhr.withCredentials = true;
11423       }
11424
11425       if (responseType) {
11426         try {
11427           xhr.responseType = responseType;
11428         } catch (e) {
11429           // WebKit added support for the json responseType value on 09/03/2013
11430           // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
11431           // known to throw when setting the value "json" as the response type. Other older
11432           // browsers implementing the responseType
11433           //
11434           // The json response type can be ignored if not supported, because JSON payloads are
11435           // parsed on the client-side regardless.
11436           if (responseType !== 'json') {
11437             throw e;
11438           }
11439         }
11440       }
11441
11442       xhr.send(isUndefined(post) ? null : post);
11443     }
11444
11445     if (timeout > 0) {
11446       var timeoutId = $browserDefer(timeoutRequest, timeout);
11447     } else if (isPromiseLike(timeout)) {
11448       timeout.then(timeoutRequest);
11449     }
11450
11451
11452     function timeoutRequest() {
11453       jsonpDone && jsonpDone();
11454       xhr && xhr.abort();
11455     }
11456
11457     function completeRequest(callback, status, response, headersString, statusText) {
11458       // cancel timeout and subsequent timeout promise resolution
11459       if (isDefined(timeoutId)) {
11460         $browserDefer.cancel(timeoutId);
11461       }
11462       jsonpDone = xhr = null;
11463
11464       callback(status, response, headersString, statusText);
11465       $browser.$$completeOutstandingRequest(noop);
11466     }
11467   };
11468
11469   function jsonpReq(url, callbackId, done) {
11470     // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
11471     // - fetches local scripts via XHR and evals them
11472     // - adds and immediately removes script elements from the document
11473     var script = rawDocument.createElement('script'), callback = null;
11474     script.type = "text/javascript";
11475     script.src = url;
11476     script.async = true;
11477
11478     callback = function(event) {
11479       removeEventListenerFn(script, "load", callback);
11480       removeEventListenerFn(script, "error", callback);
11481       rawDocument.body.removeChild(script);
11482       script = null;
11483       var status = -1;
11484       var text = "unknown";
11485
11486       if (event) {
11487         if (event.type === "load" && !callbacks[callbackId].called) {
11488           event = { type: "error" };
11489         }
11490         text = event.type;
11491         status = event.type === "error" ? 404 : 200;
11492       }
11493
11494       if (done) {
11495         done(status, text);
11496       }
11497     };
11498
11499     addEventListenerFn(script, "load", callback);
11500     addEventListenerFn(script, "error", callback);
11501     rawDocument.body.appendChild(script);
11502     return callback;
11503   }
11504 }
11505
11506 var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
11507 $interpolateMinErr.throwNoconcat = function(text) {
11508   throw $interpolateMinErr('noconcat',
11509       "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
11510       "interpolations that concatenate multiple expressions when a trusted value is " +
11511       "required.  See http://docs.angularjs.org/api/ng.$sce", text);
11512 };
11513
11514 $interpolateMinErr.interr = function(text, err) {
11515   return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
11516 };
11517
11518 /**
11519  * @ngdoc provider
11520  * @name $interpolateProvider
11521  *
11522  * @description
11523  *
11524  * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
11525  *
11526  * <div class="alert alert-danger">
11527  * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
11528  * template within a Python Jinja template (or any other template language). Mixing templating
11529  * languages is **very dangerous**. The embedding template language will not safely escape Angular
11530  * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
11531  * security bugs!
11532  * </div>
11533  *
11534  * @example
11535 <example name="custom-interpolation-markup" module="customInterpolationApp">
11536 <file name="index.html">
11537 <script>
11538   var customInterpolationApp = angular.module('customInterpolationApp', []);
11539
11540   customInterpolationApp.config(function($interpolateProvider) {
11541     $interpolateProvider.startSymbol('//');
11542     $interpolateProvider.endSymbol('//');
11543   });
11544
11545
11546   customInterpolationApp.controller('DemoController', function() {
11547       this.label = "This binding is brought you by // interpolation symbols.";
11548   });
11549 </script>
11550 <div ng-controller="DemoController as demo">
11551     //demo.label//
11552 </div>
11553 </file>
11554 <file name="protractor.js" type="protractor">
11555   it('should interpolate binding with custom symbols', function() {
11556     expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
11557   });
11558 </file>
11559 </example>
11560  */
11561 function $InterpolateProvider() {
11562   var startSymbol = '{{';
11563   var endSymbol = '}}';
11564
11565   /**
11566    * @ngdoc method
11567    * @name $interpolateProvider#startSymbol
11568    * @description
11569    * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
11570    *
11571    * @param {string=} value new value to set the starting symbol to.
11572    * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
11573    */
11574   this.startSymbol = function(value) {
11575     if (value) {
11576       startSymbol = value;
11577       return this;
11578     } else {
11579       return startSymbol;
11580     }
11581   };
11582
11583   /**
11584    * @ngdoc method
11585    * @name $interpolateProvider#endSymbol
11586    * @description
11587    * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
11588    *
11589    * @param {string=} value new value to set the ending symbol to.
11590    * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
11591    */
11592   this.endSymbol = function(value) {
11593     if (value) {
11594       endSymbol = value;
11595       return this;
11596     } else {
11597       return endSymbol;
11598     }
11599   };
11600
11601
11602   this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
11603     var startSymbolLength = startSymbol.length,
11604         endSymbolLength = endSymbol.length,
11605         escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
11606         escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
11607
11608     function escape(ch) {
11609       return '\\\\\\' + ch;
11610     }
11611
11612     function unescapeText(text) {
11613       return text.replace(escapedStartRegexp, startSymbol).
11614         replace(escapedEndRegexp, endSymbol);
11615     }
11616
11617     function stringify(value) {
11618       if (value == null) { // null || undefined
11619         return '';
11620       }
11621       switch (typeof value) {
11622         case 'string':
11623           break;
11624         case 'number':
11625           value = '' + value;
11626           break;
11627         default:
11628           value = toJson(value);
11629       }
11630
11631       return value;
11632     }
11633
11634     //TODO: this is the same as the constantWatchDelegate in parse.js
11635     function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
11636       var unwatch;
11637       return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
11638         unwatch();
11639         return constantInterp(scope);
11640       }, listener, objectEquality);
11641     }
11642
11643     /**
11644      * @ngdoc service
11645      * @name $interpolate
11646      * @kind function
11647      *
11648      * @requires $parse
11649      * @requires $sce
11650      *
11651      * @description
11652      *
11653      * Compiles a string with markup into an interpolation function. This service is used by the
11654      * HTML {@link ng.$compile $compile} service for data binding. See
11655      * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
11656      * interpolation markup.
11657      *
11658      *
11659      * ```js
11660      *   var $interpolate = ...; // injected
11661      *   var exp = $interpolate('Hello {{name | uppercase}}!');
11662      *   expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
11663      * ```
11664      *
11665      * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
11666      * `true`, the interpolation function will return `undefined` unless all embedded expressions
11667      * evaluate to a value other than `undefined`.
11668      *
11669      * ```js
11670      *   var $interpolate = ...; // injected
11671      *   var context = {greeting: 'Hello', name: undefined };
11672      *
11673      *   // default "forgiving" mode
11674      *   var exp = $interpolate('{{greeting}} {{name}}!');
11675      *   expect(exp(context)).toEqual('Hello !');
11676      *
11677      *   // "allOrNothing" mode
11678      *   exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
11679      *   expect(exp(context)).toBeUndefined();
11680      *   context.name = 'Angular';
11681      *   expect(exp(context)).toEqual('Hello Angular!');
11682      * ```
11683      *
11684      * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
11685      *
11686      * ####Escaped Interpolation
11687      * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
11688      * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
11689      * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
11690      * or binding.
11691      *
11692      * This enables web-servers to prevent script injection attacks and defacing attacks, to some
11693      * degree, while also enabling code examples to work without relying on the
11694      * {@link ng.directive:ngNonBindable ngNonBindable} directive.
11695      *
11696      * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
11697      * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
11698      * interpolation start/end markers with their escaped counterparts.**
11699      *
11700      * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
11701      * output when the $interpolate service processes the text. So, for HTML elements interpolated
11702      * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
11703      * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
11704      * this is typically useful only when user-data is used in rendering a template from the server, or
11705      * when otherwise untrusted data is used by a directive.
11706      *
11707      * <example>
11708      *  <file name="index.html">
11709      *    <div ng-init="username='A user'">
11710      *      <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
11711      *        </p>
11712      *      <p><strong>{{username}}</strong> attempts to inject code which will deface the
11713      *        application, but fails to accomplish their task, because the server has correctly
11714      *        escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
11715      *        characters.</p>
11716      *      <p>Instead, the result of the attempted script injection is visible, and can be removed
11717      *        from the database by an administrator.</p>
11718      *    </div>
11719      *  </file>
11720      * </example>
11721      *
11722      * @param {string} text The text with markup to interpolate.
11723      * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
11724      *    embedded expression in order to return an interpolation function. Strings with no
11725      *    embedded expression will return null for the interpolation function.
11726      * @param {string=} trustedContext when provided, the returned function passes the interpolated
11727      *    result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
11728      *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that
11729      *    provides Strict Contextual Escaping for details.
11730      * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
11731      *    unless all embedded expressions evaluate to a value other than `undefined`.
11732      * @returns {function(context)} an interpolation function which is used to compute the
11733      *    interpolated string. The function has these parameters:
11734      *
11735      * - `context`: evaluation context for all expressions embedded in the interpolated text
11736      */
11737     function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
11738       // Provide a quick exit and simplified result function for text with no interpolation
11739       if (!text.length || text.indexOf(startSymbol) === -1) {
11740         var constantInterp;
11741         if (!mustHaveExpression) {
11742           var unescapedText = unescapeText(text);
11743           constantInterp = valueFn(unescapedText);
11744           constantInterp.exp = text;
11745           constantInterp.expressions = [];
11746           constantInterp.$$watchDelegate = constantWatchDelegate;
11747         }
11748         return constantInterp;
11749       }
11750
11751       allOrNothing = !!allOrNothing;
11752       var startIndex,
11753           endIndex,
11754           index = 0,
11755           expressions = [],
11756           parseFns = [],
11757           textLength = text.length,
11758           exp,
11759           concat = [],
11760           expressionPositions = [];
11761
11762       while (index < textLength) {
11763         if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
11764              ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
11765           if (index !== startIndex) {
11766             concat.push(unescapeText(text.substring(index, startIndex)));
11767           }
11768           exp = text.substring(startIndex + startSymbolLength, endIndex);
11769           expressions.push(exp);
11770           parseFns.push($parse(exp, parseStringifyInterceptor));
11771           index = endIndex + endSymbolLength;
11772           expressionPositions.push(concat.length);
11773           concat.push('');
11774         } else {
11775           // we did not find an interpolation, so we have to add the remainder to the separators array
11776           if (index !== textLength) {
11777             concat.push(unescapeText(text.substring(index)));
11778           }
11779           break;
11780         }
11781       }
11782
11783       // Concatenating expressions makes it hard to reason about whether some combination of
11784       // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a
11785       // single expression be used for iframe[src], object[src], etc., we ensure that the value
11786       // that's used is assigned or constructed by some JS code somewhere that is more testable or
11787       // make it obvious that you bound the value to some user controlled value.  This helps reduce
11788       // the load when auditing for XSS issues.
11789       if (trustedContext && concat.length > 1) {
11790           $interpolateMinErr.throwNoconcat(text);
11791       }
11792
11793       if (!mustHaveExpression || expressions.length) {
11794         var compute = function(values) {
11795           for (var i = 0, ii = expressions.length; i < ii; i++) {
11796             if (allOrNothing && isUndefined(values[i])) return;
11797             concat[expressionPositions[i]] = values[i];
11798           }
11799           return concat.join('');
11800         };
11801
11802         var getValue = function(value) {
11803           return trustedContext ?
11804             $sce.getTrusted(trustedContext, value) :
11805             $sce.valueOf(value);
11806         };
11807
11808         return extend(function interpolationFn(context) {
11809             var i = 0;
11810             var ii = expressions.length;
11811             var values = new Array(ii);
11812
11813             try {
11814               for (; i < ii; i++) {
11815                 values[i] = parseFns[i](context);
11816               }
11817
11818               return compute(values);
11819             } catch (err) {
11820               $exceptionHandler($interpolateMinErr.interr(text, err));
11821             }
11822
11823           }, {
11824           // all of these properties are undocumented for now
11825           exp: text, //just for compatibility with regular watchers created via $watch
11826           expressions: expressions,
11827           $$watchDelegate: function(scope, listener) {
11828             var lastValue;
11829             return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
11830               var currValue = compute(values);
11831               if (isFunction(listener)) {
11832                 listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
11833               }
11834               lastValue = currValue;
11835             });
11836           }
11837         });
11838       }
11839
11840       function parseStringifyInterceptor(value) {
11841         try {
11842           value = getValue(value);
11843           return allOrNothing && !isDefined(value) ? value : stringify(value);
11844         } catch (err) {
11845           $exceptionHandler($interpolateMinErr.interr(text, err));
11846         }
11847       }
11848     }
11849
11850
11851     /**
11852      * @ngdoc method
11853      * @name $interpolate#startSymbol
11854      * @description
11855      * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
11856      *
11857      * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
11858      * the symbol.
11859      *
11860      * @returns {string} start symbol.
11861      */
11862     $interpolate.startSymbol = function() {
11863       return startSymbol;
11864     };
11865
11866
11867     /**
11868      * @ngdoc method
11869      * @name $interpolate#endSymbol
11870      * @description
11871      * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
11872      *
11873      * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
11874      * the symbol.
11875      *
11876      * @returns {string} end symbol.
11877      */
11878     $interpolate.endSymbol = function() {
11879       return endSymbol;
11880     };
11881
11882     return $interpolate;
11883   }];
11884 }
11885
11886 function $IntervalProvider() {
11887   this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
11888        function($rootScope,   $window,   $q,   $$q,   $browser) {
11889     var intervals = {};
11890
11891
11892      /**
11893       * @ngdoc service
11894       * @name $interval
11895       *
11896       * @description
11897       * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
11898       * milliseconds.
11899       *
11900       * The return value of registering an interval function is a promise. This promise will be
11901       * notified upon each tick of the interval, and will be resolved after `count` iterations, or
11902       * run indefinitely if `count` is not defined. The value of the notification will be the
11903       * number of iterations that have run.
11904       * To cancel an interval, call `$interval.cancel(promise)`.
11905       *
11906       * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
11907       * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
11908       * time.
11909       *
11910       * <div class="alert alert-warning">
11911       * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
11912       * with them.  In particular they are not automatically destroyed when a controller's scope or a
11913       * directive's element are destroyed.
11914       * You should take this into consideration and make sure to always cancel the interval at the
11915       * appropriate moment.  See the example below for more details on how and when to do this.
11916       * </div>
11917       *
11918       * @param {function()} fn A function that should be called repeatedly.
11919       * @param {number} delay Number of milliseconds between each function call.
11920       * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
11921       *   indefinitely.
11922       * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
11923       *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
11924       * @param {...*=} Pass additional parameters to the executed function.
11925       * @returns {promise} A promise which will be notified on each iteration.
11926       *
11927       * @example
11928       * <example module="intervalExample">
11929       * <file name="index.html">
11930       *   <script>
11931       *     angular.module('intervalExample', [])
11932       *       .controller('ExampleController', ['$scope', '$interval',
11933       *         function($scope, $interval) {
11934       *           $scope.format = 'M/d/yy h:mm:ss a';
11935       *           $scope.blood_1 = 100;
11936       *           $scope.blood_2 = 120;
11937       *
11938       *           var stop;
11939       *           $scope.fight = function() {
11940       *             // Don't start a new fight if we are already fighting
11941       *             if ( angular.isDefined(stop) ) return;
11942       *
11943       *             stop = $interval(function() {
11944       *               if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
11945       *                 $scope.blood_1 = $scope.blood_1 - 3;
11946       *                 $scope.blood_2 = $scope.blood_2 - 4;
11947       *               } else {
11948       *                 $scope.stopFight();
11949       *               }
11950       *             }, 100);
11951       *           };
11952       *
11953       *           $scope.stopFight = function() {
11954       *             if (angular.isDefined(stop)) {
11955       *               $interval.cancel(stop);
11956       *               stop = undefined;
11957       *             }
11958       *           };
11959       *
11960       *           $scope.resetFight = function() {
11961       *             $scope.blood_1 = 100;
11962       *             $scope.blood_2 = 120;
11963       *           };
11964       *
11965       *           $scope.$on('$destroy', function() {
11966       *             // Make sure that the interval is destroyed too
11967       *             $scope.stopFight();
11968       *           });
11969       *         }])
11970       *       // Register the 'myCurrentTime' directive factory method.
11971       *       // We inject $interval and dateFilter service since the factory method is DI.
11972       *       .directive('myCurrentTime', ['$interval', 'dateFilter',
11973       *         function($interval, dateFilter) {
11974       *           // return the directive link function. (compile function not needed)
11975       *           return function(scope, element, attrs) {
11976       *             var format,  // date format
11977       *                 stopTime; // so that we can cancel the time updates
11978       *
11979       *             // used to update the UI
11980       *             function updateTime() {
11981       *               element.text(dateFilter(new Date(), format));
11982       *             }
11983       *
11984       *             // watch the expression, and update the UI on change.
11985       *             scope.$watch(attrs.myCurrentTime, function(value) {
11986       *               format = value;
11987       *               updateTime();
11988       *             });
11989       *
11990       *             stopTime = $interval(updateTime, 1000);
11991       *
11992       *             // listen on DOM destroy (removal) event, and cancel the next UI update
11993       *             // to prevent updating time after the DOM element was removed.
11994       *             element.on('$destroy', function() {
11995       *               $interval.cancel(stopTime);
11996       *             });
11997       *           }
11998       *         }]);
11999       *   </script>
12000       *
12001       *   <div>
12002       *     <div ng-controller="ExampleController">
12003       *       <label>Date format: <input ng-model="format"></label> <hr/>
12004       *       Current time is: <span my-current-time="format"></span>
12005       *       <hr/>
12006       *       Blood 1 : <font color='red'>{{blood_1}}</font>
12007       *       Blood 2 : <font color='red'>{{blood_2}}</font>
12008       *       <button type="button" data-ng-click="fight()">Fight</button>
12009       *       <button type="button" data-ng-click="stopFight()">StopFight</button>
12010       *       <button type="button" data-ng-click="resetFight()">resetFight</button>
12011       *     </div>
12012       *   </div>
12013       *
12014       * </file>
12015       * </example>
12016       */
12017     function interval(fn, delay, count, invokeApply) {
12018       var hasParams = arguments.length > 4,
12019           args = hasParams ? sliceArgs(arguments, 4) : [],
12020           setInterval = $window.setInterval,
12021           clearInterval = $window.clearInterval,
12022           iteration = 0,
12023           skipApply = (isDefined(invokeApply) && !invokeApply),
12024           deferred = (skipApply ? $$q : $q).defer(),
12025           promise = deferred.promise;
12026
12027       count = isDefined(count) ? count : 0;
12028
12029       promise.$$intervalId = setInterval(function tick() {
12030         if (skipApply) {
12031           $browser.defer(callback);
12032         } else {
12033           $rootScope.$evalAsync(callback);
12034         }
12035         deferred.notify(iteration++);
12036
12037         if (count > 0 && iteration >= count) {
12038           deferred.resolve(iteration);
12039           clearInterval(promise.$$intervalId);
12040           delete intervals[promise.$$intervalId];
12041         }
12042
12043         if (!skipApply) $rootScope.$apply();
12044
12045       }, delay);
12046
12047       intervals[promise.$$intervalId] = deferred;
12048
12049       return promise;
12050
12051       function callback() {
12052         if (!hasParams) {
12053           fn(iteration);
12054         } else {
12055           fn.apply(null, args);
12056         }
12057       }
12058     }
12059
12060
12061      /**
12062       * @ngdoc method
12063       * @name $interval#cancel
12064       *
12065       * @description
12066       * Cancels a task associated with the `promise`.
12067       *
12068       * @param {Promise=} promise returned by the `$interval` function.
12069       * @returns {boolean} Returns `true` if the task was successfully canceled.
12070       */
12071     interval.cancel = function(promise) {
12072       if (promise && promise.$$intervalId in intervals) {
12073         intervals[promise.$$intervalId].reject('canceled');
12074         $window.clearInterval(promise.$$intervalId);
12075         delete intervals[promise.$$intervalId];
12076         return true;
12077       }
12078       return false;
12079     };
12080
12081     return interval;
12082   }];
12083 }
12084
12085 /**
12086  * @ngdoc service
12087  * @name $locale
12088  *
12089  * @description
12090  * $locale service provides localization rules for various Angular components. As of right now the
12091  * only public api is:
12092  *
12093  * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
12094  */
12095
12096 var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
12097     DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
12098 var $locationMinErr = minErr('$location');
12099
12100
12101 /**
12102  * Encode path using encodeUriSegment, ignoring forward slashes
12103  *
12104  * @param {string} path Path to encode
12105  * @returns {string}
12106  */
12107 function encodePath(path) {
12108   var segments = path.split('/'),
12109       i = segments.length;
12110
12111   while (i--) {
12112     segments[i] = encodeUriSegment(segments[i]);
12113   }
12114
12115   return segments.join('/');
12116 }
12117
12118 function parseAbsoluteUrl(absoluteUrl, locationObj) {
12119   var parsedUrl = urlResolve(absoluteUrl);
12120
12121   locationObj.$$protocol = parsedUrl.protocol;
12122   locationObj.$$host = parsedUrl.hostname;
12123   locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
12124 }
12125
12126
12127 function parseAppUrl(relativeUrl, locationObj) {
12128   var prefixed = (relativeUrl.charAt(0) !== '/');
12129   if (prefixed) {
12130     relativeUrl = '/' + relativeUrl;
12131   }
12132   var match = urlResolve(relativeUrl);
12133   locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
12134       match.pathname.substring(1) : match.pathname);
12135   locationObj.$$search = parseKeyValue(match.search);
12136   locationObj.$$hash = decodeURIComponent(match.hash);
12137
12138   // make sure path starts with '/';
12139   if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
12140     locationObj.$$path = '/' + locationObj.$$path;
12141   }
12142 }
12143
12144
12145 /**
12146  *
12147  * @param {string} begin
12148  * @param {string} whole
12149  * @returns {string} returns text from whole after begin or undefined if it does not begin with
12150  *                   expected string.
12151  */
12152 function beginsWith(begin, whole) {
12153   if (whole.indexOf(begin) === 0) {
12154     return whole.substr(begin.length);
12155   }
12156 }
12157
12158
12159 function stripHash(url) {
12160   var index = url.indexOf('#');
12161   return index == -1 ? url : url.substr(0, index);
12162 }
12163
12164 function trimEmptyHash(url) {
12165   return url.replace(/(#.+)|#$/, '$1');
12166 }
12167
12168
12169 function stripFile(url) {
12170   return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
12171 }
12172
12173 /* return the server only (scheme://host:port) */
12174 function serverBase(url) {
12175   return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
12176 }
12177
12178
12179 /**
12180  * LocationHtml5Url represents an url
12181  * This object is exposed as $location service when HTML5 mode is enabled and supported
12182  *
12183  * @constructor
12184  * @param {string} appBase application base URL
12185  * @param {string} appBaseNoFile application base URL stripped of any filename
12186  * @param {string} basePrefix url path prefix
12187  */
12188 function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
12189   this.$$html5 = true;
12190   basePrefix = basePrefix || '';
12191   parseAbsoluteUrl(appBase, this);
12192
12193
12194   /**
12195    * Parse given html5 (regular) url string into properties
12196    * @param {string} url HTML5 url
12197    * @private
12198    */
12199   this.$$parse = function(url) {
12200     var pathUrl = beginsWith(appBaseNoFile, url);
12201     if (!isString(pathUrl)) {
12202       throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
12203           appBaseNoFile);
12204     }
12205
12206     parseAppUrl(pathUrl, this);
12207
12208     if (!this.$$path) {
12209       this.$$path = '/';
12210     }
12211
12212     this.$$compose();
12213   };
12214
12215   /**
12216    * Compose url and update `absUrl` property
12217    * @private
12218    */
12219   this.$$compose = function() {
12220     var search = toKeyValue(this.$$search),
12221         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
12222
12223     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
12224     this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
12225   };
12226
12227   this.$$parseLinkUrl = function(url, relHref) {
12228     if (relHref && relHref[0] === '#') {
12229       // special case for links to hash fragments:
12230       // keep the old url and only replace the hash fragment
12231       this.hash(relHref.slice(1));
12232       return true;
12233     }
12234     var appUrl, prevAppUrl;
12235     var rewrittenUrl;
12236
12237     if (isDefined(appUrl = beginsWith(appBase, url))) {
12238       prevAppUrl = appUrl;
12239       if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
12240         rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
12241       } else {
12242         rewrittenUrl = appBase + prevAppUrl;
12243       }
12244     } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
12245       rewrittenUrl = appBaseNoFile + appUrl;
12246     } else if (appBaseNoFile == url + '/') {
12247       rewrittenUrl = appBaseNoFile;
12248     }
12249     if (rewrittenUrl) {
12250       this.$$parse(rewrittenUrl);
12251     }
12252     return !!rewrittenUrl;
12253   };
12254 }
12255
12256
12257 /**
12258  * LocationHashbangUrl represents url
12259  * This object is exposed as $location service when developer doesn't opt into html5 mode.
12260  * It also serves as the base class for html5 mode fallback on legacy browsers.
12261  *
12262  * @constructor
12263  * @param {string} appBase application base URL
12264  * @param {string} appBaseNoFile application base URL stripped of any filename
12265  * @param {string} hashPrefix hashbang prefix
12266  */
12267 function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
12268
12269   parseAbsoluteUrl(appBase, this);
12270
12271
12272   /**
12273    * Parse given hashbang url into properties
12274    * @param {string} url Hashbang url
12275    * @private
12276    */
12277   this.$$parse = function(url) {
12278     var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
12279     var withoutHashUrl;
12280
12281     if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
12282
12283       // The rest of the url starts with a hash so we have
12284       // got either a hashbang path or a plain hash fragment
12285       withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
12286       if (isUndefined(withoutHashUrl)) {
12287         // There was no hashbang prefix so we just have a hash fragment
12288         withoutHashUrl = withoutBaseUrl;
12289       }
12290
12291     } else {
12292       // There was no hashbang path nor hash fragment:
12293       // If we are in HTML5 mode we use what is left as the path;
12294       // Otherwise we ignore what is left
12295       if (this.$$html5) {
12296         withoutHashUrl = withoutBaseUrl;
12297       } else {
12298         withoutHashUrl = '';
12299         if (isUndefined(withoutBaseUrl)) {
12300           appBase = url;
12301           this.replace();
12302         }
12303       }
12304     }
12305
12306     parseAppUrl(withoutHashUrl, this);
12307
12308     this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
12309
12310     this.$$compose();
12311
12312     /*
12313      * In Windows, on an anchor node on documents loaded from
12314      * the filesystem, the browser will return a pathname
12315      * prefixed with the drive name ('/C:/path') when a
12316      * pathname without a drive is set:
12317      *  * a.setAttribute('href', '/foo')
12318      *   * a.pathname === '/C:/foo' //true
12319      *
12320      * Inside of Angular, we're always using pathnames that
12321      * do not include drive names for routing.
12322      */
12323     function removeWindowsDriveName(path, url, base) {
12324       /*
12325       Matches paths for file protocol on windows,
12326       such as /C:/foo/bar, and captures only /foo/bar.
12327       */
12328       var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
12329
12330       var firstPathSegmentMatch;
12331
12332       //Get the relative path from the input URL.
12333       if (url.indexOf(base) === 0) {
12334         url = url.replace(base, '');
12335       }
12336
12337       // The input URL intentionally contains a first path segment that ends with a colon.
12338       if (windowsFilePathExp.exec(url)) {
12339         return path;
12340       }
12341
12342       firstPathSegmentMatch = windowsFilePathExp.exec(path);
12343       return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
12344     }
12345   };
12346
12347   /**
12348    * Compose hashbang url and update `absUrl` property
12349    * @private
12350    */
12351   this.$$compose = function() {
12352     var search = toKeyValue(this.$$search),
12353         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
12354
12355     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
12356     this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
12357   };
12358
12359   this.$$parseLinkUrl = function(url, relHref) {
12360     if (stripHash(appBase) == stripHash(url)) {
12361       this.$$parse(url);
12362       return true;
12363     }
12364     return false;
12365   };
12366 }
12367
12368
12369 /**
12370  * LocationHashbangUrl represents url
12371  * This object is exposed as $location service when html5 history api is enabled but the browser
12372  * does not support it.
12373  *
12374  * @constructor
12375  * @param {string} appBase application base URL
12376  * @param {string} appBaseNoFile application base URL stripped of any filename
12377  * @param {string} hashPrefix hashbang prefix
12378  */
12379 function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
12380   this.$$html5 = true;
12381   LocationHashbangUrl.apply(this, arguments);
12382
12383   this.$$parseLinkUrl = function(url, relHref) {
12384     if (relHref && relHref[0] === '#') {
12385       // special case for links to hash fragments:
12386       // keep the old url and only replace the hash fragment
12387       this.hash(relHref.slice(1));
12388       return true;
12389     }
12390
12391     var rewrittenUrl;
12392     var appUrl;
12393
12394     if (appBase == stripHash(url)) {
12395       rewrittenUrl = url;
12396     } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
12397       rewrittenUrl = appBase + hashPrefix + appUrl;
12398     } else if (appBaseNoFile === url + '/') {
12399       rewrittenUrl = appBaseNoFile;
12400     }
12401     if (rewrittenUrl) {
12402       this.$$parse(rewrittenUrl);
12403     }
12404     return !!rewrittenUrl;
12405   };
12406
12407   this.$$compose = function() {
12408     var search = toKeyValue(this.$$search),
12409         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
12410
12411     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
12412     // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
12413     this.$$absUrl = appBase + hashPrefix + this.$$url;
12414   };
12415
12416 }
12417
12418
12419 var locationPrototype = {
12420
12421   /**
12422    * Are we in html5 mode?
12423    * @private
12424    */
12425   $$html5: false,
12426
12427   /**
12428    * Has any change been replacing?
12429    * @private
12430    */
12431   $$replace: false,
12432
12433   /**
12434    * @ngdoc method
12435    * @name $location#absUrl
12436    *
12437    * @description
12438    * This method is getter only.
12439    *
12440    * Return full url representation with all segments encoded according to rules specified in
12441    * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
12442    *
12443    *
12444    * ```js
12445    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12446    * var absUrl = $location.absUrl();
12447    * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
12448    * ```
12449    *
12450    * @return {string} full url
12451    */
12452   absUrl: locationGetter('$$absUrl'),
12453
12454   /**
12455    * @ngdoc method
12456    * @name $location#url
12457    *
12458    * @description
12459    * This method is getter / setter.
12460    *
12461    * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
12462    *
12463    * Change path, search and hash, when called with parameter and return `$location`.
12464    *
12465    *
12466    * ```js
12467    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12468    * var url = $location.url();
12469    * // => "/some/path?foo=bar&baz=xoxo"
12470    * ```
12471    *
12472    * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
12473    * @return {string} url
12474    */
12475   url: function(url) {
12476     if (isUndefined(url)) {
12477       return this.$$url;
12478     }
12479
12480     var match = PATH_MATCH.exec(url);
12481     if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
12482     if (match[2] || match[1] || url === '') this.search(match[3] || '');
12483     this.hash(match[5] || '');
12484
12485     return this;
12486   },
12487
12488   /**
12489    * @ngdoc method
12490    * @name $location#protocol
12491    *
12492    * @description
12493    * This method is getter only.
12494    *
12495    * Return protocol of current url.
12496    *
12497    *
12498    * ```js
12499    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12500    * var protocol = $location.protocol();
12501    * // => "http"
12502    * ```
12503    *
12504    * @return {string} protocol of current url
12505    */
12506   protocol: locationGetter('$$protocol'),
12507
12508   /**
12509    * @ngdoc method
12510    * @name $location#host
12511    *
12512    * @description
12513    * This method is getter only.
12514    *
12515    * Return host of current url.
12516    *
12517    * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
12518    *
12519    *
12520    * ```js
12521    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12522    * var host = $location.host();
12523    * // => "example.com"
12524    *
12525    * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
12526    * host = $location.host();
12527    * // => "example.com"
12528    * host = location.host;
12529    * // => "example.com:8080"
12530    * ```
12531    *
12532    * @return {string} host of current url.
12533    */
12534   host: locationGetter('$$host'),
12535
12536   /**
12537    * @ngdoc method
12538    * @name $location#port
12539    *
12540    * @description
12541    * This method is getter only.
12542    *
12543    * Return port of current url.
12544    *
12545    *
12546    * ```js
12547    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12548    * var port = $location.port();
12549    * // => 80
12550    * ```
12551    *
12552    * @return {Number} port
12553    */
12554   port: locationGetter('$$port'),
12555
12556   /**
12557    * @ngdoc method
12558    * @name $location#path
12559    *
12560    * @description
12561    * This method is getter / setter.
12562    *
12563    * Return path of current url when called without any parameter.
12564    *
12565    * Change path when called with parameter and return `$location`.
12566    *
12567    * Note: Path should always begin with forward slash (/), this method will add the forward slash
12568    * if it is missing.
12569    *
12570    *
12571    * ```js
12572    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12573    * var path = $location.path();
12574    * // => "/some/path"
12575    * ```
12576    *
12577    * @param {(string|number)=} path New path
12578    * @return {string} path
12579    */
12580   path: locationGetterSetter('$$path', function(path) {
12581     path = path !== null ? path.toString() : '';
12582     return path.charAt(0) == '/' ? path : '/' + path;
12583   }),
12584
12585   /**
12586    * @ngdoc method
12587    * @name $location#search
12588    *
12589    * @description
12590    * This method is getter / setter.
12591    *
12592    * Return search part (as object) of current url when called without any parameter.
12593    *
12594    * Change search part when called with parameter and return `$location`.
12595    *
12596    *
12597    * ```js
12598    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12599    * var searchObject = $location.search();
12600    * // => {foo: 'bar', baz: 'xoxo'}
12601    *
12602    * // set foo to 'yipee'
12603    * $location.search('foo', 'yipee');
12604    * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
12605    * ```
12606    *
12607    * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
12608    * hash object.
12609    *
12610    * When called with a single argument the method acts as a setter, setting the `search` component
12611    * of `$location` to the specified value.
12612    *
12613    * If the argument is a hash object containing an array of values, these values will be encoded
12614    * as duplicate search parameters in the url.
12615    *
12616    * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
12617    * will override only a single search property.
12618    *
12619    * If `paramValue` is an array, it will override the property of the `search` component of
12620    * `$location` specified via the first argument.
12621    *
12622    * If `paramValue` is `null`, the property specified via the first argument will be deleted.
12623    *
12624    * If `paramValue` is `true`, the property specified via the first argument will be added with no
12625    * value nor trailing equal sign.
12626    *
12627    * @return {Object} If called with no arguments returns the parsed `search` object. If called with
12628    * one or more arguments returns `$location` object itself.
12629    */
12630   search: function(search, paramValue) {
12631     switch (arguments.length) {
12632       case 0:
12633         return this.$$search;
12634       case 1:
12635         if (isString(search) || isNumber(search)) {
12636           search = search.toString();
12637           this.$$search = parseKeyValue(search);
12638         } else if (isObject(search)) {
12639           search = copy(search, {});
12640           // remove object undefined or null properties
12641           forEach(search, function(value, key) {
12642             if (value == null) delete search[key];
12643           });
12644
12645           this.$$search = search;
12646         } else {
12647           throw $locationMinErr('isrcharg',
12648               'The first argument of the `$location#search()` call must be a string or an object.');
12649         }
12650         break;
12651       default:
12652         if (isUndefined(paramValue) || paramValue === null) {
12653           delete this.$$search[search];
12654         } else {
12655           this.$$search[search] = paramValue;
12656         }
12657     }
12658
12659     this.$$compose();
12660     return this;
12661   },
12662
12663   /**
12664    * @ngdoc method
12665    * @name $location#hash
12666    *
12667    * @description
12668    * This method is getter / setter.
12669    *
12670    * Returns the hash fragment when called without any parameters.
12671    *
12672    * Changes the hash fragment when called with a parameter and returns `$location`.
12673    *
12674    *
12675    * ```js
12676    * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
12677    * var hash = $location.hash();
12678    * // => "hashValue"
12679    * ```
12680    *
12681    * @param {(string|number)=} hash New hash fragment
12682    * @return {string} hash
12683    */
12684   hash: locationGetterSetter('$$hash', function(hash) {
12685     return hash !== null ? hash.toString() : '';
12686   }),
12687
12688   /**
12689    * @ngdoc method
12690    * @name $location#replace
12691    *
12692    * @description
12693    * If called, all changes to $location during the current `$digest` will replace the current history
12694    * record, instead of adding a new one.
12695    */
12696   replace: function() {
12697     this.$$replace = true;
12698     return this;
12699   }
12700 };
12701
12702 forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
12703   Location.prototype = Object.create(locationPrototype);
12704
12705   /**
12706    * @ngdoc method
12707    * @name $location#state
12708    *
12709    * @description
12710    * This method is getter / setter.
12711    *
12712    * Return the history state object when called without any parameter.
12713    *
12714    * Change the history state object when called with one parameter and return `$location`.
12715    * The state object is later passed to `pushState` or `replaceState`.
12716    *
12717    * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
12718    * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
12719    * older browsers (like IE9 or Android < 4.0), don't use this method.
12720    *
12721    * @param {object=} state State object for pushState or replaceState
12722    * @return {object} state
12723    */
12724   Location.prototype.state = function(state) {
12725     if (!arguments.length) {
12726       return this.$$state;
12727     }
12728
12729     if (Location !== LocationHtml5Url || !this.$$html5) {
12730       throw $locationMinErr('nostate', 'History API state support is available only ' +
12731         'in HTML5 mode and only in browsers supporting HTML5 History API');
12732     }
12733     // The user might modify `stateObject` after invoking `$location.state(stateObject)`
12734     // but we're changing the $$state reference to $browser.state() during the $digest
12735     // so the modification window is narrow.
12736     this.$$state = isUndefined(state) ? null : state;
12737
12738     return this;
12739   };
12740 });
12741
12742
12743 function locationGetter(property) {
12744   return function() {
12745     return this[property];
12746   };
12747 }
12748
12749
12750 function locationGetterSetter(property, preprocess) {
12751   return function(value) {
12752     if (isUndefined(value)) {
12753       return this[property];
12754     }
12755
12756     this[property] = preprocess(value);
12757     this.$$compose();
12758
12759     return this;
12760   };
12761 }
12762
12763
12764 /**
12765  * @ngdoc service
12766  * @name $location
12767  *
12768  * @requires $rootElement
12769  *
12770  * @description
12771  * The $location service parses the URL in the browser address bar (based on the
12772  * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
12773  * available to your application. Changes to the URL in the address bar are reflected into
12774  * $location service and changes to $location are reflected into the browser address bar.
12775  *
12776  * **The $location service:**
12777  *
12778  * - Exposes the current URL in the browser address bar, so you can
12779  *   - Watch and observe the URL.
12780  *   - Change the URL.
12781  * - Synchronizes the URL with the browser when the user
12782  *   - Changes the address bar.
12783  *   - Clicks the back or forward button (or clicks a History link).
12784  *   - Clicks on a link.
12785  * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
12786  *
12787  * For more information see {@link guide/$location Developer Guide: Using $location}
12788  */
12789
12790 /**
12791  * @ngdoc provider
12792  * @name $locationProvider
12793  * @description
12794  * Use the `$locationProvider` to configure how the application deep linking paths are stored.
12795  */
12796 function $LocationProvider() {
12797   var hashPrefix = '',
12798       html5Mode = {
12799         enabled: false,
12800         requireBase: true,
12801         rewriteLinks: true
12802       };
12803
12804   /**
12805    * @ngdoc method
12806    * @name $locationProvider#hashPrefix
12807    * @description
12808    * @param {string=} prefix Prefix for hash part (containing path and search)
12809    * @returns {*} current value if used as getter or itself (chaining) if used as setter
12810    */
12811   this.hashPrefix = function(prefix) {
12812     if (isDefined(prefix)) {
12813       hashPrefix = prefix;
12814       return this;
12815     } else {
12816       return hashPrefix;
12817     }
12818   };
12819
12820   /**
12821    * @ngdoc method
12822    * @name $locationProvider#html5Mode
12823    * @description
12824    * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
12825    *   If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
12826    *   properties:
12827    *   - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
12828    *     change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
12829    *     support `pushState`.
12830    *   - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
12831    *     whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
12832    *     true, and a base tag is not present, an error will be thrown when `$location` is injected.
12833    *     See the {@link guide/$location $location guide for more information}
12834    *   - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
12835    *     enables/disables url rewriting for relative links.
12836    *
12837    * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
12838    */
12839   this.html5Mode = function(mode) {
12840     if (isBoolean(mode)) {
12841       html5Mode.enabled = mode;
12842       return this;
12843     } else if (isObject(mode)) {
12844
12845       if (isBoolean(mode.enabled)) {
12846         html5Mode.enabled = mode.enabled;
12847       }
12848
12849       if (isBoolean(mode.requireBase)) {
12850         html5Mode.requireBase = mode.requireBase;
12851       }
12852
12853       if (isBoolean(mode.rewriteLinks)) {
12854         html5Mode.rewriteLinks = mode.rewriteLinks;
12855       }
12856
12857       return this;
12858     } else {
12859       return html5Mode;
12860     }
12861   };
12862
12863   /**
12864    * @ngdoc event
12865    * @name $location#$locationChangeStart
12866    * @eventType broadcast on root scope
12867    * @description
12868    * Broadcasted before a URL will change.
12869    *
12870    * This change can be prevented by calling
12871    * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
12872    * details about event object. Upon successful change
12873    * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
12874    *
12875    * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
12876    * the browser supports the HTML5 History API.
12877    *
12878    * @param {Object} angularEvent Synthetic event object.
12879    * @param {string} newUrl New URL
12880    * @param {string=} oldUrl URL that was before it was changed.
12881    * @param {string=} newState New history state object
12882    * @param {string=} oldState History state object that was before it was changed.
12883    */
12884
12885   /**
12886    * @ngdoc event
12887    * @name $location#$locationChangeSuccess
12888    * @eventType broadcast on root scope
12889    * @description
12890    * Broadcasted after a URL was changed.
12891    *
12892    * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
12893    * the browser supports the HTML5 History API.
12894    *
12895    * @param {Object} angularEvent Synthetic event object.
12896    * @param {string} newUrl New URL
12897    * @param {string=} oldUrl URL that was before it was changed.
12898    * @param {string=} newState New history state object
12899    * @param {string=} oldState History state object that was before it was changed.
12900    */
12901
12902   this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
12903       function($rootScope, $browser, $sniffer, $rootElement, $window) {
12904     var $location,
12905         LocationMode,
12906         baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
12907         initialUrl = $browser.url(),
12908         appBase;
12909
12910     if (html5Mode.enabled) {
12911       if (!baseHref && html5Mode.requireBase) {
12912         throw $locationMinErr('nobase',
12913           "$location in HTML5 mode requires a <base> tag to be present!");
12914       }
12915       appBase = serverBase(initialUrl) + (baseHref || '/');
12916       LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
12917     } else {
12918       appBase = stripHash(initialUrl);
12919       LocationMode = LocationHashbangUrl;
12920     }
12921     var appBaseNoFile = stripFile(appBase);
12922
12923     $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
12924     $location.$$parseLinkUrl(initialUrl, initialUrl);
12925
12926     $location.$$state = $browser.state();
12927
12928     var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
12929
12930     function setBrowserUrlWithFallback(url, replace, state) {
12931       var oldUrl = $location.url();
12932       var oldState = $location.$$state;
12933       try {
12934         $browser.url(url, replace, state);
12935
12936         // Make sure $location.state() returns referentially identical (not just deeply equal)
12937         // state object; this makes possible quick checking if the state changed in the digest
12938         // loop. Checking deep equality would be too expensive.
12939         $location.$$state = $browser.state();
12940       } catch (e) {
12941         // Restore old values if pushState fails
12942         $location.url(oldUrl);
12943         $location.$$state = oldState;
12944
12945         throw e;
12946       }
12947     }
12948
12949     $rootElement.on('click', function(event) {
12950       // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
12951       // currently we open nice url link and redirect then
12952
12953       if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
12954
12955       var elm = jqLite(event.target);
12956
12957       // traverse the DOM up to find first A tag
12958       while (nodeName_(elm[0]) !== 'a') {
12959         // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
12960         if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
12961       }
12962
12963       var absHref = elm.prop('href');
12964       // get the actual href attribute - see
12965       // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
12966       var relHref = elm.attr('href') || elm.attr('xlink:href');
12967
12968       if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
12969         // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
12970         // an animation.
12971         absHref = urlResolve(absHref.animVal).href;
12972       }
12973
12974       // Ignore when url is started with javascript: or mailto:
12975       if (IGNORE_URI_REGEXP.test(absHref)) return;
12976
12977       if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
12978         if ($location.$$parseLinkUrl(absHref, relHref)) {
12979           // We do a preventDefault for all urls that are part of the angular application,
12980           // in html5mode and also without, so that we are able to abort navigation without
12981           // getting double entries in the location history.
12982           event.preventDefault();
12983           // update location manually
12984           if ($location.absUrl() != $browser.url()) {
12985             $rootScope.$apply();
12986             // hack to work around FF6 bug 684208 when scenario runner clicks on links
12987             $window.angular['ff-684208-preventDefault'] = true;
12988           }
12989         }
12990       }
12991     });
12992
12993
12994     // rewrite hashbang url <> html5 url
12995     if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
12996       $browser.url($location.absUrl(), true);
12997     }
12998
12999     var initializing = true;
13000
13001     // update $location when $browser url changes
13002     $browser.onUrlChange(function(newUrl, newState) {
13003
13004       if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
13005         // If we are navigating outside of the app then force a reload
13006         $window.location.href = newUrl;
13007         return;
13008       }
13009
13010       $rootScope.$evalAsync(function() {
13011         var oldUrl = $location.absUrl();
13012         var oldState = $location.$$state;
13013         var defaultPrevented;
13014         newUrl = trimEmptyHash(newUrl);
13015         $location.$$parse(newUrl);
13016         $location.$$state = newState;
13017
13018         defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
13019             newState, oldState).defaultPrevented;
13020
13021         // if the location was changed by a `$locationChangeStart` handler then stop
13022         // processing this location change
13023         if ($location.absUrl() !== newUrl) return;
13024
13025         if (defaultPrevented) {
13026           $location.$$parse(oldUrl);
13027           $location.$$state = oldState;
13028           setBrowserUrlWithFallback(oldUrl, false, oldState);
13029         } else {
13030           initializing = false;
13031           afterLocationChange(oldUrl, oldState);
13032         }
13033       });
13034       if (!$rootScope.$$phase) $rootScope.$digest();
13035     });
13036
13037     // update browser
13038     $rootScope.$watch(function $locationWatch() {
13039       var oldUrl = trimEmptyHash($browser.url());
13040       var newUrl = trimEmptyHash($location.absUrl());
13041       var oldState = $browser.state();
13042       var currentReplace = $location.$$replace;
13043       var urlOrStateChanged = oldUrl !== newUrl ||
13044         ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
13045
13046       if (initializing || urlOrStateChanged) {
13047         initializing = false;
13048
13049         $rootScope.$evalAsync(function() {
13050           var newUrl = $location.absUrl();
13051           var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
13052               $location.$$state, oldState).defaultPrevented;
13053
13054           // if the location was changed by a `$locationChangeStart` handler then stop
13055           // processing this location change
13056           if ($location.absUrl() !== newUrl) return;
13057
13058           if (defaultPrevented) {
13059             $location.$$parse(oldUrl);
13060             $location.$$state = oldState;
13061           } else {
13062             if (urlOrStateChanged) {
13063               setBrowserUrlWithFallback(newUrl, currentReplace,
13064                                         oldState === $location.$$state ? null : $location.$$state);
13065             }
13066             afterLocationChange(oldUrl, oldState);
13067           }
13068         });
13069       }
13070
13071       $location.$$replace = false;
13072
13073       // we don't need to return anything because $evalAsync will make the digest loop dirty when
13074       // there is a change
13075     });
13076
13077     return $location;
13078
13079     function afterLocationChange(oldUrl, oldState) {
13080       $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
13081         $location.$$state, oldState);
13082     }
13083 }];
13084 }
13085
13086 /**
13087  * @ngdoc service
13088  * @name $log
13089  * @requires $window
13090  *
13091  * @description
13092  * Simple service for logging. Default implementation safely writes the message
13093  * into the browser's console (if present).
13094  *
13095  * The main purpose of this service is to simplify debugging and troubleshooting.
13096  *
13097  * The default is to log `debug` messages. You can use
13098  * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
13099  *
13100  * @example
13101    <example module="logExample">
13102      <file name="script.js">
13103        angular.module('logExample', [])
13104          .controller('LogController', ['$scope', '$log', function($scope, $log) {
13105            $scope.$log = $log;
13106            $scope.message = 'Hello World!';
13107          }]);
13108      </file>
13109      <file name="index.html">
13110        <div ng-controller="LogController">
13111          <p>Reload this page with open console, enter text and hit the log button...</p>
13112          <label>Message:
13113          <input type="text" ng-model="message" /></label>
13114          <button ng-click="$log.log(message)">log</button>
13115          <button ng-click="$log.warn(message)">warn</button>
13116          <button ng-click="$log.info(message)">info</button>
13117          <button ng-click="$log.error(message)">error</button>
13118          <button ng-click="$log.debug(message)">debug</button>
13119        </div>
13120      </file>
13121    </example>
13122  */
13123
13124 /**
13125  * @ngdoc provider
13126  * @name $logProvider
13127  * @description
13128  * Use the `$logProvider` to configure how the application logs messages
13129  */
13130 function $LogProvider() {
13131   var debug = true,
13132       self = this;
13133
13134   /**
13135    * @ngdoc method
13136    * @name $logProvider#debugEnabled
13137    * @description
13138    * @param {boolean=} flag enable or disable debug level messages
13139    * @returns {*} current value if used as getter or itself (chaining) if used as setter
13140    */
13141   this.debugEnabled = function(flag) {
13142     if (isDefined(flag)) {
13143       debug = flag;
13144     return this;
13145     } else {
13146       return debug;
13147     }
13148   };
13149
13150   this.$get = ['$window', function($window) {
13151     return {
13152       /**
13153        * @ngdoc method
13154        * @name $log#log
13155        *
13156        * @description
13157        * Write a log message
13158        */
13159       log: consoleLog('log'),
13160
13161       /**
13162        * @ngdoc method
13163        * @name $log#info
13164        *
13165        * @description
13166        * Write an information message
13167        */
13168       info: consoleLog('info'),
13169
13170       /**
13171        * @ngdoc method
13172        * @name $log#warn
13173        *
13174        * @description
13175        * Write a warning message
13176        */
13177       warn: consoleLog('warn'),
13178
13179       /**
13180        * @ngdoc method
13181        * @name $log#error
13182        *
13183        * @description
13184        * Write an error message
13185        */
13186       error: consoleLog('error'),
13187
13188       /**
13189        * @ngdoc method
13190        * @name $log#debug
13191        *
13192        * @description
13193        * Write a debug message
13194        */
13195       debug: (function() {
13196         var fn = consoleLog('debug');
13197
13198         return function() {
13199           if (debug) {
13200             fn.apply(self, arguments);
13201           }
13202         };
13203       }())
13204     };
13205
13206     function formatError(arg) {
13207       if (arg instanceof Error) {
13208         if (arg.stack) {
13209           arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
13210               ? 'Error: ' + arg.message + '\n' + arg.stack
13211               : arg.stack;
13212         } else if (arg.sourceURL) {
13213           arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
13214         }
13215       }
13216       return arg;
13217     }
13218
13219     function consoleLog(type) {
13220       var console = $window.console || {},
13221           logFn = console[type] || console.log || noop,
13222           hasApply = false;
13223
13224       // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
13225       // The reason behind this is that console.log has type "object" in IE8...
13226       try {
13227         hasApply = !!logFn.apply;
13228       } catch (e) {}
13229
13230       if (hasApply) {
13231         return function() {
13232           var args = [];
13233           forEach(arguments, function(arg) {
13234             args.push(formatError(arg));
13235           });
13236           return logFn.apply(console, args);
13237         };
13238       }
13239
13240       // we are IE which either doesn't have window.console => this is noop and we do nothing,
13241       // or we are IE where console.log doesn't have apply so we log at least first 2 args
13242       return function(arg1, arg2) {
13243         logFn(arg1, arg2 == null ? '' : arg2);
13244       };
13245     }
13246   }];
13247 }
13248
13249 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
13250  *     Any commits to this file should be reviewed with security in mind.  *
13251  *   Changes to this file can potentially create security vulnerabilities. *
13252  *          An approval from 2 Core members with history of modifying      *
13253  *                         this file is required.                          *
13254  *                                                                         *
13255  *  Does the change somehow allow for arbitrary javascript to be executed? *
13256  *    Or allows for someone to change the prototype of built-in objects?   *
13257  *     Or gives undesired access to variables likes document or window?    *
13258  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
13259
13260 var $parseMinErr = minErr('$parse');
13261
13262 // Sandboxing Angular Expressions
13263 // ------------------------------
13264 // Angular expressions are generally considered safe because these expressions only have direct
13265 // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
13266 // obtaining a reference to native JS functions such as the Function constructor.
13267 //
13268 // As an example, consider the following Angular expression:
13269 //
13270 //   {}.toString.constructor('alert("evil JS code")')
13271 //
13272 // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
13273 // against the expression language, but not to prevent exploits that were enabled by exposing
13274 // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
13275 // practice and therefore we are not even trying to protect against interaction with an object
13276 // explicitly exposed in this way.
13277 //
13278 // In general, it is not possible to access a Window object from an angular expression unless a
13279 // window or some DOM object that has a reference to window is published onto a Scope.
13280 // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
13281 // native objects.
13282 //
13283 // See https://docs.angularjs.org/guide/security
13284
13285
13286 function ensureSafeMemberName(name, fullExpression) {
13287   if (name === "__defineGetter__" || name === "__defineSetter__"
13288       || name === "__lookupGetter__" || name === "__lookupSetter__"
13289       || name === "__proto__") {
13290     throw $parseMinErr('isecfld',
13291         'Attempting to access a disallowed field in Angular expressions! '
13292         + 'Expression: {0}', fullExpression);
13293   }
13294   return name;
13295 }
13296
13297 function getStringValue(name) {
13298   // Property names must be strings. This means that non-string objects cannot be used
13299   // as keys in an object. Any non-string object, including a number, is typecasted
13300   // into a string via the toString method.
13301   // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
13302   //
13303   // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
13304   // to a string. It's not always possible. If `name` is an object and its `toString` method is
13305   // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
13306   //
13307   // TypeError: Cannot convert object to primitive value
13308   //
13309   // For performance reasons, we don't catch this error here and allow it to propagate up the call
13310   // stack. Note that you'll get the same error in JavaScript if you try to access a property using
13311   // such a 'broken' object as a key.
13312   return name + '';
13313 }
13314
13315 function ensureSafeObject(obj, fullExpression) {
13316   // nifty check if obj is Function that is fast and works across iframes and other contexts
13317   if (obj) {
13318     if (obj.constructor === obj) {
13319       throw $parseMinErr('isecfn',
13320           'Referencing Function in Angular expressions is disallowed! Expression: {0}',
13321           fullExpression);
13322     } else if (// isWindow(obj)
13323         obj.window === obj) {
13324       throw $parseMinErr('isecwindow',
13325           'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
13326           fullExpression);
13327     } else if (// isElement(obj)
13328         obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
13329       throw $parseMinErr('isecdom',
13330           'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
13331           fullExpression);
13332     } else if (// block Object so that we can't get hold of dangerous Object.* methods
13333         obj === Object) {
13334       throw $parseMinErr('isecobj',
13335           'Referencing Object in Angular expressions is disallowed! Expression: {0}',
13336           fullExpression);
13337     }
13338   }
13339   return obj;
13340 }
13341
13342 var CALL = Function.prototype.call;
13343 var APPLY = Function.prototype.apply;
13344 var BIND = Function.prototype.bind;
13345
13346 function ensureSafeFunction(obj, fullExpression) {
13347   if (obj) {
13348     if (obj.constructor === obj) {
13349       throw $parseMinErr('isecfn',
13350         'Referencing Function in Angular expressions is disallowed! Expression: {0}',
13351         fullExpression);
13352     } else if (obj === CALL || obj === APPLY || obj === BIND) {
13353       throw $parseMinErr('isecff',
13354         'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
13355         fullExpression);
13356     }
13357   }
13358 }
13359
13360 function ensureSafeAssignContext(obj, fullExpression) {
13361   if (obj) {
13362     if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
13363         obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
13364       throw $parseMinErr('isecaf',
13365         'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
13366     }
13367   }
13368 }
13369
13370 var OPERATORS = createMap();
13371 forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
13372 var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
13373
13374
13375 /////////////////////////////////////////
13376
13377
13378 /**
13379  * @constructor
13380  */
13381 var Lexer = function(options) {
13382   this.options = options;
13383 };
13384
13385 Lexer.prototype = {
13386   constructor: Lexer,
13387
13388   lex: function(text) {
13389     this.text = text;
13390     this.index = 0;
13391     this.tokens = [];
13392
13393     while (this.index < this.text.length) {
13394       var ch = this.text.charAt(this.index);
13395       if (ch === '"' || ch === "'") {
13396         this.readString(ch);
13397       } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
13398         this.readNumber();
13399       } else if (this.isIdent(ch)) {
13400         this.readIdent();
13401       } else if (this.is(ch, '(){}[].,;:?')) {
13402         this.tokens.push({index: this.index, text: ch});
13403         this.index++;
13404       } else if (this.isWhitespace(ch)) {
13405         this.index++;
13406       } else {
13407         var ch2 = ch + this.peek();
13408         var ch3 = ch2 + this.peek(2);
13409         var op1 = OPERATORS[ch];
13410         var op2 = OPERATORS[ch2];
13411         var op3 = OPERATORS[ch3];
13412         if (op1 || op2 || op3) {
13413           var token = op3 ? ch3 : (op2 ? ch2 : ch);
13414           this.tokens.push({index: this.index, text: token, operator: true});
13415           this.index += token.length;
13416         } else {
13417           this.throwError('Unexpected next character ', this.index, this.index + 1);
13418         }
13419       }
13420     }
13421     return this.tokens;
13422   },
13423
13424   is: function(ch, chars) {
13425     return chars.indexOf(ch) !== -1;
13426   },
13427
13428   peek: function(i) {
13429     var num = i || 1;
13430     return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
13431   },
13432
13433   isNumber: function(ch) {
13434     return ('0' <= ch && ch <= '9') && typeof ch === "string";
13435   },
13436
13437   isWhitespace: function(ch) {
13438     // IE treats non-breaking space as \u00A0
13439     return (ch === ' ' || ch === '\r' || ch === '\t' ||
13440             ch === '\n' || ch === '\v' || ch === '\u00A0');
13441   },
13442
13443   isIdent: function(ch) {
13444     return ('a' <= ch && ch <= 'z' ||
13445             'A' <= ch && ch <= 'Z' ||
13446             '_' === ch || ch === '$');
13447   },
13448
13449   isExpOperator: function(ch) {
13450     return (ch === '-' || ch === '+' || this.isNumber(ch));
13451   },
13452
13453   throwError: function(error, start, end) {
13454     end = end || this.index;
13455     var colStr = (isDefined(start)
13456             ? 's ' + start +  '-' + this.index + ' [' + this.text.substring(start, end) + ']'
13457             : ' ' + end);
13458     throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
13459         error, colStr, this.text);
13460   },
13461
13462   readNumber: function() {
13463     var number = '';
13464     var start = this.index;
13465     while (this.index < this.text.length) {
13466       var ch = lowercase(this.text.charAt(this.index));
13467       if (ch == '.' || this.isNumber(ch)) {
13468         number += ch;
13469       } else {
13470         var peekCh = this.peek();
13471         if (ch == 'e' && this.isExpOperator(peekCh)) {
13472           number += ch;
13473         } else if (this.isExpOperator(ch) &&
13474             peekCh && this.isNumber(peekCh) &&
13475             number.charAt(number.length - 1) == 'e') {
13476           number += ch;
13477         } else if (this.isExpOperator(ch) &&
13478             (!peekCh || !this.isNumber(peekCh)) &&
13479             number.charAt(number.length - 1) == 'e') {
13480           this.throwError('Invalid exponent');
13481         } else {
13482           break;
13483         }
13484       }
13485       this.index++;
13486     }
13487     this.tokens.push({
13488       index: start,
13489       text: number,
13490       constant: true,
13491       value: Number(number)
13492     });
13493   },
13494
13495   readIdent: function() {
13496     var start = this.index;
13497     while (this.index < this.text.length) {
13498       var ch = this.text.charAt(this.index);
13499       if (!(this.isIdent(ch) || this.isNumber(ch))) {
13500         break;
13501       }
13502       this.index++;
13503     }
13504     this.tokens.push({
13505       index: start,
13506       text: this.text.slice(start, this.index),
13507       identifier: true
13508     });
13509   },
13510
13511   readString: function(quote) {
13512     var start = this.index;
13513     this.index++;
13514     var string = '';
13515     var rawString = quote;
13516     var escape = false;
13517     while (this.index < this.text.length) {
13518       var ch = this.text.charAt(this.index);
13519       rawString += ch;
13520       if (escape) {
13521         if (ch === 'u') {
13522           var hex = this.text.substring(this.index + 1, this.index + 5);
13523           if (!hex.match(/[\da-f]{4}/i)) {
13524             this.throwError('Invalid unicode escape [\\u' + hex + ']');
13525           }
13526           this.index += 4;
13527           string += String.fromCharCode(parseInt(hex, 16));
13528         } else {
13529           var rep = ESCAPE[ch];
13530           string = string + (rep || ch);
13531         }
13532         escape = false;
13533       } else if (ch === '\\') {
13534         escape = true;
13535       } else if (ch === quote) {
13536         this.index++;
13537         this.tokens.push({
13538           index: start,
13539           text: rawString,
13540           constant: true,
13541           value: string
13542         });
13543         return;
13544       } else {
13545         string += ch;
13546       }
13547       this.index++;
13548     }
13549     this.throwError('Unterminated quote', start);
13550   }
13551 };
13552
13553 var AST = function(lexer, options) {
13554   this.lexer = lexer;
13555   this.options = options;
13556 };
13557
13558 AST.Program = 'Program';
13559 AST.ExpressionStatement = 'ExpressionStatement';
13560 AST.AssignmentExpression = 'AssignmentExpression';
13561 AST.ConditionalExpression = 'ConditionalExpression';
13562 AST.LogicalExpression = 'LogicalExpression';
13563 AST.BinaryExpression = 'BinaryExpression';
13564 AST.UnaryExpression = 'UnaryExpression';
13565 AST.CallExpression = 'CallExpression';
13566 AST.MemberExpression = 'MemberExpression';
13567 AST.Identifier = 'Identifier';
13568 AST.Literal = 'Literal';
13569 AST.ArrayExpression = 'ArrayExpression';
13570 AST.Property = 'Property';
13571 AST.ObjectExpression = 'ObjectExpression';
13572 AST.ThisExpression = 'ThisExpression';
13573 AST.LocalsExpression = 'LocalsExpression';
13574
13575 // Internal use only
13576 AST.NGValueParameter = 'NGValueParameter';
13577
13578 AST.prototype = {
13579   ast: function(text) {
13580     this.text = text;
13581     this.tokens = this.lexer.lex(text);
13582
13583     var value = this.program();
13584
13585     if (this.tokens.length !== 0) {
13586       this.throwError('is an unexpected token', this.tokens[0]);
13587     }
13588
13589     return value;
13590   },
13591
13592   program: function() {
13593     var body = [];
13594     while (true) {
13595       if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
13596         body.push(this.expressionStatement());
13597       if (!this.expect(';')) {
13598         return { type: AST.Program, body: body};
13599       }
13600     }
13601   },
13602
13603   expressionStatement: function() {
13604     return { type: AST.ExpressionStatement, expression: this.filterChain() };
13605   },
13606
13607   filterChain: function() {
13608     var left = this.expression();
13609     var token;
13610     while ((token = this.expect('|'))) {
13611       left = this.filter(left);
13612     }
13613     return left;
13614   },
13615
13616   expression: function() {
13617     return this.assignment();
13618   },
13619
13620   assignment: function() {
13621     var result = this.ternary();
13622     if (this.expect('=')) {
13623       result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
13624     }
13625     return result;
13626   },
13627
13628   ternary: function() {
13629     var test = this.logicalOR();
13630     var alternate;
13631     var consequent;
13632     if (this.expect('?')) {
13633       alternate = this.expression();
13634       if (this.consume(':')) {
13635         consequent = this.expression();
13636         return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
13637       }
13638     }
13639     return test;
13640   },
13641
13642   logicalOR: function() {
13643     var left = this.logicalAND();
13644     while (this.expect('||')) {
13645       left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
13646     }
13647     return left;
13648   },
13649
13650   logicalAND: function() {
13651     var left = this.equality();
13652     while (this.expect('&&')) {
13653       left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
13654     }
13655     return left;
13656   },
13657
13658   equality: function() {
13659     var left = this.relational();
13660     var token;
13661     while ((token = this.expect('==','!=','===','!=='))) {
13662       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
13663     }
13664     return left;
13665   },
13666
13667   relational: function() {
13668     var left = this.additive();
13669     var token;
13670     while ((token = this.expect('<', '>', '<=', '>='))) {
13671       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
13672     }
13673     return left;
13674   },
13675
13676   additive: function() {
13677     var left = this.multiplicative();
13678     var token;
13679     while ((token = this.expect('+','-'))) {
13680       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
13681     }
13682     return left;
13683   },
13684
13685   multiplicative: function() {
13686     var left = this.unary();
13687     var token;
13688     while ((token = this.expect('*','/','%'))) {
13689       left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
13690     }
13691     return left;
13692   },
13693
13694   unary: function() {
13695     var token;
13696     if ((token = this.expect('+', '-', '!'))) {
13697       return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
13698     } else {
13699       return this.primary();
13700     }
13701   },
13702
13703   primary: function() {
13704     var primary;
13705     if (this.expect('(')) {
13706       primary = this.filterChain();
13707       this.consume(')');
13708     } else if (this.expect('[')) {
13709       primary = this.arrayDeclaration();
13710     } else if (this.expect('{')) {
13711       primary = this.object();
13712     } else if (this.constants.hasOwnProperty(this.peek().text)) {
13713       primary = copy(this.constants[this.consume().text]);
13714     } else if (this.peek().identifier) {
13715       primary = this.identifier();
13716     } else if (this.peek().constant) {
13717       primary = this.constant();
13718     } else {
13719       this.throwError('not a primary expression', this.peek());
13720     }
13721
13722     var next;
13723     while ((next = this.expect('(', '[', '.'))) {
13724       if (next.text === '(') {
13725         primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
13726         this.consume(')');
13727       } else if (next.text === '[') {
13728         primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
13729         this.consume(']');
13730       } else if (next.text === '.') {
13731         primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
13732       } else {
13733         this.throwError('IMPOSSIBLE');
13734       }
13735     }
13736     return primary;
13737   },
13738
13739   filter: function(baseExpression) {
13740     var args = [baseExpression];
13741     var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
13742
13743     while (this.expect(':')) {
13744       args.push(this.expression());
13745     }
13746
13747     return result;
13748   },
13749
13750   parseArguments: function() {
13751     var args = [];
13752     if (this.peekToken().text !== ')') {
13753       do {
13754         args.push(this.expression());
13755       } while (this.expect(','));
13756     }
13757     return args;
13758   },
13759
13760   identifier: function() {
13761     var token = this.consume();
13762     if (!token.identifier) {
13763       this.throwError('is not a valid identifier', token);
13764     }
13765     return { type: AST.Identifier, name: token.text };
13766   },
13767
13768   constant: function() {
13769     // TODO check that it is a constant
13770     return { type: AST.Literal, value: this.consume().value };
13771   },
13772
13773   arrayDeclaration: function() {
13774     var elements = [];
13775     if (this.peekToken().text !== ']') {
13776       do {
13777         if (this.peek(']')) {
13778           // Support trailing commas per ES5.1.
13779           break;
13780         }
13781         elements.push(this.expression());
13782       } while (this.expect(','));
13783     }
13784     this.consume(']');
13785
13786     return { type: AST.ArrayExpression, elements: elements };
13787   },
13788
13789   object: function() {
13790     var properties = [], property;
13791     if (this.peekToken().text !== '}') {
13792       do {
13793         if (this.peek('}')) {
13794           // Support trailing commas per ES5.1.
13795           break;
13796         }
13797         property = {type: AST.Property, kind: 'init'};
13798         if (this.peek().constant) {
13799           property.key = this.constant();
13800         } else if (this.peek().identifier) {
13801           property.key = this.identifier();
13802         } else {
13803           this.throwError("invalid key", this.peek());
13804         }
13805         this.consume(':');
13806         property.value = this.expression();
13807         properties.push(property);
13808       } while (this.expect(','));
13809     }
13810     this.consume('}');
13811
13812     return {type: AST.ObjectExpression, properties: properties };
13813   },
13814
13815   throwError: function(msg, token) {
13816     throw $parseMinErr('syntax',
13817         'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
13818           token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
13819   },
13820
13821   consume: function(e1) {
13822     if (this.tokens.length === 0) {
13823       throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
13824     }
13825
13826     var token = this.expect(e1);
13827     if (!token) {
13828       this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
13829     }
13830     return token;
13831   },
13832
13833   peekToken: function() {
13834     if (this.tokens.length === 0) {
13835       throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
13836     }
13837     return this.tokens[0];
13838   },
13839
13840   peek: function(e1, e2, e3, e4) {
13841     return this.peekAhead(0, e1, e2, e3, e4);
13842   },
13843
13844   peekAhead: function(i, e1, e2, e3, e4) {
13845     if (this.tokens.length > i) {
13846       var token = this.tokens[i];
13847       var t = token.text;
13848       if (t === e1 || t === e2 || t === e3 || t === e4 ||
13849           (!e1 && !e2 && !e3 && !e4)) {
13850         return token;
13851       }
13852     }
13853     return false;
13854   },
13855
13856   expect: function(e1, e2, e3, e4) {
13857     var token = this.peek(e1, e2, e3, e4);
13858     if (token) {
13859       this.tokens.shift();
13860       return token;
13861     }
13862     return false;
13863   },
13864
13865
13866   /* `undefined` is not a constant, it is an identifier,
13867    * but using it as an identifier is not supported
13868    */
13869   constants: {
13870     'true': { type: AST.Literal, value: true },
13871     'false': { type: AST.Literal, value: false },
13872     'null': { type: AST.Literal, value: null },
13873     'undefined': {type: AST.Literal, value: undefined },
13874     'this': {type: AST.ThisExpression },
13875     '$locals': {type: AST.LocalsExpression }
13876   }
13877 };
13878
13879 function ifDefined(v, d) {
13880   return typeof v !== 'undefined' ? v : d;
13881 }
13882
13883 function plusFn(l, r) {
13884   if (typeof l === 'undefined') return r;
13885   if (typeof r === 'undefined') return l;
13886   return l + r;
13887 }
13888
13889 function isStateless($filter, filterName) {
13890   var fn = $filter(filterName);
13891   return !fn.$stateful;
13892 }
13893
13894 function findConstantAndWatchExpressions(ast, $filter) {
13895   var allConstants;
13896   var argsToWatch;
13897   switch (ast.type) {
13898   case AST.Program:
13899     allConstants = true;
13900     forEach(ast.body, function(expr) {
13901       findConstantAndWatchExpressions(expr.expression, $filter);
13902       allConstants = allConstants && expr.expression.constant;
13903     });
13904     ast.constant = allConstants;
13905     break;
13906   case AST.Literal:
13907     ast.constant = true;
13908     ast.toWatch = [];
13909     break;
13910   case AST.UnaryExpression:
13911     findConstantAndWatchExpressions(ast.argument, $filter);
13912     ast.constant = ast.argument.constant;
13913     ast.toWatch = ast.argument.toWatch;
13914     break;
13915   case AST.BinaryExpression:
13916     findConstantAndWatchExpressions(ast.left, $filter);
13917     findConstantAndWatchExpressions(ast.right, $filter);
13918     ast.constant = ast.left.constant && ast.right.constant;
13919     ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
13920     break;
13921   case AST.LogicalExpression:
13922     findConstantAndWatchExpressions(ast.left, $filter);
13923     findConstantAndWatchExpressions(ast.right, $filter);
13924     ast.constant = ast.left.constant && ast.right.constant;
13925     ast.toWatch = ast.constant ? [] : [ast];
13926     break;
13927   case AST.ConditionalExpression:
13928     findConstantAndWatchExpressions(ast.test, $filter);
13929     findConstantAndWatchExpressions(ast.alternate, $filter);
13930     findConstantAndWatchExpressions(ast.consequent, $filter);
13931     ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
13932     ast.toWatch = ast.constant ? [] : [ast];
13933     break;
13934   case AST.Identifier:
13935     ast.constant = false;
13936     ast.toWatch = [ast];
13937     break;
13938   case AST.MemberExpression:
13939     findConstantAndWatchExpressions(ast.object, $filter);
13940     if (ast.computed) {
13941       findConstantAndWatchExpressions(ast.property, $filter);
13942     }
13943     ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
13944     ast.toWatch = [ast];
13945     break;
13946   case AST.CallExpression:
13947     allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
13948     argsToWatch = [];
13949     forEach(ast.arguments, function(expr) {
13950       findConstantAndWatchExpressions(expr, $filter);
13951       allConstants = allConstants && expr.constant;
13952       if (!expr.constant) {
13953         argsToWatch.push.apply(argsToWatch, expr.toWatch);
13954       }
13955     });
13956     ast.constant = allConstants;
13957     ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
13958     break;
13959   case AST.AssignmentExpression:
13960     findConstantAndWatchExpressions(ast.left, $filter);
13961     findConstantAndWatchExpressions(ast.right, $filter);
13962     ast.constant = ast.left.constant && ast.right.constant;
13963     ast.toWatch = [ast];
13964     break;
13965   case AST.ArrayExpression:
13966     allConstants = true;
13967     argsToWatch = [];
13968     forEach(ast.elements, function(expr) {
13969       findConstantAndWatchExpressions(expr, $filter);
13970       allConstants = allConstants && expr.constant;
13971       if (!expr.constant) {
13972         argsToWatch.push.apply(argsToWatch, expr.toWatch);
13973       }
13974     });
13975     ast.constant = allConstants;
13976     ast.toWatch = argsToWatch;
13977     break;
13978   case AST.ObjectExpression:
13979     allConstants = true;
13980     argsToWatch = [];
13981     forEach(ast.properties, function(property) {
13982       findConstantAndWatchExpressions(property.value, $filter);
13983       allConstants = allConstants && property.value.constant;
13984       if (!property.value.constant) {
13985         argsToWatch.push.apply(argsToWatch, property.value.toWatch);
13986       }
13987     });
13988     ast.constant = allConstants;
13989     ast.toWatch = argsToWatch;
13990     break;
13991   case AST.ThisExpression:
13992     ast.constant = false;
13993     ast.toWatch = [];
13994     break;
13995   case AST.LocalsExpression:
13996     ast.constant = false;
13997     ast.toWatch = [];
13998     break;
13999   }
14000 }
14001
14002 function getInputs(body) {
14003   if (body.length != 1) return;
14004   var lastExpression = body[0].expression;
14005   var candidate = lastExpression.toWatch;
14006   if (candidate.length !== 1) return candidate;
14007   return candidate[0] !== lastExpression ? candidate : undefined;
14008 }
14009
14010 function isAssignable(ast) {
14011   return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
14012 }
14013
14014 function assignableAST(ast) {
14015   if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
14016     return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
14017   }
14018 }
14019
14020 function isLiteral(ast) {
14021   return ast.body.length === 0 ||
14022       ast.body.length === 1 && (
14023       ast.body[0].expression.type === AST.Literal ||
14024       ast.body[0].expression.type === AST.ArrayExpression ||
14025       ast.body[0].expression.type === AST.ObjectExpression);
14026 }
14027
14028 function isConstant(ast) {
14029   return ast.constant;
14030 }
14031
14032 function ASTCompiler(astBuilder, $filter) {
14033   this.astBuilder = astBuilder;
14034   this.$filter = $filter;
14035 }
14036
14037 ASTCompiler.prototype = {
14038   compile: function(expression, expensiveChecks) {
14039     var self = this;
14040     var ast = this.astBuilder.ast(expression);
14041     this.state = {
14042       nextId: 0,
14043       filters: {},
14044       expensiveChecks: expensiveChecks,
14045       fn: {vars: [], body: [], own: {}},
14046       assign: {vars: [], body: [], own: {}},
14047       inputs: []
14048     };
14049     findConstantAndWatchExpressions(ast, self.$filter);
14050     var extra = '';
14051     var assignable;
14052     this.stage = 'assign';
14053     if ((assignable = assignableAST(ast))) {
14054       this.state.computing = 'assign';
14055       var result = this.nextId();
14056       this.recurse(assignable, result);
14057       this.return_(result);
14058       extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
14059     }
14060     var toWatch = getInputs(ast.body);
14061     self.stage = 'inputs';
14062     forEach(toWatch, function(watch, key) {
14063       var fnKey = 'fn' + key;
14064       self.state[fnKey] = {vars: [], body: [], own: {}};
14065       self.state.computing = fnKey;
14066       var intoId = self.nextId();
14067       self.recurse(watch, intoId);
14068       self.return_(intoId);
14069       self.state.inputs.push(fnKey);
14070       watch.watchId = key;
14071     });
14072     this.state.computing = 'fn';
14073     this.stage = 'main';
14074     this.recurse(ast);
14075     var fnString =
14076       // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
14077       // This is a workaround for this until we do a better job at only removing the prefix only when we should.
14078       '"' + this.USE + ' ' + this.STRICT + '";\n' +
14079       this.filterPrefix() +
14080       'var fn=' + this.generateFunction('fn', 's,l,a,i') +
14081       extra +
14082       this.watchFns() +
14083       'return fn;';
14084
14085     /* jshint -W054 */
14086     var fn = (new Function('$filter',
14087         'ensureSafeMemberName',
14088         'ensureSafeObject',
14089         'ensureSafeFunction',
14090         'getStringValue',
14091         'ensureSafeAssignContext',
14092         'ifDefined',
14093         'plus',
14094         'text',
14095         fnString))(
14096           this.$filter,
14097           ensureSafeMemberName,
14098           ensureSafeObject,
14099           ensureSafeFunction,
14100           getStringValue,
14101           ensureSafeAssignContext,
14102           ifDefined,
14103           plusFn,
14104           expression);
14105     /* jshint +W054 */
14106     this.state = this.stage = undefined;
14107     fn.literal = isLiteral(ast);
14108     fn.constant = isConstant(ast);
14109     return fn;
14110   },
14111
14112   USE: 'use',
14113
14114   STRICT: 'strict',
14115
14116   watchFns: function() {
14117     var result = [];
14118     var fns = this.state.inputs;
14119     var self = this;
14120     forEach(fns, function(name) {
14121       result.push('var ' + name + '=' + self.generateFunction(name, 's'));
14122     });
14123     if (fns.length) {
14124       result.push('fn.inputs=[' + fns.join(',') + '];');
14125     }
14126     return result.join('');
14127   },
14128
14129   generateFunction: function(name, params) {
14130     return 'function(' + params + '){' +
14131         this.varsPrefix(name) +
14132         this.body(name) +
14133         '};';
14134   },
14135
14136   filterPrefix: function() {
14137     var parts = [];
14138     var self = this;
14139     forEach(this.state.filters, function(id, filter) {
14140       parts.push(id + '=$filter(' + self.escape(filter) + ')');
14141     });
14142     if (parts.length) return 'var ' + parts.join(',') + ';';
14143     return '';
14144   },
14145
14146   varsPrefix: function(section) {
14147     return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
14148   },
14149
14150   body: function(section) {
14151     return this.state[section].body.join('');
14152   },
14153
14154   recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
14155     var left, right, self = this, args, expression;
14156     recursionFn = recursionFn || noop;
14157     if (!skipWatchIdCheck && isDefined(ast.watchId)) {
14158       intoId = intoId || this.nextId();
14159       this.if_('i',
14160         this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
14161         this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
14162       );
14163       return;
14164     }
14165     switch (ast.type) {
14166     case AST.Program:
14167       forEach(ast.body, function(expression, pos) {
14168         self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
14169         if (pos !== ast.body.length - 1) {
14170           self.current().body.push(right, ';');
14171         } else {
14172           self.return_(right);
14173         }
14174       });
14175       break;
14176     case AST.Literal:
14177       expression = this.escape(ast.value);
14178       this.assign(intoId, expression);
14179       recursionFn(expression);
14180       break;
14181     case AST.UnaryExpression:
14182       this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
14183       expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
14184       this.assign(intoId, expression);
14185       recursionFn(expression);
14186       break;
14187     case AST.BinaryExpression:
14188       this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
14189       this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
14190       if (ast.operator === '+') {
14191         expression = this.plus(left, right);
14192       } else if (ast.operator === '-') {
14193         expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
14194       } else {
14195         expression = '(' + left + ')' + ast.operator + '(' + right + ')';
14196       }
14197       this.assign(intoId, expression);
14198       recursionFn(expression);
14199       break;
14200     case AST.LogicalExpression:
14201       intoId = intoId || this.nextId();
14202       self.recurse(ast.left, intoId);
14203       self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
14204       recursionFn(intoId);
14205       break;
14206     case AST.ConditionalExpression:
14207       intoId = intoId || this.nextId();
14208       self.recurse(ast.test, intoId);
14209       self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
14210       recursionFn(intoId);
14211       break;
14212     case AST.Identifier:
14213       intoId = intoId || this.nextId();
14214       if (nameId) {
14215         nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
14216         nameId.computed = false;
14217         nameId.name = ast.name;
14218       }
14219       ensureSafeMemberName(ast.name);
14220       self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
14221         function() {
14222           self.if_(self.stage === 'inputs' || 's', function() {
14223             if (create && create !== 1) {
14224               self.if_(
14225                 self.not(self.nonComputedMember('s', ast.name)),
14226                 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
14227             }
14228             self.assign(intoId, self.nonComputedMember('s', ast.name));
14229           });
14230         }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
14231         );
14232       if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
14233         self.addEnsureSafeObject(intoId);
14234       }
14235       recursionFn(intoId);
14236       break;
14237     case AST.MemberExpression:
14238       left = nameId && (nameId.context = this.nextId()) || this.nextId();
14239       intoId = intoId || this.nextId();
14240       self.recurse(ast.object, left, undefined, function() {
14241         self.if_(self.notNull(left), function() {
14242           if (create && create !== 1) {
14243             self.addEnsureSafeAssignContext(left);
14244           }
14245           if (ast.computed) {
14246             right = self.nextId();
14247             self.recurse(ast.property, right);
14248             self.getStringValue(right);
14249             self.addEnsureSafeMemberName(right);
14250             if (create && create !== 1) {
14251               self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
14252             }
14253             expression = self.ensureSafeObject(self.computedMember(left, right));
14254             self.assign(intoId, expression);
14255             if (nameId) {
14256               nameId.computed = true;
14257               nameId.name = right;
14258             }
14259           } else {
14260             ensureSafeMemberName(ast.property.name);
14261             if (create && create !== 1) {
14262               self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
14263             }
14264             expression = self.nonComputedMember(left, ast.property.name);
14265             if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
14266               expression = self.ensureSafeObject(expression);
14267             }
14268             self.assign(intoId, expression);
14269             if (nameId) {
14270               nameId.computed = false;
14271               nameId.name = ast.property.name;
14272             }
14273           }
14274         }, function() {
14275           self.assign(intoId, 'undefined');
14276         });
14277         recursionFn(intoId);
14278       }, !!create);
14279       break;
14280     case AST.CallExpression:
14281       intoId = intoId || this.nextId();
14282       if (ast.filter) {
14283         right = self.filter(ast.callee.name);
14284         args = [];
14285         forEach(ast.arguments, function(expr) {
14286           var argument = self.nextId();
14287           self.recurse(expr, argument);
14288           args.push(argument);
14289         });
14290         expression = right + '(' + args.join(',') + ')';
14291         self.assign(intoId, expression);
14292         recursionFn(intoId);
14293       } else {
14294         right = self.nextId();
14295         left = {};
14296         args = [];
14297         self.recurse(ast.callee, right, left, function() {
14298           self.if_(self.notNull(right), function() {
14299             self.addEnsureSafeFunction(right);
14300             forEach(ast.arguments, function(expr) {
14301               self.recurse(expr, self.nextId(), undefined, function(argument) {
14302                 args.push(self.ensureSafeObject(argument));
14303               });
14304             });
14305             if (left.name) {
14306               if (!self.state.expensiveChecks) {
14307                 self.addEnsureSafeObject(left.context);
14308               }
14309               expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
14310             } else {
14311               expression = right + '(' + args.join(',') + ')';
14312             }
14313             expression = self.ensureSafeObject(expression);
14314             self.assign(intoId, expression);
14315           }, function() {
14316             self.assign(intoId, 'undefined');
14317           });
14318           recursionFn(intoId);
14319         });
14320       }
14321       break;
14322     case AST.AssignmentExpression:
14323       right = this.nextId();
14324       left = {};
14325       if (!isAssignable(ast.left)) {
14326         throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
14327       }
14328       this.recurse(ast.left, undefined, left, function() {
14329         self.if_(self.notNull(left.context), function() {
14330           self.recurse(ast.right, right);
14331           self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
14332           self.addEnsureSafeAssignContext(left.context);
14333           expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
14334           self.assign(intoId, expression);
14335           recursionFn(intoId || expression);
14336         });
14337       }, 1);
14338       break;
14339     case AST.ArrayExpression:
14340       args = [];
14341       forEach(ast.elements, function(expr) {
14342         self.recurse(expr, self.nextId(), undefined, function(argument) {
14343           args.push(argument);
14344         });
14345       });
14346       expression = '[' + args.join(',') + ']';
14347       this.assign(intoId, expression);
14348       recursionFn(expression);
14349       break;
14350     case AST.ObjectExpression:
14351       args = [];
14352       forEach(ast.properties, function(property) {
14353         self.recurse(property.value, self.nextId(), undefined, function(expr) {
14354           args.push(self.escape(
14355               property.key.type === AST.Identifier ? property.key.name :
14356                 ('' + property.key.value)) +
14357               ':' + expr);
14358         });
14359       });
14360       expression = '{' + args.join(',') + '}';
14361       this.assign(intoId, expression);
14362       recursionFn(expression);
14363       break;
14364     case AST.ThisExpression:
14365       this.assign(intoId, 's');
14366       recursionFn('s');
14367       break;
14368     case AST.LocalsExpression:
14369       this.assign(intoId, 'l');
14370       recursionFn('l');
14371       break;
14372     case AST.NGValueParameter:
14373       this.assign(intoId, 'v');
14374       recursionFn('v');
14375       break;
14376     }
14377   },
14378
14379   getHasOwnProperty: function(element, property) {
14380     var key = element + '.' + property;
14381     var own = this.current().own;
14382     if (!own.hasOwnProperty(key)) {
14383       own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
14384     }
14385     return own[key];
14386   },
14387
14388   assign: function(id, value) {
14389     if (!id) return;
14390     this.current().body.push(id, '=', value, ';');
14391     return id;
14392   },
14393
14394   filter: function(filterName) {
14395     if (!this.state.filters.hasOwnProperty(filterName)) {
14396       this.state.filters[filterName] = this.nextId(true);
14397     }
14398     return this.state.filters[filterName];
14399   },
14400
14401   ifDefined: function(id, defaultValue) {
14402     return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
14403   },
14404
14405   plus: function(left, right) {
14406     return 'plus(' + left + ',' + right + ')';
14407   },
14408
14409   return_: function(id) {
14410     this.current().body.push('return ', id, ';');
14411   },
14412
14413   if_: function(test, alternate, consequent) {
14414     if (test === true) {
14415       alternate();
14416     } else {
14417       var body = this.current().body;
14418       body.push('if(', test, '){');
14419       alternate();
14420       body.push('}');
14421       if (consequent) {
14422         body.push('else{');
14423         consequent();
14424         body.push('}');
14425       }
14426     }
14427   },
14428
14429   not: function(expression) {
14430     return '!(' + expression + ')';
14431   },
14432
14433   notNull: function(expression) {
14434     return expression + '!=null';
14435   },
14436
14437   nonComputedMember: function(left, right) {
14438     return left + '.' + right;
14439   },
14440
14441   computedMember: function(left, right) {
14442     return left + '[' + right + ']';
14443   },
14444
14445   member: function(left, right, computed) {
14446     if (computed) return this.computedMember(left, right);
14447     return this.nonComputedMember(left, right);
14448   },
14449
14450   addEnsureSafeObject: function(item) {
14451     this.current().body.push(this.ensureSafeObject(item), ';');
14452   },
14453
14454   addEnsureSafeMemberName: function(item) {
14455     this.current().body.push(this.ensureSafeMemberName(item), ';');
14456   },
14457
14458   addEnsureSafeFunction: function(item) {
14459     this.current().body.push(this.ensureSafeFunction(item), ';');
14460   },
14461
14462   addEnsureSafeAssignContext: function(item) {
14463     this.current().body.push(this.ensureSafeAssignContext(item), ';');
14464   },
14465
14466   ensureSafeObject: function(item) {
14467     return 'ensureSafeObject(' + item + ',text)';
14468   },
14469
14470   ensureSafeMemberName: function(item) {
14471     return 'ensureSafeMemberName(' + item + ',text)';
14472   },
14473
14474   ensureSafeFunction: function(item) {
14475     return 'ensureSafeFunction(' + item + ',text)';
14476   },
14477
14478   getStringValue: function(item) {
14479     this.assign(item, 'getStringValue(' + item + ')');
14480   },
14481
14482   ensureSafeAssignContext: function(item) {
14483     return 'ensureSafeAssignContext(' + item + ',text)';
14484   },
14485
14486   lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
14487     var self = this;
14488     return function() {
14489       self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
14490     };
14491   },
14492
14493   lazyAssign: function(id, value) {
14494     var self = this;
14495     return function() {
14496       self.assign(id, value);
14497     };
14498   },
14499
14500   stringEscapeRegex: /[^ a-zA-Z0-9]/g,
14501
14502   stringEscapeFn: function(c) {
14503     return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
14504   },
14505
14506   escape: function(value) {
14507     if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
14508     if (isNumber(value)) return value.toString();
14509     if (value === true) return 'true';
14510     if (value === false) return 'false';
14511     if (value === null) return 'null';
14512     if (typeof value === 'undefined') return 'undefined';
14513
14514     throw $parseMinErr('esc', 'IMPOSSIBLE');
14515   },
14516
14517   nextId: function(skip, init) {
14518     var id = 'v' + (this.state.nextId++);
14519     if (!skip) {
14520       this.current().vars.push(id + (init ? '=' + init : ''));
14521     }
14522     return id;
14523   },
14524
14525   current: function() {
14526     return this.state[this.state.computing];
14527   }
14528 };
14529
14530
14531 function ASTInterpreter(astBuilder, $filter) {
14532   this.astBuilder = astBuilder;
14533   this.$filter = $filter;
14534 }
14535
14536 ASTInterpreter.prototype = {
14537   compile: function(expression, expensiveChecks) {
14538     var self = this;
14539     var ast = this.astBuilder.ast(expression);
14540     this.expression = expression;
14541     this.expensiveChecks = expensiveChecks;
14542     findConstantAndWatchExpressions(ast, self.$filter);
14543     var assignable;
14544     var assign;
14545     if ((assignable = assignableAST(ast))) {
14546       assign = this.recurse(assignable);
14547     }
14548     var toWatch = getInputs(ast.body);
14549     var inputs;
14550     if (toWatch) {
14551       inputs = [];
14552       forEach(toWatch, function(watch, key) {
14553         var input = self.recurse(watch);
14554         watch.input = input;
14555         inputs.push(input);
14556         watch.watchId = key;
14557       });
14558     }
14559     var expressions = [];
14560     forEach(ast.body, function(expression) {
14561       expressions.push(self.recurse(expression.expression));
14562     });
14563     var fn = ast.body.length === 0 ? function() {} :
14564              ast.body.length === 1 ? expressions[0] :
14565              function(scope, locals) {
14566                var lastValue;
14567                forEach(expressions, function(exp) {
14568                  lastValue = exp(scope, locals);
14569                });
14570                return lastValue;
14571              };
14572     if (assign) {
14573       fn.assign = function(scope, value, locals) {
14574         return assign(scope, locals, value);
14575       };
14576     }
14577     if (inputs) {
14578       fn.inputs = inputs;
14579     }
14580     fn.literal = isLiteral(ast);
14581     fn.constant = isConstant(ast);
14582     return fn;
14583   },
14584
14585   recurse: function(ast, context, create) {
14586     var left, right, self = this, args, expression;
14587     if (ast.input) {
14588       return this.inputs(ast.input, ast.watchId);
14589     }
14590     switch (ast.type) {
14591     case AST.Literal:
14592       return this.value(ast.value, context);
14593     case AST.UnaryExpression:
14594       right = this.recurse(ast.argument);
14595       return this['unary' + ast.operator](right, context);
14596     case AST.BinaryExpression:
14597       left = this.recurse(ast.left);
14598       right = this.recurse(ast.right);
14599       return this['binary' + ast.operator](left, right, context);
14600     case AST.LogicalExpression:
14601       left = this.recurse(ast.left);
14602       right = this.recurse(ast.right);
14603       return this['binary' + ast.operator](left, right, context);
14604     case AST.ConditionalExpression:
14605       return this['ternary?:'](
14606         this.recurse(ast.test),
14607         this.recurse(ast.alternate),
14608         this.recurse(ast.consequent),
14609         context
14610       );
14611     case AST.Identifier:
14612       ensureSafeMemberName(ast.name, self.expression);
14613       return self.identifier(ast.name,
14614                              self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
14615                              context, create, self.expression);
14616     case AST.MemberExpression:
14617       left = this.recurse(ast.object, false, !!create);
14618       if (!ast.computed) {
14619         ensureSafeMemberName(ast.property.name, self.expression);
14620         right = ast.property.name;
14621       }
14622       if (ast.computed) right = this.recurse(ast.property);
14623       return ast.computed ?
14624         this.computedMember(left, right, context, create, self.expression) :
14625         this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
14626     case AST.CallExpression:
14627       args = [];
14628       forEach(ast.arguments, function(expr) {
14629         args.push(self.recurse(expr));
14630       });
14631       if (ast.filter) right = this.$filter(ast.callee.name);
14632       if (!ast.filter) right = this.recurse(ast.callee, true);
14633       return ast.filter ?
14634         function(scope, locals, assign, inputs) {
14635           var values = [];
14636           for (var i = 0; i < args.length; ++i) {
14637             values.push(args[i](scope, locals, assign, inputs));
14638           }
14639           var value = right.apply(undefined, values, inputs);
14640           return context ? {context: undefined, name: undefined, value: value} : value;
14641         } :
14642         function(scope, locals, assign, inputs) {
14643           var rhs = right(scope, locals, assign, inputs);
14644           var value;
14645           if (rhs.value != null) {
14646             ensureSafeObject(rhs.context, self.expression);
14647             ensureSafeFunction(rhs.value, self.expression);
14648             var values = [];
14649             for (var i = 0; i < args.length; ++i) {
14650               values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
14651             }
14652             value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
14653           }
14654           return context ? {value: value} : value;
14655         };
14656     case AST.AssignmentExpression:
14657       left = this.recurse(ast.left, true, 1);
14658       right = this.recurse(ast.right);
14659       return function(scope, locals, assign, inputs) {
14660         var lhs = left(scope, locals, assign, inputs);
14661         var rhs = right(scope, locals, assign, inputs);
14662         ensureSafeObject(lhs.value, self.expression);
14663         ensureSafeAssignContext(lhs.context);
14664         lhs.context[lhs.name] = rhs;
14665         return context ? {value: rhs} : rhs;
14666       };
14667     case AST.ArrayExpression:
14668       args = [];
14669       forEach(ast.elements, function(expr) {
14670         args.push(self.recurse(expr));
14671       });
14672       return function(scope, locals, assign, inputs) {
14673         var value = [];
14674         for (var i = 0; i < args.length; ++i) {
14675           value.push(args[i](scope, locals, assign, inputs));
14676         }
14677         return context ? {value: value} : value;
14678       };
14679     case AST.ObjectExpression:
14680       args = [];
14681       forEach(ast.properties, function(property) {
14682         args.push({key: property.key.type === AST.Identifier ?
14683                         property.key.name :
14684                         ('' + property.key.value),
14685                    value: self.recurse(property.value)
14686         });
14687       });
14688       return function(scope, locals, assign, inputs) {
14689         var value = {};
14690         for (var i = 0; i < args.length; ++i) {
14691           value[args[i].key] = args[i].value(scope, locals, assign, inputs);
14692         }
14693         return context ? {value: value} : value;
14694       };
14695     case AST.ThisExpression:
14696       return function(scope) {
14697         return context ? {value: scope} : scope;
14698       };
14699     case AST.LocalsExpression:
14700       return function(scope, locals) {
14701         return context ? {value: locals} : locals;
14702       };
14703     case AST.NGValueParameter:
14704       return function(scope, locals, assign, inputs) {
14705         return context ? {value: assign} : assign;
14706       };
14707     }
14708   },
14709
14710   'unary+': function(argument, context) {
14711     return function(scope, locals, assign, inputs) {
14712       var arg = argument(scope, locals, assign, inputs);
14713       if (isDefined(arg)) {
14714         arg = +arg;
14715       } else {
14716         arg = 0;
14717       }
14718       return context ? {value: arg} : arg;
14719     };
14720   },
14721   'unary-': function(argument, context) {
14722     return function(scope, locals, assign, inputs) {
14723       var arg = argument(scope, locals, assign, inputs);
14724       if (isDefined(arg)) {
14725         arg = -arg;
14726       } else {
14727         arg = 0;
14728       }
14729       return context ? {value: arg} : arg;
14730     };
14731   },
14732   'unary!': function(argument, context) {
14733     return function(scope, locals, assign, inputs) {
14734       var arg = !argument(scope, locals, assign, inputs);
14735       return context ? {value: arg} : arg;
14736     };
14737   },
14738   'binary+': function(left, right, context) {
14739     return function(scope, locals, assign, inputs) {
14740       var lhs = left(scope, locals, assign, inputs);
14741       var rhs = right(scope, locals, assign, inputs);
14742       var arg = plusFn(lhs, rhs);
14743       return context ? {value: arg} : arg;
14744     };
14745   },
14746   'binary-': function(left, right, context) {
14747     return function(scope, locals, assign, inputs) {
14748       var lhs = left(scope, locals, assign, inputs);
14749       var rhs = right(scope, locals, assign, inputs);
14750       var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
14751       return context ? {value: arg} : arg;
14752     };
14753   },
14754   'binary*': function(left, right, context) {
14755     return function(scope, locals, assign, inputs) {
14756       var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
14757       return context ? {value: arg} : arg;
14758     };
14759   },
14760   'binary/': function(left, right, context) {
14761     return function(scope, locals, assign, inputs) {
14762       var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
14763       return context ? {value: arg} : arg;
14764     };
14765   },
14766   'binary%': function(left, right, context) {
14767     return function(scope, locals, assign, inputs) {
14768       var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
14769       return context ? {value: arg} : arg;
14770     };
14771   },
14772   'binary===': function(left, right, context) {
14773     return function(scope, locals, assign, inputs) {
14774       var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
14775       return context ? {value: arg} : arg;
14776     };
14777   },
14778   'binary!==': function(left, right, context) {
14779     return function(scope, locals, assign, inputs) {
14780       var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
14781       return context ? {value: arg} : arg;
14782     };
14783   },
14784   'binary==': function(left, right, context) {
14785     return function(scope, locals, assign, inputs) {
14786       var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
14787       return context ? {value: arg} : arg;
14788     };
14789   },
14790   'binary!=': function(left, right, context) {
14791     return function(scope, locals, assign, inputs) {
14792       var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
14793       return context ? {value: arg} : arg;
14794     };
14795   },
14796   'binary<': function(left, right, context) {
14797     return function(scope, locals, assign, inputs) {
14798       var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
14799       return context ? {value: arg} : arg;
14800     };
14801   },
14802   'binary>': function(left, right, context) {
14803     return function(scope, locals, assign, inputs) {
14804       var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
14805       return context ? {value: arg} : arg;
14806     };
14807   },
14808   'binary<=': function(left, right, context) {
14809     return function(scope, locals, assign, inputs) {
14810       var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
14811       return context ? {value: arg} : arg;
14812     };
14813   },
14814   'binary>=': function(left, right, context) {
14815     return function(scope, locals, assign, inputs) {
14816       var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
14817       return context ? {value: arg} : arg;
14818     };
14819   },
14820   'binary&&': function(left, right, context) {
14821     return function(scope, locals, assign, inputs) {
14822       var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
14823       return context ? {value: arg} : arg;
14824     };
14825   },
14826   'binary||': function(left, right, context) {
14827     return function(scope, locals, assign, inputs) {
14828       var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
14829       return context ? {value: arg} : arg;
14830     };
14831   },
14832   'ternary?:': function(test, alternate, consequent, context) {
14833     return function(scope, locals, assign, inputs) {
14834       var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
14835       return context ? {value: arg} : arg;
14836     };
14837   },
14838   value: function(value, context) {
14839     return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
14840   },
14841   identifier: function(name, expensiveChecks, context, create, expression) {
14842     return function(scope, locals, assign, inputs) {
14843       var base = locals && (name in locals) ? locals : scope;
14844       if (create && create !== 1 && base && !(base[name])) {
14845         base[name] = {};
14846       }
14847       var value = base ? base[name] : undefined;
14848       if (expensiveChecks) {
14849         ensureSafeObject(value, expression);
14850       }
14851       if (context) {
14852         return {context: base, name: name, value: value};
14853       } else {
14854         return value;
14855       }
14856     };
14857   },
14858   computedMember: function(left, right, context, create, expression) {
14859     return function(scope, locals, assign, inputs) {
14860       var lhs = left(scope, locals, assign, inputs);
14861       var rhs;
14862       var value;
14863       if (lhs != null) {
14864         rhs = right(scope, locals, assign, inputs);
14865         rhs = getStringValue(rhs);
14866         ensureSafeMemberName(rhs, expression);
14867         if (create && create !== 1) {
14868           ensureSafeAssignContext(lhs);
14869           if (lhs && !(lhs[rhs])) {
14870             lhs[rhs] = {};
14871           }
14872         }
14873         value = lhs[rhs];
14874         ensureSafeObject(value, expression);
14875       }
14876       if (context) {
14877         return {context: lhs, name: rhs, value: value};
14878       } else {
14879         return value;
14880       }
14881     };
14882   },
14883   nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
14884     return function(scope, locals, assign, inputs) {
14885       var lhs = left(scope, locals, assign, inputs);
14886       if (create && create !== 1) {
14887         ensureSafeAssignContext(lhs);
14888         if (lhs && !(lhs[right])) {
14889           lhs[right] = {};
14890         }
14891       }
14892       var value = lhs != null ? lhs[right] : undefined;
14893       if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
14894         ensureSafeObject(value, expression);
14895       }
14896       if (context) {
14897         return {context: lhs, name: right, value: value};
14898       } else {
14899         return value;
14900       }
14901     };
14902   },
14903   inputs: function(input, watchId) {
14904     return function(scope, value, locals, inputs) {
14905       if (inputs) return inputs[watchId];
14906       return input(scope, value, locals);
14907     };
14908   }
14909 };
14910
14911 /**
14912  * @constructor
14913  */
14914 var Parser = function(lexer, $filter, options) {
14915   this.lexer = lexer;
14916   this.$filter = $filter;
14917   this.options = options;
14918   this.ast = new AST(this.lexer);
14919   this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
14920                                    new ASTCompiler(this.ast, $filter);
14921 };
14922
14923 Parser.prototype = {
14924   constructor: Parser,
14925
14926   parse: function(text) {
14927     return this.astCompiler.compile(text, this.options.expensiveChecks);
14928   }
14929 };
14930
14931 function isPossiblyDangerousMemberName(name) {
14932   return name == 'constructor';
14933 }
14934
14935 var objectValueOf = Object.prototype.valueOf;
14936
14937 function getValueOf(value) {
14938   return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
14939 }
14940
14941 ///////////////////////////////////
14942
14943 /**
14944  * @ngdoc service
14945  * @name $parse
14946  * @kind function
14947  *
14948  * @description
14949  *
14950  * Converts Angular {@link guide/expression expression} into a function.
14951  *
14952  * ```js
14953  *   var getter = $parse('user.name');
14954  *   var setter = getter.assign;
14955  *   var context = {user:{name:'angular'}};
14956  *   var locals = {user:{name:'local'}};
14957  *
14958  *   expect(getter(context)).toEqual('angular');
14959  *   setter(context, 'newValue');
14960  *   expect(context.user.name).toEqual('newValue');
14961  *   expect(getter(context, locals)).toEqual('local');
14962  * ```
14963  *
14964  *
14965  * @param {string} expression String expression to compile.
14966  * @returns {function(context, locals)} a function which represents the compiled expression:
14967  *
14968  *    * `context` – `{object}` – an object against which any expressions embedded in the strings
14969  *      are evaluated against (typically a scope object).
14970  *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
14971  *      `context`.
14972  *
14973  *    The returned function also has the following properties:
14974  *      * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
14975  *        literal.
14976  *      * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
14977  *        constant literals.
14978  *      * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
14979  *        set to a function to change its value on the given context.
14980  *
14981  */
14982
14983
14984 /**
14985  * @ngdoc provider
14986  * @name $parseProvider
14987  *
14988  * @description
14989  * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
14990  *  service.
14991  */
14992 function $ParseProvider() {
14993   var cacheDefault = createMap();
14994   var cacheExpensive = createMap();
14995
14996   this.$get = ['$filter', function($filter) {
14997     var noUnsafeEval = csp().noUnsafeEval;
14998     var $parseOptions = {
14999           csp: noUnsafeEval,
15000           expensiveChecks: false
15001         },
15002         $parseOptionsExpensive = {
15003           csp: noUnsafeEval,
15004           expensiveChecks: true
15005         };
15006     var runningChecksEnabled = false;
15007
15008     $parse.$$runningExpensiveChecks = function() {
15009       return runningChecksEnabled;
15010     };
15011
15012     return $parse;
15013
15014     function $parse(exp, interceptorFn, expensiveChecks) {
15015       var parsedExpression, oneTime, cacheKey;
15016
15017       expensiveChecks = expensiveChecks || runningChecksEnabled;
15018
15019       switch (typeof exp) {
15020         case 'string':
15021           exp = exp.trim();
15022           cacheKey = exp;
15023
15024           var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
15025           parsedExpression = cache[cacheKey];
15026
15027           if (!parsedExpression) {
15028             if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
15029               oneTime = true;
15030               exp = exp.substring(2);
15031             }
15032             var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
15033             var lexer = new Lexer(parseOptions);
15034             var parser = new Parser(lexer, $filter, parseOptions);
15035             parsedExpression = parser.parse(exp);
15036             if (parsedExpression.constant) {
15037               parsedExpression.$$watchDelegate = constantWatchDelegate;
15038             } else if (oneTime) {
15039               parsedExpression.$$watchDelegate = parsedExpression.literal ?
15040                   oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
15041             } else if (parsedExpression.inputs) {
15042               parsedExpression.$$watchDelegate = inputsWatchDelegate;
15043             }
15044             if (expensiveChecks) {
15045               parsedExpression = expensiveChecksInterceptor(parsedExpression);
15046             }
15047             cache[cacheKey] = parsedExpression;
15048           }
15049           return addInterceptor(parsedExpression, interceptorFn);
15050
15051         case 'function':
15052           return addInterceptor(exp, interceptorFn);
15053
15054         default:
15055           return addInterceptor(noop, interceptorFn);
15056       }
15057     }
15058
15059     function expensiveChecksInterceptor(fn) {
15060       if (!fn) return fn;
15061       expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
15062       expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
15063       expensiveCheckFn.constant = fn.constant;
15064       expensiveCheckFn.literal = fn.literal;
15065       for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
15066         fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
15067       }
15068       expensiveCheckFn.inputs = fn.inputs;
15069
15070       return expensiveCheckFn;
15071
15072       function expensiveCheckFn(scope, locals, assign, inputs) {
15073         var expensiveCheckOldValue = runningChecksEnabled;
15074         runningChecksEnabled = true;
15075         try {
15076           return fn(scope, locals, assign, inputs);
15077         } finally {
15078           runningChecksEnabled = expensiveCheckOldValue;
15079         }
15080       }
15081     }
15082
15083     function expressionInputDirtyCheck(newValue, oldValueOfValue) {
15084
15085       if (newValue == null || oldValueOfValue == null) { // null/undefined
15086         return newValue === oldValueOfValue;
15087       }
15088
15089       if (typeof newValue === 'object') {
15090
15091         // attempt to convert the value to a primitive type
15092         // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
15093         //             be cheaply dirty-checked
15094         newValue = getValueOf(newValue);
15095
15096         if (typeof newValue === 'object') {
15097           // objects/arrays are not supported - deep-watching them would be too expensive
15098           return false;
15099         }
15100
15101         // fall-through to the primitive equality check
15102       }
15103
15104       //Primitive or NaN
15105       return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
15106     }
15107
15108     function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
15109       var inputExpressions = parsedExpression.inputs;
15110       var lastResult;
15111
15112       if (inputExpressions.length === 1) {
15113         var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
15114         inputExpressions = inputExpressions[0];
15115         return scope.$watch(function expressionInputWatch(scope) {
15116           var newInputValue = inputExpressions(scope);
15117           if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
15118             lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
15119             oldInputValueOf = newInputValue && getValueOf(newInputValue);
15120           }
15121           return lastResult;
15122         }, listener, objectEquality, prettyPrintExpression);
15123       }
15124
15125       var oldInputValueOfValues = [];
15126       var oldInputValues = [];
15127       for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
15128         oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
15129         oldInputValues[i] = null;
15130       }
15131
15132       return scope.$watch(function expressionInputsWatch(scope) {
15133         var changed = false;
15134
15135         for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
15136           var newInputValue = inputExpressions[i](scope);
15137           if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
15138             oldInputValues[i] = newInputValue;
15139             oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
15140           }
15141         }
15142
15143         if (changed) {
15144           lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
15145         }
15146
15147         return lastResult;
15148       }, listener, objectEquality, prettyPrintExpression);
15149     }
15150
15151     function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
15152       var unwatch, lastValue;
15153       return unwatch = scope.$watch(function oneTimeWatch(scope) {
15154         return parsedExpression(scope);
15155       }, function oneTimeListener(value, old, scope) {
15156         lastValue = value;
15157         if (isFunction(listener)) {
15158           listener.apply(this, arguments);
15159         }
15160         if (isDefined(value)) {
15161           scope.$$postDigest(function() {
15162             if (isDefined(lastValue)) {
15163               unwatch();
15164             }
15165           });
15166         }
15167       }, objectEquality);
15168     }
15169
15170     function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
15171       var unwatch, lastValue;
15172       return unwatch = scope.$watch(function oneTimeWatch(scope) {
15173         return parsedExpression(scope);
15174       }, function oneTimeListener(value, old, scope) {
15175         lastValue = value;
15176         if (isFunction(listener)) {
15177           listener.call(this, value, old, scope);
15178         }
15179         if (isAllDefined(value)) {
15180           scope.$$postDigest(function() {
15181             if (isAllDefined(lastValue)) unwatch();
15182           });
15183         }
15184       }, objectEquality);
15185
15186       function isAllDefined(value) {
15187         var allDefined = true;
15188         forEach(value, function(val) {
15189           if (!isDefined(val)) allDefined = false;
15190         });
15191         return allDefined;
15192       }
15193     }
15194
15195     function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
15196       var unwatch;
15197       return unwatch = scope.$watch(function constantWatch(scope) {
15198         unwatch();
15199         return parsedExpression(scope);
15200       }, listener, objectEquality);
15201     }
15202
15203     function addInterceptor(parsedExpression, interceptorFn) {
15204       if (!interceptorFn) return parsedExpression;
15205       var watchDelegate = parsedExpression.$$watchDelegate;
15206       var useInputs = false;
15207
15208       var regularWatch =
15209           watchDelegate !== oneTimeLiteralWatchDelegate &&
15210           watchDelegate !== oneTimeWatchDelegate;
15211
15212       var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
15213         var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
15214         return interceptorFn(value, scope, locals);
15215       } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
15216         var value = parsedExpression(scope, locals, assign, inputs);
15217         var result = interceptorFn(value, scope, locals);
15218         // we only return the interceptor's result if the
15219         // initial value is defined (for bind-once)
15220         return isDefined(value) ? result : value;
15221       };
15222
15223       // Propagate $$watchDelegates other then inputsWatchDelegate
15224       if (parsedExpression.$$watchDelegate &&
15225           parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
15226         fn.$$watchDelegate = parsedExpression.$$watchDelegate;
15227       } else if (!interceptorFn.$stateful) {
15228         // If there is an interceptor, but no watchDelegate then treat the interceptor like
15229         // we treat filters - it is assumed to be a pure function unless flagged with $stateful
15230         fn.$$watchDelegate = inputsWatchDelegate;
15231         useInputs = !parsedExpression.inputs;
15232         fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
15233       }
15234
15235       return fn;
15236     }
15237   }];
15238 }
15239
15240 /**
15241  * @ngdoc service
15242  * @name $q
15243  * @requires $rootScope
15244  *
15245  * @description
15246  * A service that helps you run functions asynchronously, and use their return values (or exceptions)
15247  * when they are done processing.
15248  *
15249  * This is an implementation of promises/deferred objects inspired by
15250  * [Kris Kowal's Q](https://github.com/kriskowal/q).
15251  *
15252  * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
15253  * implementations, and the other which resembles ES6 promises to some degree.
15254  *
15255  * # $q constructor
15256  *
15257  * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
15258  * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
15259  * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
15260  *
15261  * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
15262  * available yet.
15263  *
15264  * It can be used like so:
15265  *
15266  * ```js
15267  *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`
15268  *   // are available in the current lexical scope (they could have been injected or passed in).
15269  *
15270  *   function asyncGreet(name) {
15271  *     // perform some asynchronous operation, resolve or reject the promise when appropriate.
15272  *     return $q(function(resolve, reject) {
15273  *       setTimeout(function() {
15274  *         if (okToGreet(name)) {
15275  *           resolve('Hello, ' + name + '!');
15276  *         } else {
15277  *           reject('Greeting ' + name + ' is not allowed.');
15278  *         }
15279  *       }, 1000);
15280  *     });
15281  *   }
15282  *
15283  *   var promise = asyncGreet('Robin Hood');
15284  *   promise.then(function(greeting) {
15285  *     alert('Success: ' + greeting);
15286  *   }, function(reason) {
15287  *     alert('Failed: ' + reason);
15288  *   });
15289  * ```
15290  *
15291  * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
15292  *
15293  * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
15294  *
15295  * However, the more traditional CommonJS-style usage is still available, and documented below.
15296  *
15297  * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
15298  * interface for interacting with an object that represents the result of an action that is
15299  * performed asynchronously, and may or may not be finished at any given point in time.
15300  *
15301  * From the perspective of dealing with error handling, deferred and promise APIs are to
15302  * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
15303  *
15304  * ```js
15305  *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`
15306  *   // are available in the current lexical scope (they could have been injected or passed in).
15307  *
15308  *   function asyncGreet(name) {
15309  *     var deferred = $q.defer();
15310  *
15311  *     setTimeout(function() {
15312  *       deferred.notify('About to greet ' + name + '.');
15313  *
15314  *       if (okToGreet(name)) {
15315  *         deferred.resolve('Hello, ' + name + '!');
15316  *       } else {
15317  *         deferred.reject('Greeting ' + name + ' is not allowed.');
15318  *       }
15319  *     }, 1000);
15320  *
15321  *     return deferred.promise;
15322  *   }
15323  *
15324  *   var promise = asyncGreet('Robin Hood');
15325  *   promise.then(function(greeting) {
15326  *     alert('Success: ' + greeting);
15327  *   }, function(reason) {
15328  *     alert('Failed: ' + reason);
15329  *   }, function(update) {
15330  *     alert('Got notification: ' + update);
15331  *   });
15332  * ```
15333  *
15334  * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
15335  * comes in the way of guarantees that promise and deferred APIs make, see
15336  * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
15337  *
15338  * Additionally the promise api allows for composition that is very hard to do with the
15339  * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
15340  * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
15341  * section on serial or parallel joining of promises.
15342  *
15343  * # The Deferred API
15344  *
15345  * A new instance of deferred is constructed by calling `$q.defer()`.
15346  *
15347  * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
15348  * that can be used for signaling the successful or unsuccessful completion, as well as the status
15349  * of the task.
15350  *
15351  * **Methods**
15352  *
15353  * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
15354  *   constructed via `$q.reject`, the promise will be rejected instead.
15355  * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
15356  *   resolving it with a rejection constructed via `$q.reject`.
15357  * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
15358  *   multiple times before the promise is either resolved or rejected.
15359  *
15360  * **Properties**
15361  *
15362  * - promise – `{Promise}` – promise object associated with this deferred.
15363  *
15364  *
15365  * # The Promise API
15366  *
15367  * A new promise instance is created when a deferred instance is created and can be retrieved by
15368  * calling `deferred.promise`.
15369  *
15370  * The purpose of the promise object is to allow for interested parties to get access to the result
15371  * of the deferred task when it completes.
15372  *
15373  * **Methods**
15374  *
15375  * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
15376  *   will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
15377  *   as soon as the result is available. The callbacks are called with a single argument: the result
15378  *   or rejection reason. Additionally, the notify callback may be called zero or more times to
15379  *   provide a progress indication, before the promise is resolved or rejected.
15380  *
15381  *   This method *returns a new promise* which is resolved or rejected via the return value of the
15382  *   `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
15383  *   with the value which is resolved in that promise using
15384  *   [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
15385  *   It also notifies via the return value of the `notifyCallback` method. The promise cannot be
15386  *   resolved or rejected from the notifyCallback method.
15387  *
15388  * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
15389  *
15390  * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
15391  *   but to do so without modifying the final value. This is useful to release resources or do some
15392  *   clean-up that needs to be done whether the promise was rejected or resolved. See the [full
15393  *   specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
15394  *   more information.
15395  *
15396  * # Chaining promises
15397  *
15398  * Because calling the `then` method of a promise returns a new derived promise, it is easily
15399  * possible to create a chain of promises:
15400  *
15401  * ```js
15402  *   promiseB = promiseA.then(function(result) {
15403  *     return result + 1;
15404  *   });
15405  *
15406  *   // promiseB will be resolved immediately after promiseA is resolved and its value
15407  *   // will be the result of promiseA incremented by 1
15408  * ```
15409  *
15410  * It is possible to create chains of any length and since a promise can be resolved with another
15411  * promise (which will defer its resolution further), it is possible to pause/defer resolution of
15412  * the promises at any point in the chain. This makes it possible to implement powerful APIs like
15413  * $http's response interceptors.
15414  *
15415  *
15416  * # Differences between Kris Kowal's Q and $q
15417  *
15418  *  There are two main differences:
15419  *
15420  * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
15421  *   mechanism in angular, which means faster propagation of resolution or rejection into your
15422  *   models and avoiding unnecessary browser repaints, which would result in flickering UI.
15423  * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
15424  *   all the important functionality needed for common async tasks.
15425  *
15426  *  # Testing
15427  *
15428  *  ```js
15429  *    it('should simulate promise', inject(function($q, $rootScope) {
15430  *      var deferred = $q.defer();
15431  *      var promise = deferred.promise;
15432  *      var resolvedValue;
15433  *
15434  *      promise.then(function(value) { resolvedValue = value; });
15435  *      expect(resolvedValue).toBeUndefined();
15436  *
15437  *      // Simulate resolving of promise
15438  *      deferred.resolve(123);
15439  *      // Note that the 'then' function does not get called synchronously.
15440  *      // This is because we want the promise API to always be async, whether or not
15441  *      // it got called synchronously or asynchronously.
15442  *      expect(resolvedValue).toBeUndefined();
15443  *
15444  *      // Propagate promise resolution to 'then' functions using $apply().
15445  *      $rootScope.$apply();
15446  *      expect(resolvedValue).toEqual(123);
15447  *    }));
15448  *  ```
15449  *
15450  * @param {function(function, function)} resolver Function which is responsible for resolving or
15451  *   rejecting the newly created promise. The first parameter is a function which resolves the
15452  *   promise, the second parameter is a function which rejects the promise.
15453  *
15454  * @returns {Promise} The newly created promise.
15455  */
15456 function $QProvider() {
15457
15458   this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
15459     return qFactory(function(callback) {
15460       $rootScope.$evalAsync(callback);
15461     }, $exceptionHandler);
15462   }];
15463 }
15464
15465 function $$QProvider() {
15466   this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
15467     return qFactory(function(callback) {
15468       $browser.defer(callback);
15469     }, $exceptionHandler);
15470   }];
15471 }
15472
15473 /**
15474  * Constructs a promise manager.
15475  *
15476  * @param {function(function)} nextTick Function for executing functions in the next turn.
15477  * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
15478  *     debugging purposes.
15479  * @returns {object} Promise manager.
15480  */
15481 function qFactory(nextTick, exceptionHandler) {
15482   var $qMinErr = minErr('$q', TypeError);
15483
15484   /**
15485    * @ngdoc method
15486    * @name ng.$q#defer
15487    * @kind function
15488    *
15489    * @description
15490    * Creates a `Deferred` object which represents a task which will finish in the future.
15491    *
15492    * @returns {Deferred} Returns a new instance of deferred.
15493    */
15494   var defer = function() {
15495     var d = new Deferred();
15496     //Necessary to support unbound execution :/
15497     d.resolve = simpleBind(d, d.resolve);
15498     d.reject = simpleBind(d, d.reject);
15499     d.notify = simpleBind(d, d.notify);
15500     return d;
15501   };
15502
15503   function Promise() {
15504     this.$$state = { status: 0 };
15505   }
15506
15507   extend(Promise.prototype, {
15508     then: function(onFulfilled, onRejected, progressBack) {
15509       if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
15510         return this;
15511       }
15512       var result = new Deferred();
15513
15514       this.$$state.pending = this.$$state.pending || [];
15515       this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
15516       if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
15517
15518       return result.promise;
15519     },
15520
15521     "catch": function(callback) {
15522       return this.then(null, callback);
15523     },
15524
15525     "finally": function(callback, progressBack) {
15526       return this.then(function(value) {
15527         return handleCallback(value, true, callback);
15528       }, function(error) {
15529         return handleCallback(error, false, callback);
15530       }, progressBack);
15531     }
15532   });
15533
15534   //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
15535   function simpleBind(context, fn) {
15536     return function(value) {
15537       fn.call(context, value);
15538     };
15539   }
15540
15541   function processQueue(state) {
15542     var fn, deferred, pending;
15543
15544     pending = state.pending;
15545     state.processScheduled = false;
15546     state.pending = undefined;
15547     for (var i = 0, ii = pending.length; i < ii; ++i) {
15548       deferred = pending[i][0];
15549       fn = pending[i][state.status];
15550       try {
15551         if (isFunction(fn)) {
15552           deferred.resolve(fn(state.value));
15553         } else if (state.status === 1) {
15554           deferred.resolve(state.value);
15555         } else {
15556           deferred.reject(state.value);
15557         }
15558       } catch (e) {
15559         deferred.reject(e);
15560         exceptionHandler(e);
15561       }
15562     }
15563   }
15564
15565   function scheduleProcessQueue(state) {
15566     if (state.processScheduled || !state.pending) return;
15567     state.processScheduled = true;
15568     nextTick(function() { processQueue(state); });
15569   }
15570
15571   function Deferred() {
15572     this.promise = new Promise();
15573   }
15574
15575   extend(Deferred.prototype, {
15576     resolve: function(val) {
15577       if (this.promise.$$state.status) return;
15578       if (val === this.promise) {
15579         this.$$reject($qMinErr(
15580           'qcycle',
15581           "Expected promise to be resolved with value other than itself '{0}'",
15582           val));
15583       } else {
15584         this.$$resolve(val);
15585       }
15586
15587     },
15588
15589     $$resolve: function(val) {
15590       var then;
15591       var that = this;
15592       var done = false;
15593       try {
15594         if ((isObject(val) || isFunction(val))) then = val && val.then;
15595         if (isFunction(then)) {
15596           this.promise.$$state.status = -1;
15597           then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
15598         } else {
15599           this.promise.$$state.value = val;
15600           this.promise.$$state.status = 1;
15601           scheduleProcessQueue(this.promise.$$state);
15602         }
15603       } catch (e) {
15604         rejectPromise(e);
15605         exceptionHandler(e);
15606       }
15607
15608       function resolvePromise(val) {
15609         if (done) return;
15610         done = true;
15611         that.$$resolve(val);
15612       }
15613       function rejectPromise(val) {
15614         if (done) return;
15615         done = true;
15616         that.$$reject(val);
15617       }
15618     },
15619
15620     reject: function(reason) {
15621       if (this.promise.$$state.status) return;
15622       this.$$reject(reason);
15623     },
15624
15625     $$reject: function(reason) {
15626       this.promise.$$state.value = reason;
15627       this.promise.$$state.status = 2;
15628       scheduleProcessQueue(this.promise.$$state);
15629     },
15630
15631     notify: function(progress) {
15632       var callbacks = this.promise.$$state.pending;
15633
15634       if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
15635         nextTick(function() {
15636           var callback, result;
15637           for (var i = 0, ii = callbacks.length; i < ii; i++) {
15638             result = callbacks[i][0];
15639             callback = callbacks[i][3];
15640             try {
15641               result.notify(isFunction(callback) ? callback(progress) : progress);
15642             } catch (e) {
15643               exceptionHandler(e);
15644             }
15645           }
15646         });
15647       }
15648     }
15649   });
15650
15651   /**
15652    * @ngdoc method
15653    * @name $q#reject
15654    * @kind function
15655    *
15656    * @description
15657    * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
15658    * used to forward rejection in a chain of promises. If you are dealing with the last promise in
15659    * a promise chain, you don't need to worry about it.
15660    *
15661    * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
15662    * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
15663    * a promise error callback and you want to forward the error to the promise derived from the
15664    * current promise, you have to "rethrow" the error by returning a rejection constructed via
15665    * `reject`.
15666    *
15667    * ```js
15668    *   promiseB = promiseA.then(function(result) {
15669    *     // success: do something and resolve promiseB
15670    *     //          with the old or a new result
15671    *     return result;
15672    *   }, function(reason) {
15673    *     // error: handle the error if possible and
15674    *     //        resolve promiseB with newPromiseOrValue,
15675    *     //        otherwise forward the rejection to promiseB
15676    *     if (canHandle(reason)) {
15677    *      // handle the error and recover
15678    *      return newPromiseOrValue;
15679    *     }
15680    *     return $q.reject(reason);
15681    *   });
15682    * ```
15683    *
15684    * @param {*} reason Constant, message, exception or an object representing the rejection reason.
15685    * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
15686    */
15687   var reject = function(reason) {
15688     var result = new Deferred();
15689     result.reject(reason);
15690     return result.promise;
15691   };
15692
15693   var makePromise = function makePromise(value, resolved) {
15694     var result = new Deferred();
15695     if (resolved) {
15696       result.resolve(value);
15697     } else {
15698       result.reject(value);
15699     }
15700     return result.promise;
15701   };
15702
15703   var handleCallback = function handleCallback(value, isResolved, callback) {
15704     var callbackOutput = null;
15705     try {
15706       if (isFunction(callback)) callbackOutput = callback();
15707     } catch (e) {
15708       return makePromise(e, false);
15709     }
15710     if (isPromiseLike(callbackOutput)) {
15711       return callbackOutput.then(function() {
15712         return makePromise(value, isResolved);
15713       }, function(error) {
15714         return makePromise(error, false);
15715       });
15716     } else {
15717       return makePromise(value, isResolved);
15718     }
15719   };
15720
15721   /**
15722    * @ngdoc method
15723    * @name $q#when
15724    * @kind function
15725    *
15726    * @description
15727    * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
15728    * This is useful when you are dealing with an object that might or might not be a promise, or if
15729    * the promise comes from a source that can't be trusted.
15730    *
15731    * @param {*} value Value or a promise
15732    * @param {Function=} successCallback
15733    * @param {Function=} errorCallback
15734    * @param {Function=} progressCallback
15735    * @returns {Promise} Returns a promise of the passed value or promise
15736    */
15737
15738
15739   var when = function(value, callback, errback, progressBack) {
15740     var result = new Deferred();
15741     result.resolve(value);
15742     return result.promise.then(callback, errback, progressBack);
15743   };
15744
15745   /**
15746    * @ngdoc method
15747    * @name $q#resolve
15748    * @kind function
15749    *
15750    * @description
15751    * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
15752    *
15753    * @param {*} value Value or a promise
15754    * @param {Function=} successCallback
15755    * @param {Function=} errorCallback
15756    * @param {Function=} progressCallback
15757    * @returns {Promise} Returns a promise of the passed value or promise
15758    */
15759   var resolve = when;
15760
15761   /**
15762    * @ngdoc method
15763    * @name $q#all
15764    * @kind function
15765    *
15766    * @description
15767    * Combines multiple promises into a single promise that is resolved when all of the input
15768    * promises are resolved.
15769    *
15770    * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
15771    * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
15772    *   each value corresponding to the promise at the same index/key in the `promises` array/hash.
15773    *   If any of the promises is resolved with a rejection, this resulting promise will be rejected
15774    *   with the same rejection value.
15775    */
15776
15777   function all(promises) {
15778     var deferred = new Deferred(),
15779         counter = 0,
15780         results = isArray(promises) ? [] : {};
15781
15782     forEach(promises, function(promise, key) {
15783       counter++;
15784       when(promise).then(function(value) {
15785         if (results.hasOwnProperty(key)) return;
15786         results[key] = value;
15787         if (!(--counter)) deferred.resolve(results);
15788       }, function(reason) {
15789         if (results.hasOwnProperty(key)) return;
15790         deferred.reject(reason);
15791       });
15792     });
15793
15794     if (counter === 0) {
15795       deferred.resolve(results);
15796     }
15797
15798     return deferred.promise;
15799   }
15800
15801   var $Q = function Q(resolver) {
15802     if (!isFunction(resolver)) {
15803       throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
15804     }
15805
15806     var deferred = new Deferred();
15807
15808     function resolveFn(value) {
15809       deferred.resolve(value);
15810     }
15811
15812     function rejectFn(reason) {
15813       deferred.reject(reason);
15814     }
15815
15816     resolver(resolveFn, rejectFn);
15817
15818     return deferred.promise;
15819   };
15820
15821   // Let's make the instanceof operator work for promises, so that
15822   // `new $q(fn) instanceof $q` would evaluate to true.
15823   $Q.prototype = Promise.prototype;
15824
15825   $Q.defer = defer;
15826   $Q.reject = reject;
15827   $Q.when = when;
15828   $Q.resolve = resolve;
15829   $Q.all = all;
15830
15831   return $Q;
15832 }
15833
15834 function $$RAFProvider() { //rAF
15835   this.$get = ['$window', '$timeout', function($window, $timeout) {
15836     var requestAnimationFrame = $window.requestAnimationFrame ||
15837                                 $window.webkitRequestAnimationFrame;
15838
15839     var cancelAnimationFrame = $window.cancelAnimationFrame ||
15840                                $window.webkitCancelAnimationFrame ||
15841                                $window.webkitCancelRequestAnimationFrame;
15842
15843     var rafSupported = !!requestAnimationFrame;
15844     var raf = rafSupported
15845       ? function(fn) {
15846           var id = requestAnimationFrame(fn);
15847           return function() {
15848             cancelAnimationFrame(id);
15849           };
15850         }
15851       : function(fn) {
15852           var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
15853           return function() {
15854             $timeout.cancel(timer);
15855           };
15856         };
15857
15858     raf.supported = rafSupported;
15859
15860     return raf;
15861   }];
15862 }
15863
15864 /**
15865  * DESIGN NOTES
15866  *
15867  * The design decisions behind the scope are heavily favored for speed and memory consumption.
15868  *
15869  * The typical use of scope is to watch the expressions, which most of the time return the same
15870  * value as last time so we optimize the operation.
15871  *
15872  * Closures construction is expensive in terms of speed as well as memory:
15873  *   - No closures, instead use prototypical inheritance for API
15874  *   - Internal state needs to be stored on scope directly, which means that private state is
15875  *     exposed as $$____ properties
15876  *
15877  * Loop operations are optimized by using while(count--) { ... }
15878  *   - This means that in order to keep the same order of execution as addition we have to add
15879  *     items to the array at the beginning (unshift) instead of at the end (push)
15880  *
15881  * Child scopes are created and removed often
15882  *   - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
15883  *
15884  * There are fewer watches than observers. This is why you don't want the observer to be implemented
15885  * in the same way as watch. Watch requires return of the initialization function which is expensive
15886  * to construct.
15887  */
15888
15889
15890 /**
15891  * @ngdoc provider
15892  * @name $rootScopeProvider
15893  * @description
15894  *
15895  * Provider for the $rootScope service.
15896  */
15897
15898 /**
15899  * @ngdoc method
15900  * @name $rootScopeProvider#digestTtl
15901  * @description
15902  *
15903  * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
15904  * assuming that the model is unstable.
15905  *
15906  * The current default is 10 iterations.
15907  *
15908  * In complex applications it's possible that the dependencies between `$watch`s will result in
15909  * several digest iterations. However if an application needs more than the default 10 digest
15910  * iterations for its model to stabilize then you should investigate what is causing the model to
15911  * continuously change during the digest.
15912  *
15913  * Increasing the TTL could have performance implications, so you should not change it without
15914  * proper justification.
15915  *
15916  * @param {number} limit The number of digest iterations.
15917  */
15918
15919
15920 /**
15921  * @ngdoc service
15922  * @name $rootScope
15923  * @description
15924  *
15925  * Every application has a single root {@link ng.$rootScope.Scope scope}.
15926  * All other scopes are descendant scopes of the root scope. Scopes provide separation
15927  * between the model and the view, via a mechanism for watching the model for changes.
15928  * They also provide event emission/broadcast and subscription facility. See the
15929  * {@link guide/scope developer guide on scopes}.
15930  */
15931 function $RootScopeProvider() {
15932   var TTL = 10;
15933   var $rootScopeMinErr = minErr('$rootScope');
15934   var lastDirtyWatch = null;
15935   var applyAsyncId = null;
15936
15937   this.digestTtl = function(value) {
15938     if (arguments.length) {
15939       TTL = value;
15940     }
15941     return TTL;
15942   };
15943
15944   function createChildScopeClass(parent) {
15945     function ChildScope() {
15946       this.$$watchers = this.$$nextSibling =
15947           this.$$childHead = this.$$childTail = null;
15948       this.$$listeners = {};
15949       this.$$listenerCount = {};
15950       this.$$watchersCount = 0;
15951       this.$id = nextUid();
15952       this.$$ChildScope = null;
15953     }
15954     ChildScope.prototype = parent;
15955     return ChildScope;
15956   }
15957
15958   this.$get = ['$exceptionHandler', '$parse', '$browser',
15959       function($exceptionHandler, $parse, $browser) {
15960
15961     function destroyChildScope($event) {
15962         $event.currentScope.$$destroyed = true;
15963     }
15964
15965     function cleanUpScope($scope) {
15966
15967       if (msie === 9) {
15968         // There is a memory leak in IE9 if all child scopes are not disconnected
15969         // completely when a scope is destroyed. So this code will recurse up through
15970         // all this scopes children
15971         //
15972         // See issue https://github.com/angular/angular.js/issues/10706
15973         $scope.$$childHead && cleanUpScope($scope.$$childHead);
15974         $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
15975       }
15976
15977       // The code below works around IE9 and V8's memory leaks
15978       //
15979       // See:
15980       // - https://code.google.com/p/v8/issues/detail?id=2073#c26
15981       // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
15982       // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
15983
15984       $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
15985           $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
15986     }
15987
15988     /**
15989      * @ngdoc type
15990      * @name $rootScope.Scope
15991      *
15992      * @description
15993      * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
15994      * {@link auto.$injector $injector}. Child scopes are created using the
15995      * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
15996      * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
15997      * an in-depth introduction and usage examples.
15998      *
15999      *
16000      * # Inheritance
16001      * A scope can inherit from a parent scope, as in this example:
16002      * ```js
16003          var parent = $rootScope;
16004          var child = parent.$new();
16005
16006          parent.salutation = "Hello";
16007          expect(child.salutation).toEqual('Hello');
16008
16009          child.salutation = "Welcome";
16010          expect(child.salutation).toEqual('Welcome');
16011          expect(parent.salutation).toEqual('Hello');
16012      * ```
16013      *
16014      * When interacting with `Scope` in tests, additional helper methods are available on the
16015      * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
16016      * details.
16017      *
16018      *
16019      * @param {Object.<string, function()>=} providers Map of service factory which need to be
16020      *                                       provided for the current scope. Defaults to {@link ng}.
16021      * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
16022      *                              append/override services provided by `providers`. This is handy
16023      *                              when unit-testing and having the need to override a default
16024      *                              service.
16025      * @returns {Object} Newly created scope.
16026      *
16027      */
16028     function Scope() {
16029       this.$id = nextUid();
16030       this.$$phase = this.$parent = this.$$watchers =
16031                      this.$$nextSibling = this.$$prevSibling =
16032                      this.$$childHead = this.$$childTail = null;
16033       this.$root = this;
16034       this.$$destroyed = false;
16035       this.$$listeners = {};
16036       this.$$listenerCount = {};
16037       this.$$watchersCount = 0;
16038       this.$$isolateBindings = null;
16039     }
16040
16041     /**
16042      * @ngdoc property
16043      * @name $rootScope.Scope#$id
16044      *
16045      * @description
16046      * Unique scope ID (monotonically increasing) useful for debugging.
16047      */
16048
16049      /**
16050       * @ngdoc property
16051       * @name $rootScope.Scope#$parent
16052       *
16053       * @description
16054       * Reference to the parent scope.
16055       */
16056
16057       /**
16058        * @ngdoc property
16059        * @name $rootScope.Scope#$root
16060        *
16061        * @description
16062        * Reference to the root scope.
16063        */
16064
16065     Scope.prototype = {
16066       constructor: Scope,
16067       /**
16068        * @ngdoc method
16069        * @name $rootScope.Scope#$new
16070        * @kind function
16071        *
16072        * @description
16073        * Creates a new child {@link ng.$rootScope.Scope scope}.
16074        *
16075        * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
16076        * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
16077        *
16078        * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
16079        * desired for the scope and its child scopes to be permanently detached from the parent and
16080        * thus stop participating in model change detection and listener notification by invoking.
16081        *
16082        * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
16083        *         parent scope. The scope is isolated, as it can not see parent scope properties.
16084        *         When creating widgets, it is useful for the widget to not accidentally read parent
16085        *         state.
16086        *
16087        * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
16088        *                              of the newly created scope. Defaults to `this` scope if not provided.
16089        *                              This is used when creating a transclude scope to correctly place it
16090        *                              in the scope hierarchy while maintaining the correct prototypical
16091        *                              inheritance.
16092        *
16093        * @returns {Object} The newly created child scope.
16094        *
16095        */
16096       $new: function(isolate, parent) {
16097         var child;
16098
16099         parent = parent || this;
16100
16101         if (isolate) {
16102           child = new Scope();
16103           child.$root = this.$root;
16104         } else {
16105           // Only create a child scope class if somebody asks for one,
16106           // but cache it to allow the VM to optimize lookups.
16107           if (!this.$$ChildScope) {
16108             this.$$ChildScope = createChildScopeClass(this);
16109           }
16110           child = new this.$$ChildScope();
16111         }
16112         child.$parent = parent;
16113         child.$$prevSibling = parent.$$childTail;
16114         if (parent.$$childHead) {
16115           parent.$$childTail.$$nextSibling = child;
16116           parent.$$childTail = child;
16117         } else {
16118           parent.$$childHead = parent.$$childTail = child;
16119         }
16120
16121         // When the new scope is not isolated or we inherit from `this`, and
16122         // the parent scope is destroyed, the property `$$destroyed` is inherited
16123         // prototypically. In all other cases, this property needs to be set
16124         // when the parent scope is destroyed.
16125         // The listener needs to be added after the parent is set
16126         if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
16127
16128         return child;
16129       },
16130
16131       /**
16132        * @ngdoc method
16133        * @name $rootScope.Scope#$watch
16134        * @kind function
16135        *
16136        * @description
16137        * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
16138        *
16139        * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
16140        *   $digest()} and should return the value that will be watched. (`watchExpression` should not change
16141        *   its value when executed multiple times with the same input because it may be executed multiple
16142        *   times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
16143        *   [idempotent](http://en.wikipedia.org/wiki/Idempotence).
16144        * - The `listener` is called only when the value from the current `watchExpression` and the
16145        *   previous call to `watchExpression` are not equal (with the exception of the initial run,
16146        *   see below). Inequality is determined according to reference inequality,
16147        *   [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
16148        *    via the `!==` Javascript operator, unless `objectEquality == true`
16149        *   (see next point)
16150        * - When `objectEquality == true`, inequality of the `watchExpression` is determined
16151        *   according to the {@link angular.equals} function. To save the value of the object for
16152        *   later comparison, the {@link angular.copy} function is used. This therefore means that
16153        *   watching complex objects will have adverse memory and performance implications.
16154        * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
16155        *   This is achieved by rerunning the watchers until no changes are detected. The rerun
16156        *   iteration limit is 10 to prevent an infinite loop deadlock.
16157        *
16158        *
16159        * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
16160        * you can register a `watchExpression` function with no `listener`. (Be prepared for
16161        * multiple calls to your `watchExpression` because it will execute multiple times in a
16162        * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
16163        *
16164        * After a watcher is registered with the scope, the `listener` fn is called asynchronously
16165        * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
16166        * watcher. In rare cases, this is undesirable because the listener is called when the result
16167        * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
16168        * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
16169        * listener was called due to initialization.
16170        *
16171        *
16172        *
16173        * # Example
16174        * ```js
16175            // let's assume that scope was dependency injected as the $rootScope
16176            var scope = $rootScope;
16177            scope.name = 'misko';
16178            scope.counter = 0;
16179
16180            expect(scope.counter).toEqual(0);
16181            scope.$watch('name', function(newValue, oldValue) {
16182              scope.counter = scope.counter + 1;
16183            });
16184            expect(scope.counter).toEqual(0);
16185
16186            scope.$digest();
16187            // the listener is always called during the first $digest loop after it was registered
16188            expect(scope.counter).toEqual(1);
16189
16190            scope.$digest();
16191            // but now it will not be called unless the value changes
16192            expect(scope.counter).toEqual(1);
16193
16194            scope.name = 'adam';
16195            scope.$digest();
16196            expect(scope.counter).toEqual(2);
16197
16198
16199
16200            // Using a function as a watchExpression
16201            var food;
16202            scope.foodCounter = 0;
16203            expect(scope.foodCounter).toEqual(0);
16204            scope.$watch(
16205              // This function returns the value being watched. It is called for each turn of the $digest loop
16206              function() { return food; },
16207              // This is the change listener, called when the value returned from the above function changes
16208              function(newValue, oldValue) {
16209                if ( newValue !== oldValue ) {
16210                  // Only increment the counter if the value changed
16211                  scope.foodCounter = scope.foodCounter + 1;
16212                }
16213              }
16214            );
16215            // No digest has been run so the counter will be zero
16216            expect(scope.foodCounter).toEqual(0);
16217
16218            // Run the digest but since food has not changed count will still be zero
16219            scope.$digest();
16220            expect(scope.foodCounter).toEqual(0);
16221
16222            // Update food and run digest.  Now the counter will increment
16223            food = 'cheeseburger';
16224            scope.$digest();
16225            expect(scope.foodCounter).toEqual(1);
16226
16227        * ```
16228        *
16229        *
16230        *
16231        * @param {(function()|string)} watchExpression Expression that is evaluated on each
16232        *    {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
16233        *    a call to the `listener`.
16234        *
16235        *    - `string`: Evaluated as {@link guide/expression expression}
16236        *    - `function(scope)`: called with current `scope` as a parameter.
16237        * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
16238        *    of `watchExpression` changes.
16239        *
16240        *    - `newVal` contains the current value of the `watchExpression`
16241        *    - `oldVal` contains the previous value of the `watchExpression`
16242        *    - `scope` refers to the current scope
16243        * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
16244        *     comparing for reference equality.
16245        * @returns {function()} Returns a deregistration function for this listener.
16246        */
16247       $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
16248         var get = $parse(watchExp);
16249
16250         if (get.$$watchDelegate) {
16251           return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
16252         }
16253         var scope = this,
16254             array = scope.$$watchers,
16255             watcher = {
16256               fn: listener,
16257               last: initWatchVal,
16258               get: get,
16259               exp: prettyPrintExpression || watchExp,
16260               eq: !!objectEquality
16261             };
16262
16263         lastDirtyWatch = null;
16264
16265         if (!isFunction(listener)) {
16266           watcher.fn = noop;
16267         }
16268
16269         if (!array) {
16270           array = scope.$$watchers = [];
16271         }
16272         // we use unshift since we use a while loop in $digest for speed.
16273         // the while loop reads in reverse order.
16274         array.unshift(watcher);
16275         incrementWatchersCount(this, 1);
16276
16277         return function deregisterWatch() {
16278           if (arrayRemove(array, watcher) >= 0) {
16279             incrementWatchersCount(scope, -1);
16280           }
16281           lastDirtyWatch = null;
16282         };
16283       },
16284
16285       /**
16286        * @ngdoc method
16287        * @name $rootScope.Scope#$watchGroup
16288        * @kind function
16289        *
16290        * @description
16291        * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
16292        * If any one expression in the collection changes the `listener` is executed.
16293        *
16294        * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
16295        *   call to $digest() to see if any items changes.
16296        * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
16297        *
16298        * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
16299        * watched using {@link ng.$rootScope.Scope#$watch $watch()}
16300        *
16301        * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
16302        *    expression in `watchExpressions` changes
16303        *    The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
16304        *    those of `watchExpression`
16305        *    and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
16306        *    those of `watchExpression`
16307        *    The `scope` refers to the current scope.
16308        * @returns {function()} Returns a de-registration function for all listeners.
16309        */
16310       $watchGroup: function(watchExpressions, listener) {
16311         var oldValues = new Array(watchExpressions.length);
16312         var newValues = new Array(watchExpressions.length);
16313         var deregisterFns = [];
16314         var self = this;
16315         var changeReactionScheduled = false;
16316         var firstRun = true;
16317
16318         if (!watchExpressions.length) {
16319           // No expressions means we call the listener ASAP
16320           var shouldCall = true;
16321           self.$evalAsync(function() {
16322             if (shouldCall) listener(newValues, newValues, self);
16323           });
16324           return function deregisterWatchGroup() {
16325             shouldCall = false;
16326           };
16327         }
16328
16329         if (watchExpressions.length === 1) {
16330           // Special case size of one
16331           return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
16332             newValues[0] = value;
16333             oldValues[0] = oldValue;
16334             listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
16335           });
16336         }
16337
16338         forEach(watchExpressions, function(expr, i) {
16339           var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
16340             newValues[i] = value;
16341             oldValues[i] = oldValue;
16342             if (!changeReactionScheduled) {
16343               changeReactionScheduled = true;
16344               self.$evalAsync(watchGroupAction);
16345             }
16346           });
16347           deregisterFns.push(unwatchFn);
16348         });
16349
16350         function watchGroupAction() {
16351           changeReactionScheduled = false;
16352
16353           if (firstRun) {
16354             firstRun = false;
16355             listener(newValues, newValues, self);
16356           } else {
16357             listener(newValues, oldValues, self);
16358           }
16359         }
16360
16361         return function deregisterWatchGroup() {
16362           while (deregisterFns.length) {
16363             deregisterFns.shift()();
16364           }
16365         };
16366       },
16367
16368
16369       /**
16370        * @ngdoc method
16371        * @name $rootScope.Scope#$watchCollection
16372        * @kind function
16373        *
16374        * @description
16375        * Shallow watches the properties of an object and fires whenever any of the properties change
16376        * (for arrays, this implies watching the array items; for object maps, this implies watching
16377        * the properties). If a change is detected, the `listener` callback is fired.
16378        *
16379        * - The `obj` collection is observed via standard $watch operation and is examined on every
16380        *   call to $digest() to see if any items have been added, removed, or moved.
16381        * - The `listener` is called whenever anything within the `obj` has changed. Examples include
16382        *   adding, removing, and moving items belonging to an object or array.
16383        *
16384        *
16385        * # Example
16386        * ```js
16387           $scope.names = ['igor', 'matias', 'misko', 'james'];
16388           $scope.dataCount = 4;
16389
16390           $scope.$watchCollection('names', function(newNames, oldNames) {
16391             $scope.dataCount = newNames.length;
16392           });
16393
16394           expect($scope.dataCount).toEqual(4);
16395           $scope.$digest();
16396
16397           //still at 4 ... no changes
16398           expect($scope.dataCount).toEqual(4);
16399
16400           $scope.names.pop();
16401           $scope.$digest();
16402
16403           //now there's been a change
16404           expect($scope.dataCount).toEqual(3);
16405        * ```
16406        *
16407        *
16408        * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
16409        *    expression value should evaluate to an object or an array which is observed on each
16410        *    {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
16411        *    collection will trigger a call to the `listener`.
16412        *
16413        * @param {function(newCollection, oldCollection, scope)} listener a callback function called
16414        *    when a change is detected.
16415        *    - The `newCollection` object is the newly modified data obtained from the `obj` expression
16416        *    - The `oldCollection` object is a copy of the former collection data.
16417        *      Due to performance considerations, the`oldCollection` value is computed only if the
16418        *      `listener` function declares two or more arguments.
16419        *    - The `scope` argument refers to the current scope.
16420        *
16421        * @returns {function()} Returns a de-registration function for this listener. When the
16422        *    de-registration function is executed, the internal watch operation is terminated.
16423        */
16424       $watchCollection: function(obj, listener) {
16425         $watchCollectionInterceptor.$stateful = true;
16426
16427         var self = this;
16428         // the current value, updated on each dirty-check run
16429         var newValue;
16430         // a shallow copy of the newValue from the last dirty-check run,
16431         // updated to match newValue during dirty-check run
16432         var oldValue;
16433         // a shallow copy of the newValue from when the last change happened
16434         var veryOldValue;
16435         // only track veryOldValue if the listener is asking for it
16436         var trackVeryOldValue = (listener.length > 1);
16437         var changeDetected = 0;
16438         var changeDetector = $parse(obj, $watchCollectionInterceptor);
16439         var internalArray = [];
16440         var internalObject = {};
16441         var initRun = true;
16442         var oldLength = 0;
16443
16444         function $watchCollectionInterceptor(_value) {
16445           newValue = _value;
16446           var newLength, key, bothNaN, newItem, oldItem;
16447
16448           // If the new value is undefined, then return undefined as the watch may be a one-time watch
16449           if (isUndefined(newValue)) return;
16450
16451           if (!isObject(newValue)) { // if primitive
16452             if (oldValue !== newValue) {
16453               oldValue = newValue;
16454               changeDetected++;
16455             }
16456           } else if (isArrayLike(newValue)) {
16457             if (oldValue !== internalArray) {
16458               // we are transitioning from something which was not an array into array.
16459               oldValue = internalArray;
16460               oldLength = oldValue.length = 0;
16461               changeDetected++;
16462             }
16463
16464             newLength = newValue.length;
16465
16466             if (oldLength !== newLength) {
16467               // if lengths do not match we need to trigger change notification
16468               changeDetected++;
16469               oldValue.length = oldLength = newLength;
16470             }
16471             // copy the items to oldValue and look for changes.
16472             for (var i = 0; i < newLength; i++) {
16473               oldItem = oldValue[i];
16474               newItem = newValue[i];
16475
16476               bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
16477               if (!bothNaN && (oldItem !== newItem)) {
16478                 changeDetected++;
16479                 oldValue[i] = newItem;
16480               }
16481             }
16482           } else {
16483             if (oldValue !== internalObject) {
16484               // we are transitioning from something which was not an object into object.
16485               oldValue = internalObject = {};
16486               oldLength = 0;
16487               changeDetected++;
16488             }
16489             // copy the items to oldValue and look for changes.
16490             newLength = 0;
16491             for (key in newValue) {
16492               if (hasOwnProperty.call(newValue, key)) {
16493                 newLength++;
16494                 newItem = newValue[key];
16495                 oldItem = oldValue[key];
16496
16497                 if (key in oldValue) {
16498                   bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
16499                   if (!bothNaN && (oldItem !== newItem)) {
16500                     changeDetected++;
16501                     oldValue[key] = newItem;
16502                   }
16503                 } else {
16504                   oldLength++;
16505                   oldValue[key] = newItem;
16506                   changeDetected++;
16507                 }
16508               }
16509             }
16510             if (oldLength > newLength) {
16511               // we used to have more keys, need to find them and destroy them.
16512               changeDetected++;
16513               for (key in oldValue) {
16514                 if (!hasOwnProperty.call(newValue, key)) {
16515                   oldLength--;
16516                   delete oldValue[key];
16517                 }
16518               }
16519             }
16520           }
16521           return changeDetected;
16522         }
16523
16524         function $watchCollectionAction() {
16525           if (initRun) {
16526             initRun = false;
16527             listener(newValue, newValue, self);
16528           } else {
16529             listener(newValue, veryOldValue, self);
16530           }
16531
16532           // make a copy for the next time a collection is changed
16533           if (trackVeryOldValue) {
16534             if (!isObject(newValue)) {
16535               //primitive
16536               veryOldValue = newValue;
16537             } else if (isArrayLike(newValue)) {
16538               veryOldValue = new Array(newValue.length);
16539               for (var i = 0; i < newValue.length; i++) {
16540                 veryOldValue[i] = newValue[i];
16541               }
16542             } else { // if object
16543               veryOldValue = {};
16544               for (var key in newValue) {
16545                 if (hasOwnProperty.call(newValue, key)) {
16546                   veryOldValue[key] = newValue[key];
16547                 }
16548               }
16549             }
16550           }
16551         }
16552
16553         return this.$watch(changeDetector, $watchCollectionAction);
16554       },
16555
16556       /**
16557        * @ngdoc method
16558        * @name $rootScope.Scope#$digest
16559        * @kind function
16560        *
16561        * @description
16562        * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
16563        * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
16564        * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
16565        * until no more listeners are firing. This means that it is possible to get into an infinite
16566        * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
16567        * iterations exceeds 10.
16568        *
16569        * Usually, you don't call `$digest()` directly in
16570        * {@link ng.directive:ngController controllers} or in
16571        * {@link ng.$compileProvider#directive directives}.
16572        * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
16573        * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
16574        *
16575        * If you want to be notified whenever `$digest()` is called,
16576        * you can register a `watchExpression` function with
16577        * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
16578        *
16579        * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
16580        *
16581        * # Example
16582        * ```js
16583            var scope = ...;
16584            scope.name = 'misko';
16585            scope.counter = 0;
16586
16587            expect(scope.counter).toEqual(0);
16588            scope.$watch('name', function(newValue, oldValue) {
16589              scope.counter = scope.counter + 1;
16590            });
16591            expect(scope.counter).toEqual(0);
16592
16593            scope.$digest();
16594            // the listener is always called during the first $digest loop after it was registered
16595            expect(scope.counter).toEqual(1);
16596
16597            scope.$digest();
16598            // but now it will not be called unless the value changes
16599            expect(scope.counter).toEqual(1);
16600
16601            scope.name = 'adam';
16602            scope.$digest();
16603            expect(scope.counter).toEqual(2);
16604        * ```
16605        *
16606        */
16607       $digest: function() {
16608         var watch, value, last, fn, get,
16609             watchers,
16610             length,
16611             dirty, ttl = TTL,
16612             next, current, target = this,
16613             watchLog = [],
16614             logIdx, logMsg, asyncTask;
16615
16616         beginPhase('$digest');
16617         // Check for changes to browser url that happened in sync before the call to $digest
16618         $browser.$$checkUrlChange();
16619
16620         if (this === $rootScope && applyAsyncId !== null) {
16621           // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
16622           // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
16623           $browser.defer.cancel(applyAsyncId);
16624           flushApplyAsync();
16625         }
16626
16627         lastDirtyWatch = null;
16628
16629         do { // "while dirty" loop
16630           dirty = false;
16631           current = target;
16632
16633           while (asyncQueue.length) {
16634             try {
16635               asyncTask = asyncQueue.shift();
16636               asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
16637             } catch (e) {
16638               $exceptionHandler(e);
16639             }
16640             lastDirtyWatch = null;
16641           }
16642
16643           traverseScopesLoop:
16644           do { // "traverse the scopes" loop
16645             if ((watchers = current.$$watchers)) {
16646               // process our watches
16647               length = watchers.length;
16648               while (length--) {
16649                 try {
16650                   watch = watchers[length];
16651                   // Most common watches are on primitives, in which case we can short
16652                   // circuit it with === operator, only when === fails do we use .equals
16653                   if (watch) {
16654                     get = watch.get;
16655                     if ((value = get(current)) !== (last = watch.last) &&
16656                         !(watch.eq
16657                             ? equals(value, last)
16658                             : (typeof value === 'number' && typeof last === 'number'
16659                                && isNaN(value) && isNaN(last)))) {
16660                       dirty = true;
16661                       lastDirtyWatch = watch;
16662                       watch.last = watch.eq ? copy(value, null) : value;
16663                       fn = watch.fn;
16664                       fn(value, ((last === initWatchVal) ? value : last), current);
16665                       if (ttl < 5) {
16666                         logIdx = 4 - ttl;
16667                         if (!watchLog[logIdx]) watchLog[logIdx] = [];
16668                         watchLog[logIdx].push({
16669                           msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
16670                           newVal: value,
16671                           oldVal: last
16672                         });
16673                       }
16674                     } else if (watch === lastDirtyWatch) {
16675                       // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
16676                       // have already been tested.
16677                       dirty = false;
16678                       break traverseScopesLoop;
16679                     }
16680                   }
16681                 } catch (e) {
16682                   $exceptionHandler(e);
16683                 }
16684               }
16685             }
16686
16687             // Insanity Warning: scope depth-first traversal
16688             // yes, this code is a bit crazy, but it works and we have tests to prove it!
16689             // this piece should be kept in sync with the traversal in $broadcast
16690             if (!(next = ((current.$$watchersCount && current.$$childHead) ||
16691                 (current !== target && current.$$nextSibling)))) {
16692               while (current !== target && !(next = current.$$nextSibling)) {
16693                 current = current.$parent;
16694               }
16695             }
16696           } while ((current = next));
16697
16698           // `break traverseScopesLoop;` takes us to here
16699
16700           if ((dirty || asyncQueue.length) && !(ttl--)) {
16701             clearPhase();
16702             throw $rootScopeMinErr('infdig',
16703                 '{0} $digest() iterations reached. Aborting!\n' +
16704                 'Watchers fired in the last 5 iterations: {1}',
16705                 TTL, watchLog);
16706           }
16707
16708         } while (dirty || asyncQueue.length);
16709
16710         clearPhase();
16711
16712         while (postDigestQueue.length) {
16713           try {
16714             postDigestQueue.shift()();
16715           } catch (e) {
16716             $exceptionHandler(e);
16717           }
16718         }
16719       },
16720
16721
16722       /**
16723        * @ngdoc event
16724        * @name $rootScope.Scope#$destroy
16725        * @eventType broadcast on scope being destroyed
16726        *
16727        * @description
16728        * Broadcasted when a scope and its children are being destroyed.
16729        *
16730        * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
16731        * clean up DOM bindings before an element is removed from the DOM.
16732        */
16733
16734       /**
16735        * @ngdoc method
16736        * @name $rootScope.Scope#$destroy
16737        * @kind function
16738        *
16739        * @description
16740        * Removes the current scope (and all of its children) from the parent scope. Removal implies
16741        * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
16742        * propagate to the current scope and its children. Removal also implies that the current
16743        * scope is eligible for garbage collection.
16744        *
16745        * The `$destroy()` is usually used by directives such as
16746        * {@link ng.directive:ngRepeat ngRepeat} for managing the
16747        * unrolling of the loop.
16748        *
16749        * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
16750        * Application code can register a `$destroy` event handler that will give it a chance to
16751        * perform any necessary cleanup.
16752        *
16753        * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
16754        * clean up DOM bindings before an element is removed from the DOM.
16755        */
16756       $destroy: function() {
16757         // We can't destroy a scope that has been already destroyed.
16758         if (this.$$destroyed) return;
16759         var parent = this.$parent;
16760
16761         this.$broadcast('$destroy');
16762         this.$$destroyed = true;
16763
16764         if (this === $rootScope) {
16765           //Remove handlers attached to window when $rootScope is removed
16766           $browser.$$applicationDestroyed();
16767         }
16768
16769         incrementWatchersCount(this, -this.$$watchersCount);
16770         for (var eventName in this.$$listenerCount) {
16771           decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
16772         }
16773
16774         // sever all the references to parent scopes (after this cleanup, the current scope should
16775         // not be retained by any of our references and should be eligible for garbage collection)
16776         if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
16777         if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
16778         if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
16779         if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
16780
16781         // Disable listeners, watchers and apply/digest methods
16782         this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
16783         this.$on = this.$watch = this.$watchGroup = function() { return noop; };
16784         this.$$listeners = {};
16785
16786         // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
16787         this.$$nextSibling = null;
16788         cleanUpScope(this);
16789       },
16790
16791       /**
16792        * @ngdoc method
16793        * @name $rootScope.Scope#$eval
16794        * @kind function
16795        *
16796        * @description
16797        * Executes the `expression` on the current scope and returns the result. Any exceptions in
16798        * the expression are propagated (uncaught). This is useful when evaluating Angular
16799        * expressions.
16800        *
16801        * # Example
16802        * ```js
16803            var scope = ng.$rootScope.Scope();
16804            scope.a = 1;
16805            scope.b = 2;
16806
16807            expect(scope.$eval('a+b')).toEqual(3);
16808            expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
16809        * ```
16810        *
16811        * @param {(string|function())=} expression An angular expression to be executed.
16812        *
16813        *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.
16814        *    - `function(scope)`: execute the function with the current `scope` parameter.
16815        *
16816        * @param {(object)=} locals Local variables object, useful for overriding values in scope.
16817        * @returns {*} The result of evaluating the expression.
16818        */
16819       $eval: function(expr, locals) {
16820         return $parse(expr)(this, locals);
16821       },
16822
16823       /**
16824        * @ngdoc method
16825        * @name $rootScope.Scope#$evalAsync
16826        * @kind function
16827        *
16828        * @description
16829        * Executes the expression on the current scope at a later point in time.
16830        *
16831        * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
16832        * that:
16833        *
16834        *   - it will execute after the function that scheduled the evaluation (preferably before DOM
16835        *     rendering).
16836        *   - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
16837        *     `expression` execution.
16838        *
16839        * Any exceptions from the execution of the expression are forwarded to the
16840        * {@link ng.$exceptionHandler $exceptionHandler} service.
16841        *
16842        * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
16843        * will be scheduled. However, it is encouraged to always call code that changes the model
16844        * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
16845        *
16846        * @param {(string|function())=} expression An angular expression to be executed.
16847        *
16848        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
16849        *    - `function(scope)`: execute the function with the current `scope` parameter.
16850        *
16851        * @param {(object)=} locals Local variables object, useful for overriding values in scope.
16852        */
16853       $evalAsync: function(expr, locals) {
16854         // if we are outside of an $digest loop and this is the first time we are scheduling async
16855         // task also schedule async auto-flush
16856         if (!$rootScope.$$phase && !asyncQueue.length) {
16857           $browser.defer(function() {
16858             if (asyncQueue.length) {
16859               $rootScope.$digest();
16860             }
16861           });
16862         }
16863
16864         asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
16865       },
16866
16867       $$postDigest: function(fn) {
16868         postDigestQueue.push(fn);
16869       },
16870
16871       /**
16872        * @ngdoc method
16873        * @name $rootScope.Scope#$apply
16874        * @kind function
16875        *
16876        * @description
16877        * `$apply()` is used to execute an expression in angular from outside of the angular
16878        * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
16879        * Because we are calling into the angular framework we need to perform proper scope life
16880        * cycle of {@link ng.$exceptionHandler exception handling},
16881        * {@link ng.$rootScope.Scope#$digest executing watches}.
16882        *
16883        * ## Life cycle
16884        *
16885        * # Pseudo-Code of `$apply()`
16886        * ```js
16887            function $apply(expr) {
16888              try {
16889                return $eval(expr);
16890              } catch (e) {
16891                $exceptionHandler(e);
16892              } finally {
16893                $root.$digest();
16894              }
16895            }
16896        * ```
16897        *
16898        *
16899        * Scope's `$apply()` method transitions through the following stages:
16900        *
16901        * 1. The {@link guide/expression expression} is executed using the
16902        *    {@link ng.$rootScope.Scope#$eval $eval()} method.
16903        * 2. Any exceptions from the execution of the expression are forwarded to the
16904        *    {@link ng.$exceptionHandler $exceptionHandler} service.
16905        * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
16906        *    expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
16907        *
16908        *
16909        * @param {(string|function())=} exp An angular expression to be executed.
16910        *
16911        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
16912        *    - `function(scope)`: execute the function with current `scope` parameter.
16913        *
16914        * @returns {*} The result of evaluating the expression.
16915        */
16916       $apply: function(expr) {
16917         try {
16918           beginPhase('$apply');
16919           try {
16920             return this.$eval(expr);
16921           } finally {
16922             clearPhase();
16923           }
16924         } catch (e) {
16925           $exceptionHandler(e);
16926         } finally {
16927           try {
16928             $rootScope.$digest();
16929           } catch (e) {
16930             $exceptionHandler(e);
16931             throw e;
16932           }
16933         }
16934       },
16935
16936       /**
16937        * @ngdoc method
16938        * @name $rootScope.Scope#$applyAsync
16939        * @kind function
16940        *
16941        * @description
16942        * Schedule the invocation of $apply to occur at a later time. The actual time difference
16943        * varies across browsers, but is typically around ~10 milliseconds.
16944        *
16945        * This can be used to queue up multiple expressions which need to be evaluated in the same
16946        * digest.
16947        *
16948        * @param {(string|function())=} exp An angular expression to be executed.
16949        *
16950        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
16951        *    - `function(scope)`: execute the function with current `scope` parameter.
16952        */
16953       $applyAsync: function(expr) {
16954         var scope = this;
16955         expr && applyAsyncQueue.push($applyAsyncExpression);
16956         expr = $parse(expr);
16957         scheduleApplyAsync();
16958
16959         function $applyAsyncExpression() {
16960           scope.$eval(expr);
16961         }
16962       },
16963
16964       /**
16965        * @ngdoc method
16966        * @name $rootScope.Scope#$on
16967        * @kind function
16968        *
16969        * @description
16970        * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
16971        * discussion of event life cycle.
16972        *
16973        * The event listener function format is: `function(event, args...)`. The `event` object
16974        * passed into the listener has the following attributes:
16975        *
16976        *   - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
16977        *     `$broadcast`-ed.
16978        *   - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
16979        *     event propagates through the scope hierarchy, this property is set to null.
16980        *   - `name` - `{string}`: name of the event.
16981        *   - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
16982        *     further event propagation (available only for events that were `$emit`-ed).
16983        *   - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
16984        *     to true.
16985        *   - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
16986        *
16987        * @param {string} name Event name to listen on.
16988        * @param {function(event, ...args)} listener Function to call when the event is emitted.
16989        * @returns {function()} Returns a deregistration function for this listener.
16990        */
16991       $on: function(name, listener) {
16992         var namedListeners = this.$$listeners[name];
16993         if (!namedListeners) {
16994           this.$$listeners[name] = namedListeners = [];
16995         }
16996         namedListeners.push(listener);
16997
16998         var current = this;
16999         do {
17000           if (!current.$$listenerCount[name]) {
17001             current.$$listenerCount[name] = 0;
17002           }
17003           current.$$listenerCount[name]++;
17004         } while ((current = current.$parent));
17005
17006         var self = this;
17007         return function() {
17008           var indexOfListener = namedListeners.indexOf(listener);
17009           if (indexOfListener !== -1) {
17010             namedListeners[indexOfListener] = null;
17011             decrementListenerCount(self, 1, name);
17012           }
17013         };
17014       },
17015
17016
17017       /**
17018        * @ngdoc method
17019        * @name $rootScope.Scope#$emit
17020        * @kind function
17021        *
17022        * @description
17023        * Dispatches an event `name` upwards through the scope hierarchy notifying the
17024        * registered {@link ng.$rootScope.Scope#$on} listeners.
17025        *
17026        * The event life cycle starts at the scope on which `$emit` was called. All
17027        * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
17028        * notified. Afterwards, the event traverses upwards toward the root scope and calls all
17029        * registered listeners along the way. The event will stop propagating if one of the listeners
17030        * cancels it.
17031        *
17032        * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
17033        * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
17034        *
17035        * @param {string} name Event name to emit.
17036        * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
17037        * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
17038        */
17039       $emit: function(name, args) {
17040         var empty = [],
17041             namedListeners,
17042             scope = this,
17043             stopPropagation = false,
17044             event = {
17045               name: name,
17046               targetScope: scope,
17047               stopPropagation: function() {stopPropagation = true;},
17048               preventDefault: function() {
17049                 event.defaultPrevented = true;
17050               },
17051               defaultPrevented: false
17052             },
17053             listenerArgs = concat([event], arguments, 1),
17054             i, length;
17055
17056         do {
17057           namedListeners = scope.$$listeners[name] || empty;
17058           event.currentScope = scope;
17059           for (i = 0, length = namedListeners.length; i < length; i++) {
17060
17061             // if listeners were deregistered, defragment the array
17062             if (!namedListeners[i]) {
17063               namedListeners.splice(i, 1);
17064               i--;
17065               length--;
17066               continue;
17067             }
17068             try {
17069               //allow all listeners attached to the current scope to run
17070               namedListeners[i].apply(null, listenerArgs);
17071             } catch (e) {
17072               $exceptionHandler(e);
17073             }
17074           }
17075           //if any listener on the current scope stops propagation, prevent bubbling
17076           if (stopPropagation) {
17077             event.currentScope = null;
17078             return event;
17079           }
17080           //traverse upwards
17081           scope = scope.$parent;
17082         } while (scope);
17083
17084         event.currentScope = null;
17085
17086         return event;
17087       },
17088
17089
17090       /**
17091        * @ngdoc method
17092        * @name $rootScope.Scope#$broadcast
17093        * @kind function
17094        *
17095        * @description
17096        * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
17097        * registered {@link ng.$rootScope.Scope#$on} listeners.
17098        *
17099        * The event life cycle starts at the scope on which `$broadcast` was called. All
17100        * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
17101        * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
17102        * scope and calls all registered listeners along the way. The event cannot be canceled.
17103        *
17104        * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
17105        * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
17106        *
17107        * @param {string} name Event name to broadcast.
17108        * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
17109        * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
17110        */
17111       $broadcast: function(name, args) {
17112         var target = this,
17113             current = target,
17114             next = target,
17115             event = {
17116               name: name,
17117               targetScope: target,
17118               preventDefault: function() {
17119                 event.defaultPrevented = true;
17120               },
17121               defaultPrevented: false
17122             };
17123
17124         if (!target.$$listenerCount[name]) return event;
17125
17126         var listenerArgs = concat([event], arguments, 1),
17127             listeners, i, length;
17128
17129         //down while you can, then up and next sibling or up and next sibling until back at root
17130         while ((current = next)) {
17131           event.currentScope = current;
17132           listeners = current.$$listeners[name] || [];
17133           for (i = 0, length = listeners.length; i < length; i++) {
17134             // if listeners were deregistered, defragment the array
17135             if (!listeners[i]) {
17136               listeners.splice(i, 1);
17137               i--;
17138               length--;
17139               continue;
17140             }
17141
17142             try {
17143               listeners[i].apply(null, listenerArgs);
17144             } catch (e) {
17145               $exceptionHandler(e);
17146             }
17147           }
17148
17149           // Insanity Warning: scope depth-first traversal
17150           // yes, this code is a bit crazy, but it works and we have tests to prove it!
17151           // this piece should be kept in sync with the traversal in $digest
17152           // (though it differs due to having the extra check for $$listenerCount)
17153           if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
17154               (current !== target && current.$$nextSibling)))) {
17155             while (current !== target && !(next = current.$$nextSibling)) {
17156               current = current.$parent;
17157             }
17158           }
17159         }
17160
17161         event.currentScope = null;
17162         return event;
17163       }
17164     };
17165
17166     var $rootScope = new Scope();
17167
17168     //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
17169     var asyncQueue = $rootScope.$$asyncQueue = [];
17170     var postDigestQueue = $rootScope.$$postDigestQueue = [];
17171     var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
17172
17173     return $rootScope;
17174
17175
17176     function beginPhase(phase) {
17177       if ($rootScope.$$phase) {
17178         throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
17179       }
17180
17181       $rootScope.$$phase = phase;
17182     }
17183
17184     function clearPhase() {
17185       $rootScope.$$phase = null;
17186     }
17187
17188     function incrementWatchersCount(current, count) {
17189       do {
17190         current.$$watchersCount += count;
17191       } while ((current = current.$parent));
17192     }
17193
17194     function decrementListenerCount(current, count, name) {
17195       do {
17196         current.$$listenerCount[name] -= count;
17197
17198         if (current.$$listenerCount[name] === 0) {
17199           delete current.$$listenerCount[name];
17200         }
17201       } while ((current = current.$parent));
17202     }
17203
17204     /**
17205      * function used as an initial value for watchers.
17206      * because it's unique we can easily tell it apart from other values
17207      */
17208     function initWatchVal() {}
17209
17210     function flushApplyAsync() {
17211       while (applyAsyncQueue.length) {
17212         try {
17213           applyAsyncQueue.shift()();
17214         } catch (e) {
17215           $exceptionHandler(e);
17216         }
17217       }
17218       applyAsyncId = null;
17219     }
17220
17221     function scheduleApplyAsync() {
17222       if (applyAsyncId === null) {
17223         applyAsyncId = $browser.defer(function() {
17224           $rootScope.$apply(flushApplyAsync);
17225         });
17226       }
17227     }
17228   }];
17229 }
17230
17231 /**
17232  * @ngdoc service
17233  * @name $rootElement
17234  *
17235  * @description
17236  * The root element of Angular application. This is either the element where {@link
17237  * ng.directive:ngApp ngApp} was declared or the element passed into
17238  * {@link angular.bootstrap}. The element represents the root element of application. It is also the
17239  * location where the application's {@link auto.$injector $injector} service gets
17240  * published, and can be retrieved using `$rootElement.injector()`.
17241  */
17242
17243
17244 // the implementation is in angular.bootstrap
17245
17246 /**
17247  * @description
17248  * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
17249  */
17250 function $$SanitizeUriProvider() {
17251   var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
17252     imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
17253
17254   /**
17255    * @description
17256    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
17257    * urls during a[href] sanitization.
17258    *
17259    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
17260    *
17261    * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
17262    * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
17263    * regular expression. If a match is found, the original url is written into the dom. Otherwise,
17264    * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
17265    *
17266    * @param {RegExp=} regexp New regexp to whitelist urls with.
17267    * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
17268    *    chaining otherwise.
17269    */
17270   this.aHrefSanitizationWhitelist = function(regexp) {
17271     if (isDefined(regexp)) {
17272       aHrefSanitizationWhitelist = regexp;
17273       return this;
17274     }
17275     return aHrefSanitizationWhitelist;
17276   };
17277
17278
17279   /**
17280    * @description
17281    * Retrieves or overrides the default regular expression that is used for whitelisting of safe
17282    * urls during img[src] sanitization.
17283    *
17284    * The sanitization is a security measure aimed at prevent XSS attacks via html links.
17285    *
17286    * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
17287    * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
17288    * regular expression. If a match is found, the original url is written into the dom. Otherwise,
17289    * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
17290    *
17291    * @param {RegExp=} regexp New regexp to whitelist urls with.
17292    * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
17293    *    chaining otherwise.
17294    */
17295   this.imgSrcSanitizationWhitelist = function(regexp) {
17296     if (isDefined(regexp)) {
17297       imgSrcSanitizationWhitelist = regexp;
17298       return this;
17299     }
17300     return imgSrcSanitizationWhitelist;
17301   };
17302
17303   this.$get = function() {
17304     return function sanitizeUri(uri, isImage) {
17305       var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
17306       var normalizedVal;
17307       normalizedVal = urlResolve(uri).href;
17308       if (normalizedVal !== '' && !normalizedVal.match(regex)) {
17309         return 'unsafe:' + normalizedVal;
17310       }
17311       return uri;
17312     };
17313   };
17314 }
17315
17316 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
17317  *     Any commits to this file should be reviewed with security in mind.  *
17318  *   Changes to this file can potentially create security vulnerabilities. *
17319  *          An approval from 2 Core members with history of modifying      *
17320  *                         this file is required.                          *
17321  *                                                                         *
17322  *  Does the change somehow allow for arbitrary javascript to be executed? *
17323  *    Or allows for someone to change the prototype of built-in objects?   *
17324  *     Or gives undesired access to variables likes document or window?    *
17325  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
17326
17327 var $sceMinErr = minErr('$sce');
17328
17329 var SCE_CONTEXTS = {
17330   HTML: 'html',
17331   CSS: 'css',
17332   URL: 'url',
17333   // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
17334   // url.  (e.g. ng-include, script src, templateUrl)
17335   RESOURCE_URL: 'resourceUrl',
17336   JS: 'js'
17337 };
17338
17339 // Helper functions follow.
17340
17341 function adjustMatcher(matcher) {
17342   if (matcher === 'self') {
17343     return matcher;
17344   } else if (isString(matcher)) {
17345     // Strings match exactly except for 2 wildcards - '*' and '**'.
17346     // '*' matches any character except those from the set ':/.?&'.
17347     // '**' matches any character (like .* in a RegExp).
17348     // More than 2 *'s raises an error as it's ill defined.
17349     if (matcher.indexOf('***') > -1) {
17350       throw $sceMinErr('iwcard',
17351           'Illegal sequence *** in string matcher.  String: {0}', matcher);
17352     }
17353     matcher = escapeForRegexp(matcher).
17354                   replace('\\*\\*', '.*').
17355                   replace('\\*', '[^:/.?&;]*');
17356     return new RegExp('^' + matcher + '$');
17357   } else if (isRegExp(matcher)) {
17358     // The only other type of matcher allowed is a Regexp.
17359     // Match entire URL / disallow partial matches.
17360     // Flags are reset (i.e. no global, ignoreCase or multiline)
17361     return new RegExp('^' + matcher.source + '$');
17362   } else {
17363     throw $sceMinErr('imatcher',
17364         'Matchers may only be "self", string patterns or RegExp objects');
17365   }
17366 }
17367
17368
17369 function adjustMatchers(matchers) {
17370   var adjustedMatchers = [];
17371   if (isDefined(matchers)) {
17372     forEach(matchers, function(matcher) {
17373       adjustedMatchers.push(adjustMatcher(matcher));
17374     });
17375   }
17376   return adjustedMatchers;
17377 }
17378
17379
17380 /**
17381  * @ngdoc service
17382  * @name $sceDelegate
17383  * @kind function
17384  *
17385  * @description
17386  *
17387  * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
17388  * Contextual Escaping (SCE)} services to AngularJS.
17389  *
17390  * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
17391  * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS.  This is
17392  * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
17393  * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
17394  * work because `$sce` delegates to `$sceDelegate` for these operations.
17395  *
17396  * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
17397  *
17398  * The default instance of `$sceDelegate` should work out of the box with little pain.  While you
17399  * can override it completely to change the behavior of `$sce`, the common case would
17400  * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
17401  * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
17402  * templates.  Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
17403  * $sceDelegateProvider.resourceUrlWhitelist} and {@link
17404  * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
17405  */
17406
17407 /**
17408  * @ngdoc provider
17409  * @name $sceDelegateProvider
17410  * @description
17411  *
17412  * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
17413  * $sceDelegate} service.  This allows one to get/set the whitelists and blacklists used to ensure
17414  * that the URLs used for sourcing Angular templates are safe.  Refer {@link
17415  * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
17416  * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
17417  *
17418  * For the general details about this service in Angular, read the main page for {@link ng.$sce
17419  * Strict Contextual Escaping (SCE)}.
17420  *
17421  * **Example**:  Consider the following case. <a name="example"></a>
17422  *
17423  * - your app is hosted at url `http://myapp.example.com/`
17424  * - but some of your templates are hosted on other domains you control such as
17425  *   `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
17426  * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
17427  *
17428  * Here is what a secure configuration for this scenario might look like:
17429  *
17430  * ```
17431  *  angular.module('myApp', []).config(function($sceDelegateProvider) {
17432  *    $sceDelegateProvider.resourceUrlWhitelist([
17433  *      // Allow same origin resource loads.
17434  *      'self',
17435  *      // Allow loading from our assets domain.  Notice the difference between * and **.
17436  *      'http://srv*.assets.example.com/**'
17437  *    ]);
17438  *
17439  *    // The blacklist overrides the whitelist so the open redirect here is blocked.
17440  *    $sceDelegateProvider.resourceUrlBlacklist([
17441  *      'http://myapp.example.com/clickThru**'
17442  *    ]);
17443  *  });
17444  * ```
17445  */
17446
17447 function $SceDelegateProvider() {
17448   this.SCE_CONTEXTS = SCE_CONTEXTS;
17449
17450   // Resource URLs can also be trusted by policy.
17451   var resourceUrlWhitelist = ['self'],
17452       resourceUrlBlacklist = [];
17453
17454   /**
17455    * @ngdoc method
17456    * @name $sceDelegateProvider#resourceUrlWhitelist
17457    * @kind function
17458    *
17459    * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
17460    *    provided.  This must be an array or null.  A snapshot of this array is used so further
17461    *    changes to the array are ignored.
17462    *
17463    *    Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
17464    *    allowed in this array.
17465    *
17466    *    <div class="alert alert-warning">
17467    *    **Note:** an empty whitelist array will block all URLs!
17468    *    </div>
17469    *
17470    * @return {Array} the currently set whitelist array.
17471    *
17472    * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
17473    * same origin resource requests.
17474    *
17475    * @description
17476    * Sets/Gets the whitelist of trusted resource URLs.
17477    */
17478   this.resourceUrlWhitelist = function(value) {
17479     if (arguments.length) {
17480       resourceUrlWhitelist = adjustMatchers(value);
17481     }
17482     return resourceUrlWhitelist;
17483   };
17484
17485   /**
17486    * @ngdoc method
17487    * @name $sceDelegateProvider#resourceUrlBlacklist
17488    * @kind function
17489    *
17490    * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
17491    *    provided.  This must be an array or null.  A snapshot of this array is used so further
17492    *    changes to the array are ignored.
17493    *
17494    *    Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
17495    *    allowed in this array.
17496    *
17497    *    The typical usage for the blacklist is to **block
17498    *    [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
17499    *    these would otherwise be trusted but actually return content from the redirected domain.
17500    *
17501    *    Finally, **the blacklist overrides the whitelist** and has the final say.
17502    *
17503    * @return {Array} the currently set blacklist array.
17504    *
17505    * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
17506    * is no blacklist.)
17507    *
17508    * @description
17509    * Sets/Gets the blacklist of trusted resource URLs.
17510    */
17511
17512   this.resourceUrlBlacklist = function(value) {
17513     if (arguments.length) {
17514       resourceUrlBlacklist = adjustMatchers(value);
17515     }
17516     return resourceUrlBlacklist;
17517   };
17518
17519   this.$get = ['$injector', function($injector) {
17520
17521     var htmlSanitizer = function htmlSanitizer(html) {
17522       throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
17523     };
17524
17525     if ($injector.has('$sanitize')) {
17526       htmlSanitizer = $injector.get('$sanitize');
17527     }
17528
17529
17530     function matchUrl(matcher, parsedUrl) {
17531       if (matcher === 'self') {
17532         return urlIsSameOrigin(parsedUrl);
17533       } else {
17534         // definitely a regex.  See adjustMatchers()
17535         return !!matcher.exec(parsedUrl.href);
17536       }
17537     }
17538
17539     function isResourceUrlAllowedByPolicy(url) {
17540       var parsedUrl = urlResolve(url.toString());
17541       var i, n, allowed = false;
17542       // Ensure that at least one item from the whitelist allows this url.
17543       for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
17544         if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
17545           allowed = true;
17546           break;
17547         }
17548       }
17549       if (allowed) {
17550         // Ensure that no item from the blacklist blocked this url.
17551         for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
17552           if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
17553             allowed = false;
17554             break;
17555           }
17556         }
17557       }
17558       return allowed;
17559     }
17560
17561     function generateHolderType(Base) {
17562       var holderType = function TrustedValueHolderType(trustedValue) {
17563         this.$$unwrapTrustedValue = function() {
17564           return trustedValue;
17565         };
17566       };
17567       if (Base) {
17568         holderType.prototype = new Base();
17569       }
17570       holderType.prototype.valueOf = function sceValueOf() {
17571         return this.$$unwrapTrustedValue();
17572       };
17573       holderType.prototype.toString = function sceToString() {
17574         return this.$$unwrapTrustedValue().toString();
17575       };
17576       return holderType;
17577     }
17578
17579     var trustedValueHolderBase = generateHolderType(),
17580         byType = {};
17581
17582     byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
17583     byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
17584     byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
17585     byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
17586     byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
17587
17588     /**
17589      * @ngdoc method
17590      * @name $sceDelegate#trustAs
17591      *
17592      * @description
17593      * Returns an object that is trusted by angular for use in specified strict
17594      * contextual escaping contexts (such as ng-bind-html, ng-include, any src
17595      * attribute interpolation, any dom event binding attribute interpolation
17596      * such as for onclick,  etc.) that uses the provided value.
17597      * See {@link ng.$sce $sce} for enabling strict contextual escaping.
17598      *
17599      * @param {string} type The kind of context in which this value is safe for use.  e.g. url,
17600      *   resourceUrl, html, js and css.
17601      * @param {*} value The value that that should be considered trusted/safe.
17602      * @returns {*} A value that can be used to stand in for the provided `value` in places
17603      * where Angular expects a $sce.trustAs() return value.
17604      */
17605     function trustAs(type, trustedValue) {
17606       var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
17607       if (!Constructor) {
17608         throw $sceMinErr('icontext',
17609             'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
17610             type, trustedValue);
17611       }
17612       if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
17613         return trustedValue;
17614       }
17615       // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting
17616       // mutable objects, we ensure here that the value passed in is actually a string.
17617       if (typeof trustedValue !== 'string') {
17618         throw $sceMinErr('itype',
17619             'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
17620             type);
17621       }
17622       return new Constructor(trustedValue);
17623     }
17624
17625     /**
17626      * @ngdoc method
17627      * @name $sceDelegate#valueOf
17628      *
17629      * @description
17630      * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
17631      * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
17632      * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
17633      *
17634      * If the passed parameter is not a value that had been returned by {@link
17635      * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
17636      *
17637      * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
17638      *      call or anything else.
17639      * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
17640      *     `$sceDelegate.trustAs`} if `value` is the result of such a call.  Otherwise, returns
17641      *     `value` unchanged.
17642      */
17643     function valueOf(maybeTrusted) {
17644       if (maybeTrusted instanceof trustedValueHolderBase) {
17645         return maybeTrusted.$$unwrapTrustedValue();
17646       } else {
17647         return maybeTrusted;
17648       }
17649     }
17650
17651     /**
17652      * @ngdoc method
17653      * @name $sceDelegate#getTrusted
17654      *
17655      * @description
17656      * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
17657      * returns the originally supplied value if the queried context type is a supertype of the
17658      * created type.  If this condition isn't satisfied, throws an exception.
17659      *
17660      * <div class="alert alert-danger">
17661      * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
17662      * (XSS) vulnerability in your application.
17663      * </div>
17664      *
17665      * @param {string} type The kind of context in which this value is to be used.
17666      * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
17667      *     `$sceDelegate.trustAs`} call.
17668      * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
17669      *     `$sceDelegate.trustAs`} if valid in this context.  Otherwise, throws an exception.
17670      */
17671     function getTrusted(type, maybeTrusted) {
17672       if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
17673         return maybeTrusted;
17674       }
17675       var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
17676       if (constructor && maybeTrusted instanceof constructor) {
17677         return maybeTrusted.$$unwrapTrustedValue();
17678       }
17679       // If we get here, then we may only take one of two actions.
17680       // 1. sanitize the value for the requested type, or
17681       // 2. throw an exception.
17682       if (type === SCE_CONTEXTS.RESOURCE_URL) {
17683         if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
17684           return maybeTrusted;
17685         } else {
17686           throw $sceMinErr('insecurl',
17687               'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: {0}',
17688               maybeTrusted.toString());
17689         }
17690       } else if (type === SCE_CONTEXTS.HTML) {
17691         return htmlSanitizer(maybeTrusted);
17692       }
17693       throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
17694     }
17695
17696     return { trustAs: trustAs,
17697              getTrusted: getTrusted,
17698              valueOf: valueOf };
17699   }];
17700 }
17701
17702
17703 /**
17704  * @ngdoc provider
17705  * @name $sceProvider
17706  * @description
17707  *
17708  * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
17709  * -   enable/disable Strict Contextual Escaping (SCE) in a module
17710  * -   override the default implementation with a custom delegate
17711  *
17712  * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
17713  */
17714
17715 /* jshint maxlen: false*/
17716
17717 /**
17718  * @ngdoc service
17719  * @name $sce
17720  * @kind function
17721  *
17722  * @description
17723  *
17724  * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
17725  *
17726  * # Strict Contextual Escaping
17727  *
17728  * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
17729  * contexts to result in a value that is marked as safe to use for that context.  One example of
17730  * such a context is binding arbitrary html controlled by the user via `ng-bind-html`.  We refer
17731  * to these contexts as privileged or SCE contexts.
17732  *
17733  * As of version 1.2, Angular ships with SCE enabled by default.
17734  *
17735  * Note:  When enabled (the default), IE<11 in quirks mode is not supported.  In this mode, IE<11 allow
17736  * one to execute arbitrary javascript by the use of the expression() syntax.  Refer
17737  * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
17738  * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
17739  * to the top of your HTML document.
17740  *
17741  * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
17742  * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
17743  *
17744  * Here's an example of a binding in a privileged context:
17745  *
17746  * ```
17747  * <input ng-model="userHtml" aria-label="User input">
17748  * <div ng-bind-html="userHtml"></div>
17749  * ```
17750  *
17751  * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user.  With SCE
17752  * disabled, this application allows the user to render arbitrary HTML into the DIV.
17753  * In a more realistic example, one may be rendering user comments, blog articles, etc. via
17754  * bindings.  (HTML is just one example of a context where rendering user controlled input creates
17755  * security vulnerabilities.)
17756  *
17757  * For the case of HTML, you might use a library, either on the client side, or on the server side,
17758  * to sanitize unsafe HTML before binding to the value and rendering it in the document.
17759  *
17760  * How would you ensure that every place that used these types of bindings was bound to a value that
17761  * was sanitized by your library (or returned as safe for rendering by your server?)  How can you
17762  * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
17763  * properties/fields and forgot to update the binding to the sanitized value?
17764  *
17765  * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
17766  * determine that something explicitly says it's safe to use a value for binding in that
17767  * context.  You can then audit your code (a simple grep would do) to ensure that this is only done
17768  * for those values that you can easily tell are safe - because they were received from your server,
17769  * sanitized by your library, etc.  You can organize your codebase to help with this - perhaps
17770  * allowing only the files in a specific directory to do this.  Ensuring that the internal API
17771  * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
17772  *
17773  * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
17774  * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
17775  * obtain values that will be accepted by SCE / privileged contexts.
17776  *
17777  *
17778  * ## How does it work?
17779  *
17780  * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
17781  * $sce.getTrusted(context, value)} rather than to the value directly.  Directives use {@link
17782  * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
17783  * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
17784  *
17785  * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
17786  * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}.  Here's the actual code (slightly
17787  * simplified):
17788  *
17789  * ```
17790  * var ngBindHtmlDirective = ['$sce', function($sce) {
17791  *   return function(scope, element, attr) {
17792  *     scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
17793  *       element.html(value || '');
17794  *     });
17795  *   };
17796  * }];
17797  * ```
17798  *
17799  * ## Impact on loading templates
17800  *
17801  * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
17802  * `templateUrl`'s specified by {@link guide/directive directives}.
17803  *
17804  * By default, Angular only loads templates from the same domain and protocol as the application
17805  * document.  This is done by calling {@link ng.$sce#getTrustedResourceUrl
17806  * $sce.getTrustedResourceUrl} on the template URL.  To load templates from other domains and/or
17807  * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
17808  * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
17809  *
17810  * *Please note*:
17811  * The browser's
17812  * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
17813  * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
17814  * policy apply in addition to this and may further restrict whether the template is successfully
17815  * loaded.  This means that without the right CORS policy, loading templates from a different domain
17816  * won't work on all browsers.  Also, loading templates from `file://` URL does not work on some
17817  * browsers.
17818  *
17819  * ## This feels like too much overhead
17820  *
17821  * It's important to remember that SCE only applies to interpolation expressions.
17822  *
17823  * If your expressions are constant literals, they're automatically trusted and you don't need to
17824  * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
17825  * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
17826  *
17827  * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
17828  * through {@link ng.$sce#getTrusted $sce.getTrusted}.  SCE doesn't play a role here.
17829  *
17830  * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
17831  * templates in `ng-include` from your application's domain without having to even know about SCE.
17832  * It blocks loading templates from other domains or loading templates over http from an https
17833  * served document.  You can change these by setting your own custom {@link
17834  * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
17835  * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
17836  *
17837  * This significantly reduces the overhead.  It is far easier to pay the small overhead and have an
17838  * application that's secure and can be audited to verify that with much more ease than bolting
17839  * security onto an application later.
17840  *
17841  * <a name="contexts"></a>
17842  * ## What trusted context types are supported?
17843  *
17844  * | Context             | Notes          |
17845  * |---------------------|----------------|
17846  * | `$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. |
17847  * | `$sce.CSS`          | For CSS that's safe to source into the application.  Currently unused.  Feel free to use it in your own directives. |
17848  * | `$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. |
17849  * | `$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. |
17850  * | `$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. |
17851  *
17852  * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
17853  *
17854  *  Each element in these arrays must be one of the following:
17855  *
17856  *  - **'self'**
17857  *    - The special **string**, `'self'`, can be used to match against all URLs of the **same
17858  *      domain** as the application document using the **same protocol**.
17859  *  - **String** (except the special value `'self'`)
17860  *    - The string is matched against the full *normalized / absolute URL* of the resource
17861  *      being tested (substring matches are not good enough.)
17862  *    - There are exactly **two wildcard sequences** - `*` and `**`.  All other characters
17863  *      match themselves.
17864  *    - `*`: matches zero or more occurrences of any character other than one of the following 6
17865  *      characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'.  It's a useful wildcard for use
17866  *      in a whitelist.
17867  *    - `**`: matches zero or more occurrences of *any* character.  As such, it's not
17868  *      appropriate for use in a scheme, domain, etc. as it would match too much.  (e.g.
17869  *      http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
17870  *      not have been the intention.)  Its usage at the very end of the path is ok.  (e.g.
17871  *      http://foo.example.com/templates/**).
17872  *  - **RegExp** (*see caveat below*)
17873  *    - *Caveat*:  While regular expressions are powerful and offer great flexibility,  their syntax
17874  *      (and all the inevitable escaping) makes them *harder to maintain*.  It's easy to
17875  *      accidentally introduce a bug when one updates a complex expression (imho, all regexes should
17876  *      have good test coverage).  For instance, the use of `.` in the regex is correct only in a
17877  *      small number of cases.  A `.` character in the regex used when matching the scheme or a
17878  *      subdomain could be matched against a `:` or literal `.` that was likely not intended.   It
17879  *      is highly recommended to use the string patterns and only fall back to regular expressions
17880  *      as a last resort.
17881  *    - The regular expression must be an instance of RegExp (i.e. not a string.)  It is
17882  *      matched against the **entire** *normalized / absolute URL* of the resource being tested
17883  *      (even when the RegExp did not have the `^` and `$` codes.)  In addition, any flags
17884  *      present on the RegExp (such as multiline, global, ignoreCase) are ignored.
17885  *    - If you are generating your JavaScript from some other templating engine (not
17886  *      recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
17887  *      remember to escape your regular expression (and be aware that you might need more than
17888  *      one level of escaping depending on your templating engine and the way you interpolated
17889  *      the value.)  Do make use of your platform's escaping mechanism as it might be good
17890  *      enough before coding your own.  E.g. Ruby has
17891  *      [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
17892  *      and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
17893  *      Javascript lacks a similar built in function for escaping.  Take a look at Google
17894  *      Closure library's [goog.string.regExpEscape(s)](
17895  *      http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
17896  *
17897  * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
17898  *
17899  * ## Show me an example using SCE.
17900  *
17901  * <example module="mySceApp" deps="angular-sanitize.js">
17902  * <file name="index.html">
17903  *   <div ng-controller="AppController as myCtrl">
17904  *     <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
17905  *     <b>User comments</b><br>
17906  *     By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
17907  *     $sanitize is available.  If $sanitize isn't available, this results in an error instead of an
17908  *     exploit.
17909  *     <div class="well">
17910  *       <div ng-repeat="userComment in myCtrl.userComments">
17911  *         <b>{{userComment.name}}</b>:
17912  *         <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
17913  *         <br>
17914  *       </div>
17915  *     </div>
17916  *   </div>
17917  * </file>
17918  *
17919  * <file name="script.js">
17920  *   angular.module('mySceApp', ['ngSanitize'])
17921  *     .controller('AppController', ['$http', '$templateCache', '$sce',
17922  *       function($http, $templateCache, $sce) {
17923  *         var self = this;
17924  *         $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
17925  *           self.userComments = userComments;
17926  *         });
17927  *         self.explicitlyTrustedHtml = $sce.trustAsHtml(
17928  *             '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
17929  *             'sanitization.&quot;">Hover over this text.</span>');
17930  *       }]);
17931  * </file>
17932  *
17933  * <file name="test_data.json">
17934  * [
17935  *   { "name": "Alice",
17936  *     "htmlComment":
17937  *         "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
17938  *   },
17939  *   { "name": "Bob",
17940  *     "htmlComment": "<i>Yes!</i>  Am I the only other one?"
17941  *   }
17942  * ]
17943  * </file>
17944  *
17945  * <file name="protractor.js" type="protractor">
17946  *   describe('SCE doc demo', function() {
17947  *     it('should sanitize untrusted values', function() {
17948  *       expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
17949  *           .toBe('<span>Is <i>anyone</i> reading this?</span>');
17950  *     });
17951  *
17952  *     it('should NOT sanitize explicitly trusted values', function() {
17953  *       expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
17954  *           '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
17955  *           'sanitization.&quot;">Hover over this text.</span>');
17956  *     });
17957  *   });
17958  * </file>
17959  * </example>
17960  *
17961  *
17962  *
17963  * ## Can I disable SCE completely?
17964  *
17965  * Yes, you can.  However, this is strongly discouraged.  SCE gives you a lot of security benefits
17966  * for little coding overhead.  It will be much harder to take an SCE disabled application and
17967  * either secure it on your own or enable SCE at a later stage.  It might make sense to disable SCE
17968  * for cases where you have a lot of existing code that was written before SCE was introduced and
17969  * you're migrating them a module at a time.
17970  *
17971  * That said, here's how you can completely disable SCE:
17972  *
17973  * ```
17974  * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
17975  *   // Completely disable SCE.  For demonstration purposes only!
17976  *   // Do not use in new projects.
17977  *   $sceProvider.enabled(false);
17978  * });
17979  * ```
17980  *
17981  */
17982 /* jshint maxlen: 100 */
17983
17984 function $SceProvider() {
17985   var enabled = true;
17986
17987   /**
17988    * @ngdoc method
17989    * @name $sceProvider#enabled
17990    * @kind function
17991    *
17992    * @param {boolean=} value If provided, then enables/disables SCE.
17993    * @return {boolean} true if SCE is enabled, false otherwise.
17994    *
17995    * @description
17996    * Enables/disables SCE and returns the current value.
17997    */
17998   this.enabled = function(value) {
17999     if (arguments.length) {
18000       enabled = !!value;
18001     }
18002     return enabled;
18003   };
18004
18005
18006   /* Design notes on the default implementation for SCE.
18007    *
18008    * The API contract for the SCE delegate
18009    * -------------------------------------
18010    * The SCE delegate object must provide the following 3 methods:
18011    *
18012    * - trustAs(contextEnum, value)
18013    *     This method is used to tell the SCE service that the provided value is OK to use in the
18014    *     contexts specified by contextEnum.  It must return an object that will be accepted by
18015    *     getTrusted() for a compatible contextEnum and return this value.
18016    *
18017    * - valueOf(value)
18018    *     For values that were not produced by trustAs(), return them as is.  For values that were
18019    *     produced by trustAs(), return the corresponding input value to trustAs.  Basically, if
18020    *     trustAs is wrapping the given values into some type, this operation unwraps it when given
18021    *     such a value.
18022    *
18023    * - getTrusted(contextEnum, value)
18024    *     This function should return the a value that is safe to use in the context specified by
18025    *     contextEnum or throw and exception otherwise.
18026    *
18027    * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
18028    * opaque or wrapped in some holder object.  That happens to be an implementation detail.  For
18029    * instance, an implementation could maintain a registry of all trusted objects by context.  In
18030    * such a case, trustAs() would return the same object that was passed in.  getTrusted() would
18031    * return the same object passed in if it was found in the registry under a compatible context or
18032    * throw an exception otherwise.  An implementation might only wrap values some of the time based
18033    * on some criteria.  getTrusted() might return a value and not throw an exception for special
18034    * constants or objects even if not wrapped.  All such implementations fulfill this contract.
18035    *
18036    *
18037    * A note on the inheritance model for SCE contexts
18038    * ------------------------------------------------
18039    * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types.  This
18040    * is purely an implementation details.
18041    *
18042    * The contract is simply this:
18043    *
18044    *     getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
18045    *     will also succeed.
18046    *
18047    * Inheritance happens to capture this in a natural way.  In some future, we
18048    * may not use inheritance anymore.  That is OK because no code outside of
18049    * sce.js and sceSpecs.js would need to be aware of this detail.
18050    */
18051
18052   this.$get = ['$parse', '$sceDelegate', function(
18053                 $parse,   $sceDelegate) {
18054     // Prereq: Ensure that we're not running in IE<11 quirks mode.  In that mode, IE < 11 allow
18055     // the "expression(javascript expression)" syntax which is insecure.
18056     if (enabled && msie < 8) {
18057       throw $sceMinErr('iequirks',
18058         'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
18059         'mode.  You can fix this by adding the text <!doctype html> to the top of your HTML ' +
18060         'document.  See http://docs.angularjs.org/api/ng.$sce for more information.');
18061     }
18062
18063     var sce = shallowCopy(SCE_CONTEXTS);
18064
18065     /**
18066      * @ngdoc method
18067      * @name $sce#isEnabled
18068      * @kind function
18069      *
18070      * @return {Boolean} true if SCE is enabled, false otherwise.  If you want to set the value, you
18071      * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
18072      *
18073      * @description
18074      * Returns a boolean indicating if SCE is enabled.
18075      */
18076     sce.isEnabled = function() {
18077       return enabled;
18078     };
18079     sce.trustAs = $sceDelegate.trustAs;
18080     sce.getTrusted = $sceDelegate.getTrusted;
18081     sce.valueOf = $sceDelegate.valueOf;
18082
18083     if (!enabled) {
18084       sce.trustAs = sce.getTrusted = function(type, value) { return value; };
18085       sce.valueOf = identity;
18086     }
18087
18088     /**
18089      * @ngdoc method
18090      * @name $sce#parseAs
18091      *
18092      * @description
18093      * Converts Angular {@link guide/expression expression} into a function.  This is like {@link
18094      * ng.$parse $parse} and is identical when the expression is a literal constant.  Otherwise, it
18095      * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
18096      * *result*)}
18097      *
18098      * @param {string} type The kind of SCE context in which this result will be used.
18099      * @param {string} expression String expression to compile.
18100      * @returns {function(context, locals)} a function which represents the compiled expression:
18101      *
18102      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
18103      *      are evaluated against (typically a scope object).
18104      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
18105      *      `context`.
18106      */
18107     sce.parseAs = function sceParseAs(type, expr) {
18108       var parsed = $parse(expr);
18109       if (parsed.literal && parsed.constant) {
18110         return parsed;
18111       } else {
18112         return $parse(expr, function(value) {
18113           return sce.getTrusted(type, value);
18114         });
18115       }
18116     };
18117
18118     /**
18119      * @ngdoc method
18120      * @name $sce#trustAs
18121      *
18122      * @description
18123      * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.  As such,
18124      * returns an object that is trusted by angular for use in specified strict contextual
18125      * escaping contexts (such as ng-bind-html, ng-include, any src attribute
18126      * interpolation, any dom event binding attribute interpolation such as for onclick,  etc.)
18127      * that uses the provided value.  See * {@link ng.$sce $sce} for enabling strict contextual
18128      * escaping.
18129      *
18130      * @param {string} type The kind of context in which this value is safe for use.  e.g. url,
18131      *   resourceUrl, html, js and css.
18132      * @param {*} value The value that that should be considered trusted/safe.
18133      * @returns {*} A value that can be used to stand in for the provided `value` in places
18134      * where Angular expects a $sce.trustAs() return value.
18135      */
18136
18137     /**
18138      * @ngdoc method
18139      * @name $sce#trustAsHtml
18140      *
18141      * @description
18142      * Shorthand method.  `$sce.trustAsHtml(value)` →
18143      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
18144      *
18145      * @param {*} value The value to trustAs.
18146      * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
18147      *     $sce.getTrustedHtml(value)} to obtain the original value.  (privileged directives
18148      *     only accept expressions that are either literal constants or are the
18149      *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
18150      */
18151
18152     /**
18153      * @ngdoc method
18154      * @name $sce#trustAsUrl
18155      *
18156      * @description
18157      * Shorthand method.  `$sce.trustAsUrl(value)` →
18158      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
18159      *
18160      * @param {*} value The value to trustAs.
18161      * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
18162      *     $sce.getTrustedUrl(value)} to obtain the original value.  (privileged directives
18163      *     only accept expressions that are either literal constants or are the
18164      *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
18165      */
18166
18167     /**
18168      * @ngdoc method
18169      * @name $sce#trustAsResourceUrl
18170      *
18171      * @description
18172      * Shorthand method.  `$sce.trustAsResourceUrl(value)` →
18173      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
18174      *
18175      * @param {*} value The value to trustAs.
18176      * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
18177      *     $sce.getTrustedResourceUrl(value)} to obtain the original value.  (privileged directives
18178      *     only accept expressions that are either literal constants or are the return
18179      *     value of {@link ng.$sce#trustAs $sce.trustAs}.)
18180      */
18181
18182     /**
18183      * @ngdoc method
18184      * @name $sce#trustAsJs
18185      *
18186      * @description
18187      * Shorthand method.  `$sce.trustAsJs(value)` →
18188      *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
18189      *
18190      * @param {*} value The value to trustAs.
18191      * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
18192      *     $sce.getTrustedJs(value)} to obtain the original value.  (privileged directives
18193      *     only accept expressions that are either literal constants or are the
18194      *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)
18195      */
18196
18197     /**
18198      * @ngdoc method
18199      * @name $sce#getTrusted
18200      *
18201      * @description
18202      * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}.  As such,
18203      * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
18204      * originally supplied value if the queried context type is a supertype of the created type.
18205      * If this condition isn't satisfied, throws an exception.
18206      *
18207      * @param {string} type The kind of context in which this value is to be used.
18208      * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
18209      *                         call.
18210      * @returns {*} The value the was originally provided to
18211      *              {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
18212      *              Otherwise, throws an exception.
18213      */
18214
18215     /**
18216      * @ngdoc method
18217      * @name $sce#getTrustedHtml
18218      *
18219      * @description
18220      * Shorthand method.  `$sce.getTrustedHtml(value)` →
18221      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
18222      *
18223      * @param {*} value The value to pass to `$sce.getTrusted`.
18224      * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
18225      */
18226
18227     /**
18228      * @ngdoc method
18229      * @name $sce#getTrustedCss
18230      *
18231      * @description
18232      * Shorthand method.  `$sce.getTrustedCss(value)` →
18233      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
18234      *
18235      * @param {*} value The value to pass to `$sce.getTrusted`.
18236      * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
18237      */
18238
18239     /**
18240      * @ngdoc method
18241      * @name $sce#getTrustedUrl
18242      *
18243      * @description
18244      * Shorthand method.  `$sce.getTrustedUrl(value)` →
18245      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
18246      *
18247      * @param {*} value The value to pass to `$sce.getTrusted`.
18248      * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
18249      */
18250
18251     /**
18252      * @ngdoc method
18253      * @name $sce#getTrustedResourceUrl
18254      *
18255      * @description
18256      * Shorthand method.  `$sce.getTrustedResourceUrl(value)` →
18257      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
18258      *
18259      * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
18260      * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
18261      */
18262
18263     /**
18264      * @ngdoc method
18265      * @name $sce#getTrustedJs
18266      *
18267      * @description
18268      * Shorthand method.  `$sce.getTrustedJs(value)` →
18269      *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
18270      *
18271      * @param {*} value The value to pass to `$sce.getTrusted`.
18272      * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
18273      */
18274
18275     /**
18276      * @ngdoc method
18277      * @name $sce#parseAsHtml
18278      *
18279      * @description
18280      * Shorthand method.  `$sce.parseAsHtml(expression string)` →
18281      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
18282      *
18283      * @param {string} expression String expression to compile.
18284      * @returns {function(context, locals)} a function which represents the compiled expression:
18285      *
18286      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
18287      *      are evaluated against (typically a scope object).
18288      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
18289      *      `context`.
18290      */
18291
18292     /**
18293      * @ngdoc method
18294      * @name $sce#parseAsCss
18295      *
18296      * @description
18297      * Shorthand method.  `$sce.parseAsCss(value)` →
18298      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
18299      *
18300      * @param {string} expression String expression to compile.
18301      * @returns {function(context, locals)} a function which represents the compiled expression:
18302      *
18303      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
18304      *      are evaluated against (typically a scope object).
18305      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
18306      *      `context`.
18307      */
18308
18309     /**
18310      * @ngdoc method
18311      * @name $sce#parseAsUrl
18312      *
18313      * @description
18314      * Shorthand method.  `$sce.parseAsUrl(value)` →
18315      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
18316      *
18317      * @param {string} expression String expression to compile.
18318      * @returns {function(context, locals)} a function which represents the compiled expression:
18319      *
18320      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
18321      *      are evaluated against (typically a scope object).
18322      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
18323      *      `context`.
18324      */
18325
18326     /**
18327      * @ngdoc method
18328      * @name $sce#parseAsResourceUrl
18329      *
18330      * @description
18331      * Shorthand method.  `$sce.parseAsResourceUrl(value)` →
18332      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
18333      *
18334      * @param {string} expression String expression to compile.
18335      * @returns {function(context, locals)} a function which represents the compiled expression:
18336      *
18337      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
18338      *      are evaluated against (typically a scope object).
18339      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
18340      *      `context`.
18341      */
18342
18343     /**
18344      * @ngdoc method
18345      * @name $sce#parseAsJs
18346      *
18347      * @description
18348      * Shorthand method.  `$sce.parseAsJs(value)` →
18349      *     {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
18350      *
18351      * @param {string} expression String expression to compile.
18352      * @returns {function(context, locals)} a function which represents the compiled expression:
18353      *
18354      *    * `context` – `{object}` – an object against which any expressions embedded in the strings
18355      *      are evaluated against (typically a scope object).
18356      *    * `locals` – `{object=}` – local variables context object, useful for overriding values in
18357      *      `context`.
18358      */
18359
18360     // Shorthand delegations.
18361     var parse = sce.parseAs,
18362         getTrusted = sce.getTrusted,
18363         trustAs = sce.trustAs;
18364
18365     forEach(SCE_CONTEXTS, function(enumValue, name) {
18366       var lName = lowercase(name);
18367       sce[camelCase("parse_as_" + lName)] = function(expr) {
18368         return parse(enumValue, expr);
18369       };
18370       sce[camelCase("get_trusted_" + lName)] = function(value) {
18371         return getTrusted(enumValue, value);
18372       };
18373       sce[camelCase("trust_as_" + lName)] = function(value) {
18374         return trustAs(enumValue, value);
18375       };
18376     });
18377
18378     return sce;
18379   }];
18380 }
18381
18382 /**
18383  * !!! This is an undocumented "private" service !!!
18384  *
18385  * @name $sniffer
18386  * @requires $window
18387  * @requires $document
18388  *
18389  * @property {boolean} history Does the browser support html5 history api ?
18390  * @property {boolean} transitions Does the browser support CSS transition events ?
18391  * @property {boolean} animations Does the browser support CSS animation events ?
18392  *
18393  * @description
18394  * This is very simple implementation of testing browser's features.
18395  */
18396 function $SnifferProvider() {
18397   this.$get = ['$window', '$document', function($window, $document) {
18398     var eventSupport = {},
18399         android =
18400           toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
18401         boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
18402         document = $document[0] || {},
18403         vendorPrefix,
18404         vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
18405         bodyStyle = document.body && document.body.style,
18406         transitions = false,
18407         animations = false,
18408         match;
18409
18410     if (bodyStyle) {
18411       for (var prop in bodyStyle) {
18412         if (match = vendorRegex.exec(prop)) {
18413           vendorPrefix = match[0];
18414           vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
18415           break;
18416         }
18417       }
18418
18419       if (!vendorPrefix) {
18420         vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
18421       }
18422
18423       transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
18424       animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
18425
18426       if (android && (!transitions ||  !animations)) {
18427         transitions = isString(bodyStyle.webkitTransition);
18428         animations = isString(bodyStyle.webkitAnimation);
18429       }
18430     }
18431
18432
18433     return {
18434       // Android has history.pushState, but it does not update location correctly
18435       // so let's not use the history API at all.
18436       // http://code.google.com/p/android/issues/detail?id=17471
18437       // https://github.com/angular/angular.js/issues/904
18438
18439       // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
18440       // so let's not use the history API also
18441       // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
18442       // jshint -W018
18443       history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
18444       // jshint +W018
18445       hasEvent: function(event) {
18446         // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
18447         // it. In particular the event is not fired when backspace or delete key are pressed or
18448         // when cut operation is performed.
18449         // IE10+ implements 'input' event but it erroneously fires under various situations,
18450         // e.g. when placeholder changes, or a form is focused.
18451         if (event === 'input' && msie <= 11) return false;
18452
18453         if (isUndefined(eventSupport[event])) {
18454           var divElm = document.createElement('div');
18455           eventSupport[event] = 'on' + event in divElm;
18456         }
18457
18458         return eventSupport[event];
18459       },
18460       csp: csp(),
18461       vendorPrefix: vendorPrefix,
18462       transitions: transitions,
18463       animations: animations,
18464       android: android
18465     };
18466   }];
18467 }
18468
18469 var $compileMinErr = minErr('$compile');
18470
18471 /**
18472  * @ngdoc provider
18473  * @name $templateRequestProvider
18474  * @description
18475  * Used to configure the options passed to the {@link $http} service when making a template request.
18476  *
18477  * For example, it can be used for specifying the "Accept" header that is sent to the server, when
18478  * requesting a template.
18479  */
18480 function $TemplateRequestProvider() {
18481
18482   var httpOptions;
18483
18484   /**
18485    * @ngdoc method
18486    * @name $templateRequestProvider#httpOptions
18487    * @description
18488    * The options to be passed to the {@link $http} service when making the request.
18489    * You can use this to override options such as the "Accept" header for template requests.
18490    *
18491    * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
18492    * options if not overridden here.
18493    *
18494    * @param {string=} value new value for the {@link $http} options.
18495    * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
18496    */
18497   this.httpOptions = function(val) {
18498     if (val) {
18499       httpOptions = val;
18500       return this;
18501     }
18502     return httpOptions;
18503   };
18504
18505   /**
18506    * @ngdoc service
18507    * @name $templateRequest
18508    *
18509    * @description
18510    * The `$templateRequest` service runs security checks then downloads the provided template using
18511    * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
18512    * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
18513    * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
18514    * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
18515    * when `tpl` is of type string and `$templateCache` has the matching entry.
18516    *
18517    * If you want to pass custom options to the `$http` service, such as setting the Accept header you
18518    * can configure this via {@link $templateRequestProvider#httpOptions}.
18519    *
18520    * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
18521    * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
18522    *
18523    * @return {Promise} a promise for the HTTP response data of the given URL.
18524    *
18525    * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
18526    */
18527   this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
18528
18529     function handleRequestFn(tpl, ignoreRequestError) {
18530       handleRequestFn.totalPendingRequests++;
18531
18532       // We consider the template cache holds only trusted templates, so
18533       // there's no need to go through whitelisting again for keys that already
18534       // are included in there. This also makes Angular accept any script
18535       // directive, no matter its name. However, we still need to unwrap trusted
18536       // types.
18537       if (!isString(tpl) || !$templateCache.get(tpl)) {
18538         tpl = $sce.getTrustedResourceUrl(tpl);
18539       }
18540
18541       var transformResponse = $http.defaults && $http.defaults.transformResponse;
18542
18543       if (isArray(transformResponse)) {
18544         transformResponse = transformResponse.filter(function(transformer) {
18545           return transformer !== defaultHttpResponseTransform;
18546         });
18547       } else if (transformResponse === defaultHttpResponseTransform) {
18548         transformResponse = null;
18549       }
18550
18551       return $http.get(tpl, extend({
18552           cache: $templateCache,
18553           transformResponse: transformResponse
18554         }, httpOptions))
18555         ['finally'](function() {
18556           handleRequestFn.totalPendingRequests--;
18557         })
18558         .then(function(response) {
18559           $templateCache.put(tpl, response.data);
18560           return response.data;
18561         }, handleError);
18562
18563       function handleError(resp) {
18564         if (!ignoreRequestError) {
18565           throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
18566             tpl, resp.status, resp.statusText);
18567         }
18568         return $q.reject(resp);
18569       }
18570     }
18571
18572     handleRequestFn.totalPendingRequests = 0;
18573
18574     return handleRequestFn;
18575   }];
18576 }
18577
18578 function $$TestabilityProvider() {
18579   this.$get = ['$rootScope', '$browser', '$location',
18580        function($rootScope,   $browser,   $location) {
18581
18582     /**
18583      * @name $testability
18584      *
18585      * @description
18586      * The private $$testability service provides a collection of methods for use when debugging
18587      * or by automated test and debugging tools.
18588      */
18589     var testability = {};
18590
18591     /**
18592      * @name $$testability#findBindings
18593      *
18594      * @description
18595      * Returns an array of elements that are bound (via ng-bind or {{}})
18596      * to expressions matching the input.
18597      *
18598      * @param {Element} element The element root to search from.
18599      * @param {string} expression The binding expression to match.
18600      * @param {boolean} opt_exactMatch If true, only returns exact matches
18601      *     for the expression. Filters and whitespace are ignored.
18602      */
18603     testability.findBindings = function(element, expression, opt_exactMatch) {
18604       var bindings = element.getElementsByClassName('ng-binding');
18605       var matches = [];
18606       forEach(bindings, function(binding) {
18607         var dataBinding = angular.element(binding).data('$binding');
18608         if (dataBinding) {
18609           forEach(dataBinding, function(bindingName) {
18610             if (opt_exactMatch) {
18611               var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
18612               if (matcher.test(bindingName)) {
18613                 matches.push(binding);
18614               }
18615             } else {
18616               if (bindingName.indexOf(expression) != -1) {
18617                 matches.push(binding);
18618               }
18619             }
18620           });
18621         }
18622       });
18623       return matches;
18624     };
18625
18626     /**
18627      * @name $$testability#findModels
18628      *
18629      * @description
18630      * Returns an array of elements that are two-way found via ng-model to
18631      * expressions matching the input.
18632      *
18633      * @param {Element} element The element root to search from.
18634      * @param {string} expression The model expression to match.
18635      * @param {boolean} opt_exactMatch If true, only returns exact matches
18636      *     for the expression.
18637      */
18638     testability.findModels = function(element, expression, opt_exactMatch) {
18639       var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
18640       for (var p = 0; p < prefixes.length; ++p) {
18641         var attributeEquals = opt_exactMatch ? '=' : '*=';
18642         var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
18643         var elements = element.querySelectorAll(selector);
18644         if (elements.length) {
18645           return elements;
18646         }
18647       }
18648     };
18649
18650     /**
18651      * @name $$testability#getLocation
18652      *
18653      * @description
18654      * Shortcut for getting the location in a browser agnostic way. Returns
18655      *     the path, search, and hash. (e.g. /path?a=b#hash)
18656      */
18657     testability.getLocation = function() {
18658       return $location.url();
18659     };
18660
18661     /**
18662      * @name $$testability#setLocation
18663      *
18664      * @description
18665      * Shortcut for navigating to a location without doing a full page reload.
18666      *
18667      * @param {string} url The location url (path, search and hash,
18668      *     e.g. /path?a=b#hash) to go to.
18669      */
18670     testability.setLocation = function(url) {
18671       if (url !== $location.url()) {
18672         $location.url(url);
18673         $rootScope.$digest();
18674       }
18675     };
18676
18677     /**
18678      * @name $$testability#whenStable
18679      *
18680      * @description
18681      * Calls the callback when $timeout and $http requests are completed.
18682      *
18683      * @param {function} callback
18684      */
18685     testability.whenStable = function(callback) {
18686       $browser.notifyWhenNoOutstandingRequests(callback);
18687     };
18688
18689     return testability;
18690   }];
18691 }
18692
18693 function $TimeoutProvider() {
18694   this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
18695        function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {
18696
18697     var deferreds = {};
18698
18699
18700      /**
18701       * @ngdoc service
18702       * @name $timeout
18703       *
18704       * @description
18705       * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
18706       * block and delegates any exceptions to
18707       * {@link ng.$exceptionHandler $exceptionHandler} service.
18708       *
18709       * The return value of calling `$timeout` is a promise, which will be resolved when
18710       * the delay has passed and the timeout function, if provided, is executed.
18711       *
18712       * To cancel a timeout request, call `$timeout.cancel(promise)`.
18713       *
18714       * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
18715       * synchronously flush the queue of deferred functions.
18716       *
18717       * If you only want a promise that will be resolved after some specified delay
18718       * then you can call `$timeout` without the `fn` function.
18719       *
18720       * @param {function()=} fn A function, whose execution should be delayed.
18721       * @param {number=} [delay=0] Delay in milliseconds.
18722       * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
18723       *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
18724       * @param {...*=} Pass additional parameters to the executed function.
18725       * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
18726       *   will be resolved with the return value of the `fn` function.
18727       *
18728       */
18729     function timeout(fn, delay, invokeApply) {
18730       if (!isFunction(fn)) {
18731         invokeApply = delay;
18732         delay = fn;
18733         fn = noop;
18734       }
18735
18736       var args = sliceArgs(arguments, 3),
18737           skipApply = (isDefined(invokeApply) && !invokeApply),
18738           deferred = (skipApply ? $$q : $q).defer(),
18739           promise = deferred.promise,
18740           timeoutId;
18741
18742       timeoutId = $browser.defer(function() {
18743         try {
18744           deferred.resolve(fn.apply(null, args));
18745         } catch (e) {
18746           deferred.reject(e);
18747           $exceptionHandler(e);
18748         }
18749         finally {
18750           delete deferreds[promise.$$timeoutId];
18751         }
18752
18753         if (!skipApply) $rootScope.$apply();
18754       }, delay);
18755
18756       promise.$$timeoutId = timeoutId;
18757       deferreds[timeoutId] = deferred;
18758
18759       return promise;
18760     }
18761
18762
18763      /**
18764       * @ngdoc method
18765       * @name $timeout#cancel
18766       *
18767       * @description
18768       * Cancels a task associated with the `promise`. As a result of this, the promise will be
18769       * resolved with a rejection.
18770       *
18771       * @param {Promise=} promise Promise returned by the `$timeout` function.
18772       * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
18773       *   canceled.
18774       */
18775     timeout.cancel = function(promise) {
18776       if (promise && promise.$$timeoutId in deferreds) {
18777         deferreds[promise.$$timeoutId].reject('canceled');
18778         delete deferreds[promise.$$timeoutId];
18779         return $browser.defer.cancel(promise.$$timeoutId);
18780       }
18781       return false;
18782     };
18783
18784     return timeout;
18785   }];
18786 }
18787
18788 // NOTE:  The usage of window and document instead of $window and $document here is
18789 // deliberate.  This service depends on the specific behavior of anchor nodes created by the
18790 // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
18791 // cause us to break tests.  In addition, when the browser resolves a URL for XHR, it
18792 // doesn't know about mocked locations and resolves URLs to the real document - which is
18793 // exactly the behavior needed here.  There is little value is mocking these out for this
18794 // service.
18795 var urlParsingNode = document.createElement("a");
18796 var originUrl = urlResolve(window.location.href);
18797
18798
18799 /**
18800  *
18801  * Implementation Notes for non-IE browsers
18802  * ----------------------------------------
18803  * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
18804  * results both in the normalizing and parsing of the URL.  Normalizing means that a relative
18805  * URL will be resolved into an absolute URL in the context of the application document.
18806  * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
18807  * properties are all populated to reflect the normalized URL.  This approach has wide
18808  * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc.  See
18809  * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
18810  *
18811  * Implementation Notes for IE
18812  * ---------------------------
18813  * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
18814  * browsers.  However, the parsed components will not be set if the URL assigned did not specify
18815  * them.  (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.)  We
18816  * work around that by performing the parsing in a 2nd step by taking a previously normalized
18817  * URL (e.g. by assigning to a.href) and assigning it a.href again.  This correctly populates the
18818  * properties such as protocol, hostname, port, etc.
18819  *
18820  * References:
18821  *   http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
18822  *   http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
18823  *   http://url.spec.whatwg.org/#urlutils
18824  *   https://github.com/angular/angular.js/pull/2902
18825  *   http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
18826  *
18827  * @kind function
18828  * @param {string} url The URL to be parsed.
18829  * @description Normalizes and parses a URL.
18830  * @returns {object} Returns the normalized URL as a dictionary.
18831  *
18832  *   | member name   | Description    |
18833  *   |---------------|----------------|
18834  *   | href          | A normalized version of the provided URL if it was not an absolute URL |
18835  *   | protocol      | The protocol including the trailing colon                              |
18836  *   | host          | The host and port (if the port is non-default) of the normalizedUrl    |
18837  *   | search        | The search params, minus the question mark                             |
18838  *   | hash          | The hash string, minus the hash symbol
18839  *   | hostname      | The hostname
18840  *   | port          | The port, without ":"
18841  *   | pathname      | The pathname, beginning with "/"
18842  *
18843  */
18844 function urlResolve(url) {
18845   var href = url;
18846
18847   if (msie) {
18848     // Normalize before parse.  Refer Implementation Notes on why this is
18849     // done in two steps on IE.
18850     urlParsingNode.setAttribute("href", href);
18851     href = urlParsingNode.href;
18852   }
18853
18854   urlParsingNode.setAttribute('href', href);
18855
18856   // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
18857   return {
18858     href: urlParsingNode.href,
18859     protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
18860     host: urlParsingNode.host,
18861     search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
18862     hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
18863     hostname: urlParsingNode.hostname,
18864     port: urlParsingNode.port,
18865     pathname: (urlParsingNode.pathname.charAt(0) === '/')
18866       ? urlParsingNode.pathname
18867       : '/' + urlParsingNode.pathname
18868   };
18869 }
18870
18871 /**
18872  * Parse a request URL and determine whether this is a same-origin request as the application document.
18873  *
18874  * @param {string|object} requestUrl The url of the request as a string that will be resolved
18875  * or a parsed URL object.
18876  * @returns {boolean} Whether the request is for the same origin as the application document.
18877  */
18878 function urlIsSameOrigin(requestUrl) {
18879   var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
18880   return (parsed.protocol === originUrl.protocol &&
18881           parsed.host === originUrl.host);
18882 }
18883
18884 /**
18885  * @ngdoc service
18886  * @name $window
18887  *
18888  * @description
18889  * A reference to the browser's `window` object. While `window`
18890  * is globally available in JavaScript, it causes testability problems, because
18891  * it is a global variable. In angular we always refer to it through the
18892  * `$window` service, so it may be overridden, removed or mocked for testing.
18893  *
18894  * Expressions, like the one defined for the `ngClick` directive in the example
18895  * below, are evaluated with respect to the current scope.  Therefore, there is
18896  * no risk of inadvertently coding in a dependency on a global value in such an
18897  * expression.
18898  *
18899  * @example
18900    <example module="windowExample">
18901      <file name="index.html">
18902        <script>
18903          angular.module('windowExample', [])
18904            .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
18905              $scope.greeting = 'Hello, World!';
18906              $scope.doGreeting = function(greeting) {
18907                $window.alert(greeting);
18908              };
18909            }]);
18910        </script>
18911        <div ng-controller="ExampleController">
18912          <input type="text" ng-model="greeting" aria-label="greeting" />
18913          <button ng-click="doGreeting(greeting)">ALERT</button>
18914        </div>
18915      </file>
18916      <file name="protractor.js" type="protractor">
18917       it('should display the greeting in the input box', function() {
18918        element(by.model('greeting')).sendKeys('Hello, E2E Tests');
18919        // If we click the button it will block the test runner
18920        // element(':button').click();
18921       });
18922      </file>
18923    </example>
18924  */
18925 function $WindowProvider() {
18926   this.$get = valueFn(window);
18927 }
18928
18929 /**
18930  * @name $$cookieReader
18931  * @requires $document
18932  *
18933  * @description
18934  * This is a private service for reading cookies used by $http and ngCookies
18935  *
18936  * @return {Object} a key/value map of the current cookies
18937  */
18938 function $$CookieReader($document) {
18939   var rawDocument = $document[0] || {};
18940   var lastCookies = {};
18941   var lastCookieString = '';
18942
18943   function safeDecodeURIComponent(str) {
18944     try {
18945       return decodeURIComponent(str);
18946     } catch (e) {
18947       return str;
18948     }
18949   }
18950
18951   return function() {
18952     var cookieArray, cookie, i, index, name;
18953     var currentCookieString = rawDocument.cookie || '';
18954
18955     if (currentCookieString !== lastCookieString) {
18956       lastCookieString = currentCookieString;
18957       cookieArray = lastCookieString.split('; ');
18958       lastCookies = {};
18959
18960       for (i = 0; i < cookieArray.length; i++) {
18961         cookie = cookieArray[i];
18962         index = cookie.indexOf('=');
18963         if (index > 0) { //ignore nameless cookies
18964           name = safeDecodeURIComponent(cookie.substring(0, index));
18965           // the first value that is seen for a cookie is the most
18966           // specific one.  values for the same cookie name that
18967           // follow are for less specific paths.
18968           if (isUndefined(lastCookies[name])) {
18969             lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
18970           }
18971         }
18972       }
18973     }
18974     return lastCookies;
18975   };
18976 }
18977
18978 $$CookieReader.$inject = ['$document'];
18979
18980 function $$CookieReaderProvider() {
18981   this.$get = $$CookieReader;
18982 }
18983
18984 /* global currencyFilter: true,
18985  dateFilter: true,
18986  filterFilter: true,
18987  jsonFilter: true,
18988  limitToFilter: true,
18989  lowercaseFilter: true,
18990  numberFilter: true,
18991  orderByFilter: true,
18992  uppercaseFilter: true,
18993  */
18994
18995 /**
18996  * @ngdoc provider
18997  * @name $filterProvider
18998  * @description
18999  *
19000  * Filters are just functions which transform input to an output. However filters need to be
19001  * Dependency Injected. To achieve this a filter definition consists of a factory function which is
19002  * annotated with dependencies and is responsible for creating a filter function.
19003  *
19004  * <div class="alert alert-warning">
19005  * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
19006  * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
19007  * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
19008  * (`myapp_subsection_filterx`).
19009  * </div>
19010  *
19011  * ```js
19012  *   // Filter registration
19013  *   function MyModule($provide, $filterProvider) {
19014  *     // create a service to demonstrate injection (not always needed)
19015  *     $provide.value('greet', function(name){
19016  *       return 'Hello ' + name + '!';
19017  *     });
19018  *
19019  *     // register a filter factory which uses the
19020  *     // greet service to demonstrate DI.
19021  *     $filterProvider.register('greet', function(greet){
19022  *       // return the filter function which uses the greet service
19023  *       // to generate salutation
19024  *       return function(text) {
19025  *         // filters need to be forgiving so check input validity
19026  *         return text && greet(text) || text;
19027  *       };
19028  *     });
19029  *   }
19030  * ```
19031  *
19032  * The filter function is registered with the `$injector` under the filter name suffix with
19033  * `Filter`.
19034  *
19035  * ```js
19036  *   it('should be the same instance', inject(
19037  *     function($filterProvider) {
19038  *       $filterProvider.register('reverse', function(){
19039  *         return ...;
19040  *       });
19041  *     },
19042  *     function($filter, reverseFilter) {
19043  *       expect($filter('reverse')).toBe(reverseFilter);
19044  *     });
19045  * ```
19046  *
19047  *
19048  * For more information about how angular filters work, and how to create your own filters, see
19049  * {@link guide/filter Filters} in the Angular Developer Guide.
19050  */
19051
19052 /**
19053  * @ngdoc service
19054  * @name $filter
19055  * @kind function
19056  * @description
19057  * Filters are used for formatting data displayed to the user.
19058  *
19059  * The general syntax in templates is as follows:
19060  *
19061  *         {{ expression [| filter_name[:parameter_value] ... ] }}
19062  *
19063  * @param {String} name Name of the filter function to retrieve
19064  * @return {Function} the filter function
19065  * @example
19066    <example name="$filter" module="filterExample">
19067      <file name="index.html">
19068        <div ng-controller="MainCtrl">
19069         <h3>{{ originalText }}</h3>
19070         <h3>{{ filteredText }}</h3>
19071        </div>
19072      </file>
19073
19074      <file name="script.js">
19075       angular.module('filterExample', [])
19076       .controller('MainCtrl', function($scope, $filter) {
19077         $scope.originalText = 'hello';
19078         $scope.filteredText = $filter('uppercase')($scope.originalText);
19079       });
19080      </file>
19081    </example>
19082   */
19083 $FilterProvider.$inject = ['$provide'];
19084 function $FilterProvider($provide) {
19085   var suffix = 'Filter';
19086
19087   /**
19088    * @ngdoc method
19089    * @name $filterProvider#register
19090    * @param {string|Object} name Name of the filter function, or an object map of filters where
19091    *    the keys are the filter names and the values are the filter factories.
19092    *
19093    *    <div class="alert alert-warning">
19094    *    **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
19095    *    Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
19096    *    your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
19097    *    (`myapp_subsection_filterx`).
19098    *    </div>
19099     * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
19100    * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
19101    *    of the registered filter instances.
19102    */
19103   function register(name, factory) {
19104     if (isObject(name)) {
19105       var filters = {};
19106       forEach(name, function(filter, key) {
19107         filters[key] = register(key, filter);
19108       });
19109       return filters;
19110     } else {
19111       return $provide.factory(name + suffix, factory);
19112     }
19113   }
19114   this.register = register;
19115
19116   this.$get = ['$injector', function($injector) {
19117     return function(name) {
19118       return $injector.get(name + suffix);
19119     };
19120   }];
19121
19122   ////////////////////////////////////////
19123
19124   /* global
19125     currencyFilter: false,
19126     dateFilter: false,
19127     filterFilter: false,
19128     jsonFilter: false,
19129     limitToFilter: false,
19130     lowercaseFilter: false,
19131     numberFilter: false,
19132     orderByFilter: false,
19133     uppercaseFilter: false,
19134   */
19135
19136   register('currency', currencyFilter);
19137   register('date', dateFilter);
19138   register('filter', filterFilter);
19139   register('json', jsonFilter);
19140   register('limitTo', limitToFilter);
19141   register('lowercase', lowercaseFilter);
19142   register('number', numberFilter);
19143   register('orderBy', orderByFilter);
19144   register('uppercase', uppercaseFilter);
19145 }
19146
19147 /**
19148  * @ngdoc filter
19149  * @name filter
19150  * @kind function
19151  *
19152  * @description
19153  * Selects a subset of items from `array` and returns it as a new array.
19154  *
19155  * @param {Array} array The source array.
19156  * @param {string|Object|function()} expression The predicate to be used for selecting items from
19157  *   `array`.
19158  *
19159  *   Can be one of:
19160  *
19161  *   - `string`: The string is used for matching against the contents of the `array`. All strings or
19162  *     objects with string properties in `array` that match this string will be returned. This also
19163  *     applies to nested object properties.
19164  *     The predicate can be negated by prefixing the string with `!`.
19165  *
19166  *   - `Object`: A pattern object can be used to filter specific properties on objects contained
19167  *     by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
19168  *     which have property `name` containing "M" and property `phone` containing "1". A special
19169  *     property name `$` can be used (as in `{$:"text"}`) to accept a match against any
19170  *     property of the object or its nested object properties. That's equivalent to the simple
19171  *     substring match with a `string` as described above. The predicate can be negated by prefixing
19172  *     the string with `!`.
19173  *     For example `{name: "!M"}` predicate will return an array of items which have property `name`
19174  *     not containing "M".
19175  *
19176  *     Note that a named property will match properties on the same level only, while the special
19177  *     `$` property will match properties on the same level or deeper. E.g. an array item like
19178  *     `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
19179  *     **will** be matched by `{$: 'John'}`.
19180  *
19181  *   - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
19182  *     The function is called for each element of the array, with the element, its index, and
19183  *     the entire array itself as arguments.
19184  *
19185  *     The final result is an array of those elements that the predicate returned true for.
19186  *
19187  * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
19188  *     determining if the expected value (from the filter expression) and actual value (from
19189  *     the object in the array) should be considered a match.
19190  *
19191  *   Can be one of:
19192  *
19193  *   - `function(actual, expected)`:
19194  *     The function will be given the object value and the predicate value to compare and
19195  *     should return true if both values should be considered equal.
19196  *
19197  *   - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
19198  *     This is essentially strict comparison of expected and actual.
19199  *
19200  *   - `false|undefined`: A short hand for a function which will look for a substring match in case
19201  *     insensitive way.
19202  *
19203  *     Primitive values are converted to strings. Objects are not compared against primitives,
19204  *     unless they have a custom `toString` method (e.g. `Date` objects).
19205  *
19206  * @example
19207    <example>
19208      <file name="index.html">
19209        <div ng-init="friends = [{name:'John', phone:'555-1276'},
19210                                 {name:'Mary', phone:'800-BIG-MARY'},
19211                                 {name:'Mike', phone:'555-4321'},
19212                                 {name:'Adam', phone:'555-5678'},
19213                                 {name:'Julie', phone:'555-8765'},
19214                                 {name:'Juliette', phone:'555-5678'}]"></div>
19215
19216        <label>Search: <input ng-model="searchText"></label>
19217        <table id="searchTextResults">
19218          <tr><th>Name</th><th>Phone</th></tr>
19219          <tr ng-repeat="friend in friends | filter:searchText">
19220            <td>{{friend.name}}</td>
19221            <td>{{friend.phone}}</td>
19222          </tr>
19223        </table>
19224        <hr>
19225        <label>Any: <input ng-model="search.$"></label> <br>
19226        <label>Name only <input ng-model="search.name"></label><br>
19227        <label>Phone only <input ng-model="search.phone"></label><br>
19228        <label>Equality <input type="checkbox" ng-model="strict"></label><br>
19229        <table id="searchObjResults">
19230          <tr><th>Name</th><th>Phone</th></tr>
19231          <tr ng-repeat="friendObj in friends | filter:search:strict">
19232            <td>{{friendObj.name}}</td>
19233            <td>{{friendObj.phone}}</td>
19234          </tr>
19235        </table>
19236      </file>
19237      <file name="protractor.js" type="protractor">
19238        var expectFriendNames = function(expectedNames, key) {
19239          element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
19240            arr.forEach(function(wd, i) {
19241              expect(wd.getText()).toMatch(expectedNames[i]);
19242            });
19243          });
19244        };
19245
19246        it('should search across all fields when filtering with a string', function() {
19247          var searchText = element(by.model('searchText'));
19248          searchText.clear();
19249          searchText.sendKeys('m');
19250          expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
19251
19252          searchText.clear();
19253          searchText.sendKeys('76');
19254          expectFriendNames(['John', 'Julie'], 'friend');
19255        });
19256
19257        it('should search in specific fields when filtering with a predicate object', function() {
19258          var searchAny = element(by.model('search.$'));
19259          searchAny.clear();
19260          searchAny.sendKeys('i');
19261          expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
19262        });
19263        it('should use a equal comparison when comparator is true', function() {
19264          var searchName = element(by.model('search.name'));
19265          var strict = element(by.model('strict'));
19266          searchName.clear();
19267          searchName.sendKeys('Julie');
19268          strict.click();
19269          expectFriendNames(['Julie'], 'friendObj');
19270        });
19271      </file>
19272    </example>
19273  */
19274 function filterFilter() {
19275   return function(array, expression, comparator) {
19276     if (!isArrayLike(array)) {
19277       if (array == null) {
19278         return array;
19279       } else {
19280         throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
19281       }
19282     }
19283
19284     var expressionType = getTypeForFilter(expression);
19285     var predicateFn;
19286     var matchAgainstAnyProp;
19287
19288     switch (expressionType) {
19289       case 'function':
19290         predicateFn = expression;
19291         break;
19292       case 'boolean':
19293       case 'null':
19294       case 'number':
19295       case 'string':
19296         matchAgainstAnyProp = true;
19297         //jshint -W086
19298       case 'object':
19299         //jshint +W086
19300         predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
19301         break;
19302       default:
19303         return array;
19304     }
19305
19306     return Array.prototype.filter.call(array, predicateFn);
19307   };
19308 }
19309
19310 // Helper functions for `filterFilter`
19311 function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
19312   var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
19313   var predicateFn;
19314
19315   if (comparator === true) {
19316     comparator = equals;
19317   } else if (!isFunction(comparator)) {
19318     comparator = function(actual, expected) {
19319       if (isUndefined(actual)) {
19320         // No substring matching against `undefined`
19321         return false;
19322       }
19323       if ((actual === null) || (expected === null)) {
19324         // No substring matching against `null`; only match against `null`
19325         return actual === expected;
19326       }
19327       if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
19328         // Should not compare primitives against objects, unless they have custom `toString` method
19329         return false;
19330       }
19331
19332       actual = lowercase('' + actual);
19333       expected = lowercase('' + expected);
19334       return actual.indexOf(expected) !== -1;
19335     };
19336   }
19337
19338   predicateFn = function(item) {
19339     if (shouldMatchPrimitives && !isObject(item)) {
19340       return deepCompare(item, expression.$, comparator, false);
19341     }
19342     return deepCompare(item, expression, comparator, matchAgainstAnyProp);
19343   };
19344
19345   return predicateFn;
19346 }
19347
19348 function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
19349   var actualType = getTypeForFilter(actual);
19350   var expectedType = getTypeForFilter(expected);
19351
19352   if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
19353     return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
19354   } else if (isArray(actual)) {
19355     // In case `actual` is an array, consider it a match
19356     // if ANY of it's items matches `expected`
19357     return actual.some(function(item) {
19358       return deepCompare(item, expected, comparator, matchAgainstAnyProp);
19359     });
19360   }
19361
19362   switch (actualType) {
19363     case 'object':
19364       var key;
19365       if (matchAgainstAnyProp) {
19366         for (key in actual) {
19367           if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
19368             return true;
19369           }
19370         }
19371         return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
19372       } else if (expectedType === 'object') {
19373         for (key in expected) {
19374           var expectedVal = expected[key];
19375           if (isFunction(expectedVal) || isUndefined(expectedVal)) {
19376             continue;
19377           }
19378
19379           var matchAnyProperty = key === '$';
19380           var actualVal = matchAnyProperty ? actual : actual[key];
19381           if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
19382             return false;
19383           }
19384         }
19385         return true;
19386       } else {
19387         return comparator(actual, expected);
19388       }
19389       break;
19390     case 'function':
19391       return false;
19392     default:
19393       return comparator(actual, expected);
19394   }
19395 }
19396
19397 // Used for easily differentiating between `null` and actual `object`
19398 function getTypeForFilter(val) {
19399   return (val === null) ? 'null' : typeof val;
19400 }
19401
19402 var MAX_DIGITS = 22;
19403 var DECIMAL_SEP = '.';
19404 var ZERO_CHAR = '0';
19405
19406 /**
19407  * @ngdoc filter
19408  * @name currency
19409  * @kind function
19410  *
19411  * @description
19412  * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
19413  * symbol for current locale is used.
19414  *
19415  * @param {number} amount Input to filter.
19416  * @param {string=} symbol Currency symbol or identifier to be displayed.
19417  * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
19418  * @returns {string} Formatted number.
19419  *
19420  *
19421  * @example
19422    <example module="currencyExample">
19423      <file name="index.html">
19424        <script>
19425          angular.module('currencyExample', [])
19426            .controller('ExampleController', ['$scope', function($scope) {
19427              $scope.amount = 1234.56;
19428            }]);
19429        </script>
19430        <div ng-controller="ExampleController">
19431          <input type="number" ng-model="amount" aria-label="amount"> <br>
19432          default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
19433          custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
19434          no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
19435        </div>
19436      </file>
19437      <file name="protractor.js" type="protractor">
19438        it('should init with 1234.56', function() {
19439          expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
19440          expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
19441          expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
19442        });
19443        it('should update', function() {
19444          if (browser.params.browser == 'safari') {
19445            // Safari does not understand the minus key. See
19446            // https://github.com/angular/protractor/issues/481
19447            return;
19448          }
19449          element(by.model('amount')).clear();
19450          element(by.model('amount')).sendKeys('-1234');
19451          expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
19452          expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
19453          expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
19454        });
19455      </file>
19456    </example>
19457  */
19458 currencyFilter.$inject = ['$locale'];
19459 function currencyFilter($locale) {
19460   var formats = $locale.NUMBER_FORMATS;
19461   return function(amount, currencySymbol, fractionSize) {
19462     if (isUndefined(currencySymbol)) {
19463       currencySymbol = formats.CURRENCY_SYM;
19464     }
19465
19466     if (isUndefined(fractionSize)) {
19467       fractionSize = formats.PATTERNS[1].maxFrac;
19468     }
19469
19470     // if null or undefined pass it through
19471     return (amount == null)
19472         ? amount
19473         : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
19474             replace(/\u00A4/g, currencySymbol);
19475   };
19476 }
19477
19478 /**
19479  * @ngdoc filter
19480  * @name number
19481  * @kind function
19482  *
19483  * @description
19484  * Formats a number as text.
19485  *
19486  * If the input is null or undefined, it will just be returned.
19487  * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
19488  * If the input is not a number an empty string is returned.
19489  *
19490  *
19491  * @param {number|string} number Number to format.
19492  * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
19493  * If this is not provided then the fraction size is computed from the current locale's number
19494  * formatting pattern. In the case of the default locale, it will be 3.
19495  * @returns {string} Number rounded to fractionSize and places a “,” after each third digit.
19496  *
19497  * @example
19498    <example module="numberFilterExample">
19499      <file name="index.html">
19500        <script>
19501          angular.module('numberFilterExample', [])
19502            .controller('ExampleController', ['$scope', function($scope) {
19503              $scope.val = 1234.56789;
19504            }]);
19505        </script>
19506        <div ng-controller="ExampleController">
19507          <label>Enter number: <input ng-model='val'></label><br>
19508          Default formatting: <span id='number-default'>{{val | number}}</span><br>
19509          No fractions: <span>{{val | number:0}}</span><br>
19510          Negative number: <span>{{-val | number:4}}</span>
19511        </div>
19512      </file>
19513      <file name="protractor.js" type="protractor">
19514        it('should format numbers', function() {
19515          expect(element(by.id('number-default')).getText()).toBe('1,234.568');
19516          expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
19517          expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
19518        });
19519
19520        it('should update', function() {
19521          element(by.model('val')).clear();
19522          element(by.model('val')).sendKeys('3374.333');
19523          expect(element(by.id('number-default')).getText()).toBe('3,374.333');
19524          expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
19525          expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
19526       });
19527      </file>
19528    </example>
19529  */
19530 numberFilter.$inject = ['$locale'];
19531 function numberFilter($locale) {
19532   var formats = $locale.NUMBER_FORMATS;
19533   return function(number, fractionSize) {
19534
19535     // if null or undefined pass it through
19536     return (number == null)
19537         ? number
19538         : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
19539                        fractionSize);
19540   };
19541 }
19542
19543 /**
19544  * Parse a number (as a string) into three components that can be used
19545  * for formatting the number.
19546  *
19547  * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
19548  *
19549  * @param  {string} numStr The number to parse
19550  * @return {object} An object describing this number, containing the following keys:
19551  *  - d : an array of digits containing leading zeros as necessary
19552  *  - i : the number of the digits in `d` that are to the left of the decimal point
19553  *  - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
19554  *
19555  */
19556 function parse(numStr) {
19557   var exponent = 0, digits, numberOfIntegerDigits;
19558   var i, j, zeros;
19559
19560   // Decimal point?
19561   if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
19562     numStr = numStr.replace(DECIMAL_SEP, '');
19563   }
19564
19565   // Exponential form?
19566   if ((i = numStr.search(/e/i)) > 0) {
19567     // Work out the exponent.
19568     if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
19569     numberOfIntegerDigits += +numStr.slice(i + 1);
19570     numStr = numStr.substring(0, i);
19571   } else if (numberOfIntegerDigits < 0) {
19572     // There was no decimal point or exponent so it is an integer.
19573     numberOfIntegerDigits = numStr.length;
19574   }
19575
19576   // Count the number of leading zeros.
19577   for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++);
19578
19579   if (i == (zeros = numStr.length)) {
19580     // The digits are all zero.
19581     digits = [0];
19582     numberOfIntegerDigits = 1;
19583   } else {
19584     // Count the number of trailing zeros
19585     zeros--;
19586     while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
19587
19588     // Trailing zeros are insignificant so ignore them
19589     numberOfIntegerDigits -= i;
19590     digits = [];
19591     // Convert string to array of digits without leading/trailing zeros.
19592     for (j = 0; i <= zeros; i++, j++) {
19593       digits[j] = +numStr.charAt(i);
19594     }
19595   }
19596
19597   // If the number overflows the maximum allowed digits then use an exponent.
19598   if (numberOfIntegerDigits > MAX_DIGITS) {
19599     digits = digits.splice(0, MAX_DIGITS - 1);
19600     exponent = numberOfIntegerDigits - 1;
19601     numberOfIntegerDigits = 1;
19602   }
19603
19604   return { d: digits, e: exponent, i: numberOfIntegerDigits };
19605 }
19606
19607 /**
19608  * Round the parsed number to the specified number of decimal places
19609  * This function changed the parsedNumber in-place
19610  */
19611 function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
19612     var digits = parsedNumber.d;
19613     var fractionLen = digits.length - parsedNumber.i;
19614
19615     // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
19616     fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
19617
19618     // The index of the digit to where rounding is to occur
19619     var roundAt = fractionSize + parsedNumber.i;
19620     var digit = digits[roundAt];
19621
19622     if (roundAt > 0) {
19623       digits.splice(roundAt);
19624     } else {
19625       // We rounded to zero so reset the parsedNumber
19626       parsedNumber.i = 1;
19627       digits.length = roundAt = fractionSize + 1;
19628       for (var i=0; i < roundAt; i++) digits[i] = 0;
19629     }
19630
19631     if (digit >= 5) digits[roundAt - 1]++;
19632
19633     // Pad out with zeros to get the required fraction length
19634     for (; fractionLen < fractionSize; fractionLen++) digits.push(0);
19635
19636
19637     // Do any carrying, e.g. a digit was rounded up to 10
19638     var carry = digits.reduceRight(function(carry, d, i, digits) {
19639       d = d + carry;
19640       digits[i] = d % 10;
19641       return Math.floor(d / 10);
19642     }, 0);
19643     if (carry) {
19644       digits.unshift(carry);
19645       parsedNumber.i++;
19646     }
19647 }
19648
19649 /**
19650  * Format a number into a string
19651  * @param  {number} number       The number to format
19652  * @param  {{
19653  *           minFrac, // the minimum number of digits required in the fraction part of the number
19654  *           maxFrac, // the maximum number of digits required in the fraction part of the number
19655  *           gSize,   // number of digits in each group of separated digits
19656  *           lgSize,  // number of digits in the last group of digits before the decimal separator
19657  *           negPre,  // the string to go in front of a negative number (e.g. `-` or `(`))
19658  *           posPre,  // the string to go in front of a positive number
19659  *           negSuf,  // the string to go after a negative number (e.g. `)`)
19660  *           posSuf   // the string to go after a positive number
19661  *         }} pattern
19662  * @param  {string} groupSep     The string to separate groups of number (e.g. `,`)
19663  * @param  {string} decimalSep   The string to act as the decimal separator (e.g. `.`)
19664  * @param  {[type]} fractionSize The size of the fractional part of the number
19665  * @return {string}              The number formatted as a string
19666  */
19667 function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
19668
19669   if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
19670
19671   var isInfinity = !isFinite(number);
19672   var isZero = false;
19673   var numStr = Math.abs(number) + '',
19674       formattedText = '',
19675       parsedNumber;
19676
19677   if (isInfinity) {
19678     formattedText = '\u221e';
19679   } else {
19680     parsedNumber = parse(numStr);
19681
19682     roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
19683
19684     var digits = parsedNumber.d;
19685     var integerLen = parsedNumber.i;
19686     var exponent = parsedNumber.e;
19687     var decimals = [];
19688     isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
19689
19690     // pad zeros for small numbers
19691     while (integerLen < 0) {
19692       digits.unshift(0);
19693       integerLen++;
19694     }
19695
19696     // extract decimals digits
19697     if (integerLen > 0) {
19698       decimals = digits.splice(integerLen);
19699     } else {
19700       decimals = digits;
19701       digits = [0];
19702     }
19703
19704     // format the integer digits with grouping separators
19705     var groups = [];
19706     if (digits.length > pattern.lgSize) {
19707       groups.unshift(digits.splice(-pattern.lgSize).join(''));
19708     }
19709     while (digits.length > pattern.gSize) {
19710       groups.unshift(digits.splice(-pattern.gSize).join(''));
19711     }
19712     if (digits.length) {
19713       groups.unshift(digits.join(''));
19714     }
19715     formattedText = groups.join(groupSep);
19716
19717     // append the decimal digits
19718     if (decimals.length) {
19719       formattedText += decimalSep + decimals.join('');
19720     }
19721
19722     if (exponent) {
19723       formattedText += 'e+' + exponent;
19724     }
19725   }
19726   if (number < 0 && !isZero) {
19727     return pattern.negPre + formattedText + pattern.negSuf;
19728   } else {
19729     return pattern.posPre + formattedText + pattern.posSuf;
19730   }
19731 }
19732
19733 function padNumber(num, digits, trim) {
19734   var neg = '';
19735   if (num < 0) {
19736     neg =  '-';
19737     num = -num;
19738   }
19739   num = '' + num;
19740   while (num.length < digits) num = ZERO_CHAR + num;
19741   if (trim) {
19742     num = num.substr(num.length - digits);
19743   }
19744   return neg + num;
19745 }
19746
19747
19748 function dateGetter(name, size, offset, trim) {
19749   offset = offset || 0;
19750   return function(date) {
19751     var value = date['get' + name]();
19752     if (offset > 0 || value > -offset) {
19753       value += offset;
19754     }
19755     if (value === 0 && offset == -12) value = 12;
19756     return padNumber(value, size, trim);
19757   };
19758 }
19759
19760 function dateStrGetter(name, shortForm) {
19761   return function(date, formats) {
19762     var value = date['get' + name]();
19763     var get = uppercase(shortForm ? ('SHORT' + name) : name);
19764
19765     return formats[get][value];
19766   };
19767 }
19768
19769 function timeZoneGetter(date, formats, offset) {
19770   var zone = -1 * offset;
19771   var paddedZone = (zone >= 0) ? "+" : "";
19772
19773   paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
19774                 padNumber(Math.abs(zone % 60), 2);
19775
19776   return paddedZone;
19777 }
19778
19779 function getFirstThursdayOfYear(year) {
19780     // 0 = index of January
19781     var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
19782     // 4 = index of Thursday (+1 to account for 1st = 5)
19783     // 11 = index of *next* Thursday (+1 account for 1st = 12)
19784     return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
19785 }
19786
19787 function getThursdayThisWeek(datetime) {
19788     return new Date(datetime.getFullYear(), datetime.getMonth(),
19789       // 4 = index of Thursday
19790       datetime.getDate() + (4 - datetime.getDay()));
19791 }
19792
19793 function weekGetter(size) {
19794    return function(date) {
19795       var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
19796          thisThurs = getThursdayThisWeek(date);
19797
19798       var diff = +thisThurs - +firstThurs,
19799          result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
19800
19801       return padNumber(result, size);
19802    };
19803 }
19804
19805 function ampmGetter(date, formats) {
19806   return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
19807 }
19808
19809 function eraGetter(date, formats) {
19810   return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
19811 }
19812
19813 function longEraGetter(date, formats) {
19814   return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
19815 }
19816
19817 var DATE_FORMATS = {
19818   yyyy: dateGetter('FullYear', 4),
19819     yy: dateGetter('FullYear', 2, 0, true),
19820      y: dateGetter('FullYear', 1),
19821   MMMM: dateStrGetter('Month'),
19822    MMM: dateStrGetter('Month', true),
19823     MM: dateGetter('Month', 2, 1),
19824      M: dateGetter('Month', 1, 1),
19825     dd: dateGetter('Date', 2),
19826      d: dateGetter('Date', 1),
19827     HH: dateGetter('Hours', 2),
19828      H: dateGetter('Hours', 1),
19829     hh: dateGetter('Hours', 2, -12),
19830      h: dateGetter('Hours', 1, -12),
19831     mm: dateGetter('Minutes', 2),
19832      m: dateGetter('Minutes', 1),
19833     ss: dateGetter('Seconds', 2),
19834      s: dateGetter('Seconds', 1),
19835      // while ISO 8601 requires fractions to be prefixed with `.` or `,`
19836      // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
19837    sss: dateGetter('Milliseconds', 3),
19838   EEEE: dateStrGetter('Day'),
19839    EEE: dateStrGetter('Day', true),
19840      a: ampmGetter,
19841      Z: timeZoneGetter,
19842     ww: weekGetter(2),
19843      w: weekGetter(1),
19844      G: eraGetter,
19845      GG: eraGetter,
19846      GGG: eraGetter,
19847      GGGG: longEraGetter
19848 };
19849
19850 var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
19851     NUMBER_STRING = /^\-?\d+$/;
19852
19853 /**
19854  * @ngdoc filter
19855  * @name date
19856  * @kind function
19857  *
19858  * @description
19859  *   Formats `date` to a string based on the requested `format`.
19860  *
19861  *   `format` string can be composed of the following elements:
19862  *
19863  *   * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
19864  *   * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
19865  *   * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
19866  *   * `'MMMM'`: Month in year (January-December)
19867  *   * `'MMM'`: Month in year (Jan-Dec)
19868  *   * `'MM'`: Month in year, padded (01-12)
19869  *   * `'M'`: Month in year (1-12)
19870  *   * `'dd'`: Day in month, padded (01-31)
19871  *   * `'d'`: Day in month (1-31)
19872  *   * `'EEEE'`: Day in Week,(Sunday-Saturday)
19873  *   * `'EEE'`: Day in Week, (Sun-Sat)
19874  *   * `'HH'`: Hour in day, padded (00-23)
19875  *   * `'H'`: Hour in day (0-23)
19876  *   * `'hh'`: Hour in AM/PM, padded (01-12)
19877  *   * `'h'`: Hour in AM/PM, (1-12)
19878  *   * `'mm'`: Minute in hour, padded (00-59)
19879  *   * `'m'`: Minute in hour (0-59)
19880  *   * `'ss'`: Second in minute, padded (00-59)
19881  *   * `'s'`: Second in minute (0-59)
19882  *   * `'sss'`: Millisecond in second, padded (000-999)
19883  *   * `'a'`: AM/PM marker
19884  *   * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
19885  *   * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
19886  *   * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
19887  *   * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
19888  *   * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
19889  *
19890  *   `format` string can also be one of the following predefined
19891  *   {@link guide/i18n localizable formats}:
19892  *
19893  *   * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
19894  *     (e.g. Sep 3, 2010 12:05:08 PM)
19895  *   * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US  locale (e.g. 9/3/10 12:05 PM)
19896  *   * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US  locale
19897  *     (e.g. Friday, September 3, 2010)
19898  *   * `'longDate'`: equivalent to `'MMMM d, y'` for en_US  locale (e.g. September 3, 2010)
19899  *   * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US  locale (e.g. Sep 3, 2010)
19900  *   * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
19901  *   * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
19902  *   * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
19903  *
19904  *   `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
19905  *   `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
19906  *   (e.g. `"h 'o''clock'"`).
19907  *
19908  * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
19909  *    number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
19910  *    shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
19911  *    specified in the string input, the time is considered to be in the local timezone.
19912  * @param {string=} format Formatting rules (see Description). If not specified,
19913  *    `mediumDate` is used.
19914  * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
19915  *    continental US time zone abbreviations, but for general use, use a time zone offset, for
19916  *    example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
19917  *    If not specified, the timezone of the browser will be used.
19918  * @returns {string} Formatted string or the input if input is not recognized as date/millis.
19919  *
19920  * @example
19921    <example>
19922      <file name="index.html">
19923        <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
19924            <span>{{1288323623006 | date:'medium'}}</span><br>
19925        <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
19926           <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
19927        <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
19928           <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
19929        <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
19930           <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
19931      </file>
19932      <file name="protractor.js" type="protractor">
19933        it('should format date', function() {
19934          expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
19935             toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
19936          expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
19937             toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
19938          expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
19939             toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
19940          expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
19941             toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
19942        });
19943      </file>
19944    </example>
19945  */
19946 dateFilter.$inject = ['$locale'];
19947 function dateFilter($locale) {
19948
19949
19950   var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
19951                      // 1        2       3         4          5          6          7          8  9     10      11
19952   function jsonStringToDate(string) {
19953     var match;
19954     if (match = string.match(R_ISO8601_STR)) {
19955       var date = new Date(0),
19956           tzHour = 0,
19957           tzMin  = 0,
19958           dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
19959           timeSetter = match[8] ? date.setUTCHours : date.setHours;
19960
19961       if (match[9]) {
19962         tzHour = toInt(match[9] + match[10]);
19963         tzMin = toInt(match[9] + match[11]);
19964       }
19965       dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
19966       var h = toInt(match[4] || 0) - tzHour;
19967       var m = toInt(match[5] || 0) - tzMin;
19968       var s = toInt(match[6] || 0);
19969       var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
19970       timeSetter.call(date, h, m, s, ms);
19971       return date;
19972     }
19973     return string;
19974   }
19975
19976
19977   return function(date, format, timezone) {
19978     var text = '',
19979         parts = [],
19980         fn, match;
19981
19982     format = format || 'mediumDate';
19983     format = $locale.DATETIME_FORMATS[format] || format;
19984     if (isString(date)) {
19985       date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
19986     }
19987
19988     if (isNumber(date)) {
19989       date = new Date(date);
19990     }
19991
19992     if (!isDate(date) || !isFinite(date.getTime())) {
19993       return date;
19994     }
19995
19996     while (format) {
19997       match = DATE_FORMATS_SPLIT.exec(format);
19998       if (match) {
19999         parts = concat(parts, match, 1);
20000         format = parts.pop();
20001       } else {
20002         parts.push(format);
20003         format = null;
20004       }
20005     }
20006
20007     var dateTimezoneOffset = date.getTimezoneOffset();
20008     if (timezone) {
20009       dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
20010       date = convertTimezoneToLocal(date, timezone, true);
20011     }
20012     forEach(parts, function(value) {
20013       fn = DATE_FORMATS[value];
20014       text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
20015                  : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
20016     });
20017
20018     return text;
20019   };
20020 }
20021
20022
20023 /**
20024  * @ngdoc filter
20025  * @name json
20026  * @kind function
20027  *
20028  * @description
20029  *   Allows you to convert a JavaScript object into JSON string.
20030  *
20031  *   This filter is mostly useful for debugging. When using the double curly {{value}} notation
20032  *   the binding is automatically converted to JSON.
20033  *
20034  * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
20035  * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
20036  * @returns {string} JSON string.
20037  *
20038  *
20039  * @example
20040    <example>
20041      <file name="index.html">
20042        <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
20043        <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
20044      </file>
20045      <file name="protractor.js" type="protractor">
20046        it('should jsonify filtered objects', function() {
20047          expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n  "name": ?"value"\n}/);
20048          expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n    "name": ?"value"\n}/);
20049        });
20050      </file>
20051    </example>
20052  *
20053  */
20054 function jsonFilter() {
20055   return function(object, spacing) {
20056     if (isUndefined(spacing)) {
20057         spacing = 2;
20058     }
20059     return toJson(object, spacing);
20060   };
20061 }
20062
20063
20064 /**
20065  * @ngdoc filter
20066  * @name lowercase
20067  * @kind function
20068  * @description
20069  * Converts string to lowercase.
20070  * @see angular.lowercase
20071  */
20072 var lowercaseFilter = valueFn(lowercase);
20073
20074
20075 /**
20076  * @ngdoc filter
20077  * @name uppercase
20078  * @kind function
20079  * @description
20080  * Converts string to uppercase.
20081  * @see angular.uppercase
20082  */
20083 var uppercaseFilter = valueFn(uppercase);
20084
20085 /**
20086  * @ngdoc filter
20087  * @name limitTo
20088  * @kind function
20089  *
20090  * @description
20091  * Creates a new array or string containing only a specified number of elements. The elements
20092  * are taken from either the beginning or the end of the source array, string or number, as specified by
20093  * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
20094  * converted to a string.
20095  *
20096  * @param {Array|string|number} input Source array, string or number to be limited.
20097  * @param {string|number} limit The length of the returned array or string. If the `limit` number
20098  *     is positive, `limit` number of items from the beginning of the source array/string are copied.
20099  *     If the number is negative, `limit` number  of items from the end of the source array/string
20100  *     are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
20101  *     the input will be returned unchanged.
20102  * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
20103  *     indicates an offset from the end of `input`. Defaults to `0`.
20104  * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
20105  *     had less than `limit` elements.
20106  *
20107  * @example
20108    <example module="limitToExample">
20109      <file name="index.html">
20110        <script>
20111          angular.module('limitToExample', [])
20112            .controller('ExampleController', ['$scope', function($scope) {
20113              $scope.numbers = [1,2,3,4,5,6,7,8,9];
20114              $scope.letters = "abcdefghi";
20115              $scope.longNumber = 2345432342;
20116              $scope.numLimit = 3;
20117              $scope.letterLimit = 3;
20118              $scope.longNumberLimit = 3;
20119            }]);
20120        </script>
20121        <div ng-controller="ExampleController">
20122          <label>
20123             Limit {{numbers}} to:
20124             <input type="number" step="1" ng-model="numLimit">
20125          </label>
20126          <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
20127          <label>
20128             Limit {{letters}} to:
20129             <input type="number" step="1" ng-model="letterLimit">
20130          </label>
20131          <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
20132          <label>
20133             Limit {{longNumber}} to:
20134             <input type="number" step="1" ng-model="longNumberLimit">
20135          </label>
20136          <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
20137        </div>
20138      </file>
20139      <file name="protractor.js" type="protractor">
20140        var numLimitInput = element(by.model('numLimit'));
20141        var letterLimitInput = element(by.model('letterLimit'));
20142        var longNumberLimitInput = element(by.model('longNumberLimit'));
20143        var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
20144        var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
20145        var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
20146
20147        it('should limit the number array to first three items', function() {
20148          expect(numLimitInput.getAttribute('value')).toBe('3');
20149          expect(letterLimitInput.getAttribute('value')).toBe('3');
20150          expect(longNumberLimitInput.getAttribute('value')).toBe('3');
20151          expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
20152          expect(limitedLetters.getText()).toEqual('Output letters: abc');
20153          expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
20154        });
20155
20156        // There is a bug in safari and protractor that doesn't like the minus key
20157        // it('should update the output when -3 is entered', function() {
20158        //   numLimitInput.clear();
20159        //   numLimitInput.sendKeys('-3');
20160        //   letterLimitInput.clear();
20161        //   letterLimitInput.sendKeys('-3');
20162        //   longNumberLimitInput.clear();
20163        //   longNumberLimitInput.sendKeys('-3');
20164        //   expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
20165        //   expect(limitedLetters.getText()).toEqual('Output letters: ghi');
20166        //   expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
20167        // });
20168
20169        it('should not exceed the maximum size of input array', function() {
20170          numLimitInput.clear();
20171          numLimitInput.sendKeys('100');
20172          letterLimitInput.clear();
20173          letterLimitInput.sendKeys('100');
20174          longNumberLimitInput.clear();
20175          longNumberLimitInput.sendKeys('100');
20176          expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
20177          expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
20178          expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
20179        });
20180      </file>
20181    </example>
20182 */
20183 function limitToFilter() {
20184   return function(input, limit, begin) {
20185     if (Math.abs(Number(limit)) === Infinity) {
20186       limit = Number(limit);
20187     } else {
20188       limit = toInt(limit);
20189     }
20190     if (isNaN(limit)) return input;
20191
20192     if (isNumber(input)) input = input.toString();
20193     if (!isArray(input) && !isString(input)) return input;
20194
20195     begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
20196     begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
20197
20198     if (limit >= 0) {
20199       return input.slice(begin, begin + limit);
20200     } else {
20201       if (begin === 0) {
20202         return input.slice(limit, input.length);
20203       } else {
20204         return input.slice(Math.max(0, begin + limit), begin);
20205       }
20206     }
20207   };
20208 }
20209
20210 /**
20211  * @ngdoc filter
20212  * @name orderBy
20213  * @kind function
20214  *
20215  * @description
20216  * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
20217  * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
20218  * as expected, make sure they are actually being saved as numbers and not strings.
20219  * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
20220  *
20221  * @param {Array} array The array (or array-like object) to sort.
20222  * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
20223  *    used by the comparator to determine the order of elements.
20224  *
20225  *    Can be one of:
20226  *
20227  *    - `function`: Getter function. The result of this function will be sorted using the
20228  *      `<`, `===`, `>` operator.
20229  *    - `string`: An Angular expression. The result of this expression is used to compare elements
20230  *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
20231  *      3 first characters of a property called `name`). The result of a constant expression
20232  *      is interpreted as a property name to be used in comparisons (for example `"special name"`
20233  *      to sort object by the value of their `special name` property). An expression can be
20234  *      optionally prefixed with `+` or `-` to control ascending or descending sort order
20235  *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
20236  *      element itself is used to compare where sorting.
20237  *    - `Array`: An array of function or string predicates. The first predicate in the array
20238  *      is used for sorting, but when two items are equivalent, the next predicate is used.
20239  *
20240  *    If the predicate is missing or empty then it defaults to `'+'`.
20241  *
20242  * @param {boolean=} reverse Reverse the order of the array.
20243  * @returns {Array} Sorted copy of the source array.
20244  *
20245  *
20246  * @example
20247  * The example below demonstrates a simple ngRepeat, where the data is sorted
20248  * by age in descending order (predicate is set to `'-age'`).
20249  * `reverse` is not set, which means it defaults to `false`.
20250    <example module="orderByExample">
20251      <file name="index.html">
20252        <div ng-controller="ExampleController">
20253          <table class="friend">
20254            <tr>
20255              <th>Name</th>
20256              <th>Phone Number</th>
20257              <th>Age</th>
20258            </tr>
20259            <tr ng-repeat="friend in friends | orderBy:'-age'">
20260              <td>{{friend.name}}</td>
20261              <td>{{friend.phone}}</td>
20262              <td>{{friend.age}}</td>
20263            </tr>
20264          </table>
20265        </div>
20266      </file>
20267      <file name="script.js">
20268        angular.module('orderByExample', [])
20269          .controller('ExampleController', ['$scope', function($scope) {
20270            $scope.friends =
20271                [{name:'John', phone:'555-1212', age:10},
20272                 {name:'Mary', phone:'555-9876', age:19},
20273                 {name:'Mike', phone:'555-4321', age:21},
20274                 {name:'Adam', phone:'555-5678', age:35},
20275                 {name:'Julie', phone:'555-8765', age:29}];
20276          }]);
20277      </file>
20278    </example>
20279  *
20280  * The predicate and reverse parameters can be controlled dynamically through scope properties,
20281  * as shown in the next example.
20282  * @example
20283    <example module="orderByExample">
20284      <file name="index.html">
20285        <div ng-controller="ExampleController">
20286          <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
20287          <hr/>
20288          <button ng-click="predicate=''">Set to unsorted</button>
20289          <table class="friend">
20290            <tr>
20291             <th>
20292                 <button ng-click="order('name')">Name</button>
20293                 <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
20294             </th>
20295             <th>
20296                 <button ng-click="order('phone')">Phone Number</button>
20297                 <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
20298             </th>
20299             <th>
20300                 <button ng-click="order('age')">Age</button>
20301                 <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
20302             </th>
20303            </tr>
20304            <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
20305              <td>{{friend.name}}</td>
20306              <td>{{friend.phone}}</td>
20307              <td>{{friend.age}}</td>
20308            </tr>
20309          </table>
20310        </div>
20311      </file>
20312      <file name="script.js">
20313        angular.module('orderByExample', [])
20314          .controller('ExampleController', ['$scope', function($scope) {
20315            $scope.friends =
20316                [{name:'John', phone:'555-1212', age:10},
20317                 {name:'Mary', phone:'555-9876', age:19},
20318                 {name:'Mike', phone:'555-4321', age:21},
20319                 {name:'Adam', phone:'555-5678', age:35},
20320                 {name:'Julie', phone:'555-8765', age:29}];
20321            $scope.predicate = 'age';
20322            $scope.reverse = true;
20323            $scope.order = function(predicate) {
20324              $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
20325              $scope.predicate = predicate;
20326            };
20327          }]);
20328       </file>
20329      <file name="style.css">
20330        .sortorder:after {
20331          content: '\25b2';
20332        }
20333        .sortorder.reverse:after {
20334          content: '\25bc';
20335        }
20336      </file>
20337    </example>
20338  *
20339  * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
20340  * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
20341  * desired parameters.
20342  *
20343  * Example:
20344  *
20345  * @example
20346   <example module="orderByExample">
20347     <file name="index.html">
20348     <div ng-controller="ExampleController">
20349       <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
20350       <table class="friend">
20351         <tr>
20352           <th>
20353               <button ng-click="order('name')">Name</button>
20354               <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
20355           </th>
20356           <th>
20357               <button ng-click="order('phone')">Phone Number</button>
20358               <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
20359           </th>
20360           <th>
20361               <button ng-click="order('age')">Age</button>
20362               <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
20363           </th>
20364         </tr>
20365         <tr ng-repeat="friend in friends">
20366           <td>{{friend.name}}</td>
20367           <td>{{friend.phone}}</td>
20368           <td>{{friend.age}}</td>
20369         </tr>
20370       </table>
20371     </div>
20372     </file>
20373
20374     <file name="script.js">
20375       angular.module('orderByExample', [])
20376         .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
20377           var orderBy = $filter('orderBy');
20378           $scope.friends = [
20379             { name: 'John',    phone: '555-1212',    age: 10 },
20380             { name: 'Mary',    phone: '555-9876',    age: 19 },
20381             { name: 'Mike',    phone: '555-4321',    age: 21 },
20382             { name: 'Adam',    phone: '555-5678',    age: 35 },
20383             { name: 'Julie',   phone: '555-8765',    age: 29 }
20384           ];
20385           $scope.order = function(predicate) {
20386             $scope.predicate = predicate;
20387             $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
20388             $scope.friends = orderBy($scope.friends, predicate, $scope.reverse);
20389           };
20390           $scope.order('age', true);
20391         }]);
20392     </file>
20393
20394     <file name="style.css">
20395        .sortorder:after {
20396          content: '\25b2';
20397        }
20398        .sortorder.reverse:after {
20399          content: '\25bc';
20400        }
20401     </file>
20402 </example>
20403  */
20404 orderByFilter.$inject = ['$parse'];
20405 function orderByFilter($parse) {
20406   return function(array, sortPredicate, reverseOrder) {
20407
20408     if (array == null) return array;
20409     if (!isArrayLike(array)) {
20410       throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
20411     }
20412
20413     if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
20414     if (sortPredicate.length === 0) { sortPredicate = ['+']; }
20415
20416     var predicates = processPredicates(sortPredicate, reverseOrder);
20417     // Add a predicate at the end that evaluates to the element index. This makes the
20418     // sort stable as it works as a tie-breaker when all the input predicates cannot
20419     // distinguish between two elements.
20420     predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
20421
20422     // The next three lines are a version of a Swartzian Transform idiom from Perl
20423     // (sometimes called the Decorate-Sort-Undecorate idiom)
20424     // See https://en.wikipedia.org/wiki/Schwartzian_transform
20425     var compareValues = Array.prototype.map.call(array, getComparisonObject);
20426     compareValues.sort(doComparison);
20427     array = compareValues.map(function(item) { return item.value; });
20428
20429     return array;
20430
20431     function getComparisonObject(value, index) {
20432       return {
20433         value: value,
20434         predicateValues: predicates.map(function(predicate) {
20435           return getPredicateValue(predicate.get(value), index);
20436         })
20437       };
20438     }
20439
20440     function doComparison(v1, v2) {
20441       var result = 0;
20442       for (var index=0, length = predicates.length; index < length; ++index) {
20443         result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
20444         if (result) break;
20445       }
20446       return result;
20447     }
20448   };
20449
20450   function processPredicates(sortPredicate, reverseOrder) {
20451     reverseOrder = reverseOrder ? -1 : 1;
20452     return sortPredicate.map(function(predicate) {
20453       var descending = 1, get = identity;
20454
20455       if (isFunction(predicate)) {
20456         get = predicate;
20457       } else if (isString(predicate)) {
20458         if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
20459           descending = predicate.charAt(0) == '-' ? -1 : 1;
20460           predicate = predicate.substring(1);
20461         }
20462         if (predicate !== '') {
20463           get = $parse(predicate);
20464           if (get.constant) {
20465             var key = get();
20466             get = function(value) { return value[key]; };
20467           }
20468         }
20469       }
20470       return { get: get, descending: descending * reverseOrder };
20471     });
20472   }
20473
20474   function isPrimitive(value) {
20475     switch (typeof value) {
20476       case 'number': /* falls through */
20477       case 'boolean': /* falls through */
20478       case 'string':
20479         return true;
20480       default:
20481         return false;
20482     }
20483   }
20484
20485   function objectValue(value, index) {
20486     // If `valueOf` is a valid function use that
20487     if (typeof value.valueOf === 'function') {
20488       value = value.valueOf();
20489       if (isPrimitive(value)) return value;
20490     }
20491     // If `toString` is a valid function and not the one from `Object.prototype` use that
20492     if (hasCustomToString(value)) {
20493       value = value.toString();
20494       if (isPrimitive(value)) return value;
20495     }
20496     // We have a basic object so we use the position of the object in the collection
20497     return index;
20498   }
20499
20500   function getPredicateValue(value, index) {
20501     var type = typeof value;
20502     if (value === null) {
20503       type = 'string';
20504       value = 'null';
20505     } else if (type === 'string') {
20506       value = value.toLowerCase();
20507     } else if (type === 'object') {
20508       value = objectValue(value, index);
20509     }
20510     return { value: value, type: type };
20511   }
20512
20513   function compare(v1, v2) {
20514     var result = 0;
20515     if (v1.type === v2.type) {
20516       if (v1.value !== v2.value) {
20517         result = v1.value < v2.value ? -1 : 1;
20518       }
20519     } else {
20520       result = v1.type < v2.type ? -1 : 1;
20521     }
20522     return result;
20523   }
20524 }
20525
20526 function ngDirective(directive) {
20527   if (isFunction(directive)) {
20528     directive = {
20529       link: directive
20530     };
20531   }
20532   directive.restrict = directive.restrict || 'AC';
20533   return valueFn(directive);
20534 }
20535
20536 /**
20537  * @ngdoc directive
20538  * @name a
20539  * @restrict E
20540  *
20541  * @description
20542  * Modifies the default behavior of the html A tag so that the default action is prevented when
20543  * the href attribute is empty.
20544  *
20545  * This change permits the easy creation of action links with the `ngClick` directive
20546  * without changing the location or causing page reloads, e.g.:
20547  * `<a href="" ng-click="list.addItem()">Add Item</a>`
20548  */
20549 var htmlAnchorDirective = valueFn({
20550   restrict: 'E',
20551   compile: function(element, attr) {
20552     if (!attr.href && !attr.xlinkHref) {
20553       return function(scope, element) {
20554         // If the linked element is not an anchor tag anymore, do nothing
20555         if (element[0].nodeName.toLowerCase() !== 'a') return;
20556
20557         // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
20558         var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
20559                    'xlink:href' : 'href';
20560         element.on('click', function(event) {
20561           // if we have no href url, then don't navigate anywhere.
20562           if (!element.attr(href)) {
20563             event.preventDefault();
20564           }
20565         });
20566       };
20567     }
20568   }
20569 });
20570
20571 /**
20572  * @ngdoc directive
20573  * @name ngHref
20574  * @restrict A
20575  * @priority 99
20576  *
20577  * @description
20578  * Using Angular markup like `{{hash}}` in an href attribute will
20579  * make the link go to the wrong URL if the user clicks it before
20580  * Angular has a chance to replace the `{{hash}}` markup with its
20581  * value. Until Angular replaces the markup the link will be broken
20582  * and will most likely return a 404 error. The `ngHref` directive
20583  * solves this problem.
20584  *
20585  * The wrong way to write it:
20586  * ```html
20587  * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
20588  * ```
20589  *
20590  * The correct way to write it:
20591  * ```html
20592  * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
20593  * ```
20594  *
20595  * @element A
20596  * @param {template} ngHref any string which can contain `{{}}` markup.
20597  *
20598  * @example
20599  * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
20600  * in links and their different behaviors:
20601     <example>
20602       <file name="index.html">
20603         <input ng-model="value" /><br />
20604         <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
20605         <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
20606         <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
20607         <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
20608         <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
20609         <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
20610       </file>
20611       <file name="protractor.js" type="protractor">
20612         it('should execute ng-click but not reload when href without value', function() {
20613           element(by.id('link-1')).click();
20614           expect(element(by.model('value')).getAttribute('value')).toEqual('1');
20615           expect(element(by.id('link-1')).getAttribute('href')).toBe('');
20616         });
20617
20618         it('should execute ng-click but not reload when href empty string', function() {
20619           element(by.id('link-2')).click();
20620           expect(element(by.model('value')).getAttribute('value')).toEqual('2');
20621           expect(element(by.id('link-2')).getAttribute('href')).toBe('');
20622         });
20623
20624         it('should execute ng-click and change url when ng-href specified', function() {
20625           expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
20626
20627           element(by.id('link-3')).click();
20628
20629           // At this point, we navigate away from an Angular page, so we need
20630           // to use browser.driver to get the base webdriver.
20631
20632           browser.wait(function() {
20633             return browser.driver.getCurrentUrl().then(function(url) {
20634               return url.match(/\/123$/);
20635             });
20636           }, 5000, 'page should navigate to /123');
20637         });
20638
20639         it('should execute ng-click but not reload when href empty string and name specified', function() {
20640           element(by.id('link-4')).click();
20641           expect(element(by.model('value')).getAttribute('value')).toEqual('4');
20642           expect(element(by.id('link-4')).getAttribute('href')).toBe('');
20643         });
20644
20645         it('should execute ng-click but not reload when no href but name specified', function() {
20646           element(by.id('link-5')).click();
20647           expect(element(by.model('value')).getAttribute('value')).toEqual('5');
20648           expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
20649         });
20650
20651         it('should only change url when only ng-href', function() {
20652           element(by.model('value')).clear();
20653           element(by.model('value')).sendKeys('6');
20654           expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
20655
20656           element(by.id('link-6')).click();
20657
20658           // At this point, we navigate away from an Angular page, so we need
20659           // to use browser.driver to get the base webdriver.
20660           browser.wait(function() {
20661             return browser.driver.getCurrentUrl().then(function(url) {
20662               return url.match(/\/6$/);
20663             });
20664           }, 5000, 'page should navigate to /6');
20665         });
20666       </file>
20667     </example>
20668  */
20669
20670 /**
20671  * @ngdoc directive
20672  * @name ngSrc
20673  * @restrict A
20674  * @priority 99
20675  *
20676  * @description
20677  * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
20678  * work right: The browser will fetch from the URL with the literal
20679  * text `{{hash}}` until Angular replaces the expression inside
20680  * `{{hash}}`. The `ngSrc` directive solves this problem.
20681  *
20682  * The buggy way to write it:
20683  * ```html
20684  * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
20685  * ```
20686  *
20687  * The correct way to write it:
20688  * ```html
20689  * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
20690  * ```
20691  *
20692  * @element IMG
20693  * @param {template} ngSrc any string which can contain `{{}}` markup.
20694  */
20695
20696 /**
20697  * @ngdoc directive
20698  * @name ngSrcset
20699  * @restrict A
20700  * @priority 99
20701  *
20702  * @description
20703  * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
20704  * work right: The browser will fetch from the URL with the literal
20705  * text `{{hash}}` until Angular replaces the expression inside
20706  * `{{hash}}`. The `ngSrcset` directive solves this problem.
20707  *
20708  * The buggy way to write it:
20709  * ```html
20710  * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
20711  * ```
20712  *
20713  * The correct way to write it:
20714  * ```html
20715  * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
20716  * ```
20717  *
20718  * @element IMG
20719  * @param {template} ngSrcset any string which can contain `{{}}` markup.
20720  */
20721
20722 /**
20723  * @ngdoc directive
20724  * @name ngDisabled
20725  * @restrict A
20726  * @priority 100
20727  *
20728  * @description
20729  *
20730  * This directive sets the `disabled` attribute on the element if the
20731  * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
20732  *
20733  * A special directive is necessary because we cannot use interpolation inside the `disabled`
20734  * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20735  *
20736  * @example
20737     <example>
20738       <file name="index.html">
20739         <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
20740         <button ng-model="button" ng-disabled="checked">Button</button>
20741       </file>
20742       <file name="protractor.js" type="protractor">
20743         it('should toggle button', function() {
20744           expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
20745           element(by.model('checked')).click();
20746           expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
20747         });
20748       </file>
20749     </example>
20750  *
20751  * @element INPUT
20752  * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
20753  *     then the `disabled` attribute will be set on the element
20754  */
20755
20756
20757 /**
20758  * @ngdoc directive
20759  * @name ngChecked
20760  * @restrict A
20761  * @priority 100
20762  *
20763  * @description
20764  * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
20765  *
20766  * Note that this directive should not be used together with {@link ngModel `ngModel`},
20767  * as this can lead to unexpected behavior.
20768  *
20769  * A special directive is necessary because we cannot use interpolation inside the `checked`
20770  * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20771  *
20772  * @example
20773     <example>
20774       <file name="index.html">
20775         <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
20776         <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
20777       </file>
20778       <file name="protractor.js" type="protractor">
20779         it('should check both checkBoxes', function() {
20780           expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
20781           element(by.model('master')).click();
20782           expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
20783         });
20784       </file>
20785     </example>
20786  *
20787  * @element INPUT
20788  * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
20789  *     then the `checked` attribute will be set on the element
20790  */
20791
20792
20793 /**
20794  * @ngdoc directive
20795  * @name ngReadonly
20796  * @restrict A
20797  * @priority 100
20798  *
20799  * @description
20800  *
20801  * Sets the `readOnly` attribute on the element, if the expression inside `ngReadonly` is truthy.
20802  *
20803  * A special directive is necessary because we cannot use interpolation inside the `readOnly`
20804  * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20805  *
20806  * @example
20807     <example>
20808       <file name="index.html">
20809         <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
20810         <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
20811       </file>
20812       <file name="protractor.js" type="protractor">
20813         it('should toggle readonly attr', function() {
20814           expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
20815           element(by.model('checked')).click();
20816           expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
20817         });
20818       </file>
20819     </example>
20820  *
20821  * @element INPUT
20822  * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
20823  *     then special attribute "readonly" will be set on the element
20824  */
20825
20826
20827 /**
20828  * @ngdoc directive
20829  * @name ngSelected
20830  * @restrict A
20831  * @priority 100
20832  *
20833  * @description
20834  *
20835  * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
20836  *
20837  * A special directive is necessary because we cannot use interpolation inside the `selected`
20838  * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20839  *
20840  * @example
20841     <example>
20842       <file name="index.html">
20843         <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
20844         <select aria-label="ngSelected demo">
20845           <option>Hello!</option>
20846           <option id="greet" ng-selected="selected">Greetings!</option>
20847         </select>
20848       </file>
20849       <file name="protractor.js" type="protractor">
20850         it('should select Greetings!', function() {
20851           expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
20852           element(by.model('selected')).click();
20853           expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
20854         });
20855       </file>
20856     </example>
20857  *
20858  * @element OPTION
20859  * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
20860  *     then special attribute "selected" will be set on the element
20861  */
20862
20863 /**
20864  * @ngdoc directive
20865  * @name ngOpen
20866  * @restrict A
20867  * @priority 100
20868  *
20869  * @description
20870  *
20871  * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
20872  *
20873  * A special directive is necessary because we cannot use interpolation inside the `open`
20874  * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20875  *
20876  * @example
20877      <example>
20878        <file name="index.html">
20879          <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
20880          <details id="details" ng-open="open">
20881             <summary>Show/Hide me</summary>
20882          </details>
20883        </file>
20884        <file name="protractor.js" type="protractor">
20885          it('should toggle open', function() {
20886            expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
20887            element(by.model('open')).click();
20888            expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
20889          });
20890        </file>
20891      </example>
20892  *
20893  * @element DETAILS
20894  * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
20895  *     then special attribute "open" will be set on the element
20896  */
20897
20898 var ngAttributeAliasDirectives = {};
20899
20900 // boolean attrs are evaluated
20901 forEach(BOOLEAN_ATTR, function(propName, attrName) {
20902   // binding to multiple is not supported
20903   if (propName == "multiple") return;
20904
20905   function defaultLinkFn(scope, element, attr) {
20906     scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
20907       attr.$set(attrName, !!value);
20908     });
20909   }
20910
20911   var normalized = directiveNormalize('ng-' + attrName);
20912   var linkFn = defaultLinkFn;
20913
20914   if (propName === 'checked') {
20915     linkFn = function(scope, element, attr) {
20916       // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
20917       if (attr.ngModel !== attr[normalized]) {
20918         defaultLinkFn(scope, element, attr);
20919       }
20920     };
20921   }
20922
20923   ngAttributeAliasDirectives[normalized] = function() {
20924     return {
20925       restrict: 'A',
20926       priority: 100,
20927       link: linkFn
20928     };
20929   };
20930 });
20931
20932 // aliased input attrs are evaluated
20933 forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
20934   ngAttributeAliasDirectives[ngAttr] = function() {
20935     return {
20936       priority: 100,
20937       link: function(scope, element, attr) {
20938         //special case ngPattern when a literal regular expression value
20939         //is used as the expression (this way we don't have to watch anything).
20940         if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
20941           var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
20942           if (match) {
20943             attr.$set("ngPattern", new RegExp(match[1], match[2]));
20944             return;
20945           }
20946         }
20947
20948         scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
20949           attr.$set(ngAttr, value);
20950         });
20951       }
20952     };
20953   };
20954 });
20955
20956 // ng-src, ng-srcset, ng-href are interpolated
20957 forEach(['src', 'srcset', 'href'], function(attrName) {
20958   var normalized = directiveNormalize('ng-' + attrName);
20959   ngAttributeAliasDirectives[normalized] = function() {
20960     return {
20961       priority: 99, // it needs to run after the attributes are interpolated
20962       link: function(scope, element, attr) {
20963         var propName = attrName,
20964             name = attrName;
20965
20966         if (attrName === 'href' &&
20967             toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
20968           name = 'xlinkHref';
20969           attr.$attr[name] = 'xlink:href';
20970           propName = null;
20971         }
20972
20973         attr.$observe(normalized, function(value) {
20974           if (!value) {
20975             if (attrName === 'href') {
20976               attr.$set(name, null);
20977             }
20978             return;
20979           }
20980
20981           attr.$set(name, value);
20982
20983           // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
20984           // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
20985           // to set the property as well to achieve the desired effect.
20986           // we use attr[attrName] value since $set can sanitize the url.
20987           if (msie && propName) element.prop(propName, attr[name]);
20988         });
20989       }
20990     };
20991   };
20992 });
20993
20994 /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
20995  */
20996 var nullFormCtrl = {
20997   $addControl: noop,
20998   $$renameControl: nullFormRenameControl,
20999   $removeControl: noop,
21000   $setValidity: noop,
21001   $setDirty: noop,
21002   $setPristine: noop,
21003   $setSubmitted: noop
21004 },
21005 SUBMITTED_CLASS = 'ng-submitted';
21006
21007 function nullFormRenameControl(control, name) {
21008   control.$name = name;
21009 }
21010
21011 /**
21012  * @ngdoc type
21013  * @name form.FormController
21014  *
21015  * @property {boolean} $pristine True if user has not interacted with the form yet.
21016  * @property {boolean} $dirty True if user has already interacted with the form.
21017  * @property {boolean} $valid True if all of the containing forms and controls are valid.
21018  * @property {boolean} $invalid True if at least one containing control or form is invalid.
21019  * @property {boolean} $pending True if at least one containing control or form is pending.
21020  * @property {boolean} $submitted True if user has submitted the form even if its invalid.
21021  *
21022  * @property {Object} $error Is an object hash, containing references to controls or
21023  *  forms with failing validators, where:
21024  *
21025  *  - keys are validation tokens (error names),
21026  *  - values are arrays of controls or forms that have a failing validator for given error name.
21027  *
21028  *  Built-in validation tokens:
21029  *
21030  *  - `email`
21031  *  - `max`
21032  *  - `maxlength`
21033  *  - `min`
21034  *  - `minlength`
21035  *  - `number`
21036  *  - `pattern`
21037  *  - `required`
21038  *  - `url`
21039  *  - `date`
21040  *  - `datetimelocal`
21041  *  - `time`
21042  *  - `week`
21043  *  - `month`
21044  *
21045  * @description
21046  * `FormController` keeps track of all its controls and nested forms as well as the state of them,
21047  * such as being valid/invalid or dirty/pristine.
21048  *
21049  * Each {@link ng.directive:form form} directive creates an instance
21050  * of `FormController`.
21051  *
21052  */
21053 //asks for $scope to fool the BC controller module
21054 FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
21055 function FormController(element, attrs, $scope, $animate, $interpolate) {
21056   var form = this,
21057       controls = [];
21058
21059   // init state
21060   form.$error = {};
21061   form.$$success = {};
21062   form.$pending = undefined;
21063   form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
21064   form.$dirty = false;
21065   form.$pristine = true;
21066   form.$valid = true;
21067   form.$invalid = false;
21068   form.$submitted = false;
21069   form.$$parentForm = nullFormCtrl;
21070
21071   /**
21072    * @ngdoc method
21073    * @name form.FormController#$rollbackViewValue
21074    *
21075    * @description
21076    * Rollback all form controls pending updates to the `$modelValue`.
21077    *
21078    * Updates may be pending by a debounced event or because the input is waiting for a some future
21079    * event defined in `ng-model-options`. This method is typically needed by the reset button of
21080    * a form that uses `ng-model-options` to pend updates.
21081    */
21082   form.$rollbackViewValue = function() {
21083     forEach(controls, function(control) {
21084       control.$rollbackViewValue();
21085     });
21086   };
21087
21088   /**
21089    * @ngdoc method
21090    * @name form.FormController#$commitViewValue
21091    *
21092    * @description
21093    * Commit all form controls pending updates to the `$modelValue`.
21094    *
21095    * Updates may be pending by a debounced event or because the input is waiting for a some future
21096    * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
21097    * usually handles calling this in response to input events.
21098    */
21099   form.$commitViewValue = function() {
21100     forEach(controls, function(control) {
21101       control.$commitViewValue();
21102     });
21103   };
21104
21105   /**
21106    * @ngdoc method
21107    * @name form.FormController#$addControl
21108    * @param {object} control control object, either a {@link form.FormController} or an
21109    * {@link ngModel.NgModelController}
21110    *
21111    * @description
21112    * Register a control with the form. Input elements using ngModelController do this automatically
21113    * when they are linked.
21114    *
21115    * Note that the current state of the control will not be reflected on the new parent form. This
21116    * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
21117    * state.
21118    *
21119    * However, if the method is used programmatically, for example by adding dynamically created controls,
21120    * or controls that have been previously removed without destroying their corresponding DOM element,
21121    * it's the developers responsibility to make sure the current state propagates to the parent form.
21122    *
21123    * For example, if an input control is added that is already `$dirty` and has `$error` properties,
21124    * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
21125    */
21126   form.$addControl = function(control) {
21127     // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
21128     // and not added to the scope.  Now we throw an error.
21129     assertNotHasOwnProperty(control.$name, 'input');
21130     controls.push(control);
21131
21132     if (control.$name) {
21133       form[control.$name] = control;
21134     }
21135
21136     control.$$parentForm = form;
21137   };
21138
21139   // Private API: rename a form control
21140   form.$$renameControl = function(control, newName) {
21141     var oldName = control.$name;
21142
21143     if (form[oldName] === control) {
21144       delete form[oldName];
21145     }
21146     form[newName] = control;
21147     control.$name = newName;
21148   };
21149
21150   /**
21151    * @ngdoc method
21152    * @name form.FormController#$removeControl
21153    * @param {object} control control object, either a {@link form.FormController} or an
21154    * {@link ngModel.NgModelController}
21155    *
21156    * @description
21157    * Deregister a control from the form.
21158    *
21159    * Input elements using ngModelController do this automatically when they are destroyed.
21160    *
21161    * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
21162    * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
21163    * different from case to case. For example, removing the only `$dirty` control from a form may or
21164    * may not mean that the form is still `$dirty`.
21165    */
21166   form.$removeControl = function(control) {
21167     if (control.$name && form[control.$name] === control) {
21168       delete form[control.$name];
21169     }
21170     forEach(form.$pending, function(value, name) {
21171       form.$setValidity(name, null, control);
21172     });
21173     forEach(form.$error, function(value, name) {
21174       form.$setValidity(name, null, control);
21175     });
21176     forEach(form.$$success, function(value, name) {
21177       form.$setValidity(name, null, control);
21178     });
21179
21180     arrayRemove(controls, control);
21181     control.$$parentForm = nullFormCtrl;
21182   };
21183
21184
21185   /**
21186    * @ngdoc method
21187    * @name form.FormController#$setValidity
21188    *
21189    * @description
21190    * Sets the validity of a form control.
21191    *
21192    * This method will also propagate to parent forms.
21193    */
21194   addSetValidityMethod({
21195     ctrl: this,
21196     $element: element,
21197     set: function(object, property, controller) {
21198       var list = object[property];
21199       if (!list) {
21200         object[property] = [controller];
21201       } else {
21202         var index = list.indexOf(controller);
21203         if (index === -1) {
21204           list.push(controller);
21205         }
21206       }
21207     },
21208     unset: function(object, property, controller) {
21209       var list = object[property];
21210       if (!list) {
21211         return;
21212       }
21213       arrayRemove(list, controller);
21214       if (list.length === 0) {
21215         delete object[property];
21216       }
21217     },
21218     $animate: $animate
21219   });
21220
21221   /**
21222    * @ngdoc method
21223    * @name form.FormController#$setDirty
21224    *
21225    * @description
21226    * Sets the form to a dirty state.
21227    *
21228    * This method can be called to add the 'ng-dirty' class and set the form to a dirty
21229    * state (ng-dirty class). This method will also propagate to parent forms.
21230    */
21231   form.$setDirty = function() {
21232     $animate.removeClass(element, PRISTINE_CLASS);
21233     $animate.addClass(element, DIRTY_CLASS);
21234     form.$dirty = true;
21235     form.$pristine = false;
21236     form.$$parentForm.$setDirty();
21237   };
21238
21239   /**
21240    * @ngdoc method
21241    * @name form.FormController#$setPristine
21242    *
21243    * @description
21244    * Sets the form to its pristine state.
21245    *
21246    * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
21247    * state (ng-pristine class). This method will also propagate to all the controls contained
21248    * in this form.
21249    *
21250    * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
21251    * saving or resetting it.
21252    */
21253   form.$setPristine = function() {
21254     $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
21255     form.$dirty = false;
21256     form.$pristine = true;
21257     form.$submitted = false;
21258     forEach(controls, function(control) {
21259       control.$setPristine();
21260     });
21261   };
21262
21263   /**
21264    * @ngdoc method
21265    * @name form.FormController#$setUntouched
21266    *
21267    * @description
21268    * Sets the form to its untouched state.
21269    *
21270    * This method can be called to remove the 'ng-touched' class and set the form controls to their
21271    * untouched state (ng-untouched class).
21272    *
21273    * Setting a form controls back to their untouched state is often useful when setting the form
21274    * back to its pristine state.
21275    */
21276   form.$setUntouched = function() {
21277     forEach(controls, function(control) {
21278       control.$setUntouched();
21279     });
21280   };
21281
21282   /**
21283    * @ngdoc method
21284    * @name form.FormController#$setSubmitted
21285    *
21286    * @description
21287    * Sets the form to its submitted state.
21288    */
21289   form.$setSubmitted = function() {
21290     $animate.addClass(element, SUBMITTED_CLASS);
21291     form.$submitted = true;
21292     form.$$parentForm.$setSubmitted();
21293   };
21294 }
21295
21296 /**
21297  * @ngdoc directive
21298  * @name ngForm
21299  * @restrict EAC
21300  *
21301  * @description
21302  * Nestable alias of {@link ng.directive:form `form`} directive. HTML
21303  * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
21304  * sub-group of controls needs to be determined.
21305  *
21306  * Note: the purpose of `ngForm` is to group controls,
21307  * but not to be a replacement for the `<form>` tag with all of its capabilities
21308  * (e.g. posting to the server, ...).
21309  *
21310  * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
21311  *                       related scope, under this name.
21312  *
21313  */
21314
21315  /**
21316  * @ngdoc directive
21317  * @name form
21318  * @restrict E
21319  *
21320  * @description
21321  * Directive that instantiates
21322  * {@link form.FormController FormController}.
21323  *
21324  * If the `name` attribute is specified, the form controller is published onto the current scope under
21325  * this name.
21326  *
21327  * # Alias: {@link ng.directive:ngForm `ngForm`}
21328  *
21329  * In Angular, forms can be nested. This means that the outer form is valid when all of the child
21330  * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
21331  * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
21332  * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
21333  * of controls needs to be determined.
21334  *
21335  * # CSS classes
21336  *  - `ng-valid` is set if the form is valid.
21337  *  - `ng-invalid` is set if the form is invalid.
21338  *  - `ng-pending` is set if the form is pending.
21339  *  - `ng-pristine` is set if the form is pristine.
21340  *  - `ng-dirty` is set if the form is dirty.
21341  *  - `ng-submitted` is set if the form was submitted.
21342  *
21343  * Keep in mind that ngAnimate can detect each of these classes when added and removed.
21344  *
21345  *
21346  * # Submitting a form and preventing the default action
21347  *
21348  * Since the role of forms in client-side Angular applications is different than in classical
21349  * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
21350  * page reload that sends the data to the server. Instead some javascript logic should be triggered
21351  * to handle the form submission in an application-specific way.
21352  *
21353  * For this reason, Angular prevents the default action (form submission to the server) unless the
21354  * `<form>` element has an `action` attribute specified.
21355  *
21356  * You can use one of the following two ways to specify what javascript method should be called when
21357  * a form is submitted:
21358  *
21359  * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
21360  * - {@link ng.directive:ngClick ngClick} directive on the first
21361   *  button or input field of type submit (input[type=submit])
21362  *
21363  * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
21364  * or {@link ng.directive:ngClick ngClick} directives.
21365  * This is because of the following form submission rules in the HTML specification:
21366  *
21367  * - If a form has only one input field then hitting enter in this field triggers form submit
21368  * (`ngSubmit`)
21369  * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
21370  * doesn't trigger submit
21371  * - if a form has one or more input fields and one or more buttons or input[type=submit] then
21372  * hitting enter in any of the input fields will trigger the click handler on the *first* button or
21373  * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
21374  *
21375  * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
21376  * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
21377  * to have access to the updated model.
21378  *
21379  * ## Animation Hooks
21380  *
21381  * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
21382  * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
21383  * other validations that are performed within the form. Animations in ngForm are similar to how
21384  * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
21385  * as JS animations.
21386  *
21387  * The following example shows a simple way to utilize CSS transitions to style a form element
21388  * that has been rendered as invalid after it has been validated:
21389  *
21390  * <pre>
21391  * //be sure to include ngAnimate as a module to hook into more
21392  * //advanced animations
21393  * .my-form {
21394  *   transition:0.5s linear all;
21395  *   background: white;
21396  * }
21397  * .my-form.ng-invalid {
21398  *   background: red;
21399  *   color:white;
21400  * }
21401  * </pre>
21402  *
21403  * @example
21404     <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
21405       <file name="index.html">
21406        <script>
21407          angular.module('formExample', [])
21408            .controller('FormController', ['$scope', function($scope) {
21409              $scope.userType = 'guest';
21410            }]);
21411        </script>
21412        <style>
21413         .my-form {
21414           transition:all linear 0.5s;
21415           background: transparent;
21416         }
21417         .my-form.ng-invalid {
21418           background: red;
21419         }
21420        </style>
21421        <form name="myForm" ng-controller="FormController" class="my-form">
21422          userType: <input name="input" ng-model="userType" required>
21423          <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
21424          <code>userType = {{userType}}</code><br>
21425          <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
21426          <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
21427          <code>myForm.$valid = {{myForm.$valid}}</code><br>
21428          <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
21429         </form>
21430       </file>
21431       <file name="protractor.js" type="protractor">
21432         it('should initialize to model', function() {
21433           var userType = element(by.binding('userType'));
21434           var valid = element(by.binding('myForm.input.$valid'));
21435
21436           expect(userType.getText()).toContain('guest');
21437           expect(valid.getText()).toContain('true');
21438         });
21439
21440         it('should be invalid if empty', function() {
21441           var userType = element(by.binding('userType'));
21442           var valid = element(by.binding('myForm.input.$valid'));
21443           var userInput = element(by.model('userType'));
21444
21445           userInput.clear();
21446           userInput.sendKeys('');
21447
21448           expect(userType.getText()).toEqual('userType =');
21449           expect(valid.getText()).toContain('false');
21450         });
21451       </file>
21452     </example>
21453  *
21454  * @param {string=} name Name of the form. If specified, the form controller will be published into
21455  *                       related scope, under this name.
21456  */
21457 var formDirectiveFactory = function(isNgForm) {
21458   return ['$timeout', '$parse', function($timeout, $parse) {
21459     var formDirective = {
21460       name: 'form',
21461       restrict: isNgForm ? 'EAC' : 'E',
21462       require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
21463       controller: FormController,
21464       compile: function ngFormCompile(formElement, attr) {
21465         // Setup initial state of the control
21466         formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
21467
21468         var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
21469
21470         return {
21471           pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
21472             var controller = ctrls[0];
21473
21474             // if `action` attr is not present on the form, prevent the default action (submission)
21475             if (!('action' in attr)) {
21476               // we can't use jq events because if a form is destroyed during submission the default
21477               // action is not prevented. see #1238
21478               //
21479               // IE 9 is not affected because it doesn't fire a submit event and try to do a full
21480               // page reload if the form was destroyed by submission of the form via a click handler
21481               // on a button in the form. Looks like an IE9 specific bug.
21482               var handleFormSubmission = function(event) {
21483                 scope.$apply(function() {
21484                   controller.$commitViewValue();
21485                   controller.$setSubmitted();
21486                 });
21487
21488                 event.preventDefault();
21489               };
21490
21491               addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
21492
21493               // unregister the preventDefault listener so that we don't not leak memory but in a
21494               // way that will achieve the prevention of the default action.
21495               formElement.on('$destroy', function() {
21496                 $timeout(function() {
21497                   removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
21498                 }, 0, false);
21499               });
21500             }
21501
21502             var parentFormCtrl = ctrls[1] || controller.$$parentForm;
21503             parentFormCtrl.$addControl(controller);
21504
21505             var setter = nameAttr ? getSetter(controller.$name) : noop;
21506
21507             if (nameAttr) {
21508               setter(scope, controller);
21509               attr.$observe(nameAttr, function(newValue) {
21510                 if (controller.$name === newValue) return;
21511                 setter(scope, undefined);
21512                 controller.$$parentForm.$$renameControl(controller, newValue);
21513                 setter = getSetter(controller.$name);
21514                 setter(scope, controller);
21515               });
21516             }
21517             formElement.on('$destroy', function() {
21518               controller.$$parentForm.$removeControl(controller);
21519               setter(scope, undefined);
21520               extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
21521             });
21522           }
21523         };
21524       }
21525     };
21526
21527     return formDirective;
21528
21529     function getSetter(expression) {
21530       if (expression === '') {
21531         //create an assignable expression, so forms with an empty name can be renamed later
21532         return $parse('this[""]').assign;
21533       }
21534       return $parse(expression).assign || noop;
21535     }
21536   }];
21537 };
21538
21539 var formDirective = formDirectiveFactory();
21540 var ngFormDirective = formDirectiveFactory(true);
21541
21542 /* global VALID_CLASS: false,
21543   INVALID_CLASS: false,
21544   PRISTINE_CLASS: false,
21545   DIRTY_CLASS: false,
21546   UNTOUCHED_CLASS: false,
21547   TOUCHED_CLASS: false,
21548   ngModelMinErr: false,
21549 */
21550
21551 // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
21552 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)/;
21553 // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
21554 // Note: We are being more lenient, because browsers are too.
21555 //   1. Scheme
21556 //   2. Slashes
21557 //   3. Username
21558 //   4. Password
21559 //   5. Hostname
21560 //   6. Port
21561 //   7. Path
21562 //   8. Query
21563 //   9. Fragment
21564 //                 1111111111111111 222   333333    44444        555555555555555555555555    666     77777777     8888888     999
21565 var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
21566 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;
21567 var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
21568 var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
21569 var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
21570 var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
21571 var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
21572 var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
21573
21574 var inputType = {
21575
21576   /**
21577    * @ngdoc input
21578    * @name input[text]
21579    *
21580    * @description
21581    * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
21582    *
21583    *
21584    * @param {string} ngModel Assignable angular expression to data-bind to.
21585    * @param {string=} name Property name of the form under which the control is published.
21586    * @param {string=} required Adds `required` validation error key if the value is not entered.
21587    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21588    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21589    *    `required` when you want to data-bind to the `required` attribute.
21590    * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
21591    *    minlength.
21592    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
21593    *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
21594    *    any length.
21595    * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
21596    *    that contains the regular expression body that will be converted to a regular expression
21597    *    as in the ngPattern directive.
21598    * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
21599    *    does not match a RegExp found by evaluating the Angular expression given in the attribute value.
21600    *    If the expression evaluates to a RegExp object, then this is used directly.
21601    *    If the expression evaluates to a string, then it will be converted to a RegExp
21602    *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
21603    *    `new RegExp('^abc$')`.<br />
21604    *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
21605    *    start at the index of the last search's match, thus not taking the whole input value into
21606    *    account.
21607    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21608    *    interaction with the input element.
21609    * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
21610    *    This parameter is ignored for input[type=password] controls, which will never trim the
21611    *    input.
21612    *
21613    * @example
21614       <example name="text-input-directive" module="textInputExample">
21615         <file name="index.html">
21616          <script>
21617            angular.module('textInputExample', [])
21618              .controller('ExampleController', ['$scope', function($scope) {
21619                $scope.example = {
21620                  text: 'guest',
21621                  word: /^\s*\w*\s*$/
21622                };
21623              }]);
21624          </script>
21625          <form name="myForm" ng-controller="ExampleController">
21626            <label>Single word:
21627              <input type="text" name="input" ng-model="example.text"
21628                     ng-pattern="example.word" required ng-trim="false">
21629            </label>
21630            <div role="alert">
21631              <span class="error" ng-show="myForm.input.$error.required">
21632                Required!</span>
21633              <span class="error" ng-show="myForm.input.$error.pattern">
21634                Single word only!</span>
21635            </div>
21636            <tt>text = {{example.text}}</tt><br/>
21637            <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21638            <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21639            <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21640            <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21641           </form>
21642         </file>
21643         <file name="protractor.js" type="protractor">
21644           var text = element(by.binding('example.text'));
21645           var valid = element(by.binding('myForm.input.$valid'));
21646           var input = element(by.model('example.text'));
21647
21648           it('should initialize to model', function() {
21649             expect(text.getText()).toContain('guest');
21650             expect(valid.getText()).toContain('true');
21651           });
21652
21653           it('should be invalid if empty', function() {
21654             input.clear();
21655             input.sendKeys('');
21656
21657             expect(text.getText()).toEqual('text =');
21658             expect(valid.getText()).toContain('false');
21659           });
21660
21661           it('should be invalid if multi word', function() {
21662             input.clear();
21663             input.sendKeys('hello world');
21664
21665             expect(valid.getText()).toContain('false');
21666           });
21667         </file>
21668       </example>
21669    */
21670   'text': textInputType,
21671
21672     /**
21673      * @ngdoc input
21674      * @name input[date]
21675      *
21676      * @description
21677      * Input with date validation and transformation. In browsers that do not yet support
21678      * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
21679      * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
21680      * modern browsers do not yet support this input type, it is important to provide cues to users on the
21681      * expected input format via a placeholder or label.
21682      *
21683      * The model must always be a Date object, otherwise Angular will throw an error.
21684      * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21685      *
21686      * The timezone to be used to read/write the `Date` instance in the model can be defined using
21687      * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21688      *
21689      * @param {string} ngModel Assignable angular expression to data-bind to.
21690      * @param {string=} name Property name of the form under which the control is published.
21691      * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
21692      *   valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
21693      *   (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
21694      *   constraint validation.
21695      * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
21696      *   a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
21697      *   (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
21698      *   constraint validation.
21699      * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
21700      *   the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21701      * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
21702      *   the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21703      * @param {string=} required Sets `required` validation error key if the value is not entered.
21704      * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21705      *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21706      *    `required` when you want to data-bind to the `required` attribute.
21707      * @param {string=} ngChange Angular expression to be executed when input changes due to user
21708      *    interaction with the input element.
21709      *
21710      * @example
21711      <example name="date-input-directive" module="dateInputExample">
21712      <file name="index.html">
21713        <script>
21714           angular.module('dateInputExample', [])
21715             .controller('DateController', ['$scope', function($scope) {
21716               $scope.example = {
21717                 value: new Date(2013, 9, 22)
21718               };
21719             }]);
21720        </script>
21721        <form name="myForm" ng-controller="DateController as dateCtrl">
21722           <label for="exampleInput">Pick a date in 2013:</label>
21723           <input type="date" id="exampleInput" name="input" ng-model="example.value"
21724               placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
21725           <div role="alert">
21726             <span class="error" ng-show="myForm.input.$error.required">
21727                 Required!</span>
21728             <span class="error" ng-show="myForm.input.$error.date">
21729                 Not a valid date!</span>
21730            </div>
21731            <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
21732            <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21733            <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21734            <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21735            <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21736        </form>
21737      </file>
21738      <file name="protractor.js" type="protractor">
21739         var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
21740         var valid = element(by.binding('myForm.input.$valid'));
21741         var input = element(by.model('example.value'));
21742
21743         // currently protractor/webdriver does not support
21744         // sending keys to all known HTML5 input controls
21745         // for various browsers (see https://github.com/angular/protractor/issues/562).
21746         function setInput(val) {
21747           // set the value of the element and force validation.
21748           var scr = "var ipt = document.getElementById('exampleInput'); " +
21749           "ipt.value = '" + val + "';" +
21750           "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21751           browser.executeScript(scr);
21752         }
21753
21754         it('should initialize to model', function() {
21755           expect(value.getText()).toContain('2013-10-22');
21756           expect(valid.getText()).toContain('myForm.input.$valid = true');
21757         });
21758
21759         it('should be invalid if empty', function() {
21760           setInput('');
21761           expect(value.getText()).toEqual('value =');
21762           expect(valid.getText()).toContain('myForm.input.$valid = false');
21763         });
21764
21765         it('should be invalid if over max', function() {
21766           setInput('2015-01-01');
21767           expect(value.getText()).toContain('');
21768           expect(valid.getText()).toContain('myForm.input.$valid = false');
21769         });
21770      </file>
21771      </example>
21772      */
21773   'date': createDateInputType('date', DATE_REGEXP,
21774          createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
21775          'yyyy-MM-dd'),
21776
21777    /**
21778     * @ngdoc input
21779     * @name input[datetime-local]
21780     *
21781     * @description
21782     * Input with datetime validation and transformation. In browsers that do not yet support
21783     * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21784     * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
21785     *
21786     * The model must always be a Date object, otherwise Angular will throw an error.
21787     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21788     *
21789     * The timezone to be used to read/write the `Date` instance in the model can be defined using
21790     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
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=} min Sets the `min` validation error key if the value entered is less than `min`.
21795     *   This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
21796     *   inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
21797     *   Note that `min` will also add native HTML5 constraint validation.
21798     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21799     *   This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
21800     *   inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
21801     *   Note that `max` will also add native HTML5 constraint validation.
21802     * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
21803     *   the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21804     * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
21805     *   the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21806     * @param {string=} required Sets `required` validation error key if the value is not entered.
21807     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21808     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21809     *    `required` when you want to data-bind to the `required` attribute.
21810     * @param {string=} ngChange Angular expression to be executed when input changes due to user
21811     *    interaction with the input element.
21812     *
21813     * @example
21814     <example name="datetimelocal-input-directive" module="dateExample">
21815     <file name="index.html">
21816       <script>
21817         angular.module('dateExample', [])
21818           .controller('DateController', ['$scope', function($scope) {
21819             $scope.example = {
21820               value: new Date(2010, 11, 28, 14, 57)
21821             };
21822           }]);
21823       </script>
21824       <form name="myForm" ng-controller="DateController as dateCtrl">
21825         <label for="exampleInput">Pick a date between in 2013:</label>
21826         <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
21827             placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
21828         <div role="alert">
21829           <span class="error" ng-show="myForm.input.$error.required">
21830               Required!</span>
21831           <span class="error" ng-show="myForm.input.$error.datetimelocal">
21832               Not a valid date!</span>
21833         </div>
21834         <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
21835         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21836         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21837         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21838         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21839       </form>
21840     </file>
21841     <file name="protractor.js" type="protractor">
21842       var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
21843       var valid = element(by.binding('myForm.input.$valid'));
21844       var input = element(by.model('example.value'));
21845
21846       // currently protractor/webdriver does not support
21847       // sending keys to all known HTML5 input controls
21848       // for various browsers (https://github.com/angular/protractor/issues/562).
21849       function setInput(val) {
21850         // set the value of the element and force validation.
21851         var scr = "var ipt = document.getElementById('exampleInput'); " +
21852         "ipt.value = '" + val + "';" +
21853         "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21854         browser.executeScript(scr);
21855       }
21856
21857       it('should initialize to model', function() {
21858         expect(value.getText()).toContain('2010-12-28T14:57:00');
21859         expect(valid.getText()).toContain('myForm.input.$valid = true');
21860       });
21861
21862       it('should be invalid if empty', function() {
21863         setInput('');
21864         expect(value.getText()).toEqual('value =');
21865         expect(valid.getText()).toContain('myForm.input.$valid = false');
21866       });
21867
21868       it('should be invalid if over max', function() {
21869         setInput('2015-01-01T23:59:00');
21870         expect(value.getText()).toContain('');
21871         expect(valid.getText()).toContain('myForm.input.$valid = false');
21872       });
21873     </file>
21874     </example>
21875     */
21876   'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
21877       createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
21878       'yyyy-MM-ddTHH:mm:ss.sss'),
21879
21880   /**
21881    * @ngdoc input
21882    * @name input[time]
21883    *
21884    * @description
21885    * Input with time validation and transformation. In browsers that do not yet support
21886    * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21887    * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
21888    * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
21889    *
21890    * The model must always be a Date object, otherwise Angular will throw an error.
21891    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21892    *
21893    * The timezone to be used to read/write the `Date` instance in the model can be defined using
21894    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21895    *
21896    * @param {string} ngModel Assignable angular expression to data-bind to.
21897    * @param {string=} name Property name of the form under which the control is published.
21898    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21899    *   This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
21900    *   attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
21901    *   native HTML5 constraint validation.
21902    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21903    *   This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
21904    *   attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
21905    *   native HTML5 constraint validation.
21906    * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
21907    *   `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21908    * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
21909    *   `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21910    * @param {string=} required Sets `required` validation error key if the value is not entered.
21911    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21912    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21913    *    `required` when you want to data-bind to the `required` attribute.
21914    * @param {string=} ngChange Angular expression to be executed when input changes due to user
21915    *    interaction with the input element.
21916    *
21917    * @example
21918    <example name="time-input-directive" module="timeExample">
21919    <file name="index.html">
21920      <script>
21921       angular.module('timeExample', [])
21922         .controller('DateController', ['$scope', function($scope) {
21923           $scope.example = {
21924             value: new Date(1970, 0, 1, 14, 57, 0)
21925           };
21926         }]);
21927      </script>
21928      <form name="myForm" ng-controller="DateController as dateCtrl">
21929         <label for="exampleInput">Pick a between 8am and 5pm:</label>
21930         <input type="time" id="exampleInput" name="input" ng-model="example.value"
21931             placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
21932         <div role="alert">
21933           <span class="error" ng-show="myForm.input.$error.required">
21934               Required!</span>
21935           <span class="error" ng-show="myForm.input.$error.time">
21936               Not a valid date!</span>
21937         </div>
21938         <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
21939         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21940         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21941         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21942         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21943      </form>
21944    </file>
21945    <file name="protractor.js" type="protractor">
21946       var value = element(by.binding('example.value | date: "HH:mm:ss"'));
21947       var valid = element(by.binding('myForm.input.$valid'));
21948       var input = element(by.model('example.value'));
21949
21950       // currently protractor/webdriver does not support
21951       // sending keys to all known HTML5 input controls
21952       // for various browsers (https://github.com/angular/protractor/issues/562).
21953       function setInput(val) {
21954         // set the value of the element and force validation.
21955         var scr = "var ipt = document.getElementById('exampleInput'); " +
21956         "ipt.value = '" + val + "';" +
21957         "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21958         browser.executeScript(scr);
21959       }
21960
21961       it('should initialize to model', function() {
21962         expect(value.getText()).toContain('14:57:00');
21963         expect(valid.getText()).toContain('myForm.input.$valid = true');
21964       });
21965
21966       it('should be invalid if empty', function() {
21967         setInput('');
21968         expect(value.getText()).toEqual('value =');
21969         expect(valid.getText()).toContain('myForm.input.$valid = false');
21970       });
21971
21972       it('should be invalid if over max', function() {
21973         setInput('23:59:00');
21974         expect(value.getText()).toContain('');
21975         expect(valid.getText()).toContain('myForm.input.$valid = false');
21976       });
21977    </file>
21978    </example>
21979    */
21980   'time': createDateInputType('time', TIME_REGEXP,
21981       createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
21982      'HH:mm:ss.sss'),
21983
21984    /**
21985     * @ngdoc input
21986     * @name input[week]
21987     *
21988     * @description
21989     * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
21990     * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21991     * week format (yyyy-W##), for example: `2013-W02`.
21992     *
21993     * The model must always be a Date object, otherwise Angular will throw an error.
21994     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21995     *
21996     * The timezone to be used to read/write the `Date` instance in the model can be defined using
21997     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21998     *
21999     * @param {string} ngModel Assignable angular expression to data-bind to.
22000     * @param {string=} name Property name of the form under which the control is published.
22001     * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
22002     *   This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
22003     *   attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
22004     *   native HTML5 constraint validation.
22005     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
22006     *   This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
22007     *   attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
22008     *   native HTML5 constraint validation.
22009     * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
22010     *   the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
22011     * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
22012     *   the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
22013     * @param {string=} required Sets `required` validation error key if the value is not entered.
22014     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22015     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22016     *    `required` when you want to data-bind to the `required` attribute.
22017     * @param {string=} ngChange Angular expression to be executed when input changes due to user
22018     *    interaction with the input element.
22019     *
22020     * @example
22021     <example name="week-input-directive" module="weekExample">
22022     <file name="index.html">
22023       <script>
22024       angular.module('weekExample', [])
22025         .controller('DateController', ['$scope', function($scope) {
22026           $scope.example = {
22027             value: new Date(2013, 0, 3)
22028           };
22029         }]);
22030       </script>
22031       <form name="myForm" ng-controller="DateController as dateCtrl">
22032         <label>Pick a date between in 2013:
22033           <input id="exampleInput" type="week" name="input" ng-model="example.value"
22034                  placeholder="YYYY-W##" min="2012-W32"
22035                  max="2013-W52" required />
22036         </label>
22037         <div role="alert">
22038           <span class="error" ng-show="myForm.input.$error.required">
22039               Required!</span>
22040           <span class="error" ng-show="myForm.input.$error.week">
22041               Not a valid date!</span>
22042         </div>
22043         <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
22044         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22045         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22046         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22047         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22048       </form>
22049     </file>
22050     <file name="protractor.js" type="protractor">
22051       var value = element(by.binding('example.value | date: "yyyy-Www"'));
22052       var valid = element(by.binding('myForm.input.$valid'));
22053       var input = element(by.model('example.value'));
22054
22055       // currently protractor/webdriver does not support
22056       // sending keys to all known HTML5 input controls
22057       // for various browsers (https://github.com/angular/protractor/issues/562).
22058       function setInput(val) {
22059         // set the value of the element and force validation.
22060         var scr = "var ipt = document.getElementById('exampleInput'); " +
22061         "ipt.value = '" + val + "';" +
22062         "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
22063         browser.executeScript(scr);
22064       }
22065
22066       it('should initialize to model', function() {
22067         expect(value.getText()).toContain('2013-W01');
22068         expect(valid.getText()).toContain('myForm.input.$valid = true');
22069       });
22070
22071       it('should be invalid if empty', function() {
22072         setInput('');
22073         expect(value.getText()).toEqual('value =');
22074         expect(valid.getText()).toContain('myForm.input.$valid = false');
22075       });
22076
22077       it('should be invalid if over max', function() {
22078         setInput('2015-W01');
22079         expect(value.getText()).toContain('');
22080         expect(valid.getText()).toContain('myForm.input.$valid = false');
22081       });
22082     </file>
22083     </example>
22084     */
22085   'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
22086
22087   /**
22088    * @ngdoc input
22089    * @name input[month]
22090    *
22091    * @description
22092    * Input with month validation and transformation. In browsers that do not yet support
22093    * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
22094    * month format (yyyy-MM), for example: `2009-01`.
22095    *
22096    * The model must always be a Date object, otherwise Angular will throw an error.
22097    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
22098    * If the model is not set to the first of the month, the next view to model update will set it
22099    * to the first of the month.
22100    *
22101    * The timezone to be used to read/write the `Date` instance in the model can be defined using
22102    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
22103    *
22104    * @param {string} ngModel Assignable angular expression to data-bind to.
22105    * @param {string=} name Property name of the form under which the control is published.
22106    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
22107    *   This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
22108    *   attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
22109    *   native HTML5 constraint validation.
22110    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
22111    *   This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
22112    *   attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
22113    *   native HTML5 constraint validation.
22114    * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
22115    *   the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
22116    * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
22117    *   the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
22118
22119    * @param {string=} required Sets `required` validation error key if the value is not entered.
22120    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22121    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22122    *    `required` when you want to data-bind to the `required` attribute.
22123    * @param {string=} ngChange Angular expression to be executed when input changes due to user
22124    *    interaction with the input element.
22125    *
22126    * @example
22127    <example name="month-input-directive" module="monthExample">
22128    <file name="index.html">
22129      <script>
22130       angular.module('monthExample', [])
22131         .controller('DateController', ['$scope', function($scope) {
22132           $scope.example = {
22133             value: new Date(2013, 9, 1)
22134           };
22135         }]);
22136      </script>
22137      <form name="myForm" ng-controller="DateController as dateCtrl">
22138        <label for="exampleInput">Pick a month in 2013:</label>
22139        <input id="exampleInput" type="month" name="input" ng-model="example.value"
22140           placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
22141        <div role="alert">
22142          <span class="error" ng-show="myForm.input.$error.required">
22143             Required!</span>
22144          <span class="error" ng-show="myForm.input.$error.month">
22145             Not a valid month!</span>
22146        </div>
22147        <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
22148        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22149        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22150        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22151        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22152      </form>
22153    </file>
22154    <file name="protractor.js" type="protractor">
22155       var value = element(by.binding('example.value | date: "yyyy-MM"'));
22156       var valid = element(by.binding('myForm.input.$valid'));
22157       var input = element(by.model('example.value'));
22158
22159       // currently protractor/webdriver does not support
22160       // sending keys to all known HTML5 input controls
22161       // for various browsers (https://github.com/angular/protractor/issues/562).
22162       function setInput(val) {
22163         // set the value of the element and force validation.
22164         var scr = "var ipt = document.getElementById('exampleInput'); " +
22165         "ipt.value = '" + val + "';" +
22166         "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
22167         browser.executeScript(scr);
22168       }
22169
22170       it('should initialize to model', function() {
22171         expect(value.getText()).toContain('2013-10');
22172         expect(valid.getText()).toContain('myForm.input.$valid = true');
22173       });
22174
22175       it('should be invalid if empty', function() {
22176         setInput('');
22177         expect(value.getText()).toEqual('value =');
22178         expect(valid.getText()).toContain('myForm.input.$valid = false');
22179       });
22180
22181       it('should be invalid if over max', function() {
22182         setInput('2015-01');
22183         expect(value.getText()).toContain('');
22184         expect(valid.getText()).toContain('myForm.input.$valid = false');
22185       });
22186    </file>
22187    </example>
22188    */
22189   'month': createDateInputType('month', MONTH_REGEXP,
22190      createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
22191      'yyyy-MM'),
22192
22193   /**
22194    * @ngdoc input
22195    * @name input[number]
22196    *
22197    * @description
22198    * Text input with number validation and transformation. Sets the `number` validation
22199    * error if not a valid number.
22200    *
22201    * <div class="alert alert-warning">
22202    * The model must always be of type `number` otherwise Angular will throw an error.
22203    * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
22204    * error docs for more information and an example of how to convert your model if necessary.
22205    * </div>
22206    *
22207    * ## Issues with HTML5 constraint validation
22208    *
22209    * In browsers that follow the
22210    * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
22211    * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
22212    * If a non-number is entered in the input, the browser will report the value as an empty string,
22213    * which means the view / model values in `ngModel` and subsequently the scope value
22214    * will also be an empty string.
22215    *
22216    *
22217    * @param {string} ngModel Assignable angular expression to data-bind to.
22218    * @param {string=} name Property name of the form under which the control is published.
22219    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
22220    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
22221    * @param {string=} required Sets `required` validation error key if the value is not entered.
22222    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22223    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22224    *    `required` when you want to data-bind to the `required` attribute.
22225    * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22226    *    minlength.
22227    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22228    *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
22229    *    any length.
22230    * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
22231    *    that contains the regular expression body that will be converted to a regular expression
22232    *    as in the ngPattern directive.
22233    * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
22234    *    does not match a RegExp found by evaluating the Angular expression given in the attribute value.
22235    *    If the expression evaluates to a RegExp object, then this is used directly.
22236    *    If the expression evaluates to a string, then it will be converted to a RegExp
22237    *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22238    *    `new RegExp('^abc$')`.<br />
22239    *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22240    *    start at the index of the last search's match, thus not taking the whole input value into
22241    *    account.
22242    * @param {string=} ngChange Angular expression to be executed when input changes due to user
22243    *    interaction with the input element.
22244    *
22245    * @example
22246       <example name="number-input-directive" module="numberExample">
22247         <file name="index.html">
22248          <script>
22249            angular.module('numberExample', [])
22250              .controller('ExampleController', ['$scope', function($scope) {
22251                $scope.example = {
22252                  value: 12
22253                };
22254              }]);
22255          </script>
22256          <form name="myForm" ng-controller="ExampleController">
22257            <label>Number:
22258              <input type="number" name="input" ng-model="example.value"
22259                     min="0" max="99" required>
22260           </label>
22261            <div role="alert">
22262              <span class="error" ng-show="myForm.input.$error.required">
22263                Required!</span>
22264              <span class="error" ng-show="myForm.input.$error.number">
22265                Not valid number!</span>
22266            </div>
22267            <tt>value = {{example.value}}</tt><br/>
22268            <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22269            <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22270            <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22271            <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22272           </form>
22273         </file>
22274         <file name="protractor.js" type="protractor">
22275           var value = element(by.binding('example.value'));
22276           var valid = element(by.binding('myForm.input.$valid'));
22277           var input = element(by.model('example.value'));
22278
22279           it('should initialize to model', function() {
22280             expect(value.getText()).toContain('12');
22281             expect(valid.getText()).toContain('true');
22282           });
22283
22284           it('should be invalid if empty', function() {
22285             input.clear();
22286             input.sendKeys('');
22287             expect(value.getText()).toEqual('value =');
22288             expect(valid.getText()).toContain('false');
22289           });
22290
22291           it('should be invalid if over max', function() {
22292             input.clear();
22293             input.sendKeys('123');
22294             expect(value.getText()).toEqual('value =');
22295             expect(valid.getText()).toContain('false');
22296           });
22297         </file>
22298       </example>
22299    */
22300   'number': numberInputType,
22301
22302
22303   /**
22304    * @ngdoc input
22305    * @name input[url]
22306    *
22307    * @description
22308    * Text input with URL validation. Sets the `url` validation error key if the content is not a
22309    * valid URL.
22310    *
22311    * <div class="alert alert-warning">
22312    * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
22313    * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
22314    * the built-in validators (see the {@link guide/forms Forms guide})
22315    * </div>
22316    *
22317    * @param {string} ngModel Assignable angular expression to data-bind to.
22318    * @param {string=} name Property name of the form under which the control is published.
22319    * @param {string=} required Sets `required` validation error key if the value is not entered.
22320    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22321    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22322    *    `required` when you want to data-bind to the `required` attribute.
22323    * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22324    *    minlength.
22325    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22326    *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
22327    *    any length.
22328    * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
22329    *    that contains the regular expression body that will be converted to a regular expression
22330    *    as in the ngPattern directive.
22331    * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
22332    *    does not match a RegExp found by evaluating the Angular expression given in the attribute value.
22333    *    If the expression evaluates to a RegExp object, then this is used directly.
22334    *    If the expression evaluates to a string, then it will be converted to a RegExp
22335    *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22336    *    `new RegExp('^abc$')`.<br />
22337    *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22338    *    start at the index of the last search's match, thus not taking the whole input value into
22339    *    account.
22340    * @param {string=} ngChange Angular expression to be executed when input changes due to user
22341    *    interaction with the input element.
22342    *
22343    * @example
22344       <example name="url-input-directive" module="urlExample">
22345         <file name="index.html">
22346          <script>
22347            angular.module('urlExample', [])
22348              .controller('ExampleController', ['$scope', function($scope) {
22349                $scope.url = {
22350                  text: 'http://google.com'
22351                };
22352              }]);
22353          </script>
22354          <form name="myForm" ng-controller="ExampleController">
22355            <label>URL:
22356              <input type="url" name="input" ng-model="url.text" required>
22357            <label>
22358            <div role="alert">
22359              <span class="error" ng-show="myForm.input.$error.required">
22360                Required!</span>
22361              <span class="error" ng-show="myForm.input.$error.url">
22362                Not valid url!</span>
22363            </div>
22364            <tt>text = {{url.text}}</tt><br/>
22365            <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22366            <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22367            <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22368            <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22369            <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
22370           </form>
22371         </file>
22372         <file name="protractor.js" type="protractor">
22373           var text = element(by.binding('url.text'));
22374           var valid = element(by.binding('myForm.input.$valid'));
22375           var input = element(by.model('url.text'));
22376
22377           it('should initialize to model', function() {
22378             expect(text.getText()).toContain('http://google.com');
22379             expect(valid.getText()).toContain('true');
22380           });
22381
22382           it('should be invalid if empty', function() {
22383             input.clear();
22384             input.sendKeys('');
22385
22386             expect(text.getText()).toEqual('text =');
22387             expect(valid.getText()).toContain('false');
22388           });
22389
22390           it('should be invalid if not url', function() {
22391             input.clear();
22392             input.sendKeys('box');
22393
22394             expect(valid.getText()).toContain('false');
22395           });
22396         </file>
22397       </example>
22398    */
22399   'url': urlInputType,
22400
22401
22402   /**
22403    * @ngdoc input
22404    * @name input[email]
22405    *
22406    * @description
22407    * Text input with email validation. Sets the `email` validation error key if not a valid email
22408    * address.
22409    *
22410    * <div class="alert alert-warning">
22411    * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
22412    * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
22413    * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
22414    * </div>
22415    *
22416    * @param {string} ngModel Assignable angular expression to data-bind to.
22417    * @param {string=} name Property name of the form under which the control is published.
22418    * @param {string=} required Sets `required` validation error key if the value is not entered.
22419    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22420    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22421    *    `required` when you want to data-bind to the `required` attribute.
22422    * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22423    *    minlength.
22424    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22425    *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
22426    *    any length.
22427    * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
22428    *    that contains the regular expression body that will be converted to a regular expression
22429    *    as in the ngPattern directive.
22430    * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
22431    *    does not match a RegExp found by evaluating the Angular expression given in the attribute value.
22432    *    If the expression evaluates to a RegExp object, then this is used directly.
22433    *    If the expression evaluates to a string, then it will be converted to a RegExp
22434    *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22435    *    `new RegExp('^abc$')`.<br />
22436    *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22437    *    start at the index of the last search's match, thus not taking the whole input value into
22438    *    account.
22439    * @param {string=} ngChange Angular expression to be executed when input changes due to user
22440    *    interaction with the input element.
22441    *
22442    * @example
22443       <example name="email-input-directive" module="emailExample">
22444         <file name="index.html">
22445          <script>
22446            angular.module('emailExample', [])
22447              .controller('ExampleController', ['$scope', function($scope) {
22448                $scope.email = {
22449                  text: 'me@example.com'
22450                };
22451              }]);
22452          </script>
22453            <form name="myForm" ng-controller="ExampleController">
22454              <label>Email:
22455                <input type="email" name="input" ng-model="email.text" required>
22456              </label>
22457              <div role="alert">
22458                <span class="error" ng-show="myForm.input.$error.required">
22459                  Required!</span>
22460                <span class="error" ng-show="myForm.input.$error.email">
22461                  Not valid email!</span>
22462              </div>
22463              <tt>text = {{email.text}}</tt><br/>
22464              <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22465              <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22466              <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22467              <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22468              <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
22469            </form>
22470          </file>
22471         <file name="protractor.js" type="protractor">
22472           var text = element(by.binding('email.text'));
22473           var valid = element(by.binding('myForm.input.$valid'));
22474           var input = element(by.model('email.text'));
22475
22476           it('should initialize to model', function() {
22477             expect(text.getText()).toContain('me@example.com');
22478             expect(valid.getText()).toContain('true');
22479           });
22480
22481           it('should be invalid if empty', function() {
22482             input.clear();
22483             input.sendKeys('');
22484             expect(text.getText()).toEqual('text =');
22485             expect(valid.getText()).toContain('false');
22486           });
22487
22488           it('should be invalid if not email', function() {
22489             input.clear();
22490             input.sendKeys('xxx');
22491
22492             expect(valid.getText()).toContain('false');
22493           });
22494         </file>
22495       </example>
22496    */
22497   'email': emailInputType,
22498
22499
22500   /**
22501    * @ngdoc input
22502    * @name input[radio]
22503    *
22504    * @description
22505    * HTML radio button.
22506    *
22507    * @param {string} ngModel Assignable angular expression to data-bind to.
22508    * @param {string} value The value to which the `ngModel` expression should be set when selected.
22509    *    Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
22510    *    too. Use `ngValue` if you need complex models (`number`, `object`, ...).
22511    * @param {string=} name Property name of the form under which the control is published.
22512    * @param {string=} ngChange Angular expression to be executed when input changes due to user
22513    *    interaction with the input element.
22514    * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
22515    *    is selected. Should be used instead of the `value` attribute if you need
22516    *    a non-string `ngModel` (`boolean`, `array`, ...).
22517    *
22518    * @example
22519       <example name="radio-input-directive" module="radioExample">
22520         <file name="index.html">
22521          <script>
22522            angular.module('radioExample', [])
22523              .controller('ExampleController', ['$scope', function($scope) {
22524                $scope.color = {
22525                  name: 'blue'
22526                };
22527                $scope.specialValue = {
22528                  "id": "12345",
22529                  "value": "green"
22530                };
22531              }]);
22532          </script>
22533          <form name="myForm" ng-controller="ExampleController">
22534            <label>
22535              <input type="radio" ng-model="color.name" value="red">
22536              Red
22537            </label><br/>
22538            <label>
22539              <input type="radio" ng-model="color.name" ng-value="specialValue">
22540              Green
22541            </label><br/>
22542            <label>
22543              <input type="radio" ng-model="color.name" value="blue">
22544              Blue
22545            </label><br/>
22546            <tt>color = {{color.name | json}}</tt><br/>
22547           </form>
22548           Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
22549         </file>
22550         <file name="protractor.js" type="protractor">
22551           it('should change state', function() {
22552             var color = element(by.binding('color.name'));
22553
22554             expect(color.getText()).toContain('blue');
22555
22556             element.all(by.model('color.name')).get(0).click();
22557
22558             expect(color.getText()).toContain('red');
22559           });
22560         </file>
22561       </example>
22562    */
22563   'radio': radioInputType,
22564
22565
22566   /**
22567    * @ngdoc input
22568    * @name input[checkbox]
22569    *
22570    * @description
22571    * HTML checkbox.
22572    *
22573    * @param {string} ngModel Assignable angular expression to data-bind to.
22574    * @param {string=} name Property name of the form under which the control is published.
22575    * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
22576    * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
22577    * @param {string=} ngChange Angular expression to be executed when input changes due to user
22578    *    interaction with the input element.
22579    *
22580    * @example
22581       <example name="checkbox-input-directive" module="checkboxExample">
22582         <file name="index.html">
22583          <script>
22584            angular.module('checkboxExample', [])
22585              .controller('ExampleController', ['$scope', function($scope) {
22586                $scope.checkboxModel = {
22587                 value1 : true,
22588                 value2 : 'YES'
22589               };
22590              }]);
22591          </script>
22592          <form name="myForm" ng-controller="ExampleController">
22593            <label>Value1:
22594              <input type="checkbox" ng-model="checkboxModel.value1">
22595            </label><br/>
22596            <label>Value2:
22597              <input type="checkbox" ng-model="checkboxModel.value2"
22598                     ng-true-value="'YES'" ng-false-value="'NO'">
22599             </label><br/>
22600            <tt>value1 = {{checkboxModel.value1}}</tt><br/>
22601            <tt>value2 = {{checkboxModel.value2}}</tt><br/>
22602           </form>
22603         </file>
22604         <file name="protractor.js" type="protractor">
22605           it('should change state', function() {
22606             var value1 = element(by.binding('checkboxModel.value1'));
22607             var value2 = element(by.binding('checkboxModel.value2'));
22608
22609             expect(value1.getText()).toContain('true');
22610             expect(value2.getText()).toContain('YES');
22611
22612             element(by.model('checkboxModel.value1')).click();
22613             element(by.model('checkboxModel.value2')).click();
22614
22615             expect(value1.getText()).toContain('false');
22616             expect(value2.getText()).toContain('NO');
22617           });
22618         </file>
22619       </example>
22620    */
22621   'checkbox': checkboxInputType,
22622
22623   'hidden': noop,
22624   'button': noop,
22625   'submit': noop,
22626   'reset': noop,
22627   'file': noop
22628 };
22629
22630 function stringBasedInputType(ctrl) {
22631   ctrl.$formatters.push(function(value) {
22632     return ctrl.$isEmpty(value) ? value : value.toString();
22633   });
22634 }
22635
22636 function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22637   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22638   stringBasedInputType(ctrl);
22639 }
22640
22641 function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22642   var type = lowercase(element[0].type);
22643
22644   // In composition mode, users are still inputing intermediate text buffer,
22645   // hold the listener until composition is done.
22646   // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
22647   if (!$sniffer.android) {
22648     var composing = false;
22649
22650     element.on('compositionstart', function(data) {
22651       composing = true;
22652     });
22653
22654     element.on('compositionend', function() {
22655       composing = false;
22656       listener();
22657     });
22658   }
22659
22660   var listener = function(ev) {
22661     if (timeout) {
22662       $browser.defer.cancel(timeout);
22663       timeout = null;
22664     }
22665     if (composing) return;
22666     var value = element.val(),
22667         event = ev && ev.type;
22668
22669     // By default we will trim the value
22670     // If the attribute ng-trim exists we will avoid trimming
22671     // If input type is 'password', the value is never trimmed
22672     if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
22673       value = trim(value);
22674     }
22675
22676     // If a control is suffering from bad input (due to native validators), browsers discard its
22677     // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
22678     // control's value is the same empty value twice in a row.
22679     if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
22680       ctrl.$setViewValue(value, event);
22681     }
22682   };
22683
22684   // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
22685   // input event on backspace, delete or cut
22686   if ($sniffer.hasEvent('input')) {
22687     element.on('input', listener);
22688   } else {
22689     var timeout;
22690
22691     var deferListener = function(ev, input, origValue) {
22692       if (!timeout) {
22693         timeout = $browser.defer(function() {
22694           timeout = null;
22695           if (!input || input.value !== origValue) {
22696             listener(ev);
22697           }
22698         });
22699       }
22700     };
22701
22702     element.on('keydown', function(event) {
22703       var key = event.keyCode;
22704
22705       // ignore
22706       //    command            modifiers                   arrows
22707       if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
22708
22709       deferListener(event, this, this.value);
22710     });
22711
22712     // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
22713     if ($sniffer.hasEvent('paste')) {
22714       element.on('paste cut', deferListener);
22715     }
22716   }
22717
22718   // if user paste into input using mouse on older browser
22719   // or form autocomplete on newer browser, we need "change" event to catch it
22720   element.on('change', listener);
22721
22722   ctrl.$render = function() {
22723     // Workaround for Firefox validation #12102.
22724     var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
22725     if (element.val() !== value) {
22726       element.val(value);
22727     }
22728   };
22729 }
22730
22731 function weekParser(isoWeek, existingDate) {
22732   if (isDate(isoWeek)) {
22733     return isoWeek;
22734   }
22735
22736   if (isString(isoWeek)) {
22737     WEEK_REGEXP.lastIndex = 0;
22738     var parts = WEEK_REGEXP.exec(isoWeek);
22739     if (parts) {
22740       var year = +parts[1],
22741           week = +parts[2],
22742           hours = 0,
22743           minutes = 0,
22744           seconds = 0,
22745           milliseconds = 0,
22746           firstThurs = getFirstThursdayOfYear(year),
22747           addDays = (week - 1) * 7;
22748
22749       if (existingDate) {
22750         hours = existingDate.getHours();
22751         minutes = existingDate.getMinutes();
22752         seconds = existingDate.getSeconds();
22753         milliseconds = existingDate.getMilliseconds();
22754       }
22755
22756       return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
22757     }
22758   }
22759
22760   return NaN;
22761 }
22762
22763 function createDateParser(regexp, mapping) {
22764   return function(iso, date) {
22765     var parts, map;
22766
22767     if (isDate(iso)) {
22768       return iso;
22769     }
22770
22771     if (isString(iso)) {
22772       // When a date is JSON'ified to wraps itself inside of an extra
22773       // set of double quotes. This makes the date parsing code unable
22774       // to match the date string and parse it as a date.
22775       if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
22776         iso = iso.substring(1, iso.length - 1);
22777       }
22778       if (ISO_DATE_REGEXP.test(iso)) {
22779         return new Date(iso);
22780       }
22781       regexp.lastIndex = 0;
22782       parts = regexp.exec(iso);
22783
22784       if (parts) {
22785         parts.shift();
22786         if (date) {
22787           map = {
22788             yyyy: date.getFullYear(),
22789             MM: date.getMonth() + 1,
22790             dd: date.getDate(),
22791             HH: date.getHours(),
22792             mm: date.getMinutes(),
22793             ss: date.getSeconds(),
22794             sss: date.getMilliseconds() / 1000
22795           };
22796         } else {
22797           map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
22798         }
22799
22800         forEach(parts, function(part, index) {
22801           if (index < mapping.length) {
22802             map[mapping[index]] = +part;
22803           }
22804         });
22805         return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
22806       }
22807     }
22808
22809     return NaN;
22810   };
22811 }
22812
22813 function createDateInputType(type, regexp, parseDate, format) {
22814   return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
22815     badInputChecker(scope, element, attr, ctrl);
22816     baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22817     var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
22818     var previousDate;
22819
22820     ctrl.$$parserName = type;
22821     ctrl.$parsers.push(function(value) {
22822       if (ctrl.$isEmpty(value)) return null;
22823       if (regexp.test(value)) {
22824         // Note: We cannot read ctrl.$modelValue, as there might be a different
22825         // parser/formatter in the processing chain so that the model
22826         // contains some different data format!
22827         var parsedDate = parseDate(value, previousDate);
22828         if (timezone) {
22829           parsedDate = convertTimezoneToLocal(parsedDate, timezone);
22830         }
22831         return parsedDate;
22832       }
22833       return undefined;
22834     });
22835
22836     ctrl.$formatters.push(function(value) {
22837       if (value && !isDate(value)) {
22838         throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
22839       }
22840       if (isValidDate(value)) {
22841         previousDate = value;
22842         if (previousDate && timezone) {
22843           previousDate = convertTimezoneToLocal(previousDate, timezone, true);
22844         }
22845         return $filter('date')(value, format, timezone);
22846       } else {
22847         previousDate = null;
22848         return '';
22849       }
22850     });
22851
22852     if (isDefined(attr.min) || attr.ngMin) {
22853       var minVal;
22854       ctrl.$validators.min = function(value) {
22855         return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
22856       };
22857       attr.$observe('min', function(val) {
22858         minVal = parseObservedDateValue(val);
22859         ctrl.$validate();
22860       });
22861     }
22862
22863     if (isDefined(attr.max) || attr.ngMax) {
22864       var maxVal;
22865       ctrl.$validators.max = function(value) {
22866         return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
22867       };
22868       attr.$observe('max', function(val) {
22869         maxVal = parseObservedDateValue(val);
22870         ctrl.$validate();
22871       });
22872     }
22873
22874     function isValidDate(value) {
22875       // Invalid Date: getTime() returns NaN
22876       return value && !(value.getTime && value.getTime() !== value.getTime());
22877     }
22878
22879     function parseObservedDateValue(val) {
22880       return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
22881     }
22882   };
22883 }
22884
22885 function badInputChecker(scope, element, attr, ctrl) {
22886   var node = element[0];
22887   var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
22888   if (nativeValidation) {
22889     ctrl.$parsers.push(function(value) {
22890       var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
22891       return validity.badInput || validity.typeMismatch ? undefined : value;
22892     });
22893   }
22894 }
22895
22896 function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22897   badInputChecker(scope, element, attr, ctrl);
22898   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22899
22900   ctrl.$$parserName = 'number';
22901   ctrl.$parsers.push(function(value) {
22902     if (ctrl.$isEmpty(value))      return null;
22903     if (NUMBER_REGEXP.test(value)) return parseFloat(value);
22904     return undefined;
22905   });
22906
22907   ctrl.$formatters.push(function(value) {
22908     if (!ctrl.$isEmpty(value)) {
22909       if (!isNumber(value)) {
22910         throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
22911       }
22912       value = value.toString();
22913     }
22914     return value;
22915   });
22916
22917   if (isDefined(attr.min) || attr.ngMin) {
22918     var minVal;
22919     ctrl.$validators.min = function(value) {
22920       return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
22921     };
22922
22923     attr.$observe('min', function(val) {
22924       if (isDefined(val) && !isNumber(val)) {
22925         val = parseFloat(val, 10);
22926       }
22927       minVal = isNumber(val) && !isNaN(val) ? val : undefined;
22928       // TODO(matsko): implement validateLater to reduce number of validations
22929       ctrl.$validate();
22930     });
22931   }
22932
22933   if (isDefined(attr.max) || attr.ngMax) {
22934     var maxVal;
22935     ctrl.$validators.max = function(value) {
22936       return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
22937     };
22938
22939     attr.$observe('max', function(val) {
22940       if (isDefined(val) && !isNumber(val)) {
22941         val = parseFloat(val, 10);
22942       }
22943       maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
22944       // TODO(matsko): implement validateLater to reduce number of validations
22945       ctrl.$validate();
22946     });
22947   }
22948 }
22949
22950 function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22951   // Note: no badInputChecker here by purpose as `url` is only a validation
22952   // in browsers, i.e. we can always read out input.value even if it is not valid!
22953   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22954   stringBasedInputType(ctrl);
22955
22956   ctrl.$$parserName = 'url';
22957   ctrl.$validators.url = function(modelValue, viewValue) {
22958     var value = modelValue || viewValue;
22959     return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
22960   };
22961 }
22962
22963 function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22964   // Note: no badInputChecker here by purpose as `url` is only a validation
22965   // in browsers, i.e. we can always read out input.value even if it is not valid!
22966   baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22967   stringBasedInputType(ctrl);
22968
22969   ctrl.$$parserName = 'email';
22970   ctrl.$validators.email = function(modelValue, viewValue) {
22971     var value = modelValue || viewValue;
22972     return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
22973   };
22974 }
22975
22976 function radioInputType(scope, element, attr, ctrl) {
22977   // make the name unique, if not defined
22978   if (isUndefined(attr.name)) {
22979     element.attr('name', nextUid());
22980   }
22981
22982   var listener = function(ev) {
22983     if (element[0].checked) {
22984       ctrl.$setViewValue(attr.value, ev && ev.type);
22985     }
22986   };
22987
22988   element.on('click', listener);
22989
22990   ctrl.$render = function() {
22991     var value = attr.value;
22992     element[0].checked = (value == ctrl.$viewValue);
22993   };
22994
22995   attr.$observe('value', ctrl.$render);
22996 }
22997
22998 function parseConstantExpr($parse, context, name, expression, fallback) {
22999   var parseFn;
23000   if (isDefined(expression)) {
23001     parseFn = $parse(expression);
23002     if (!parseFn.constant) {
23003       throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
23004                                    '`{1}`.', name, expression);
23005     }
23006     return parseFn(context);
23007   }
23008   return fallback;
23009 }
23010
23011 function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
23012   var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
23013   var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
23014
23015   var listener = function(ev) {
23016     ctrl.$setViewValue(element[0].checked, ev && ev.type);
23017   };
23018
23019   element.on('click', listener);
23020
23021   ctrl.$render = function() {
23022     element[0].checked = ctrl.$viewValue;
23023   };
23024
23025   // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
23026   // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
23027   // it to a boolean.
23028   ctrl.$isEmpty = function(value) {
23029     return value === false;
23030   };
23031
23032   ctrl.$formatters.push(function(value) {
23033     return equals(value, trueValue);
23034   });
23035
23036   ctrl.$parsers.push(function(value) {
23037     return value ? trueValue : falseValue;
23038   });
23039 }
23040
23041
23042 /**
23043  * @ngdoc directive
23044  * @name textarea
23045  * @restrict E
23046  *
23047  * @description
23048  * HTML textarea element control with angular data-binding. The data-binding and validation
23049  * properties of this element are exactly the same as those of the
23050  * {@link ng.directive:input input element}.
23051  *
23052  * @param {string} ngModel Assignable angular expression to data-bind to.
23053  * @param {string=} name Property name of the form under which the control is published.
23054  * @param {string=} required Sets `required` validation error key if the value is not entered.
23055  * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23056  *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23057  *    `required` when you want to data-bind to the `required` attribute.
23058  * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
23059  *    minlength.
23060  * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
23061  *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
23062  *    length.
23063  * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
23064  *    does not match a RegExp found by evaluating the Angular expression given in the attribute value.
23065  *    If the expression evaluates to a RegExp object, then this is used directly.
23066  *    If the expression evaluates to a string, then it will be converted to a RegExp
23067  *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
23068  *    `new RegExp('^abc$')`.<br />
23069  *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
23070  *    start at the index of the last search's match, thus not taking the whole input value into
23071  *    account.
23072  * @param {string=} ngChange Angular expression to be executed when input changes due to user
23073  *    interaction with the input element.
23074  * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
23075  */
23076
23077
23078 /**
23079  * @ngdoc directive
23080  * @name input
23081  * @restrict E
23082  *
23083  * @description
23084  * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
23085  * input state control, and validation.
23086  * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
23087  *
23088  * <div class="alert alert-warning">
23089  * **Note:** Not every feature offered is available for all input types.
23090  * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
23091  * </div>
23092  *
23093  * @param {string} ngModel Assignable angular expression to data-bind to.
23094  * @param {string=} name Property name of the form under which the control is published.
23095  * @param {string=} required Sets `required` validation error key if the value is not entered.
23096  * @param {boolean=} ngRequired Sets `required` attribute if set to true
23097  * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
23098  *    minlength.
23099  * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
23100  *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
23101  *    length.
23102  * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
23103  *    value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
23104  *    If the expression evaluates to a RegExp object, then this is used directly.
23105  *    If the expression evaluates to a string, then it will be converted to a RegExp
23106  *    after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
23107  *    `new RegExp('^abc$')`.<br />
23108  *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
23109  *    start at the index of the last search's match, thus not taking the whole input value into
23110  *    account.
23111  * @param {string=} ngChange Angular expression to be executed when input changes due to user
23112  *    interaction with the input element.
23113  * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
23114  *    This parameter is ignored for input[type=password] controls, which will never trim the
23115  *    input.
23116  *
23117  * @example
23118     <example name="input-directive" module="inputExample">
23119       <file name="index.html">
23120        <script>
23121           angular.module('inputExample', [])
23122             .controller('ExampleController', ['$scope', function($scope) {
23123               $scope.user = {name: 'guest', last: 'visitor'};
23124             }]);
23125        </script>
23126        <div ng-controller="ExampleController">
23127          <form name="myForm">
23128            <label>
23129               User name:
23130               <input type="text" name="userName" ng-model="user.name" required>
23131            </label>
23132            <div role="alert">
23133              <span class="error" ng-show="myForm.userName.$error.required">
23134               Required!</span>
23135            </div>
23136            <label>
23137               Last name:
23138               <input type="text" name="lastName" ng-model="user.last"
23139               ng-minlength="3" ng-maxlength="10">
23140            </label>
23141            <div role="alert">
23142              <span class="error" ng-show="myForm.lastName.$error.minlength">
23143                Too short!</span>
23144              <span class="error" ng-show="myForm.lastName.$error.maxlength">
23145                Too long!</span>
23146            </div>
23147          </form>
23148          <hr>
23149          <tt>user = {{user}}</tt><br/>
23150          <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
23151          <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
23152          <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
23153          <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
23154          <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
23155          <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
23156          <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
23157          <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
23158        </div>
23159       </file>
23160       <file name="protractor.js" type="protractor">
23161         var user = element(by.exactBinding('user'));
23162         var userNameValid = element(by.binding('myForm.userName.$valid'));
23163         var lastNameValid = element(by.binding('myForm.lastName.$valid'));
23164         var lastNameError = element(by.binding('myForm.lastName.$error'));
23165         var formValid = element(by.binding('myForm.$valid'));
23166         var userNameInput = element(by.model('user.name'));
23167         var userLastInput = element(by.model('user.last'));
23168
23169         it('should initialize to model', function() {
23170           expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
23171           expect(userNameValid.getText()).toContain('true');
23172           expect(formValid.getText()).toContain('true');
23173         });
23174
23175         it('should be invalid if empty when required', function() {
23176           userNameInput.clear();
23177           userNameInput.sendKeys('');
23178
23179           expect(user.getText()).toContain('{"last":"visitor"}');
23180           expect(userNameValid.getText()).toContain('false');
23181           expect(formValid.getText()).toContain('false');
23182         });
23183
23184         it('should be valid if empty when min length is set', function() {
23185           userLastInput.clear();
23186           userLastInput.sendKeys('');
23187
23188           expect(user.getText()).toContain('{"name":"guest","last":""}');
23189           expect(lastNameValid.getText()).toContain('true');
23190           expect(formValid.getText()).toContain('true');
23191         });
23192
23193         it('should be invalid if less than required min length', function() {
23194           userLastInput.clear();
23195           userLastInput.sendKeys('xx');
23196
23197           expect(user.getText()).toContain('{"name":"guest"}');
23198           expect(lastNameValid.getText()).toContain('false');
23199           expect(lastNameError.getText()).toContain('minlength');
23200           expect(formValid.getText()).toContain('false');
23201         });
23202
23203         it('should be invalid if longer than max length', function() {
23204           userLastInput.clear();
23205           userLastInput.sendKeys('some ridiculously long name');
23206
23207           expect(user.getText()).toContain('{"name":"guest"}');
23208           expect(lastNameValid.getText()).toContain('false');
23209           expect(lastNameError.getText()).toContain('maxlength');
23210           expect(formValid.getText()).toContain('false');
23211         });
23212       </file>
23213     </example>
23214  */
23215 var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
23216     function($browser, $sniffer, $filter, $parse) {
23217   return {
23218     restrict: 'E',
23219     require: ['?ngModel'],
23220     link: {
23221       pre: function(scope, element, attr, ctrls) {
23222         if (ctrls[0]) {
23223           (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
23224                                                               $browser, $filter, $parse);
23225         }
23226       }
23227     }
23228   };
23229 }];
23230
23231
23232
23233 var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
23234 /**
23235  * @ngdoc directive
23236  * @name ngValue
23237  *
23238  * @description
23239  * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
23240  * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
23241  * the bound value.
23242  *
23243  * `ngValue` is useful when dynamically generating lists of radio buttons using
23244  * {@link ngRepeat `ngRepeat`}, as shown below.
23245  *
23246  * Likewise, `ngValue` can be used to generate `<option>` elements for
23247  * the {@link select `select`} element. In that case however, only strings are supported
23248  * for the `value `attribute, so the resulting `ngModel` will always be a string.
23249  * Support for `select` models with non-string values is available via `ngOptions`.
23250  *
23251  * @element input
23252  * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
23253  *   of the `input` element
23254  *
23255  * @example
23256     <example name="ngValue-directive" module="valueExample">
23257       <file name="index.html">
23258        <script>
23259           angular.module('valueExample', [])
23260             .controller('ExampleController', ['$scope', function($scope) {
23261               $scope.names = ['pizza', 'unicorns', 'robots'];
23262               $scope.my = { favorite: 'unicorns' };
23263             }]);
23264        </script>
23265         <form ng-controller="ExampleController">
23266           <h2>Which is your favorite?</h2>
23267             <label ng-repeat="name in names" for="{{name}}">
23268               {{name}}
23269               <input type="radio"
23270                      ng-model="my.favorite"
23271                      ng-value="name"
23272                      id="{{name}}"
23273                      name="favorite">
23274             </label>
23275           <div>You chose {{my.favorite}}</div>
23276         </form>
23277       </file>
23278       <file name="protractor.js" type="protractor">
23279         var favorite = element(by.binding('my.favorite'));
23280
23281         it('should initialize to model', function() {
23282           expect(favorite.getText()).toContain('unicorns');
23283         });
23284         it('should bind the values to the inputs', function() {
23285           element.all(by.model('my.favorite')).get(0).click();
23286           expect(favorite.getText()).toContain('pizza');
23287         });
23288       </file>
23289     </example>
23290  */
23291 var ngValueDirective = function() {
23292   return {
23293     restrict: 'A',
23294     priority: 100,
23295     compile: function(tpl, tplAttr) {
23296       if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
23297         return function ngValueConstantLink(scope, elm, attr) {
23298           attr.$set('value', scope.$eval(attr.ngValue));
23299         };
23300       } else {
23301         return function ngValueLink(scope, elm, attr) {
23302           scope.$watch(attr.ngValue, function valueWatchAction(value) {
23303             attr.$set('value', value);
23304           });
23305         };
23306       }
23307     }
23308   };
23309 };
23310
23311 /**
23312  * @ngdoc directive
23313  * @name ngBind
23314  * @restrict AC
23315  *
23316  * @description
23317  * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
23318  * with the value of a given expression, and to update the text content when the value of that
23319  * expression changes.
23320  *
23321  * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
23322  * `{{ expression }}` which is similar but less verbose.
23323  *
23324  * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
23325  * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
23326  * element attribute, it makes the bindings invisible to the user while the page is loading.
23327  *
23328  * An alternative solution to this problem would be using the
23329  * {@link ng.directive:ngCloak ngCloak} directive.
23330  *
23331  *
23332  * @element ANY
23333  * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
23334  *
23335  * @example
23336  * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
23337    <example module="bindExample">
23338      <file name="index.html">
23339        <script>
23340          angular.module('bindExample', [])
23341            .controller('ExampleController', ['$scope', function($scope) {
23342              $scope.name = 'Whirled';
23343            }]);
23344        </script>
23345        <div ng-controller="ExampleController">
23346          <label>Enter name: <input type="text" ng-model="name"></label><br>
23347          Hello <span ng-bind="name"></span>!
23348        </div>
23349      </file>
23350      <file name="protractor.js" type="protractor">
23351        it('should check ng-bind', function() {
23352          var nameInput = element(by.model('name'));
23353
23354          expect(element(by.binding('name')).getText()).toBe('Whirled');
23355          nameInput.clear();
23356          nameInput.sendKeys('world');
23357          expect(element(by.binding('name')).getText()).toBe('world');
23358        });
23359      </file>
23360    </example>
23361  */
23362 var ngBindDirective = ['$compile', function($compile) {
23363   return {
23364     restrict: 'AC',
23365     compile: function ngBindCompile(templateElement) {
23366       $compile.$$addBindingClass(templateElement);
23367       return function ngBindLink(scope, element, attr) {
23368         $compile.$$addBindingInfo(element, attr.ngBind);
23369         element = element[0];
23370         scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
23371           element.textContent = isUndefined(value) ? '' : value;
23372         });
23373       };
23374     }
23375   };
23376 }];
23377
23378
23379 /**
23380  * @ngdoc directive
23381  * @name ngBindTemplate
23382  *
23383  * @description
23384  * The `ngBindTemplate` directive specifies that the element
23385  * text content should be replaced with the interpolation of the template
23386  * in the `ngBindTemplate` attribute.
23387  * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
23388  * expressions. This directive is needed since some HTML elements
23389  * (such as TITLE and OPTION) cannot contain SPAN elements.
23390  *
23391  * @element ANY
23392  * @param {string} ngBindTemplate template of form
23393  *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
23394  *
23395  * @example
23396  * Try it here: enter text in text box and watch the greeting change.
23397    <example module="bindExample">
23398      <file name="index.html">
23399        <script>
23400          angular.module('bindExample', [])
23401            .controller('ExampleController', ['$scope', function($scope) {
23402              $scope.salutation = 'Hello';
23403              $scope.name = 'World';
23404            }]);
23405        </script>
23406        <div ng-controller="ExampleController">
23407         <label>Salutation: <input type="text" ng-model="salutation"></label><br>
23408         <label>Name: <input type="text" ng-model="name"></label><br>
23409         <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
23410        </div>
23411      </file>
23412      <file name="protractor.js" type="protractor">
23413        it('should check ng-bind', function() {
23414          var salutationElem = element(by.binding('salutation'));
23415          var salutationInput = element(by.model('salutation'));
23416          var nameInput = element(by.model('name'));
23417
23418          expect(salutationElem.getText()).toBe('Hello World!');
23419
23420          salutationInput.clear();
23421          salutationInput.sendKeys('Greetings');
23422          nameInput.clear();
23423          nameInput.sendKeys('user');
23424
23425          expect(salutationElem.getText()).toBe('Greetings user!');
23426        });
23427      </file>
23428    </example>
23429  */
23430 var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
23431   return {
23432     compile: function ngBindTemplateCompile(templateElement) {
23433       $compile.$$addBindingClass(templateElement);
23434       return function ngBindTemplateLink(scope, element, attr) {
23435         var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
23436         $compile.$$addBindingInfo(element, interpolateFn.expressions);
23437         element = element[0];
23438         attr.$observe('ngBindTemplate', function(value) {
23439           element.textContent = isUndefined(value) ? '' : value;
23440         });
23441       };
23442     }
23443   };
23444 }];
23445
23446
23447 /**
23448  * @ngdoc directive
23449  * @name ngBindHtml
23450  *
23451  * @description
23452  * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
23453  * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
23454  * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
23455  * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
23456  * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
23457  *
23458  * You may also bypass sanitization for values you know are safe. To do so, bind to
23459  * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}.  See the example
23460  * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
23461  *
23462  * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
23463  * will have an exception (instead of an exploit.)
23464  *
23465  * @element ANY
23466  * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
23467  *
23468  * @example
23469
23470    <example module="bindHtmlExample" deps="angular-sanitize.js">
23471      <file name="index.html">
23472        <div ng-controller="ExampleController">
23473         <p ng-bind-html="myHTML"></p>
23474        </div>
23475      </file>
23476
23477      <file name="script.js">
23478        angular.module('bindHtmlExample', ['ngSanitize'])
23479          .controller('ExampleController', ['$scope', function($scope) {
23480            $scope.myHTML =
23481               'I am an <code>HTML</code>string with ' +
23482               '<a href="#">links!</a> and other <em>stuff</em>';
23483          }]);
23484      </file>
23485
23486      <file name="protractor.js" type="protractor">
23487        it('should check ng-bind-html', function() {
23488          expect(element(by.binding('myHTML')).getText()).toBe(
23489              'I am an HTMLstring with links! and other stuff');
23490        });
23491      </file>
23492    </example>
23493  */
23494 var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
23495   return {
23496     restrict: 'A',
23497     compile: function ngBindHtmlCompile(tElement, tAttrs) {
23498       var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
23499       var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
23500         return (value || '').toString();
23501       });
23502       $compile.$$addBindingClass(tElement);
23503
23504       return function ngBindHtmlLink(scope, element, attr) {
23505         $compile.$$addBindingInfo(element, attr.ngBindHtml);
23506
23507         scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
23508           // we re-evaluate the expr because we want a TrustedValueHolderType
23509           // for $sce, not a string
23510           element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
23511         });
23512       };
23513     }
23514   };
23515 }];
23516
23517 /**
23518  * @ngdoc directive
23519  * @name ngChange
23520  *
23521  * @description
23522  * Evaluate the given expression when the user changes the input.
23523  * The expression is evaluated immediately, unlike the JavaScript onchange event
23524  * which only triggers at the end of a change (usually, when the user leaves the
23525  * form element or presses the return key).
23526  *
23527  * The `ngChange` expression is only evaluated when a change in the input value causes
23528  * a new value to be committed to the model.
23529  *
23530  * It will not be evaluated:
23531  * * if the value returned from the `$parsers` transformation pipeline has not changed
23532  * * if the input has continued to be invalid since the model will stay `null`
23533  * * if the model is changed programmatically and not by a change to the input value
23534  *
23535  *
23536  * Note, this directive requires `ngModel` to be present.
23537  *
23538  * @element input
23539  * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
23540  * in input value.
23541  *
23542  * @example
23543  * <example name="ngChange-directive" module="changeExample">
23544  *   <file name="index.html">
23545  *     <script>
23546  *       angular.module('changeExample', [])
23547  *         .controller('ExampleController', ['$scope', function($scope) {
23548  *           $scope.counter = 0;
23549  *           $scope.change = function() {
23550  *             $scope.counter++;
23551  *           };
23552  *         }]);
23553  *     </script>
23554  *     <div ng-controller="ExampleController">
23555  *       <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
23556  *       <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
23557  *       <label for="ng-change-example2">Confirmed</label><br />
23558  *       <tt>debug = {{confirmed}}</tt><br/>
23559  *       <tt>counter = {{counter}}</tt><br/>
23560  *     </div>
23561  *   </file>
23562  *   <file name="protractor.js" type="protractor">
23563  *     var counter = element(by.binding('counter'));
23564  *     var debug = element(by.binding('confirmed'));
23565  *
23566  *     it('should evaluate the expression if changing from view', function() {
23567  *       expect(counter.getText()).toContain('0');
23568  *
23569  *       element(by.id('ng-change-example1')).click();
23570  *
23571  *       expect(counter.getText()).toContain('1');
23572  *       expect(debug.getText()).toContain('true');
23573  *     });
23574  *
23575  *     it('should not evaluate the expression if changing from model', function() {
23576  *       element(by.id('ng-change-example2')).click();
23577
23578  *       expect(counter.getText()).toContain('0');
23579  *       expect(debug.getText()).toContain('true');
23580  *     });
23581  *   </file>
23582  * </example>
23583  */
23584 var ngChangeDirective = valueFn({
23585   restrict: 'A',
23586   require: 'ngModel',
23587   link: function(scope, element, attr, ctrl) {
23588     ctrl.$viewChangeListeners.push(function() {
23589       scope.$eval(attr.ngChange);
23590     });
23591   }
23592 });
23593
23594 function classDirective(name, selector) {
23595   name = 'ngClass' + name;
23596   return ['$animate', function($animate) {
23597     return {
23598       restrict: 'AC',
23599       link: function(scope, element, attr) {
23600         var oldVal;
23601
23602         scope.$watch(attr[name], ngClassWatchAction, true);
23603
23604         attr.$observe('class', function(value) {
23605           ngClassWatchAction(scope.$eval(attr[name]));
23606         });
23607
23608
23609         if (name !== 'ngClass') {
23610           scope.$watch('$index', function($index, old$index) {
23611             // jshint bitwise: false
23612             var mod = $index & 1;
23613             if (mod !== (old$index & 1)) {
23614               var classes = arrayClasses(scope.$eval(attr[name]));
23615               mod === selector ?
23616                 addClasses(classes) :
23617                 removeClasses(classes);
23618             }
23619           });
23620         }
23621
23622         function addClasses(classes) {
23623           var newClasses = digestClassCounts(classes, 1);
23624           attr.$addClass(newClasses);
23625         }
23626
23627         function removeClasses(classes) {
23628           var newClasses = digestClassCounts(classes, -1);
23629           attr.$removeClass(newClasses);
23630         }
23631
23632         function digestClassCounts(classes, count) {
23633           // Use createMap() to prevent class assumptions involving property
23634           // names in Object.prototype
23635           var classCounts = element.data('$classCounts') || createMap();
23636           var classesToUpdate = [];
23637           forEach(classes, function(className) {
23638             if (count > 0 || classCounts[className]) {
23639               classCounts[className] = (classCounts[className] || 0) + count;
23640               if (classCounts[className] === +(count > 0)) {
23641                 classesToUpdate.push(className);
23642               }
23643             }
23644           });
23645           element.data('$classCounts', classCounts);
23646           return classesToUpdate.join(' ');
23647         }
23648
23649         function updateClasses(oldClasses, newClasses) {
23650           var toAdd = arrayDifference(newClasses, oldClasses);
23651           var toRemove = arrayDifference(oldClasses, newClasses);
23652           toAdd = digestClassCounts(toAdd, 1);
23653           toRemove = digestClassCounts(toRemove, -1);
23654           if (toAdd && toAdd.length) {
23655             $animate.addClass(element, toAdd);
23656           }
23657           if (toRemove && toRemove.length) {
23658             $animate.removeClass(element, toRemove);
23659           }
23660         }
23661
23662         function ngClassWatchAction(newVal) {
23663           if (selector === true || scope.$index % 2 === selector) {
23664             var newClasses = arrayClasses(newVal || []);
23665             if (!oldVal) {
23666               addClasses(newClasses);
23667             } else if (!equals(newVal,oldVal)) {
23668               var oldClasses = arrayClasses(oldVal);
23669               updateClasses(oldClasses, newClasses);
23670             }
23671           }
23672           oldVal = shallowCopy(newVal);
23673         }
23674       }
23675     };
23676
23677     function arrayDifference(tokens1, tokens2) {
23678       var values = [];
23679
23680       outer:
23681       for (var i = 0; i < tokens1.length; i++) {
23682         var token = tokens1[i];
23683         for (var j = 0; j < tokens2.length; j++) {
23684           if (token == tokens2[j]) continue outer;
23685         }
23686         values.push(token);
23687       }
23688       return values;
23689     }
23690
23691     function arrayClasses(classVal) {
23692       var classes = [];
23693       if (isArray(classVal)) {
23694         forEach(classVal, function(v) {
23695           classes = classes.concat(arrayClasses(v));
23696         });
23697         return classes;
23698       } else if (isString(classVal)) {
23699         return classVal.split(' ');
23700       } else if (isObject(classVal)) {
23701         forEach(classVal, function(v, k) {
23702           if (v) {
23703             classes = classes.concat(k.split(' '));
23704           }
23705         });
23706         return classes;
23707       }
23708       return classVal;
23709     }
23710   }];
23711 }
23712
23713 /**
23714  * @ngdoc directive
23715  * @name ngClass
23716  * @restrict AC
23717  *
23718  * @description
23719  * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
23720  * an expression that represents all classes to be added.
23721  *
23722  * The directive operates in three different ways, depending on which of three types the expression
23723  * evaluates to:
23724  *
23725  * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
23726  * names.
23727  *
23728  * 2. If the expression evaluates to an object, then for each key-value pair of the
23729  * object with a truthy value the corresponding key is used as a class name.
23730  *
23731  * 3. If the expression evaluates to an array, each element of the array should either be a string as in
23732  * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
23733  * to give you more control over what CSS classes appear. See the code below for an example of this.
23734  *
23735  *
23736  * The directive won't add duplicate classes if a particular class was already set.
23737  *
23738  * When the expression changes, the previously added classes are removed and only then are the
23739  * new classes added.
23740  *
23741  * @animations
23742  * **add** - happens just before the class is applied to the elements
23743  *
23744  * **remove** - happens just before the class is removed from the element
23745  *
23746  * @element ANY
23747  * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
23748  *   of the evaluation can be a string representing space delimited class
23749  *   names, an array, or a map of class names to boolean values. In the case of a map, the
23750  *   names of the properties whose values are truthy will be added as css classes to the
23751  *   element.
23752  *
23753  * @example Example that demonstrates basic bindings via ngClass directive.
23754    <example>
23755      <file name="index.html">
23756        <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
23757        <label>
23758           <input type="checkbox" ng-model="deleted">
23759           deleted (apply "strike" class)
23760        </label><br>
23761        <label>
23762           <input type="checkbox" ng-model="important">
23763           important (apply "bold" class)
23764        </label><br>
23765        <label>
23766           <input type="checkbox" ng-model="error">
23767           error (apply "has-error" class)
23768        </label>
23769        <hr>
23770        <p ng-class="style">Using String Syntax</p>
23771        <input type="text" ng-model="style"
23772               placeholder="Type: bold strike red" aria-label="Type: bold strike red">
23773        <hr>
23774        <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
23775        <input ng-model="style1"
23776               placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
23777        <input ng-model="style2"
23778               placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
23779        <input ng-model="style3"
23780               placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
23781        <hr>
23782        <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
23783        <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
23784        <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
23785      </file>
23786      <file name="style.css">
23787        .strike {
23788            text-decoration: line-through;
23789        }
23790        .bold {
23791            font-weight: bold;
23792        }
23793        .red {
23794            color: red;
23795        }
23796        .has-error {
23797            color: red;
23798            background-color: yellow;
23799        }
23800        .orange {
23801            color: orange;
23802        }
23803      </file>
23804      <file name="protractor.js" type="protractor">
23805        var ps = element.all(by.css('p'));
23806
23807        it('should let you toggle the class', function() {
23808
23809          expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
23810          expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
23811
23812          element(by.model('important')).click();
23813          expect(ps.first().getAttribute('class')).toMatch(/bold/);
23814
23815          element(by.model('error')).click();
23816          expect(ps.first().getAttribute('class')).toMatch(/has-error/);
23817        });
23818
23819        it('should let you toggle string example', function() {
23820          expect(ps.get(1).getAttribute('class')).toBe('');
23821          element(by.model('style')).clear();
23822          element(by.model('style')).sendKeys('red');
23823          expect(ps.get(1).getAttribute('class')).toBe('red');
23824        });
23825
23826        it('array example should have 3 classes', function() {
23827          expect(ps.get(2).getAttribute('class')).toBe('');
23828          element(by.model('style1')).sendKeys('bold');
23829          element(by.model('style2')).sendKeys('strike');
23830          element(by.model('style3')).sendKeys('red');
23831          expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
23832        });
23833
23834        it('array with map example should have 2 classes', function() {
23835          expect(ps.last().getAttribute('class')).toBe('');
23836          element(by.model('style4')).sendKeys('bold');
23837          element(by.model('warning')).click();
23838          expect(ps.last().getAttribute('class')).toBe('bold orange');
23839        });
23840      </file>
23841    </example>
23842
23843    ## Animations
23844
23845    The example below demonstrates how to perform animations using ngClass.
23846
23847    <example module="ngAnimate" deps="angular-animate.js" animations="true">
23848      <file name="index.html">
23849       <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
23850       <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
23851       <br>
23852       <span class="base-class" ng-class="myVar">Sample Text</span>
23853      </file>
23854      <file name="style.css">
23855        .base-class {
23856          transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
23857        }
23858
23859        .base-class.my-class {
23860          color: red;
23861          font-size:3em;
23862        }
23863      </file>
23864      <file name="protractor.js" type="protractor">
23865        it('should check ng-class', function() {
23866          expect(element(by.css('.base-class')).getAttribute('class')).not.
23867            toMatch(/my-class/);
23868
23869          element(by.id('setbtn')).click();
23870
23871          expect(element(by.css('.base-class')).getAttribute('class')).
23872            toMatch(/my-class/);
23873
23874          element(by.id('clearbtn')).click();
23875
23876          expect(element(by.css('.base-class')).getAttribute('class')).not.
23877            toMatch(/my-class/);
23878        });
23879      </file>
23880    </example>
23881
23882
23883    ## ngClass and pre-existing CSS3 Transitions/Animations
23884    The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
23885    Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
23886    any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
23887    to view the step by step details of {@link $animate#addClass $animate.addClass} and
23888    {@link $animate#removeClass $animate.removeClass}.
23889  */
23890 var ngClassDirective = classDirective('', true);
23891
23892 /**
23893  * @ngdoc directive
23894  * @name ngClassOdd
23895  * @restrict AC
23896  *
23897  * @description
23898  * The `ngClassOdd` and `ngClassEven` directives work exactly as
23899  * {@link ng.directive:ngClass ngClass}, except they work in
23900  * conjunction with `ngRepeat` and take effect only on odd (even) rows.
23901  *
23902  * This directive can be applied only within the scope of an
23903  * {@link ng.directive:ngRepeat ngRepeat}.
23904  *
23905  * @element ANY
23906  * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
23907  *   of the evaluation can be a string representing space delimited class names or an array.
23908  *
23909  * @example
23910    <example>
23911      <file name="index.html">
23912         <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23913           <li ng-repeat="name in names">
23914            <span ng-class-odd="'odd'" ng-class-even="'even'">
23915              {{name}}
23916            </span>
23917           </li>
23918         </ol>
23919      </file>
23920      <file name="style.css">
23921        .odd {
23922          color: red;
23923        }
23924        .even {
23925          color: blue;
23926        }
23927      </file>
23928      <file name="protractor.js" type="protractor">
23929        it('should check ng-class-odd and ng-class-even', function() {
23930          expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
23931            toMatch(/odd/);
23932          expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
23933            toMatch(/even/);
23934        });
23935      </file>
23936    </example>
23937  */
23938 var ngClassOddDirective = classDirective('Odd', 0);
23939
23940 /**
23941  * @ngdoc directive
23942  * @name ngClassEven
23943  * @restrict AC
23944  *
23945  * @description
23946  * The `ngClassOdd` and `ngClassEven` directives work exactly as
23947  * {@link ng.directive:ngClass ngClass}, except they work in
23948  * conjunction with `ngRepeat` and take effect only on odd (even) rows.
23949  *
23950  * This directive can be applied only within the scope of an
23951  * {@link ng.directive:ngRepeat ngRepeat}.
23952  *
23953  * @element ANY
23954  * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
23955  *   result of the evaluation can be a string representing space delimited class names or an array.
23956  *
23957  * @example
23958    <example>
23959      <file name="index.html">
23960         <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23961           <li ng-repeat="name in names">
23962            <span ng-class-odd="'odd'" ng-class-even="'even'">
23963              {{name}} &nbsp; &nbsp; &nbsp;
23964            </span>
23965           </li>
23966         </ol>
23967      </file>
23968      <file name="style.css">
23969        .odd {
23970          color: red;
23971        }
23972        .even {
23973          color: blue;
23974        }
23975      </file>
23976      <file name="protractor.js" type="protractor">
23977        it('should check ng-class-odd and ng-class-even', function() {
23978          expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
23979            toMatch(/odd/);
23980          expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
23981            toMatch(/even/);
23982        });
23983      </file>
23984    </example>
23985  */
23986 var ngClassEvenDirective = classDirective('Even', 1);
23987
23988 /**
23989  * @ngdoc directive
23990  * @name ngCloak
23991  * @restrict AC
23992  *
23993  * @description
23994  * The `ngCloak` directive is used to prevent the Angular html template from being briefly
23995  * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
23996  * directive to avoid the undesirable flicker effect caused by the html template display.
23997  *
23998  * The directive can be applied to the `<body>` element, but the preferred usage is to apply
23999  * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
24000  * of the browser view.
24001  *
24002  * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
24003  * `angular.min.js`.
24004  * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
24005  *
24006  * ```css
24007  * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
24008  *   display: none !important;
24009  * }
24010  * ```
24011  *
24012  * When this css rule is loaded by the browser, all html elements (including their children) that
24013  * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
24014  * during the compilation of the template it deletes the `ngCloak` element attribute, making
24015  * the compiled element visible.
24016  *
24017  * For the best result, the `angular.js` script must be loaded in the head section of the html
24018  * document; alternatively, the css rule above must be included in the external stylesheet of the
24019  * application.
24020  *
24021  * @element ANY
24022  *
24023  * @example
24024    <example>
24025      <file name="index.html">
24026         <div id="template1" ng-cloak>{{ 'hello' }}</div>
24027         <div id="template2" class="ng-cloak">{{ 'world' }}</div>
24028      </file>
24029      <file name="protractor.js" type="protractor">
24030        it('should remove the template directive and css class', function() {
24031          expect($('#template1').getAttribute('ng-cloak')).
24032            toBeNull();
24033          expect($('#template2').getAttribute('ng-cloak')).
24034            toBeNull();
24035        });
24036      </file>
24037    </example>
24038  *
24039  */
24040 var ngCloakDirective = ngDirective({
24041   compile: function(element, attr) {
24042     attr.$set('ngCloak', undefined);
24043     element.removeClass('ng-cloak');
24044   }
24045 });
24046
24047 /**
24048  * @ngdoc directive
24049  * @name ngController
24050  *
24051  * @description
24052  * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
24053  * supports the principles behind the Model-View-Controller design pattern.
24054  *
24055  * MVC components in angular:
24056  *
24057  * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
24058  *   are accessed through bindings.
24059  * * View — The template (HTML with data bindings) that is rendered into the View.
24060  * * Controller — The `ngController` directive specifies a Controller class; the class contains business
24061  *   logic behind the application to decorate the scope with functions and values
24062  *
24063  * Note that you can also attach controllers to the DOM by declaring it in a route definition
24064  * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
24065  * again using `ng-controller` in the template itself.  This will cause the controller to be attached
24066  * and executed twice.
24067  *
24068  * @element ANY
24069  * @scope
24070  * @priority 500
24071  * @param {expression} ngController Name of a constructor function registered with the current
24072  * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
24073  * that on the current scope evaluates to a constructor function.
24074  *
24075  * The controller instance can be published into a scope property by specifying
24076  * `ng-controller="as propertyName"`.
24077  *
24078  * If the current `$controllerProvider` is configured to use globals (via
24079  * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
24080  * also be the name of a globally accessible constructor function (not recommended).
24081  *
24082  * @example
24083  * Here is a simple form for editing user contact information. Adding, removing, clearing, and
24084  * greeting are methods declared on the controller (see source tab). These methods can
24085  * easily be called from the angular markup. Any changes to the data are automatically reflected
24086  * in the View without the need for a manual update.
24087  *
24088  * Two different declaration styles are included below:
24089  *
24090  * * one binds methods and properties directly onto the controller using `this`:
24091  * `ng-controller="SettingsController1 as settings"`
24092  * * one injects `$scope` into the controller:
24093  * `ng-controller="SettingsController2"`
24094  *
24095  * The second option is more common in the Angular community, and is generally used in boilerplates
24096  * and in this guide. However, there are advantages to binding properties directly to the controller
24097  * and avoiding scope.
24098  *
24099  * * Using `controller as` makes it obvious which controller you are accessing in the template when
24100  * multiple controllers apply to an element.
24101  * * If you are writing your controllers as classes you have easier access to the properties and
24102  * methods, which will appear on the scope, from inside the controller code.
24103  * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
24104  * inheritance masking primitives.
24105  *
24106  * This example demonstrates the `controller as` syntax.
24107  *
24108  * <example name="ngControllerAs" module="controllerAsExample">
24109  *   <file name="index.html">
24110  *    <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
24111  *      <label>Name: <input type="text" ng-model="settings.name"/></label>
24112  *      <button ng-click="settings.greet()">greet</button><br/>
24113  *      Contact:
24114  *      <ul>
24115  *        <li ng-repeat="contact in settings.contacts">
24116  *          <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
24117  *             <option>phone</option>
24118  *             <option>email</option>
24119  *          </select>
24120  *          <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
24121  *          <button ng-click="settings.clearContact(contact)">clear</button>
24122  *          <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
24123  *        </li>
24124  *        <li><button ng-click="settings.addContact()">add</button></li>
24125  *     </ul>
24126  *    </div>
24127  *   </file>
24128  *   <file name="app.js">
24129  *    angular.module('controllerAsExample', [])
24130  *      .controller('SettingsController1', SettingsController1);
24131  *
24132  *    function SettingsController1() {
24133  *      this.name = "John Smith";
24134  *      this.contacts = [
24135  *        {type: 'phone', value: '408 555 1212'},
24136  *        {type: 'email', value: 'john.smith@example.org'} ];
24137  *    }
24138  *
24139  *    SettingsController1.prototype.greet = function() {
24140  *      alert(this.name);
24141  *    };
24142  *
24143  *    SettingsController1.prototype.addContact = function() {
24144  *      this.contacts.push({type: 'email', value: 'yourname@example.org'});
24145  *    };
24146  *
24147  *    SettingsController1.prototype.removeContact = function(contactToRemove) {
24148  *     var index = this.contacts.indexOf(contactToRemove);
24149  *      this.contacts.splice(index, 1);
24150  *    };
24151  *
24152  *    SettingsController1.prototype.clearContact = function(contact) {
24153  *      contact.type = 'phone';
24154  *      contact.value = '';
24155  *    };
24156  *   </file>
24157  *   <file name="protractor.js" type="protractor">
24158  *     it('should check controller as', function() {
24159  *       var container = element(by.id('ctrl-as-exmpl'));
24160  *         expect(container.element(by.model('settings.name'))
24161  *           .getAttribute('value')).toBe('John Smith');
24162  *
24163  *       var firstRepeat =
24164  *           container.element(by.repeater('contact in settings.contacts').row(0));
24165  *       var secondRepeat =
24166  *           container.element(by.repeater('contact in settings.contacts').row(1));
24167  *
24168  *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
24169  *           .toBe('408 555 1212');
24170  *
24171  *       expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
24172  *           .toBe('john.smith@example.org');
24173  *
24174  *       firstRepeat.element(by.buttonText('clear')).click();
24175  *
24176  *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
24177  *           .toBe('');
24178  *
24179  *       container.element(by.buttonText('add')).click();
24180  *
24181  *       expect(container.element(by.repeater('contact in settings.contacts').row(2))
24182  *           .element(by.model('contact.value'))
24183  *           .getAttribute('value'))
24184  *           .toBe('yourname@example.org');
24185  *     });
24186  *   </file>
24187  * </example>
24188  *
24189  * This example demonstrates the "attach to `$scope`" style of controller.
24190  *
24191  * <example name="ngController" module="controllerExample">
24192  *  <file name="index.html">
24193  *   <div id="ctrl-exmpl" ng-controller="SettingsController2">
24194  *     <label>Name: <input type="text" ng-model="name"/></label>
24195  *     <button ng-click="greet()">greet</button><br/>
24196  *     Contact:
24197  *     <ul>
24198  *       <li ng-repeat="contact in contacts">
24199  *         <select ng-model="contact.type" id="select_{{$index}}">
24200  *            <option>phone</option>
24201  *            <option>email</option>
24202  *         </select>
24203  *         <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
24204  *         <button ng-click="clearContact(contact)">clear</button>
24205  *         <button ng-click="removeContact(contact)">X</button>
24206  *       </li>
24207  *       <li>[ <button ng-click="addContact()">add</button> ]</li>
24208  *    </ul>
24209  *   </div>
24210  *  </file>
24211  *  <file name="app.js">
24212  *   angular.module('controllerExample', [])
24213  *     .controller('SettingsController2', ['$scope', SettingsController2]);
24214  *
24215  *   function SettingsController2($scope) {
24216  *     $scope.name = "John Smith";
24217  *     $scope.contacts = [
24218  *       {type:'phone', value:'408 555 1212'},
24219  *       {type:'email', value:'john.smith@example.org'} ];
24220  *
24221  *     $scope.greet = function() {
24222  *       alert($scope.name);
24223  *     };
24224  *
24225  *     $scope.addContact = function() {
24226  *       $scope.contacts.push({type:'email', value:'yourname@example.org'});
24227  *     };
24228  *
24229  *     $scope.removeContact = function(contactToRemove) {
24230  *       var index = $scope.contacts.indexOf(contactToRemove);
24231  *       $scope.contacts.splice(index, 1);
24232  *     };
24233  *
24234  *     $scope.clearContact = function(contact) {
24235  *       contact.type = 'phone';
24236  *       contact.value = '';
24237  *     };
24238  *   }
24239  *  </file>
24240  *  <file name="protractor.js" type="protractor">
24241  *    it('should check controller', function() {
24242  *      var container = element(by.id('ctrl-exmpl'));
24243  *
24244  *      expect(container.element(by.model('name'))
24245  *          .getAttribute('value')).toBe('John Smith');
24246  *
24247  *      var firstRepeat =
24248  *          container.element(by.repeater('contact in contacts').row(0));
24249  *      var secondRepeat =
24250  *          container.element(by.repeater('contact in contacts').row(1));
24251  *
24252  *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
24253  *          .toBe('408 555 1212');
24254  *      expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
24255  *          .toBe('john.smith@example.org');
24256  *
24257  *      firstRepeat.element(by.buttonText('clear')).click();
24258  *
24259  *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
24260  *          .toBe('');
24261  *
24262  *      container.element(by.buttonText('add')).click();
24263  *
24264  *      expect(container.element(by.repeater('contact in contacts').row(2))
24265  *          .element(by.model('contact.value'))
24266  *          .getAttribute('value'))
24267  *          .toBe('yourname@example.org');
24268  *    });
24269  *  </file>
24270  *</example>
24271
24272  */
24273 var ngControllerDirective = [function() {
24274   return {
24275     restrict: 'A',
24276     scope: true,
24277     controller: '@',
24278     priority: 500
24279   };
24280 }];
24281
24282 /**
24283  * @ngdoc directive
24284  * @name ngCsp
24285  *
24286  * @element html
24287  * @description
24288  *
24289  * Angular has some features that can break certain
24290  * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
24291  *
24292  * If you intend to implement these rules then you must tell Angular not to use these features.
24293  *
24294  * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
24295  *
24296  *
24297  * The following rules affect Angular:
24298  *
24299  * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
24300  * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
24301  * increase in the speed of evaluating Angular expressions.
24302  *
24303  * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
24304  * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
24305  * To make these directives work when a CSP rule is blocking inline styles, you must link to the
24306  * `angular-csp.css` in your HTML manually.
24307  *
24308  * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
24309  * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
24310  * however, triggers a CSP error to be logged in the console:
24311  *
24312  * ```
24313  * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
24314  * script in the following Content Security Policy directive: "default-src 'self'". Note that
24315  * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
24316  * ```
24317  *
24318  * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
24319  * directive on an element of the HTML document that appears before the `<script>` tag that loads
24320  * the `angular.js` file.
24321  *
24322  * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
24323  *
24324  * You can specify which of the CSP related Angular features should be deactivated by providing
24325  * a value for the `ng-csp` attribute. The options are as follows:
24326  *
24327  * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
24328  *
24329  * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
24330  *
24331  * You can use these values in the following combinations:
24332  *
24333  *
24334  * * No declaration means that Angular will assume that you can do inline styles, but it will do
24335  * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
24336  * of Angular.
24337  *
24338  * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
24339  * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
24340  * of Angular.
24341  *
24342  * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
24343  * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
24344  *
24345  * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
24346  * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
24347  *
24348  * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
24349  * styles nor use eval, which is the same as an empty: ng-csp.
24350  * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
24351  *
24352  * @example
24353  * This example shows how to apply the `ngCsp` directive to the `html` tag.
24354    ```html
24355      <!doctype html>
24356      <html ng-app ng-csp>
24357      ...
24358      ...
24359      </html>
24360    ```
24361   * @example
24362       // Note: the suffix `.csp` in the example name triggers
24363       // csp mode in our http server!
24364       <example name="example.csp" module="cspExample" ng-csp="true">
24365         <file name="index.html">
24366           <div ng-controller="MainController as ctrl">
24367             <div>
24368               <button ng-click="ctrl.inc()" id="inc">Increment</button>
24369               <span id="counter">
24370                 {{ctrl.counter}}
24371               </span>
24372             </div>
24373
24374             <div>
24375               <button ng-click="ctrl.evil()" id="evil">Evil</button>
24376               <span id="evilError">
24377                 {{ctrl.evilError}}
24378               </span>
24379             </div>
24380           </div>
24381         </file>
24382         <file name="script.js">
24383            angular.module('cspExample', [])
24384              .controller('MainController', function() {
24385                 this.counter = 0;
24386                 this.inc = function() {
24387                   this.counter++;
24388                 };
24389                 this.evil = function() {
24390                   // jshint evil:true
24391                   try {
24392                     eval('1+2');
24393                   } catch (e) {
24394                     this.evilError = e.message;
24395                   }
24396                 };
24397               });
24398         </file>
24399         <file name="protractor.js" type="protractor">
24400           var util, webdriver;
24401
24402           var incBtn = element(by.id('inc'));
24403           var counter = element(by.id('counter'));
24404           var evilBtn = element(by.id('evil'));
24405           var evilError = element(by.id('evilError'));
24406
24407           function getAndClearSevereErrors() {
24408             return browser.manage().logs().get('browser').then(function(browserLog) {
24409               return browserLog.filter(function(logEntry) {
24410                 return logEntry.level.value > webdriver.logging.Level.WARNING.value;
24411               });
24412             });
24413           }
24414
24415           function clearErrors() {
24416             getAndClearSevereErrors();
24417           }
24418
24419           function expectNoErrors() {
24420             getAndClearSevereErrors().then(function(filteredLog) {
24421               expect(filteredLog.length).toEqual(0);
24422               if (filteredLog.length) {
24423                 console.log('browser console errors: ' + util.inspect(filteredLog));
24424               }
24425             });
24426           }
24427
24428           function expectError(regex) {
24429             getAndClearSevereErrors().then(function(filteredLog) {
24430               var found = false;
24431               filteredLog.forEach(function(log) {
24432                 if (log.message.match(regex)) {
24433                   found = true;
24434                 }
24435               });
24436               if (!found) {
24437                 throw new Error('expected an error that matches ' + regex);
24438               }
24439             });
24440           }
24441
24442           beforeEach(function() {
24443             util = require('util');
24444             webdriver = require('protractor/node_modules/selenium-webdriver');
24445           });
24446
24447           // For now, we only test on Chrome,
24448           // as Safari does not load the page with Protractor's injected scripts,
24449           // and Firefox webdriver always disables content security policy (#6358)
24450           if (browser.params.browser !== 'chrome') {
24451             return;
24452           }
24453
24454           it('should not report errors when the page is loaded', function() {
24455             // clear errors so we are not dependent on previous tests
24456             clearErrors();
24457             // Need to reload the page as the page is already loaded when
24458             // we come here
24459             browser.driver.getCurrentUrl().then(function(url) {
24460               browser.get(url);
24461             });
24462             expectNoErrors();
24463           });
24464
24465           it('should evaluate expressions', function() {
24466             expect(counter.getText()).toEqual('0');
24467             incBtn.click();
24468             expect(counter.getText()).toEqual('1');
24469             expectNoErrors();
24470           });
24471
24472           it('should throw and report an error when using "eval"', function() {
24473             evilBtn.click();
24474             expect(evilError.getText()).toMatch(/Content Security Policy/);
24475             expectError(/Content Security Policy/);
24476           });
24477         </file>
24478       </example>
24479   */
24480
24481 // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
24482 // bootstrap the system (before $parse is instantiated), for this reason we just have
24483 // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
24484
24485 /**
24486  * @ngdoc directive
24487  * @name ngClick
24488  *
24489  * @description
24490  * The ngClick directive allows you to specify custom behavior when
24491  * an element is clicked.
24492  *
24493  * @element ANY
24494  * @priority 0
24495  * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
24496  * click. ({@link guide/expression#-event- Event object is available as `$event`})
24497  *
24498  * @example
24499    <example>
24500      <file name="index.html">
24501       <button ng-click="count = count + 1" ng-init="count=0">
24502         Increment
24503       </button>
24504       <span>
24505         count: {{count}}
24506       </span>
24507      </file>
24508      <file name="protractor.js" type="protractor">
24509        it('should check ng-click', function() {
24510          expect(element(by.binding('count')).getText()).toMatch('0');
24511          element(by.css('button')).click();
24512          expect(element(by.binding('count')).getText()).toMatch('1');
24513        });
24514      </file>
24515    </example>
24516  */
24517 /*
24518  * A collection of directives that allows creation of custom event handlers that are defined as
24519  * angular expressions and are compiled and executed within the current scope.
24520  */
24521 var ngEventDirectives = {};
24522
24523 // For events that might fire synchronously during DOM manipulation
24524 // we need to execute their event handlers asynchronously using $evalAsync,
24525 // so that they are not executed in an inconsistent state.
24526 var forceAsyncEvents = {
24527   'blur': true,
24528   'focus': true
24529 };
24530 forEach(
24531   'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
24532   function(eventName) {
24533     var directiveName = directiveNormalize('ng-' + eventName);
24534     ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
24535       return {
24536         restrict: 'A',
24537         compile: function($element, attr) {
24538           // We expose the powerful $event object on the scope that provides access to the Window,
24539           // etc. that isn't protected by the fast paths in $parse.  We explicitly request better
24540           // checks at the cost of speed since event handler expressions are not executed as
24541           // frequently as regular change detection.
24542           var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
24543           return function ngEventHandler(scope, element) {
24544             element.on(eventName, function(event) {
24545               var callback = function() {
24546                 fn(scope, {$event:event});
24547               };
24548               if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
24549                 scope.$evalAsync(callback);
24550               } else {
24551                 scope.$apply(callback);
24552               }
24553             });
24554           };
24555         }
24556       };
24557     }];
24558   }
24559 );
24560
24561 /**
24562  * @ngdoc directive
24563  * @name ngDblclick
24564  *
24565  * @description
24566  * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
24567  *
24568  * @element ANY
24569  * @priority 0
24570  * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
24571  * a dblclick. (The Event object is available as `$event`)
24572  *
24573  * @example
24574    <example>
24575      <file name="index.html">
24576       <button ng-dblclick="count = count + 1" ng-init="count=0">
24577         Increment (on double click)
24578       </button>
24579       count: {{count}}
24580      </file>
24581    </example>
24582  */
24583
24584
24585 /**
24586  * @ngdoc directive
24587  * @name ngMousedown
24588  *
24589  * @description
24590  * The ngMousedown directive allows you to specify custom behavior on mousedown event.
24591  *
24592  * @element ANY
24593  * @priority 0
24594  * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
24595  * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
24596  *
24597  * @example
24598    <example>
24599      <file name="index.html">
24600       <button ng-mousedown="count = count + 1" ng-init="count=0">
24601         Increment (on mouse down)
24602       </button>
24603       count: {{count}}
24604      </file>
24605    </example>
24606  */
24607
24608
24609 /**
24610  * @ngdoc directive
24611  * @name ngMouseup
24612  *
24613  * @description
24614  * Specify custom behavior on mouseup event.
24615  *
24616  * @element ANY
24617  * @priority 0
24618  * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
24619  * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
24620  *
24621  * @example
24622    <example>
24623      <file name="index.html">
24624       <button ng-mouseup="count = count + 1" ng-init="count=0">
24625         Increment (on mouse up)
24626       </button>
24627       count: {{count}}
24628      </file>
24629    </example>
24630  */
24631
24632 /**
24633  * @ngdoc directive
24634  * @name ngMouseover
24635  *
24636  * @description
24637  * Specify custom behavior on mouseover event.
24638  *
24639  * @element ANY
24640  * @priority 0
24641  * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
24642  * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
24643  *
24644  * @example
24645    <example>
24646      <file name="index.html">
24647       <button ng-mouseover="count = count + 1" ng-init="count=0">
24648         Increment (when mouse is over)
24649       </button>
24650       count: {{count}}
24651      </file>
24652    </example>
24653  */
24654
24655
24656 /**
24657  * @ngdoc directive
24658  * @name ngMouseenter
24659  *
24660  * @description
24661  * Specify custom behavior on mouseenter event.
24662  *
24663  * @element ANY
24664  * @priority 0
24665  * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
24666  * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
24667  *
24668  * @example
24669    <example>
24670      <file name="index.html">
24671       <button ng-mouseenter="count = count + 1" ng-init="count=0">
24672         Increment (when mouse enters)
24673       </button>
24674       count: {{count}}
24675      </file>
24676    </example>
24677  */
24678
24679
24680 /**
24681  * @ngdoc directive
24682  * @name ngMouseleave
24683  *
24684  * @description
24685  * Specify custom behavior on mouseleave event.
24686  *
24687  * @element ANY
24688  * @priority 0
24689  * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
24690  * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
24691  *
24692  * @example
24693    <example>
24694      <file name="index.html">
24695       <button ng-mouseleave="count = count + 1" ng-init="count=0">
24696         Increment (when mouse leaves)
24697       </button>
24698       count: {{count}}
24699      </file>
24700    </example>
24701  */
24702
24703
24704 /**
24705  * @ngdoc directive
24706  * @name ngMousemove
24707  *
24708  * @description
24709  * Specify custom behavior on mousemove event.
24710  *
24711  * @element ANY
24712  * @priority 0
24713  * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
24714  * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
24715  *
24716  * @example
24717    <example>
24718      <file name="index.html">
24719       <button ng-mousemove="count = count + 1" ng-init="count=0">
24720         Increment (when mouse moves)
24721       </button>
24722       count: {{count}}
24723      </file>
24724    </example>
24725  */
24726
24727
24728 /**
24729  * @ngdoc directive
24730  * @name ngKeydown
24731  *
24732  * @description
24733  * Specify custom behavior on keydown event.
24734  *
24735  * @element ANY
24736  * @priority 0
24737  * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
24738  * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
24739  *
24740  * @example
24741    <example>
24742      <file name="index.html">
24743       <input ng-keydown="count = count + 1" ng-init="count=0">
24744       key down count: {{count}}
24745      </file>
24746    </example>
24747  */
24748
24749
24750 /**
24751  * @ngdoc directive
24752  * @name ngKeyup
24753  *
24754  * @description
24755  * Specify custom behavior on keyup event.
24756  *
24757  * @element ANY
24758  * @priority 0
24759  * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
24760  * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
24761  *
24762  * @example
24763    <example>
24764      <file name="index.html">
24765        <p>Typing in the input box below updates the key count</p>
24766        <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
24767
24768        <p>Typing in the input box below updates the keycode</p>
24769        <input ng-keyup="event=$event">
24770        <p>event keyCode: {{ event.keyCode }}</p>
24771        <p>event altKey: {{ event.altKey }}</p>
24772      </file>
24773    </example>
24774  */
24775
24776
24777 /**
24778  * @ngdoc directive
24779  * @name ngKeypress
24780  *
24781  * @description
24782  * Specify custom behavior on keypress event.
24783  *
24784  * @element ANY
24785  * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
24786  * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
24787  * and can be interrogated for keyCode, altKey, etc.)
24788  *
24789  * @example
24790    <example>
24791      <file name="index.html">
24792       <input ng-keypress="count = count + 1" ng-init="count=0">
24793       key press count: {{count}}
24794      </file>
24795    </example>
24796  */
24797
24798
24799 /**
24800  * @ngdoc directive
24801  * @name ngSubmit
24802  *
24803  * @description
24804  * Enables binding angular expressions to onsubmit events.
24805  *
24806  * Additionally it prevents the default action (which for form means sending the request to the
24807  * server and reloading the current page), but only if the form does not contain `action`,
24808  * `data-action`, or `x-action` attributes.
24809  *
24810  * <div class="alert alert-warning">
24811  * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
24812  * `ngSubmit` handlers together. See the
24813  * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
24814  * for a detailed discussion of when `ngSubmit` may be triggered.
24815  * </div>
24816  *
24817  * @element form
24818  * @priority 0
24819  * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
24820  * ({@link guide/expression#-event- Event object is available as `$event`})
24821  *
24822  * @example
24823    <example module="submitExample">
24824      <file name="index.html">
24825       <script>
24826         angular.module('submitExample', [])
24827           .controller('ExampleController', ['$scope', function($scope) {
24828             $scope.list = [];
24829             $scope.text = 'hello';
24830             $scope.submit = function() {
24831               if ($scope.text) {
24832                 $scope.list.push(this.text);
24833                 $scope.text = '';
24834               }
24835             };
24836           }]);
24837       </script>
24838       <form ng-submit="submit()" ng-controller="ExampleController">
24839         Enter text and hit enter:
24840         <input type="text" ng-model="text" name="text" />
24841         <input type="submit" id="submit" value="Submit" />
24842         <pre>list={{list}}</pre>
24843       </form>
24844      </file>
24845      <file name="protractor.js" type="protractor">
24846        it('should check ng-submit', function() {
24847          expect(element(by.binding('list')).getText()).toBe('list=[]');
24848          element(by.css('#submit')).click();
24849          expect(element(by.binding('list')).getText()).toContain('hello');
24850          expect(element(by.model('text')).getAttribute('value')).toBe('');
24851        });
24852        it('should ignore empty strings', function() {
24853          expect(element(by.binding('list')).getText()).toBe('list=[]');
24854          element(by.css('#submit')).click();
24855          element(by.css('#submit')).click();
24856          expect(element(by.binding('list')).getText()).toContain('hello');
24857         });
24858      </file>
24859    </example>
24860  */
24861
24862 /**
24863  * @ngdoc directive
24864  * @name ngFocus
24865  *
24866  * @description
24867  * Specify custom behavior on focus event.
24868  *
24869  * Note: As the `focus` event is executed synchronously when calling `input.focus()`
24870  * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
24871  * during an `$apply` to ensure a consistent state.
24872  *
24873  * @element window, input, select, textarea, a
24874  * @priority 0
24875  * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
24876  * focus. ({@link guide/expression#-event- Event object is available as `$event`})
24877  *
24878  * @example
24879  * See {@link ng.directive:ngClick ngClick}
24880  */
24881
24882 /**
24883  * @ngdoc directive
24884  * @name ngBlur
24885  *
24886  * @description
24887  * Specify custom behavior on blur event.
24888  *
24889  * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
24890  * an element has lost focus.
24891  *
24892  * Note: As the `blur` event is executed synchronously also during DOM manipulations
24893  * (e.g. removing a focussed input),
24894  * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
24895  * during an `$apply` to ensure a consistent state.
24896  *
24897  * @element window, input, select, textarea, a
24898  * @priority 0
24899  * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
24900  * blur. ({@link guide/expression#-event- Event object is available as `$event`})
24901  *
24902  * @example
24903  * See {@link ng.directive:ngClick ngClick}
24904  */
24905
24906 /**
24907  * @ngdoc directive
24908  * @name ngCopy
24909  *
24910  * @description
24911  * Specify custom behavior on copy event.
24912  *
24913  * @element window, input, select, textarea, a
24914  * @priority 0
24915  * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
24916  * copy. ({@link guide/expression#-event- Event object is available as `$event`})
24917  *
24918  * @example
24919    <example>
24920      <file name="index.html">
24921       <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
24922       copied: {{copied}}
24923      </file>
24924    </example>
24925  */
24926
24927 /**
24928  * @ngdoc directive
24929  * @name ngCut
24930  *
24931  * @description
24932  * Specify custom behavior on cut event.
24933  *
24934  * @element window, input, select, textarea, a
24935  * @priority 0
24936  * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
24937  * cut. ({@link guide/expression#-event- Event object is available as `$event`})
24938  *
24939  * @example
24940    <example>
24941      <file name="index.html">
24942       <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
24943       cut: {{cut}}
24944      </file>
24945    </example>
24946  */
24947
24948 /**
24949  * @ngdoc directive
24950  * @name ngPaste
24951  *
24952  * @description
24953  * Specify custom behavior on paste event.
24954  *
24955  * @element window, input, select, textarea, a
24956  * @priority 0
24957  * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
24958  * paste. ({@link guide/expression#-event- Event object is available as `$event`})
24959  *
24960  * @example
24961    <example>
24962      <file name="index.html">
24963       <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
24964       pasted: {{paste}}
24965      </file>
24966    </example>
24967  */
24968
24969 /**
24970  * @ngdoc directive
24971  * @name ngIf
24972  * @restrict A
24973  * @multiElement
24974  *
24975  * @description
24976  * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
24977  * {expression}. If the expression assigned to `ngIf` evaluates to a false
24978  * value then the element is removed from the DOM, otherwise a clone of the
24979  * element is reinserted into the DOM.
24980  *
24981  * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
24982  * element in the DOM rather than changing its visibility via the `display` css property.  A common
24983  * case when this difference is significant is when using css selectors that rely on an element's
24984  * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
24985  *
24986  * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
24987  * is created when the element is restored.  The scope created within `ngIf` inherits from
24988  * its parent scope using
24989  * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
24990  * An important implication of this is if `ngModel` is used within `ngIf` to bind to
24991  * a javascript primitive defined in the parent scope. In this case any modifications made to the
24992  * variable within the child scope will override (hide) the value in the parent scope.
24993  *
24994  * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
24995  * is if an element's class attribute is directly modified after it's compiled, using something like
24996  * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
24997  * the added class will be lost because the original compiled state is used to regenerate the element.
24998  *
24999  * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
25000  * and `leave` effects.
25001  *
25002  * @animations
25003  * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
25004  * leave - happens just before the `ngIf` contents are removed from the DOM
25005  *
25006  * @element ANY
25007  * @scope
25008  * @priority 600
25009  * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
25010  *     the element is removed from the DOM tree. If it is truthy a copy of the compiled
25011  *     element is added to the DOM tree.
25012  *
25013  * @example
25014   <example module="ngAnimate" deps="angular-animate.js" animations="true">
25015     <file name="index.html">
25016       <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
25017       Show when checked:
25018       <span ng-if="checked" class="animate-if">
25019         This is removed when the checkbox is unchecked.
25020       </span>
25021     </file>
25022     <file name="animations.css">
25023       .animate-if {
25024         background:white;
25025         border:1px solid black;
25026         padding:10px;
25027       }
25028
25029       .animate-if.ng-enter, .animate-if.ng-leave {
25030         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
25031       }
25032
25033       .animate-if.ng-enter,
25034       .animate-if.ng-leave.ng-leave-active {
25035         opacity:0;
25036       }
25037
25038       .animate-if.ng-leave,
25039       .animate-if.ng-enter.ng-enter-active {
25040         opacity:1;
25041       }
25042     </file>
25043   </example>
25044  */
25045 var ngIfDirective = ['$animate', function($animate) {
25046   return {
25047     multiElement: true,
25048     transclude: 'element',
25049     priority: 600,
25050     terminal: true,
25051     restrict: 'A',
25052     $$tlb: true,
25053     link: function($scope, $element, $attr, ctrl, $transclude) {
25054         var block, childScope, previousElements;
25055         $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
25056
25057           if (value) {
25058             if (!childScope) {
25059               $transclude(function(clone, newScope) {
25060                 childScope = newScope;
25061                 clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
25062                 // Note: We only need the first/last node of the cloned nodes.
25063                 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
25064                 // by a directive with templateUrl when its template arrives.
25065                 block = {
25066                   clone: clone
25067                 };
25068                 $animate.enter(clone, $element.parent(), $element);
25069               });
25070             }
25071           } else {
25072             if (previousElements) {
25073               previousElements.remove();
25074               previousElements = null;
25075             }
25076             if (childScope) {
25077               childScope.$destroy();
25078               childScope = null;
25079             }
25080             if (block) {
25081               previousElements = getBlockNodes(block.clone);
25082               $animate.leave(previousElements).then(function() {
25083                 previousElements = null;
25084               });
25085               block = null;
25086             }
25087           }
25088         });
25089     }
25090   };
25091 }];
25092
25093 /**
25094  * @ngdoc directive
25095  * @name ngInclude
25096  * @restrict ECA
25097  *
25098  * @description
25099  * Fetches, compiles and includes an external HTML fragment.
25100  *
25101  * By default, the template URL is restricted to the same domain and protocol as the
25102  * application document. This is done by calling {@link $sce#getTrustedResourceUrl
25103  * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
25104  * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
25105  * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
25106  * ng.$sce Strict Contextual Escaping}.
25107  *
25108  * In addition, the browser's
25109  * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
25110  * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
25111  * policy may further restrict whether the template is successfully loaded.
25112  * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
25113  * access on some browsers.
25114  *
25115  * @animations
25116  * enter - animation is used to bring new content into the browser.
25117  * leave - animation is used to animate existing content away.
25118  *
25119  * The enter and leave animation occur concurrently.
25120  *
25121  * @scope
25122  * @priority 400
25123  *
25124  * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
25125  *                 make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
25126  * @param {string=} onload Expression to evaluate when a new partial is loaded.
25127  *                  <div class="alert alert-warning">
25128  *                  **Note:** When using onload on SVG elements in IE11, the browser will try to call
25129  *                  a function with the name on the window element, which will usually throw a
25130  *                  "function is undefined" error. To fix this, you can instead use `data-onload` or a
25131  *                  different form that {@link guide/directive#normalization matches} `onload`.
25132  *                  </div>
25133    *
25134  * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
25135  *                  $anchorScroll} to scroll the viewport after the content is loaded.
25136  *
25137  *                  - If the attribute is not set, disable scrolling.
25138  *                  - If the attribute is set without value, enable scrolling.
25139  *                  - Otherwise enable scrolling only if the expression evaluates to truthy value.
25140  *
25141  * @example
25142   <example module="includeExample" deps="angular-animate.js" animations="true">
25143     <file name="index.html">
25144      <div ng-controller="ExampleController">
25145        <select ng-model="template" ng-options="t.name for t in templates">
25146         <option value="">(blank)</option>
25147        </select>
25148        url of the template: <code>{{template.url}}</code>
25149        <hr/>
25150        <div class="slide-animate-container">
25151          <div class="slide-animate" ng-include="template.url"></div>
25152        </div>
25153      </div>
25154     </file>
25155     <file name="script.js">
25156       angular.module('includeExample', ['ngAnimate'])
25157         .controller('ExampleController', ['$scope', function($scope) {
25158           $scope.templates =
25159             [ { name: 'template1.html', url: 'template1.html'},
25160               { name: 'template2.html', url: 'template2.html'} ];
25161           $scope.template = $scope.templates[0];
25162         }]);
25163      </file>
25164     <file name="template1.html">
25165       Content of template1.html
25166     </file>
25167     <file name="template2.html">
25168       Content of template2.html
25169     </file>
25170     <file name="animations.css">
25171       .slide-animate-container {
25172         position:relative;
25173         background:white;
25174         border:1px solid black;
25175         height:40px;
25176         overflow:hidden;
25177       }
25178
25179       .slide-animate {
25180         padding:10px;
25181       }
25182
25183       .slide-animate.ng-enter, .slide-animate.ng-leave {
25184         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
25185
25186         position:absolute;
25187         top:0;
25188         left:0;
25189         right:0;
25190         bottom:0;
25191         display:block;
25192         padding:10px;
25193       }
25194
25195       .slide-animate.ng-enter {
25196         top:-50px;
25197       }
25198       .slide-animate.ng-enter.ng-enter-active {
25199         top:0;
25200       }
25201
25202       .slide-animate.ng-leave {
25203         top:0;
25204       }
25205       .slide-animate.ng-leave.ng-leave-active {
25206         top:50px;
25207       }
25208     </file>
25209     <file name="protractor.js" type="protractor">
25210       var templateSelect = element(by.model('template'));
25211       var includeElem = element(by.css('[ng-include]'));
25212
25213       it('should load template1.html', function() {
25214         expect(includeElem.getText()).toMatch(/Content of template1.html/);
25215       });
25216
25217       it('should load template2.html', function() {
25218         if (browser.params.browser == 'firefox') {
25219           // Firefox can't handle using selects
25220           // See https://github.com/angular/protractor/issues/480
25221           return;
25222         }
25223         templateSelect.click();
25224         templateSelect.all(by.css('option')).get(2).click();
25225         expect(includeElem.getText()).toMatch(/Content of template2.html/);
25226       });
25227
25228       it('should change to blank', function() {
25229         if (browser.params.browser == 'firefox') {
25230           // Firefox can't handle using selects
25231           return;
25232         }
25233         templateSelect.click();
25234         templateSelect.all(by.css('option')).get(0).click();
25235         expect(includeElem.isPresent()).toBe(false);
25236       });
25237     </file>
25238   </example>
25239  */
25240
25241
25242 /**
25243  * @ngdoc event
25244  * @name ngInclude#$includeContentRequested
25245  * @eventType emit on the scope ngInclude was declared in
25246  * @description
25247  * Emitted every time the ngInclude content is requested.
25248  *
25249  * @param {Object} angularEvent Synthetic event object.
25250  * @param {String} src URL of content to load.
25251  */
25252
25253
25254 /**
25255  * @ngdoc event
25256  * @name ngInclude#$includeContentLoaded
25257  * @eventType emit on the current ngInclude scope
25258  * @description
25259  * Emitted every time the ngInclude content is reloaded.
25260  *
25261  * @param {Object} angularEvent Synthetic event object.
25262  * @param {String} src URL of content to load.
25263  */
25264
25265
25266 /**
25267  * @ngdoc event
25268  * @name ngInclude#$includeContentError
25269  * @eventType emit on the scope ngInclude was declared in
25270  * @description
25271  * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
25272  *
25273  * @param {Object} angularEvent Synthetic event object.
25274  * @param {String} src URL of content to load.
25275  */
25276 var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
25277                   function($templateRequest,   $anchorScroll,   $animate) {
25278   return {
25279     restrict: 'ECA',
25280     priority: 400,
25281     terminal: true,
25282     transclude: 'element',
25283     controller: angular.noop,
25284     compile: function(element, attr) {
25285       var srcExp = attr.ngInclude || attr.src,
25286           onloadExp = attr.onload || '',
25287           autoScrollExp = attr.autoscroll;
25288
25289       return function(scope, $element, $attr, ctrl, $transclude) {
25290         var changeCounter = 0,
25291             currentScope,
25292             previousElement,
25293             currentElement;
25294
25295         var cleanupLastIncludeContent = function() {
25296           if (previousElement) {
25297             previousElement.remove();
25298             previousElement = null;
25299           }
25300           if (currentScope) {
25301             currentScope.$destroy();
25302             currentScope = null;
25303           }
25304           if (currentElement) {
25305             $animate.leave(currentElement).then(function() {
25306               previousElement = null;
25307             });
25308             previousElement = currentElement;
25309             currentElement = null;
25310           }
25311         };
25312
25313         scope.$watch(srcExp, function ngIncludeWatchAction(src) {
25314           var afterAnimation = function() {
25315             if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
25316               $anchorScroll();
25317             }
25318           };
25319           var thisChangeId = ++changeCounter;
25320
25321           if (src) {
25322             //set the 2nd param to true to ignore the template request error so that the inner
25323             //contents and scope can be cleaned up.
25324             $templateRequest(src, true).then(function(response) {
25325               if (scope.$$destroyed) return;
25326
25327               if (thisChangeId !== changeCounter) return;
25328               var newScope = scope.$new();
25329               ctrl.template = response;
25330
25331               // Note: This will also link all children of ng-include that were contained in the original
25332               // html. If that content contains controllers, ... they could pollute/change the scope.
25333               // However, using ng-include on an element with additional content does not make sense...
25334               // Note: We can't remove them in the cloneAttchFn of $transclude as that
25335               // function is called before linking the content, which would apply child
25336               // directives to non existing elements.
25337               var clone = $transclude(newScope, function(clone) {
25338                 cleanupLastIncludeContent();
25339                 $animate.enter(clone, null, $element).then(afterAnimation);
25340               });
25341
25342               currentScope = newScope;
25343               currentElement = clone;
25344
25345               currentScope.$emit('$includeContentLoaded', src);
25346               scope.$eval(onloadExp);
25347             }, function() {
25348               if (scope.$$destroyed) return;
25349
25350               if (thisChangeId === changeCounter) {
25351                 cleanupLastIncludeContent();
25352                 scope.$emit('$includeContentError', src);
25353               }
25354             });
25355             scope.$emit('$includeContentRequested', src);
25356           } else {
25357             cleanupLastIncludeContent();
25358             ctrl.template = null;
25359           }
25360         });
25361       };
25362     }
25363   };
25364 }];
25365
25366 // This directive is called during the $transclude call of the first `ngInclude` directive.
25367 // It will replace and compile the content of the element with the loaded template.
25368 // We need this directive so that the element content is already filled when
25369 // the link function of another directive on the same element as ngInclude
25370 // is called.
25371 var ngIncludeFillContentDirective = ['$compile',
25372   function($compile) {
25373     return {
25374       restrict: 'ECA',
25375       priority: -400,
25376       require: 'ngInclude',
25377       link: function(scope, $element, $attr, ctrl) {
25378         if (toString.call($element[0]).match(/SVG/)) {
25379           // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
25380           // support innerHTML, so detect this here and try to generate the contents
25381           // specially.
25382           $element.empty();
25383           $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
25384               function namespaceAdaptedClone(clone) {
25385             $element.append(clone);
25386           }, {futureParentElement: $element});
25387           return;
25388         }
25389
25390         $element.html(ctrl.template);
25391         $compile($element.contents())(scope);
25392       }
25393     };
25394   }];
25395
25396 /**
25397  * @ngdoc directive
25398  * @name ngInit
25399  * @restrict AC
25400  *
25401  * @description
25402  * The `ngInit` directive allows you to evaluate an expression in the
25403  * current scope.
25404  *
25405  * <div class="alert alert-danger">
25406  * This directive can be abused to add unnecessary amounts of logic into your templates.
25407  * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
25408  * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
25409  * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
25410  * rather than `ngInit` to initialize values on a scope.
25411  * </div>
25412  *
25413  * <div class="alert alert-warning">
25414  * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
25415  * sure you have parentheses to ensure correct operator precedence:
25416  * <pre class="prettyprint">
25417  * `<div ng-init="test1 = ($index | toString)"></div>`
25418  * </pre>
25419  * </div>
25420  *
25421  * @priority 450
25422  *
25423  * @element ANY
25424  * @param {expression} ngInit {@link guide/expression Expression} to eval.
25425  *
25426  * @example
25427    <example module="initExample">
25428      <file name="index.html">
25429    <script>
25430      angular.module('initExample', [])
25431        .controller('ExampleController', ['$scope', function($scope) {
25432          $scope.list = [['a', 'b'], ['c', 'd']];
25433        }]);
25434    </script>
25435    <div ng-controller="ExampleController">
25436      <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
25437        <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
25438           <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
25439        </div>
25440      </div>
25441    </div>
25442      </file>
25443      <file name="protractor.js" type="protractor">
25444        it('should alias index positions', function() {
25445          var elements = element.all(by.css('.example-init'));
25446          expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
25447          expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
25448          expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
25449          expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
25450        });
25451      </file>
25452    </example>
25453  */
25454 var ngInitDirective = ngDirective({
25455   priority: 450,
25456   compile: function() {
25457     return {
25458       pre: function(scope, element, attrs) {
25459         scope.$eval(attrs.ngInit);
25460       }
25461     };
25462   }
25463 });
25464
25465 /**
25466  * @ngdoc directive
25467  * @name ngList
25468  *
25469  * @description
25470  * Text input that converts between a delimited string and an array of strings. The default
25471  * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
25472  * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
25473  *
25474  * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
25475  * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
25476  *   list item is respected. This implies that the user of the directive is responsible for
25477  *   dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
25478  *   tab or newline character.
25479  * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
25480  *   when joining the list items back together) and whitespace around each list item is stripped
25481  *   before it is added to the model.
25482  *
25483  * ### Example with Validation
25484  *
25485  * <example name="ngList-directive" module="listExample">
25486  *   <file name="app.js">
25487  *      angular.module('listExample', [])
25488  *        .controller('ExampleController', ['$scope', function($scope) {
25489  *          $scope.names = ['morpheus', 'neo', 'trinity'];
25490  *        }]);
25491  *   </file>
25492  *   <file name="index.html">
25493  *    <form name="myForm" ng-controller="ExampleController">
25494  *      <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
25495  *      <span role="alert">
25496  *        <span class="error" ng-show="myForm.namesInput.$error.required">
25497  *        Required!</span>
25498  *      </span>
25499  *      <br>
25500  *      <tt>names = {{names}}</tt><br/>
25501  *      <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
25502  *      <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
25503  *      <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
25504  *      <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
25505  *     </form>
25506  *   </file>
25507  *   <file name="protractor.js" type="protractor">
25508  *     var listInput = element(by.model('names'));
25509  *     var names = element(by.exactBinding('names'));
25510  *     var valid = element(by.binding('myForm.namesInput.$valid'));
25511  *     var error = element(by.css('span.error'));
25512  *
25513  *     it('should initialize to model', function() {
25514  *       expect(names.getText()).toContain('["morpheus","neo","trinity"]');
25515  *       expect(valid.getText()).toContain('true');
25516  *       expect(error.getCssValue('display')).toBe('none');
25517  *     });
25518  *
25519  *     it('should be invalid if empty', function() {
25520  *       listInput.clear();
25521  *       listInput.sendKeys('');
25522  *
25523  *       expect(names.getText()).toContain('');
25524  *       expect(valid.getText()).toContain('false');
25525  *       expect(error.getCssValue('display')).not.toBe('none');
25526  *     });
25527  *   </file>
25528  * </example>
25529  *
25530  * ### Example - splitting on newline
25531  * <example name="ngList-directive-newlines">
25532  *   <file name="index.html">
25533  *    <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
25534  *    <pre>{{ list | json }}</pre>
25535  *   </file>
25536  *   <file name="protractor.js" type="protractor">
25537  *     it("should split the text by newlines", function() {
25538  *       var listInput = element(by.model('list'));
25539  *       var output = element(by.binding('list | json'));
25540  *       listInput.sendKeys('abc\ndef\nghi');
25541  *       expect(output.getText()).toContain('[\n  "abc",\n  "def",\n  "ghi"\n]');
25542  *     });
25543  *   </file>
25544  * </example>
25545  *
25546  * @element input
25547  * @param {string=} ngList optional delimiter that should be used to split the value.
25548  */
25549 var ngListDirective = function() {
25550   return {
25551     restrict: 'A',
25552     priority: 100,
25553     require: 'ngModel',
25554     link: function(scope, element, attr, ctrl) {
25555       // We want to control whitespace trimming so we use this convoluted approach
25556       // to access the ngList attribute, which doesn't pre-trim the attribute
25557       var ngList = element.attr(attr.$attr.ngList) || ', ';
25558       var trimValues = attr.ngTrim !== 'false';
25559       var separator = trimValues ? trim(ngList) : ngList;
25560
25561       var parse = function(viewValue) {
25562         // If the viewValue is invalid (say required but empty) it will be `undefined`
25563         if (isUndefined(viewValue)) return;
25564
25565         var list = [];
25566
25567         if (viewValue) {
25568           forEach(viewValue.split(separator), function(value) {
25569             if (value) list.push(trimValues ? trim(value) : value);
25570           });
25571         }
25572
25573         return list;
25574       };
25575
25576       ctrl.$parsers.push(parse);
25577       ctrl.$formatters.push(function(value) {
25578         if (isArray(value)) {
25579           return value.join(ngList);
25580         }
25581
25582         return undefined;
25583       });
25584
25585       // Override the standard $isEmpty because an empty array means the input is empty.
25586       ctrl.$isEmpty = function(value) {
25587         return !value || !value.length;
25588       };
25589     }
25590   };
25591 };
25592
25593 /* global VALID_CLASS: true,
25594   INVALID_CLASS: true,
25595   PRISTINE_CLASS: true,
25596   DIRTY_CLASS: true,
25597   UNTOUCHED_CLASS: true,
25598   TOUCHED_CLASS: true,
25599 */
25600
25601 var VALID_CLASS = 'ng-valid',
25602     INVALID_CLASS = 'ng-invalid',
25603     PRISTINE_CLASS = 'ng-pristine',
25604     DIRTY_CLASS = 'ng-dirty',
25605     UNTOUCHED_CLASS = 'ng-untouched',
25606     TOUCHED_CLASS = 'ng-touched',
25607     PENDING_CLASS = 'ng-pending',
25608     EMPTY_CLASS = 'ng-empty',
25609     NOT_EMPTY_CLASS = 'ng-not-empty';
25610
25611 var ngModelMinErr = minErr('ngModel');
25612
25613 /**
25614  * @ngdoc type
25615  * @name ngModel.NgModelController
25616  *
25617  * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
25618  * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
25619  * is set.
25620  * @property {*} $modelValue The value in the model that the control is bound to.
25621  * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
25622        the control reads value from the DOM. The functions are called in array order, each passing
25623        its return value through to the next. The last return value is forwarded to the
25624        {@link ngModel.NgModelController#$validators `$validators`} collection.
25625
25626 Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
25627 `$viewValue`}.
25628
25629 Returning `undefined` from a parser means a parse error occurred. In that case,
25630 no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
25631 will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
25632 is set to `true`. The parse error is stored in `ngModel.$error.parse`.
25633
25634  *
25635  * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
25636        the model value changes. The functions are called in reverse array order, each passing the value through to the
25637        next. The last return value is used as the actual DOM value.
25638        Used to format / convert values for display in the control.
25639  * ```js
25640  * function formatter(value) {
25641  *   if (value) {
25642  *     return value.toUpperCase();
25643  *   }
25644  * }
25645  * ngModel.$formatters.push(formatter);
25646  * ```
25647  *
25648  * @property {Object.<string, function>} $validators A collection of validators that are applied
25649  *      whenever the model value changes. The key value within the object refers to the name of the
25650  *      validator while the function refers to the validation operation. The validation operation is
25651  *      provided with the model value as an argument and must return a true or false value depending
25652  *      on the response of that validation.
25653  *
25654  * ```js
25655  * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
25656  *   var value = modelValue || viewValue;
25657  *   return /[0-9]+/.test(value) &&
25658  *          /[a-z]+/.test(value) &&
25659  *          /[A-Z]+/.test(value) &&
25660  *          /\W+/.test(value);
25661  * };
25662  * ```
25663  *
25664  * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
25665  *      perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
25666  *      is expected to return a promise when it is run during the model validation process. Once the promise
25667  *      is delivered then the validation status will be set to true when fulfilled and false when rejected.
25668  *      When the asynchronous validators are triggered, each of the validators will run in parallel and the model
25669  *      value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
25670  *      is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
25671  *      will only run once all synchronous validators have passed.
25672  *
25673  * Please note that if $http is used then it is important that the server returns a success HTTP response code
25674  * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
25675  *
25676  * ```js
25677  * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
25678  *   var value = modelValue || viewValue;
25679  *
25680  *   // Lookup user by username
25681  *   return $http.get('/api/users/' + value).
25682  *      then(function resolved() {
25683  *        //username exists, this means validation fails
25684  *        return $q.reject('exists');
25685  *      }, function rejected() {
25686  *        //username does not exist, therefore this validation passes
25687  *        return true;
25688  *      });
25689  * };
25690  * ```
25691  *
25692  * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
25693  *     view value has changed. It is called with no arguments, and its return value is ignored.
25694  *     This can be used in place of additional $watches against the model value.
25695  *
25696  * @property {Object} $error An object hash with all failing validator ids as keys.
25697  * @property {Object} $pending An object hash with all pending validator ids as keys.
25698  *
25699  * @property {boolean} $untouched True if control has not lost focus yet.
25700  * @property {boolean} $touched True if control has lost focus.
25701  * @property {boolean} $pristine True if user has not interacted with the control yet.
25702  * @property {boolean} $dirty True if user has already interacted with the control.
25703  * @property {boolean} $valid True if there is no error.
25704  * @property {boolean} $invalid True if at least one error on the control.
25705  * @property {string} $name The name attribute of the control.
25706  *
25707  * @description
25708  *
25709  * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
25710  * The controller contains services for data-binding, validation, CSS updates, and value formatting
25711  * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
25712  * listening to DOM events.
25713  * Such DOM related logic should be provided by other directives which make use of
25714  * `NgModelController` for data-binding to control elements.
25715  * Angular provides this DOM logic for most {@link input `input`} elements.
25716  * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
25717  * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
25718  *
25719  * @example
25720  * ### Custom Control Example
25721  * This example shows how to use `NgModelController` with a custom control to achieve
25722  * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
25723  * collaborate together to achieve the desired result.
25724  *
25725  * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
25726  * contents be edited in place by the user.
25727  *
25728  * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
25729  * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
25730  * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
25731  * that content using the `$sce` service.
25732  *
25733  * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
25734     <file name="style.css">
25735       [contenteditable] {
25736         border: 1px solid black;
25737         background-color: white;
25738         min-height: 20px;
25739       }
25740
25741       .ng-invalid {
25742         border: 1px solid red;
25743       }
25744
25745     </file>
25746     <file name="script.js">
25747       angular.module('customControl', ['ngSanitize']).
25748         directive('contenteditable', ['$sce', function($sce) {
25749           return {
25750             restrict: 'A', // only activate on element attribute
25751             require: '?ngModel', // get a hold of NgModelController
25752             link: function(scope, element, attrs, ngModel) {
25753               if (!ngModel) return; // do nothing if no ng-model
25754
25755               // Specify how UI should be updated
25756               ngModel.$render = function() {
25757                 element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
25758               };
25759
25760               // Listen for change events to enable binding
25761               element.on('blur keyup change', function() {
25762                 scope.$evalAsync(read);
25763               });
25764               read(); // initialize
25765
25766               // Write data to the model
25767               function read() {
25768                 var html = element.html();
25769                 // When we clear the content editable the browser leaves a <br> behind
25770                 // If strip-br attribute is provided then we strip this out
25771                 if ( attrs.stripBr && html == '<br>' ) {
25772                   html = '';
25773                 }
25774                 ngModel.$setViewValue(html);
25775               }
25776             }
25777           };
25778         }]);
25779     </file>
25780     <file name="index.html">
25781       <form name="myForm">
25782        <div contenteditable
25783             name="myWidget" ng-model="userContent"
25784             strip-br="true"
25785             required>Change me!</div>
25786         <span ng-show="myForm.myWidget.$error.required">Required!</span>
25787        <hr>
25788        <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
25789       </form>
25790     </file>
25791     <file name="protractor.js" type="protractor">
25792     it('should data-bind and become invalid', function() {
25793       if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
25794         // SafariDriver can't handle contenteditable
25795         // and Firefox driver can't clear contenteditables very well
25796         return;
25797       }
25798       var contentEditable = element(by.css('[contenteditable]'));
25799       var content = 'Change me!';
25800
25801       expect(contentEditable.getText()).toEqual(content);
25802
25803       contentEditable.clear();
25804       contentEditable.sendKeys(protractor.Key.BACK_SPACE);
25805       expect(contentEditable.getText()).toEqual('');
25806       expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
25807     });
25808     </file>
25809  * </example>
25810  *
25811  *
25812  */
25813 var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
25814     function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
25815   this.$viewValue = Number.NaN;
25816   this.$modelValue = Number.NaN;
25817   this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
25818   this.$validators = {};
25819   this.$asyncValidators = {};
25820   this.$parsers = [];
25821   this.$formatters = [];
25822   this.$viewChangeListeners = [];
25823   this.$untouched = true;
25824   this.$touched = false;
25825   this.$pristine = true;
25826   this.$dirty = false;
25827   this.$valid = true;
25828   this.$invalid = false;
25829   this.$error = {}; // keep invalid keys here
25830   this.$$success = {}; // keep valid keys here
25831   this.$pending = undefined; // keep pending keys here
25832   this.$name = $interpolate($attr.name || '', false)($scope);
25833   this.$$parentForm = nullFormCtrl;
25834
25835   var parsedNgModel = $parse($attr.ngModel),
25836       parsedNgModelAssign = parsedNgModel.assign,
25837       ngModelGet = parsedNgModel,
25838       ngModelSet = parsedNgModelAssign,
25839       pendingDebounce = null,
25840       parserValid,
25841       ctrl = this;
25842
25843   this.$$setOptions = function(options) {
25844     ctrl.$options = options;
25845     if (options && options.getterSetter) {
25846       var invokeModelGetter = $parse($attr.ngModel + '()'),
25847           invokeModelSetter = $parse($attr.ngModel + '($$$p)');
25848
25849       ngModelGet = function($scope) {
25850         var modelValue = parsedNgModel($scope);
25851         if (isFunction(modelValue)) {
25852           modelValue = invokeModelGetter($scope);
25853         }
25854         return modelValue;
25855       };
25856       ngModelSet = function($scope, newValue) {
25857         if (isFunction(parsedNgModel($scope))) {
25858           invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
25859         } else {
25860           parsedNgModelAssign($scope, ctrl.$modelValue);
25861         }
25862       };
25863     } else if (!parsedNgModel.assign) {
25864       throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
25865           $attr.ngModel, startingTag($element));
25866     }
25867   };
25868
25869   /**
25870    * @ngdoc method
25871    * @name ngModel.NgModelController#$render
25872    *
25873    * @description
25874    * Called when the view needs to be updated. It is expected that the user of the ng-model
25875    * directive will implement this method.
25876    *
25877    * The `$render()` method is invoked in the following situations:
25878    *
25879    * * `$rollbackViewValue()` is called.  If we are rolling back the view value to the last
25880    *   committed value then `$render()` is called to update the input control.
25881    * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
25882    *   the `$viewValue` are different from last time.
25883    *
25884    * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
25885    * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
25886    * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
25887    * invoked if you only change a property on the objects.
25888    */
25889   this.$render = noop;
25890
25891   /**
25892    * @ngdoc method
25893    * @name ngModel.NgModelController#$isEmpty
25894    *
25895    * @description
25896    * This is called when we need to determine if the value of an input is empty.
25897    *
25898    * For instance, the required directive does this to work out if the input has data or not.
25899    *
25900    * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
25901    *
25902    * You can override this for input directives whose concept of being empty is different from the
25903    * default. The `checkboxInputType` directive does this because in its case a value of `false`
25904    * implies empty.
25905    *
25906    * @param {*} value The value of the input to check for emptiness.
25907    * @returns {boolean} True if `value` is "empty".
25908    */
25909   this.$isEmpty = function(value) {
25910     return isUndefined(value) || value === '' || value === null || value !== value;
25911   };
25912
25913   this.$$updateEmptyClasses = function(value) {
25914     if (ctrl.$isEmpty(value)) {
25915       $animate.removeClass($element, NOT_EMPTY_CLASS);
25916       $animate.addClass($element, EMPTY_CLASS);
25917     } else {
25918       $animate.removeClass($element, EMPTY_CLASS);
25919       $animate.addClass($element, NOT_EMPTY_CLASS);
25920     }
25921   };
25922
25923
25924   var currentValidationRunId = 0;
25925
25926   /**
25927    * @ngdoc method
25928    * @name ngModel.NgModelController#$setValidity
25929    *
25930    * @description
25931    * Change the validity state, and notify the form.
25932    *
25933    * This method can be called within $parsers/$formatters or a custom validation implementation.
25934    * However, in most cases it should be sufficient to use the `ngModel.$validators` and
25935    * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
25936    *
25937    * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
25938    *        to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
25939    *        (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
25940    *        The `validationErrorKey` should be in camelCase and will get converted into dash-case
25941    *        for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
25942    *        class and can be bound to as  `{{someForm.someControl.$error.myError}}` .
25943    * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
25944    *                          or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
25945    *                          Skipped is used by Angular when validators do not run because of parse errors and
25946    *                          when `$asyncValidators` do not run because any of the `$validators` failed.
25947    */
25948   addSetValidityMethod({
25949     ctrl: this,
25950     $element: $element,
25951     set: function(object, property) {
25952       object[property] = true;
25953     },
25954     unset: function(object, property) {
25955       delete object[property];
25956     },
25957     $animate: $animate
25958   });
25959
25960   /**
25961    * @ngdoc method
25962    * @name ngModel.NgModelController#$setPristine
25963    *
25964    * @description
25965    * Sets the control to its pristine state.
25966    *
25967    * This method can be called to remove the `ng-dirty` class and set the control to its pristine
25968    * state (`ng-pristine` class). A model is considered to be pristine when the control
25969    * has not been changed from when first compiled.
25970    */
25971   this.$setPristine = function() {
25972     ctrl.$dirty = false;
25973     ctrl.$pristine = true;
25974     $animate.removeClass($element, DIRTY_CLASS);
25975     $animate.addClass($element, PRISTINE_CLASS);
25976   };
25977
25978   /**
25979    * @ngdoc method
25980    * @name ngModel.NgModelController#$setDirty
25981    *
25982    * @description
25983    * Sets the control to its dirty state.
25984    *
25985    * This method can be called to remove the `ng-pristine` class and set the control to its dirty
25986    * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
25987    * from when first compiled.
25988    */
25989   this.$setDirty = function() {
25990     ctrl.$dirty = true;
25991     ctrl.$pristine = false;
25992     $animate.removeClass($element, PRISTINE_CLASS);
25993     $animate.addClass($element, DIRTY_CLASS);
25994     ctrl.$$parentForm.$setDirty();
25995   };
25996
25997   /**
25998    * @ngdoc method
25999    * @name ngModel.NgModelController#$setUntouched
26000    *
26001    * @description
26002    * Sets the control to its untouched state.
26003    *
26004    * This method can be called to remove the `ng-touched` class and set the control to its
26005    * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
26006    * by default, however this function can be used to restore that state if the model has
26007    * already been touched by the user.
26008    */
26009   this.$setUntouched = function() {
26010     ctrl.$touched = false;
26011     ctrl.$untouched = true;
26012     $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
26013   };
26014
26015   /**
26016    * @ngdoc method
26017    * @name ngModel.NgModelController#$setTouched
26018    *
26019    * @description
26020    * Sets the control to its touched state.
26021    *
26022    * This method can be called to remove the `ng-untouched` class and set the control to its
26023    * touched state (`ng-touched` class). A model is considered to be touched when the user has
26024    * first focused the control element and then shifted focus away from the control (blur event).
26025    */
26026   this.$setTouched = function() {
26027     ctrl.$touched = true;
26028     ctrl.$untouched = false;
26029     $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
26030   };
26031
26032   /**
26033    * @ngdoc method
26034    * @name ngModel.NgModelController#$rollbackViewValue
26035    *
26036    * @description
26037    * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
26038    * which may be caused by a pending debounced event or because the input is waiting for a some
26039    * future event.
26040    *
26041    * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
26042    * depend on special events such as blur, you can have a situation where there is a period when
26043    * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
26044    *
26045    * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
26046    * and reset the input to the last committed view value.
26047    *
26048    * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
26049    * programmatically before these debounced/future events have resolved/occurred, because Angular's
26050    * dirty checking mechanism is not able to tell whether the model has actually changed or not.
26051    *
26052    * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
26053    * input which may have such events pending. This is important in order to make sure that the
26054    * input field will be updated with the new model value and any pending operations are cancelled.
26055    *
26056    * <example name="ng-model-cancel-update" module="cancel-update-example">
26057    *   <file name="app.js">
26058    *     angular.module('cancel-update-example', [])
26059    *
26060    *     .controller('CancelUpdateController', ['$scope', function($scope) {
26061    *       $scope.model = {};
26062    *
26063    *       $scope.setEmpty = function(e, value, rollback) {
26064    *         if (e.keyCode == 27) {
26065    *           e.preventDefault();
26066    *           if (rollback) {
26067    *             $scope.myForm[value].$rollbackViewValue();
26068    *           }
26069    *           $scope.model[value] = '';
26070    *         }
26071    *       };
26072    *     }]);
26073    *   </file>
26074    *   <file name="index.html">
26075    *     <div ng-controller="CancelUpdateController">
26076    *        <p>Both of these inputs are only updated if they are blurred. Hitting escape should
26077    *        empty them. Follow these steps and observe the difference:</p>
26078    *       <ol>
26079    *         <li>Type something in the input. You will see that the model is not yet updated</li>
26080    *         <li>Press the Escape key.
26081    *           <ol>
26082    *             <li> In the first example, nothing happens, because the model is already '', and no
26083    *             update is detected. If you blur the input, the model will be set to the current view.
26084    *             </li>
26085    *             <li> In the second example, the pending update is cancelled, and the input is set back
26086    *             to the last committed view value (''). Blurring the input does nothing.
26087    *             </li>
26088    *           </ol>
26089    *         </li>
26090    *       </ol>
26091    *
26092    *       <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
26093    *         <div>
26094    *        <p id="inputDescription1">Without $rollbackViewValue():</p>
26095    *         <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
26096    *                ng-keydown="setEmpty($event, 'value1')">
26097    *         value1: "{{ model.value1 }}"
26098    *         </div>
26099    *
26100    *         <div>
26101    *        <p id="inputDescription2">With $rollbackViewValue():</p>
26102    *         <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
26103    *                ng-keydown="setEmpty($event, 'value2', true)">
26104    *         value2: "{{ model.value2 }}"
26105    *         </div>
26106    *       </form>
26107    *     </div>
26108    *   </file>
26109        <file name="style.css">
26110           div {
26111             display: table-cell;
26112           }
26113           div:nth-child(1) {
26114             padding-right: 30px;
26115           }
26116
26117         </file>
26118    * </example>
26119    */
26120   this.$rollbackViewValue = function() {
26121     $timeout.cancel(pendingDebounce);
26122     ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
26123     ctrl.$render();
26124   };
26125
26126   /**
26127    * @ngdoc method
26128    * @name ngModel.NgModelController#$validate
26129    *
26130    * @description
26131    * Runs each of the registered validators (first synchronous validators and then
26132    * asynchronous validators).
26133    * If the validity changes to invalid, the model will be set to `undefined`,
26134    * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
26135    * If the validity changes to valid, it will set the model to the last available valid
26136    * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
26137    */
26138   this.$validate = function() {
26139     // ignore $validate before model is initialized
26140     if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
26141       return;
26142     }
26143
26144     var viewValue = ctrl.$$lastCommittedViewValue;
26145     // Note: we use the $$rawModelValue as $modelValue might have been
26146     // set to undefined during a view -> model update that found validation
26147     // errors. We can't parse the view here, since that could change
26148     // the model although neither viewValue nor the model on the scope changed
26149     var modelValue = ctrl.$$rawModelValue;
26150
26151     var prevValid = ctrl.$valid;
26152     var prevModelValue = ctrl.$modelValue;
26153
26154     var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
26155
26156     ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
26157       // If there was no change in validity, don't update the model
26158       // This prevents changing an invalid modelValue to undefined
26159       if (!allowInvalid && prevValid !== allValid) {
26160         // Note: Don't check ctrl.$valid here, as we could have
26161         // external validators (e.g. calculated on the server),
26162         // that just call $setValidity and need the model value
26163         // to calculate their validity.
26164         ctrl.$modelValue = allValid ? modelValue : undefined;
26165
26166         if (ctrl.$modelValue !== prevModelValue) {
26167           ctrl.$$writeModelToScope();
26168         }
26169       }
26170     });
26171
26172   };
26173
26174   this.$$runValidators = function(modelValue, viewValue, doneCallback) {
26175     currentValidationRunId++;
26176     var localValidationRunId = currentValidationRunId;
26177
26178     // check parser error
26179     if (!processParseErrors()) {
26180       validationDone(false);
26181       return;
26182     }
26183     if (!processSyncValidators()) {
26184       validationDone(false);
26185       return;
26186     }
26187     processAsyncValidators();
26188
26189     function processParseErrors() {
26190       var errorKey = ctrl.$$parserName || 'parse';
26191       if (isUndefined(parserValid)) {
26192         setValidity(errorKey, null);
26193       } else {
26194         if (!parserValid) {
26195           forEach(ctrl.$validators, function(v, name) {
26196             setValidity(name, null);
26197           });
26198           forEach(ctrl.$asyncValidators, function(v, name) {
26199             setValidity(name, null);
26200           });
26201         }
26202         // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
26203         setValidity(errorKey, parserValid);
26204         return parserValid;
26205       }
26206       return true;
26207     }
26208
26209     function processSyncValidators() {
26210       var syncValidatorsValid = true;
26211       forEach(ctrl.$validators, function(validator, name) {
26212         var result = validator(modelValue, viewValue);
26213         syncValidatorsValid = syncValidatorsValid && result;
26214         setValidity(name, result);
26215       });
26216       if (!syncValidatorsValid) {
26217         forEach(ctrl.$asyncValidators, function(v, name) {
26218           setValidity(name, null);
26219         });
26220         return false;
26221       }
26222       return true;
26223     }
26224
26225     function processAsyncValidators() {
26226       var validatorPromises = [];
26227       var allValid = true;
26228       forEach(ctrl.$asyncValidators, function(validator, name) {
26229         var promise = validator(modelValue, viewValue);
26230         if (!isPromiseLike(promise)) {
26231           throw ngModelMinErr('nopromise',
26232             "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
26233         }
26234         setValidity(name, undefined);
26235         validatorPromises.push(promise.then(function() {
26236           setValidity(name, true);
26237         }, function(error) {
26238           allValid = false;
26239           setValidity(name, false);
26240         }));
26241       });
26242       if (!validatorPromises.length) {
26243         validationDone(true);
26244       } else {
26245         $q.all(validatorPromises).then(function() {
26246           validationDone(allValid);
26247         }, noop);
26248       }
26249     }
26250
26251     function setValidity(name, isValid) {
26252       if (localValidationRunId === currentValidationRunId) {
26253         ctrl.$setValidity(name, isValid);
26254       }
26255     }
26256
26257     function validationDone(allValid) {
26258       if (localValidationRunId === currentValidationRunId) {
26259
26260         doneCallback(allValid);
26261       }
26262     }
26263   };
26264
26265   /**
26266    * @ngdoc method
26267    * @name ngModel.NgModelController#$commitViewValue
26268    *
26269    * @description
26270    * Commit a pending update to the `$modelValue`.
26271    *
26272    * Updates may be pending by a debounced event or because the input is waiting for a some future
26273    * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
26274    * usually handles calling this in response to input events.
26275    */
26276   this.$commitViewValue = function() {
26277     var viewValue = ctrl.$viewValue;
26278
26279     $timeout.cancel(pendingDebounce);
26280
26281     // If the view value has not changed then we should just exit, except in the case where there is
26282     // a native validator on the element. In this case the validation state may have changed even though
26283     // the viewValue has stayed empty.
26284     if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
26285       return;
26286     }
26287     ctrl.$$updateEmptyClasses(viewValue);
26288     ctrl.$$lastCommittedViewValue = viewValue;
26289
26290     // change to dirty
26291     if (ctrl.$pristine) {
26292       this.$setDirty();
26293     }
26294     this.$$parseAndValidate();
26295   };
26296
26297   this.$$parseAndValidate = function() {
26298     var viewValue = ctrl.$$lastCommittedViewValue;
26299     var modelValue = viewValue;
26300     parserValid = isUndefined(modelValue) ? undefined : true;
26301
26302     if (parserValid) {
26303       for (var i = 0; i < ctrl.$parsers.length; i++) {
26304         modelValue = ctrl.$parsers[i](modelValue);
26305         if (isUndefined(modelValue)) {
26306           parserValid = false;
26307           break;
26308         }
26309       }
26310     }
26311     if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
26312       // ctrl.$modelValue has not been touched yet...
26313       ctrl.$modelValue = ngModelGet($scope);
26314     }
26315     var prevModelValue = ctrl.$modelValue;
26316     var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
26317     ctrl.$$rawModelValue = modelValue;
26318
26319     if (allowInvalid) {
26320       ctrl.$modelValue = modelValue;
26321       writeToModelIfNeeded();
26322     }
26323
26324     // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
26325     // This can happen if e.g. $setViewValue is called from inside a parser
26326     ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
26327       if (!allowInvalid) {
26328         // Note: Don't check ctrl.$valid here, as we could have
26329         // external validators (e.g. calculated on the server),
26330         // that just call $setValidity and need the model value
26331         // to calculate their validity.
26332         ctrl.$modelValue = allValid ? modelValue : undefined;
26333         writeToModelIfNeeded();
26334       }
26335     });
26336
26337     function writeToModelIfNeeded() {
26338       if (ctrl.$modelValue !== prevModelValue) {
26339         ctrl.$$writeModelToScope();
26340       }
26341     }
26342   };
26343
26344   this.$$writeModelToScope = function() {
26345     ngModelSet($scope, ctrl.$modelValue);
26346     forEach(ctrl.$viewChangeListeners, function(listener) {
26347       try {
26348         listener();
26349       } catch (e) {
26350         $exceptionHandler(e);
26351       }
26352     });
26353   };
26354
26355   /**
26356    * @ngdoc method
26357    * @name ngModel.NgModelController#$setViewValue
26358    *
26359    * @description
26360    * Update the view value.
26361    *
26362    * This method should be called when a control wants to change the view value; typically,
26363    * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
26364    * directive calls it when the value of the input changes and {@link ng.directive:select select}
26365    * calls it when an option is selected.
26366    *
26367    * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
26368    * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
26369    * value sent directly for processing, finally to be applied to `$modelValue` and then the
26370    * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
26371    * in the `$viewChangeListeners` list, are called.
26372    *
26373    * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
26374    * and the `default` trigger is not listed, all those actions will remain pending until one of the
26375    * `updateOn` events is triggered on the DOM element.
26376    * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
26377    * directive is used with a custom debounce for this particular event.
26378    * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
26379    * is specified, once the timer runs out.
26380    *
26381    * When used with standard inputs, the view value will always be a string (which is in some cases
26382    * parsed into another type, such as a `Date` object for `input[date]`.)
26383    * However, custom controls might also pass objects to this method. In this case, we should make
26384    * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
26385    * perform a deep watch of objects, it only looks for a change of identity. If you only change
26386    * the property of the object then ngModel will not realize that the object has changed and
26387    * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
26388    * not change properties of the copy once it has been passed to `$setViewValue`.
26389    * Otherwise you may cause the model value on the scope to change incorrectly.
26390    *
26391    * <div class="alert alert-info">
26392    * In any case, the value passed to the method should always reflect the current value
26393    * of the control. For example, if you are calling `$setViewValue` for an input element,
26394    * you should pass the input DOM value. Otherwise, the control and the scope model become
26395    * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
26396    * the control's DOM value in any way. If we want to change the control's DOM value
26397    * programmatically, we should update the `ngModel` scope expression. Its new value will be
26398    * picked up by the model controller, which will run it through the `$formatters`, `$render` it
26399    * to update the DOM, and finally call `$validate` on it.
26400    * </div>
26401    *
26402    * @param {*} value value from the view.
26403    * @param {string} trigger Event that triggered the update.
26404    */
26405   this.$setViewValue = function(value, trigger) {
26406     ctrl.$viewValue = value;
26407     if (!ctrl.$options || ctrl.$options.updateOnDefault) {
26408       ctrl.$$debounceViewValueCommit(trigger);
26409     }
26410   };
26411
26412   this.$$debounceViewValueCommit = function(trigger) {
26413     var debounceDelay = 0,
26414         options = ctrl.$options,
26415         debounce;
26416
26417     if (options && isDefined(options.debounce)) {
26418       debounce = options.debounce;
26419       if (isNumber(debounce)) {
26420         debounceDelay = debounce;
26421       } else if (isNumber(debounce[trigger])) {
26422         debounceDelay = debounce[trigger];
26423       } else if (isNumber(debounce['default'])) {
26424         debounceDelay = debounce['default'];
26425       }
26426     }
26427
26428     $timeout.cancel(pendingDebounce);
26429     if (debounceDelay) {
26430       pendingDebounce = $timeout(function() {
26431         ctrl.$commitViewValue();
26432       }, debounceDelay);
26433     } else if ($rootScope.$$phase) {
26434       ctrl.$commitViewValue();
26435     } else {
26436       $scope.$apply(function() {
26437         ctrl.$commitViewValue();
26438       });
26439     }
26440   };
26441
26442   // model -> value
26443   // Note: we cannot use a normal scope.$watch as we want to detect the following:
26444   // 1. scope value is 'a'
26445   // 2. user enters 'b'
26446   // 3. ng-change kicks in and reverts scope value to 'a'
26447   //    -> scope value did not change since the last digest as
26448   //       ng-change executes in apply phase
26449   // 4. view should be changed back to 'a'
26450   $scope.$watch(function ngModelWatch() {
26451     var modelValue = ngModelGet($scope);
26452
26453     // if scope model value and ngModel value are out of sync
26454     // TODO(perf): why not move this to the action fn?
26455     if (modelValue !== ctrl.$modelValue &&
26456        // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
26457        (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
26458     ) {
26459       ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
26460       parserValid = undefined;
26461
26462       var formatters = ctrl.$formatters,
26463           idx = formatters.length;
26464
26465       var viewValue = modelValue;
26466       while (idx--) {
26467         viewValue = formatters[idx](viewValue);
26468       }
26469       if (ctrl.$viewValue !== viewValue) {
26470         ctrl.$$updateEmptyClasses(viewValue);
26471         ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
26472         ctrl.$render();
26473
26474         ctrl.$$runValidators(modelValue, viewValue, noop);
26475       }
26476     }
26477
26478     return modelValue;
26479   });
26480 }];
26481
26482
26483 /**
26484  * @ngdoc directive
26485  * @name ngModel
26486  *
26487  * @element input
26488  * @priority 1
26489  *
26490  * @description
26491  * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
26492  * property on the scope using {@link ngModel.NgModelController NgModelController},
26493  * which is created and exposed by this directive.
26494  *
26495  * `ngModel` is responsible for:
26496  *
26497  * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
26498  *   require.
26499  * - Providing validation behavior (i.e. required, number, email, url).
26500  * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
26501  * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
26502  *   `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
26503  * - Registering the control with its parent {@link ng.directive:form form}.
26504  *
26505  * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
26506  * current scope. If the property doesn't already exist on this scope, it will be created
26507  * implicitly and added to the scope.
26508  *
26509  * For best practices on using `ngModel`, see:
26510  *
26511  *  - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
26512  *
26513  * For basic examples, how to use `ngModel`, see:
26514  *
26515  *  - {@link ng.directive:input input}
26516  *    - {@link input[text] text}
26517  *    - {@link input[checkbox] checkbox}
26518  *    - {@link input[radio] radio}
26519  *    - {@link input[number] number}
26520  *    - {@link input[email] email}
26521  *    - {@link input[url] url}
26522  *    - {@link input[date] date}
26523  *    - {@link input[datetime-local] datetime-local}
26524  *    - {@link input[time] time}
26525  *    - {@link input[month] month}
26526  *    - {@link input[week] week}
26527  *  - {@link ng.directive:select select}
26528  *  - {@link ng.directive:textarea textarea}
26529  *
26530  * # Complex Models (objects or collections)
26531  *
26532  * By default, `ngModel` watches the model by reference, not value. This is important to know when
26533  * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
26534  * object or collection change, `ngModel` will not be notified and so the input will not be  re-rendered.
26535  *
26536  * The model must be assigned an entirely new object or collection before a re-rendering will occur.
26537  *
26538  * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
26539  * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
26540  * if the select is given the `multiple` attribute.
26541  *
26542  * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
26543  * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
26544  * not trigger a re-rendering of the model.
26545  *
26546  * # CSS classes
26547  * The following CSS classes are added and removed on the associated input/select/textarea element
26548  * depending on the validity of the model.
26549  *
26550  *  - `ng-valid`: the model is valid
26551  *  - `ng-invalid`: the model is invalid
26552  *  - `ng-valid-[key]`: for each valid key added by `$setValidity`
26553  *  - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
26554  *  - `ng-pristine`: the control hasn't been interacted with yet
26555  *  - `ng-dirty`: the control has been interacted with
26556  *  - `ng-touched`: the control has been blurred
26557  *  - `ng-untouched`: the control hasn't been blurred
26558  *  - `ng-pending`: any `$asyncValidators` are unfulfilled
26559  *  - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
26560  *     by the {@link ngModel.NgModelController#$isEmpty} method
26561  *  - `ng-not-empty`: the view contains a non-empty value
26562  *
26563  * Keep in mind that ngAnimate can detect each of these classes when added and removed.
26564  *
26565  * ## Animation Hooks
26566  *
26567  * Animations within models are triggered when any of the associated CSS classes are added and removed
26568  * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
26569  * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
26570  * The animations that are triggered within ngModel are similar to how they work in ngClass and
26571  * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
26572  *
26573  * The following example shows a simple way to utilize CSS transitions to style an input element
26574  * that has been rendered as invalid after it has been validated:
26575  *
26576  * <pre>
26577  * //be sure to include ngAnimate as a module to hook into more
26578  * //advanced animations
26579  * .my-input {
26580  *   transition:0.5s linear all;
26581  *   background: white;
26582  * }
26583  * .my-input.ng-invalid {
26584  *   background: red;
26585  *   color:white;
26586  * }
26587  * </pre>
26588  *
26589  * @example
26590  * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
26591      <file name="index.html">
26592        <script>
26593         angular.module('inputExample', [])
26594           .controller('ExampleController', ['$scope', function($scope) {
26595             $scope.val = '1';
26596           }]);
26597        </script>
26598        <style>
26599          .my-input {
26600            transition:all linear 0.5s;
26601            background: transparent;
26602          }
26603          .my-input.ng-invalid {
26604            color:white;
26605            background: red;
26606          }
26607        </style>
26608        <p id="inputDescription">
26609         Update input to see transitions when valid/invalid.
26610         Integer is a valid value.
26611        </p>
26612        <form name="testForm" ng-controller="ExampleController">
26613          <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
26614                 aria-describedby="inputDescription" />
26615        </form>
26616      </file>
26617  * </example>
26618  *
26619  * ## Binding to a getter/setter
26620  *
26621  * Sometimes it's helpful to bind `ngModel` to a getter/setter function.  A getter/setter is a
26622  * function that returns a representation of the model when called with zero arguments, and sets
26623  * the internal state of a model when called with an argument. It's sometimes useful to use this
26624  * for models that have an internal representation that's different from what the model exposes
26625  * to the view.
26626  *
26627  * <div class="alert alert-success">
26628  * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
26629  * frequently than other parts of your code.
26630  * </div>
26631  *
26632  * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
26633  * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
26634  * a `<form>`, which will enable this behavior for all `<input>`s within it. See
26635  * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
26636  *
26637  * The following example shows how to use `ngModel` with a getter/setter:
26638  *
26639  * @example
26640  * <example name="ngModel-getter-setter" module="getterSetterExample">
26641      <file name="index.html">
26642        <div ng-controller="ExampleController">
26643          <form name="userForm">
26644            <label>Name:
26645              <input type="text" name="userName"
26646                     ng-model="user.name"
26647                     ng-model-options="{ getterSetter: true }" />
26648            </label>
26649          </form>
26650          <pre>user.name = <span ng-bind="user.name()"></span></pre>
26651        </div>
26652      </file>
26653      <file name="app.js">
26654        angular.module('getterSetterExample', [])
26655          .controller('ExampleController', ['$scope', function($scope) {
26656            var _name = 'Brian';
26657            $scope.user = {
26658              name: function(newName) {
26659               // Note that newName can be undefined for two reasons:
26660               // 1. Because it is called as a getter and thus called with no arguments
26661               // 2. Because the property should actually be set to undefined. This happens e.g. if the
26662               //    input is invalid
26663               return arguments.length ? (_name = newName) : _name;
26664              }
26665            };
26666          }]);
26667      </file>
26668  * </example>
26669  */
26670 var ngModelDirective = ['$rootScope', function($rootScope) {
26671   return {
26672     restrict: 'A',
26673     require: ['ngModel', '^?form', '^?ngModelOptions'],
26674     controller: NgModelController,
26675     // Prelink needs to run before any input directive
26676     // so that we can set the NgModelOptions in NgModelController
26677     // before anyone else uses it.
26678     priority: 1,
26679     compile: function ngModelCompile(element) {
26680       // Setup initial state of the control
26681       element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
26682
26683       return {
26684         pre: function ngModelPreLink(scope, element, attr, ctrls) {
26685           var modelCtrl = ctrls[0],
26686               formCtrl = ctrls[1] || modelCtrl.$$parentForm;
26687
26688           modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
26689
26690           // notify others, especially parent forms
26691           formCtrl.$addControl(modelCtrl);
26692
26693           attr.$observe('name', function(newValue) {
26694             if (modelCtrl.$name !== newValue) {
26695               modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
26696             }
26697           });
26698
26699           scope.$on('$destroy', function() {
26700             modelCtrl.$$parentForm.$removeControl(modelCtrl);
26701           });
26702         },
26703         post: function ngModelPostLink(scope, element, attr, ctrls) {
26704           var modelCtrl = ctrls[0];
26705           if (modelCtrl.$options && modelCtrl.$options.updateOn) {
26706             element.on(modelCtrl.$options.updateOn, function(ev) {
26707               modelCtrl.$$debounceViewValueCommit(ev && ev.type);
26708             });
26709           }
26710
26711           element.on('blur', function(ev) {
26712             if (modelCtrl.$touched) return;
26713
26714             if ($rootScope.$$phase) {
26715               scope.$evalAsync(modelCtrl.$setTouched);
26716             } else {
26717               scope.$apply(modelCtrl.$setTouched);
26718             }
26719           });
26720         }
26721       };
26722     }
26723   };
26724 }];
26725
26726 var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
26727
26728 /**
26729  * @ngdoc directive
26730  * @name ngModelOptions
26731  *
26732  * @description
26733  * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
26734  * events that will trigger a model update and/or a debouncing delay so that the actual update only
26735  * takes place when a timer expires; this timer will be reset after another change takes place.
26736  *
26737  * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
26738  * be different from the value in the actual model. This means that if you update the model you
26739  * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
26740  * order to make sure it is synchronized with the model and that any debounced action is canceled.
26741  *
26742  * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
26743  * method is by making sure the input is placed inside a form that has a `name` attribute. This is
26744  * important because `form` controllers are published to the related scope under the name in their
26745  * `name` attribute.
26746  *
26747  * Any pending changes will take place immediately when an enclosing form is submitted via the
26748  * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
26749  * to have access to the updated model.
26750  *
26751  * `ngModelOptions` has an effect on the element it's declared on and its descendants.
26752  *
26753  * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
26754  *   - `updateOn`: string specifying which event should the input be bound to. You can set several
26755  *     events using an space delimited list. There is a special event called `default` that
26756  *     matches the default events belonging of the control.
26757  *   - `debounce`: integer value which contains the debounce model update value in milliseconds. A
26758  *     value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
26759  *     custom value for each event. For example:
26760  *     `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
26761  *   - `allowInvalid`: boolean value which indicates that the model can be set with values that did
26762  *     not validate correctly instead of the default behavior of setting the model to undefined.
26763  *   - `getterSetter`: boolean value which determines whether or not to treat functions bound to
26764        `ngModel` as getters/setters.
26765  *   - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
26766  *     `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
26767  *     continental US time zone abbreviations, but for general use, use a time zone offset, for
26768  *     example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
26769  *     If not specified, the timezone of the browser will be used.
26770  *
26771  * @example
26772
26773   The following example shows how to override immediate updates. Changes on the inputs within the
26774   form will update the model only when the control loses focus (blur event). If `escape` key is
26775   pressed while the input field is focused, the value is reset to the value in the current model.
26776
26777   <example name="ngModelOptions-directive-blur" module="optionsExample">
26778     <file name="index.html">
26779       <div ng-controller="ExampleController">
26780         <form name="userForm">
26781           <label>Name:
26782             <input type="text" name="userName"
26783                    ng-model="user.name"
26784                    ng-model-options="{ updateOn: 'blur' }"
26785                    ng-keyup="cancel($event)" />
26786           </label><br />
26787           <label>Other data:
26788             <input type="text" ng-model="user.data" />
26789           </label><br />
26790         </form>
26791         <pre>user.name = <span ng-bind="user.name"></span></pre>
26792         <pre>user.data = <span ng-bind="user.data"></span></pre>
26793       </div>
26794     </file>
26795     <file name="app.js">
26796       angular.module('optionsExample', [])
26797         .controller('ExampleController', ['$scope', function($scope) {
26798           $scope.user = { name: 'John', data: '' };
26799
26800           $scope.cancel = function(e) {
26801             if (e.keyCode == 27) {
26802               $scope.userForm.userName.$rollbackViewValue();
26803             }
26804           };
26805         }]);
26806     </file>
26807     <file name="protractor.js" type="protractor">
26808       var model = element(by.binding('user.name'));
26809       var input = element(by.model('user.name'));
26810       var other = element(by.model('user.data'));
26811
26812       it('should allow custom events', function() {
26813         input.sendKeys(' Doe');
26814         input.click();
26815         expect(model.getText()).toEqual('John');
26816         other.click();
26817         expect(model.getText()).toEqual('John Doe');
26818       });
26819
26820       it('should $rollbackViewValue when model changes', function() {
26821         input.sendKeys(' Doe');
26822         expect(input.getAttribute('value')).toEqual('John Doe');
26823         input.sendKeys(protractor.Key.ESCAPE);
26824         expect(input.getAttribute('value')).toEqual('John');
26825         other.click();
26826         expect(model.getText()).toEqual('John');
26827       });
26828     </file>
26829   </example>
26830
26831   This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
26832   If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
26833
26834   <example name="ngModelOptions-directive-debounce" module="optionsExample">
26835     <file name="index.html">
26836       <div ng-controller="ExampleController">
26837         <form name="userForm">
26838           <label>Name:
26839             <input type="text" name="userName"
26840                    ng-model="user.name"
26841                    ng-model-options="{ debounce: 1000 }" />
26842           </label>
26843           <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
26844           <br />
26845         </form>
26846         <pre>user.name = <span ng-bind="user.name"></span></pre>
26847       </div>
26848     </file>
26849     <file name="app.js">
26850       angular.module('optionsExample', [])
26851         .controller('ExampleController', ['$scope', function($scope) {
26852           $scope.user = { name: 'Igor' };
26853         }]);
26854     </file>
26855   </example>
26856
26857   This one shows how to bind to getter/setters:
26858
26859   <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
26860     <file name="index.html">
26861       <div ng-controller="ExampleController">
26862         <form name="userForm">
26863           <label>Name:
26864             <input type="text" name="userName"
26865                    ng-model="user.name"
26866                    ng-model-options="{ getterSetter: true }" />
26867           </label>
26868         </form>
26869         <pre>user.name = <span ng-bind="user.name()"></span></pre>
26870       </div>
26871     </file>
26872     <file name="app.js">
26873       angular.module('getterSetterExample', [])
26874         .controller('ExampleController', ['$scope', function($scope) {
26875           var _name = 'Brian';
26876           $scope.user = {
26877             name: function(newName) {
26878               // Note that newName can be undefined for two reasons:
26879               // 1. Because it is called as a getter and thus called with no arguments
26880               // 2. Because the property should actually be set to undefined. This happens e.g. if the
26881               //    input is invalid
26882               return arguments.length ? (_name = newName) : _name;
26883             }
26884           };
26885         }]);
26886     </file>
26887   </example>
26888  */
26889 var ngModelOptionsDirective = function() {
26890   return {
26891     restrict: 'A',
26892     controller: ['$scope', '$attrs', function($scope, $attrs) {
26893       var that = this;
26894       this.$options = copy($scope.$eval($attrs.ngModelOptions));
26895       // Allow adding/overriding bound events
26896       if (isDefined(this.$options.updateOn)) {
26897         this.$options.updateOnDefault = false;
26898         // extract "default" pseudo-event from list of events that can trigger a model update
26899         this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
26900           that.$options.updateOnDefault = true;
26901           return ' ';
26902         }));
26903       } else {
26904         this.$options.updateOnDefault = true;
26905       }
26906     }]
26907   };
26908 };
26909
26910
26911
26912 // helper methods
26913 function addSetValidityMethod(context) {
26914   var ctrl = context.ctrl,
26915       $element = context.$element,
26916       classCache = {},
26917       set = context.set,
26918       unset = context.unset,
26919       $animate = context.$animate;
26920
26921   classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
26922
26923   ctrl.$setValidity = setValidity;
26924
26925   function setValidity(validationErrorKey, state, controller) {
26926     if (isUndefined(state)) {
26927       createAndSet('$pending', validationErrorKey, controller);
26928     } else {
26929       unsetAndCleanup('$pending', validationErrorKey, controller);
26930     }
26931     if (!isBoolean(state)) {
26932       unset(ctrl.$error, validationErrorKey, controller);
26933       unset(ctrl.$$success, validationErrorKey, controller);
26934     } else {
26935       if (state) {
26936         unset(ctrl.$error, validationErrorKey, controller);
26937         set(ctrl.$$success, validationErrorKey, controller);
26938       } else {
26939         set(ctrl.$error, validationErrorKey, controller);
26940         unset(ctrl.$$success, validationErrorKey, controller);
26941       }
26942     }
26943     if (ctrl.$pending) {
26944       cachedToggleClass(PENDING_CLASS, true);
26945       ctrl.$valid = ctrl.$invalid = undefined;
26946       toggleValidationCss('', null);
26947     } else {
26948       cachedToggleClass(PENDING_CLASS, false);
26949       ctrl.$valid = isObjectEmpty(ctrl.$error);
26950       ctrl.$invalid = !ctrl.$valid;
26951       toggleValidationCss('', ctrl.$valid);
26952     }
26953
26954     // re-read the state as the set/unset methods could have
26955     // combined state in ctrl.$error[validationError] (used for forms),
26956     // where setting/unsetting only increments/decrements the value,
26957     // and does not replace it.
26958     var combinedState;
26959     if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
26960       combinedState = undefined;
26961     } else if (ctrl.$error[validationErrorKey]) {
26962       combinedState = false;
26963     } else if (ctrl.$$success[validationErrorKey]) {
26964       combinedState = true;
26965     } else {
26966       combinedState = null;
26967     }
26968
26969     toggleValidationCss(validationErrorKey, combinedState);
26970     ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
26971   }
26972
26973   function createAndSet(name, value, controller) {
26974     if (!ctrl[name]) {
26975       ctrl[name] = {};
26976     }
26977     set(ctrl[name], value, controller);
26978   }
26979
26980   function unsetAndCleanup(name, value, controller) {
26981     if (ctrl[name]) {
26982       unset(ctrl[name], value, controller);
26983     }
26984     if (isObjectEmpty(ctrl[name])) {
26985       ctrl[name] = undefined;
26986     }
26987   }
26988
26989   function cachedToggleClass(className, switchValue) {
26990     if (switchValue && !classCache[className]) {
26991       $animate.addClass($element, className);
26992       classCache[className] = true;
26993     } else if (!switchValue && classCache[className]) {
26994       $animate.removeClass($element, className);
26995       classCache[className] = false;
26996     }
26997   }
26998
26999   function toggleValidationCss(validationErrorKey, isValid) {
27000     validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
27001
27002     cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
27003     cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
27004   }
27005 }
27006
27007 function isObjectEmpty(obj) {
27008   if (obj) {
27009     for (var prop in obj) {
27010       if (obj.hasOwnProperty(prop)) {
27011         return false;
27012       }
27013     }
27014   }
27015   return true;
27016 }
27017
27018 /**
27019  * @ngdoc directive
27020  * @name ngNonBindable
27021  * @restrict AC
27022  * @priority 1000
27023  *
27024  * @description
27025  * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
27026  * DOM element. This is useful if the element contains what appears to be Angular directives and
27027  * bindings but which should be ignored by Angular. This could be the case if you have a site that
27028  * displays snippets of code, for instance.
27029  *
27030  * @element ANY
27031  *
27032  * @example
27033  * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
27034  * but the one wrapped in `ngNonBindable` is left alone.
27035  *
27036  * @example
27037     <example>
27038       <file name="index.html">
27039         <div>Normal: {{1 + 2}}</div>
27040         <div ng-non-bindable>Ignored: {{1 + 2}}</div>
27041       </file>
27042       <file name="protractor.js" type="protractor">
27043        it('should check ng-non-bindable', function() {
27044          expect(element(by.binding('1 + 2')).getText()).toContain('3');
27045          expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
27046        });
27047       </file>
27048     </example>
27049  */
27050 var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
27051
27052 /* global jqLiteRemove */
27053
27054 var ngOptionsMinErr = minErr('ngOptions');
27055
27056 /**
27057  * @ngdoc directive
27058  * @name ngOptions
27059  * @restrict A
27060  *
27061  * @description
27062  *
27063  * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
27064  * elements for the `<select>` element using the array or object obtained by evaluating the
27065  * `ngOptions` comprehension expression.
27066  *
27067  * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
27068  * similar result. However, `ngOptions` provides some benefits such as reducing memory and
27069  * increasing speed by not creating a new scope for each repeated instance, as well as providing
27070  * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
27071  * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
27072  *  to a non-string value. This is because an option element can only be bound to string values at
27073  * present.
27074  *
27075  * When an item in the `<select>` menu is selected, the array element or object property
27076  * represented by the selected option will be bound to the model identified by the `ngModel`
27077  * directive.
27078  *
27079  * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
27080  * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
27081  * option. See example below for demonstration.
27082  *
27083  * ## Complex Models (objects or collections)
27084  *
27085  * By default, `ngModel` watches the model by reference, not value. This is important to know when
27086  * binding the select to a model that is an object or a collection.
27087  *
27088  * One issue occurs if you want to preselect an option. For example, if you set
27089  * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
27090  * because the objects are not identical. So by default, you should always reference the item in your collection
27091  * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
27092  *
27093  * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
27094  * of the item not by reference, but by the result of the `track by` expression. For example, if your
27095  * collection items have an id property, you would `track by item.id`.
27096  *
27097  * A different issue with objects or collections is that ngModel won't detect if an object property or
27098  * a collection item changes. For that reason, `ngOptions` additionally watches the model using
27099  * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
27100  * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
27101  * has not changed identity, but only a property on the object or an item in the collection changes.
27102  *
27103  * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
27104  * if the model is an array). This means that changing a property deeper than the first level inside the
27105  * object/collection will not trigger a re-rendering.
27106  *
27107  * ## `select` **`as`**
27108  *
27109  * Using `select` **`as`** will bind the result of the `select` expression to the model, but
27110  * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
27111  * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
27112  * is used, the result of that expression will be set as the value of the `option` and `select` elements.
27113  *
27114  *
27115  * ### `select` **`as`** and **`track by`**
27116  *
27117  * <div class="alert alert-warning">
27118  * Be careful when using `select` **`as`** and **`track by`** in the same expression.
27119  * </div>
27120  *
27121  * Given this array of items on the $scope:
27122  *
27123  * ```js
27124  * $scope.items = [{
27125  *   id: 1,
27126  *   label: 'aLabel',
27127  *   subItem: { name: 'aSubItem' }
27128  * }, {
27129  *   id: 2,
27130  *   label: 'bLabel',
27131  *   subItem: { name: 'bSubItem' }
27132  * }];
27133  * ```
27134  *
27135  * This will work:
27136  *
27137  * ```html
27138  * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
27139  * ```
27140  * ```js
27141  * $scope.selected = $scope.items[0];
27142  * ```
27143  *
27144  * but this will not work:
27145  *
27146  * ```html
27147  * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
27148  * ```
27149  * ```js
27150  * $scope.selected = $scope.items[0].subItem;
27151  * ```
27152  *
27153  * In both examples, the **`track by`** expression is applied successfully to each `item` in the
27154  * `items` array. Because the selected option has been set programmatically in the controller, the
27155  * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
27156  * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
27157  * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
27158  * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
27159  * is not matched against any `<option>` and the `<select>` appears as having no selected value.
27160  *
27161  *
27162  * @param {string} ngModel Assignable angular expression to data-bind to.
27163  * @param {string=} name Property name of the form under which the control is published.
27164  * @param {string=} required The control is considered valid only if value is entered.
27165  * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
27166  *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
27167  *    `required` when you want to data-bind to the `required` attribute.
27168  * @param {comprehension_expression=} ngOptions in one of the following forms:
27169  *
27170  *   * for array data sources:
27171  *     * `label` **`for`** `value` **`in`** `array`
27172  *     * `select` **`as`** `label` **`for`** `value` **`in`** `array`
27173  *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
27174  *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
27175  *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
27176  *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
27177  *     * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
27178  *        (for including a filter with `track by`)
27179  *   * for object data sources:
27180  *     * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
27181  *     * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
27182  *     * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
27183  *     * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
27184  *     * `select` **`as`** `label` **`group by`** `group`
27185  *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`
27186  *     * `select` **`as`** `label` **`disable when`** `disable`
27187  *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`
27188  *
27189  * Where:
27190  *
27191  *   * `array` / `object`: an expression which evaluates to an array / object to iterate over.
27192  *   * `value`: local variable which will refer to each item in the `array` or each property value
27193  *      of `object` during iteration.
27194  *   * `key`: local variable which will refer to a property name in `object` during iteration.
27195  *   * `label`: The result of this expression will be the label for `<option>` element. The
27196  *     `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
27197  *   * `select`: The result of this expression will be bound to the model of the parent `<select>`
27198  *      element. If not specified, `select` expression will default to `value`.
27199  *   * `group`: The result of this expression will be used to group options using the `<optgroup>`
27200  *      DOM element.
27201  *   * `disable`: The result of this expression will be used to disable the rendered `<option>`
27202  *      element. Return `true` to disable.
27203  *   * `trackexpr`: Used when working with an array of objects. The result of this expression will be
27204  *      used to identify the objects in the array. The `trackexpr` will most likely refer to the
27205  *     `value` variable (e.g. `value.propertyName`). With this the selection is preserved
27206  *      even when the options are recreated (e.g. reloaded from the server).
27207  *
27208  * @example
27209     <example module="selectExample">
27210       <file name="index.html">
27211         <script>
27212         angular.module('selectExample', [])
27213           .controller('ExampleController', ['$scope', function($scope) {
27214             $scope.colors = [
27215               {name:'black', shade:'dark'},
27216               {name:'white', shade:'light', notAnOption: true},
27217               {name:'red', shade:'dark'},
27218               {name:'blue', shade:'dark', notAnOption: true},
27219               {name:'yellow', shade:'light', notAnOption: false}
27220             ];
27221             $scope.myColor = $scope.colors[2]; // red
27222           }]);
27223         </script>
27224         <div ng-controller="ExampleController">
27225           <ul>
27226             <li ng-repeat="color in colors">
27227               <label>Name: <input ng-model="color.name"></label>
27228               <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
27229               <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
27230             </li>
27231             <li>
27232               <button ng-click="colors.push({})">add</button>
27233             </li>
27234           </ul>
27235           <hr/>
27236           <label>Color (null not allowed):
27237             <select ng-model="myColor" ng-options="color.name for color in colors"></select>
27238           </label><br/>
27239           <label>Color (null allowed):
27240           <span  class="nullable">
27241             <select ng-model="myColor" ng-options="color.name for color in colors">
27242               <option value="">-- choose color --</option>
27243             </select>
27244           </span></label><br/>
27245
27246           <label>Color grouped by shade:
27247             <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
27248             </select>
27249           </label><br/>
27250
27251           <label>Color grouped by shade, with some disabled:
27252             <select ng-model="myColor"
27253                   ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
27254             </select>
27255           </label><br/>
27256
27257
27258
27259           Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
27260           <br/>
27261           <hr/>
27262           Currently selected: {{ {selected_color:myColor} }}
27263           <div style="border:solid 1px black; height:20px"
27264                ng-style="{'background-color':myColor.name}">
27265           </div>
27266         </div>
27267       </file>
27268       <file name="protractor.js" type="protractor">
27269          it('should check ng-options', function() {
27270            expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
27271            element.all(by.model('myColor')).first().click();
27272            element.all(by.css('select[ng-model="myColor"] option')).first().click();
27273            expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
27274            element(by.css('.nullable select[ng-model="myColor"]')).click();
27275            element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
27276            expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
27277          });
27278       </file>
27279     </example>
27280  */
27281
27282 // jshint maxlen: false
27283 //                     //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
27284 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]+?))?$/;
27285                         // 1: value expression (valueFn)
27286                         // 2: label expression (displayFn)
27287                         // 3: group by expression (groupByFn)
27288                         // 4: disable when expression (disableWhenFn)
27289                         // 5: array item variable name
27290                         // 6: object item key variable name
27291                         // 7: object item value variable name
27292                         // 8: collection expression
27293                         // 9: track by expression
27294 // jshint maxlen: 100
27295
27296
27297 var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
27298
27299   function parseOptionsExpression(optionsExp, selectElement, scope) {
27300
27301     var match = optionsExp.match(NG_OPTIONS_REGEXP);
27302     if (!(match)) {
27303       throw ngOptionsMinErr('iexp',
27304         "Expected expression in form of " +
27305         "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
27306         " but got '{0}'. Element: {1}",
27307         optionsExp, startingTag(selectElement));
27308     }
27309
27310     // Extract the parts from the ngOptions expression
27311
27312     // The variable name for the value of the item in the collection
27313     var valueName = match[5] || match[7];
27314     // The variable name for the key of the item in the collection
27315     var keyName = match[6];
27316
27317     // An expression that generates the viewValue for an option if there is a label expression
27318     var selectAs = / as /.test(match[0]) && match[1];
27319     // An expression that is used to track the id of each object in the options collection
27320     var trackBy = match[9];
27321     // An expression that generates the viewValue for an option if there is no label expression
27322     var valueFn = $parse(match[2] ? match[1] : valueName);
27323     var selectAsFn = selectAs && $parse(selectAs);
27324     var viewValueFn = selectAsFn || valueFn;
27325     var trackByFn = trackBy && $parse(trackBy);
27326
27327     // Get the value by which we are going to track the option
27328     // if we have a trackFn then use that (passing scope and locals)
27329     // otherwise just hash the given viewValue
27330     var getTrackByValueFn = trackBy ?
27331                               function(value, locals) { return trackByFn(scope, locals); } :
27332                               function getHashOfValue(value) { return hashKey(value); };
27333     var getTrackByValue = function(value, key) {
27334       return getTrackByValueFn(value, getLocals(value, key));
27335     };
27336
27337     var displayFn = $parse(match[2] || match[1]);
27338     var groupByFn = $parse(match[3] || '');
27339     var disableWhenFn = $parse(match[4] || '');
27340     var valuesFn = $parse(match[8]);
27341
27342     var locals = {};
27343     var getLocals = keyName ? function(value, key) {
27344       locals[keyName] = key;
27345       locals[valueName] = value;
27346       return locals;
27347     } : function(value) {
27348       locals[valueName] = value;
27349       return locals;
27350     };
27351
27352
27353     function Option(selectValue, viewValue, label, group, disabled) {
27354       this.selectValue = selectValue;
27355       this.viewValue = viewValue;
27356       this.label = label;
27357       this.group = group;
27358       this.disabled = disabled;
27359     }
27360
27361     function getOptionValuesKeys(optionValues) {
27362       var optionValuesKeys;
27363
27364       if (!keyName && isArrayLike(optionValues)) {
27365         optionValuesKeys = optionValues;
27366       } else {
27367         // if object, extract keys, in enumeration order, unsorted
27368         optionValuesKeys = [];
27369         for (var itemKey in optionValues) {
27370           if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
27371             optionValuesKeys.push(itemKey);
27372           }
27373         }
27374       }
27375       return optionValuesKeys;
27376     }
27377
27378     return {
27379       trackBy: trackBy,
27380       getTrackByValue: getTrackByValue,
27381       getWatchables: $parse(valuesFn, function(optionValues) {
27382         // Create a collection of things that we would like to watch (watchedArray)
27383         // so that they can all be watched using a single $watchCollection
27384         // that only runs the handler once if anything changes
27385         var watchedArray = [];
27386         optionValues = optionValues || [];
27387
27388         var optionValuesKeys = getOptionValuesKeys(optionValues);
27389         var optionValuesLength = optionValuesKeys.length;
27390         for (var index = 0; index < optionValuesLength; index++) {
27391           var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
27392           var value = optionValues[key];
27393
27394           var locals = getLocals(optionValues[key], key);
27395           var selectValue = getTrackByValueFn(optionValues[key], locals);
27396           watchedArray.push(selectValue);
27397
27398           // Only need to watch the displayFn if there is a specific label expression
27399           if (match[2] || match[1]) {
27400             var label = displayFn(scope, locals);
27401             watchedArray.push(label);
27402           }
27403
27404           // Only need to watch the disableWhenFn if there is a specific disable expression
27405           if (match[4]) {
27406             var disableWhen = disableWhenFn(scope, locals);
27407             watchedArray.push(disableWhen);
27408           }
27409         }
27410         return watchedArray;
27411       }),
27412
27413       getOptions: function() {
27414
27415         var optionItems = [];
27416         var selectValueMap = {};
27417
27418         // The option values were already computed in the `getWatchables` fn,
27419         // which must have been called to trigger `getOptions`
27420         var optionValues = valuesFn(scope) || [];
27421         var optionValuesKeys = getOptionValuesKeys(optionValues);
27422         var optionValuesLength = optionValuesKeys.length;
27423
27424         for (var index = 0; index < optionValuesLength; index++) {
27425           var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
27426           var value = optionValues[key];
27427           var locals = getLocals(value, key);
27428           var viewValue = viewValueFn(scope, locals);
27429           var selectValue = getTrackByValueFn(viewValue, locals);
27430           var label = displayFn(scope, locals);
27431           var group = groupByFn(scope, locals);
27432           var disabled = disableWhenFn(scope, locals);
27433           var optionItem = new Option(selectValue, viewValue, label, group, disabled);
27434
27435           optionItems.push(optionItem);
27436           selectValueMap[selectValue] = optionItem;
27437         }
27438
27439         return {
27440           items: optionItems,
27441           selectValueMap: selectValueMap,
27442           getOptionFromViewValue: function(value) {
27443             return selectValueMap[getTrackByValue(value)];
27444           },
27445           getViewValueFromOption: function(option) {
27446             // If the viewValue could be an object that may be mutated by the application,
27447             // we need to make a copy and not return the reference to the value on the option.
27448             return trackBy ? angular.copy(option.viewValue) : option.viewValue;
27449           }
27450         };
27451       }
27452     };
27453   }
27454
27455
27456   // we can't just jqLite('<option>') since jqLite is not smart enough
27457   // to create it in <select> and IE barfs otherwise.
27458   var optionTemplate = document.createElement('option'),
27459       optGroupTemplate = document.createElement('optgroup');
27460
27461     function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
27462
27463       var selectCtrl = ctrls[0];
27464       var ngModelCtrl = ctrls[1];
27465       var multiple = attr.multiple;
27466
27467       // The emptyOption allows the application developer to provide their own custom "empty"
27468       // option when the viewValue does not match any of the option values.
27469       var emptyOption;
27470       for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
27471         if (children[i].value === '') {
27472           emptyOption = children.eq(i);
27473           break;
27474         }
27475       }
27476
27477       var providedEmptyOption = !!emptyOption;
27478
27479       var unknownOption = jqLite(optionTemplate.cloneNode(false));
27480       unknownOption.val('?');
27481
27482       var options;
27483       var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
27484
27485
27486       var renderEmptyOption = function() {
27487         if (!providedEmptyOption) {
27488           selectElement.prepend(emptyOption);
27489         }
27490         selectElement.val('');
27491         emptyOption.prop('selected', true); // needed for IE
27492         emptyOption.attr('selected', true);
27493       };
27494
27495       var removeEmptyOption = function() {
27496         if (!providedEmptyOption) {
27497           emptyOption.remove();
27498         }
27499       };
27500
27501
27502       var renderUnknownOption = function() {
27503         selectElement.prepend(unknownOption);
27504         selectElement.val('?');
27505         unknownOption.prop('selected', true); // needed for IE
27506         unknownOption.attr('selected', true);
27507       };
27508
27509       var removeUnknownOption = function() {
27510         unknownOption.remove();
27511       };
27512
27513       // Update the controller methods for multiple selectable options
27514       if (!multiple) {
27515
27516         selectCtrl.writeValue = function writeNgOptionsValue(value) {
27517           var option = options.getOptionFromViewValue(value);
27518
27519           if (option && !option.disabled) {
27520             if (selectElement[0].value !== option.selectValue) {
27521               removeUnknownOption();
27522               removeEmptyOption();
27523
27524               selectElement[0].value = option.selectValue;
27525               option.element.selected = true;
27526               option.element.setAttribute('selected', 'selected');
27527             }
27528           } else {
27529             if (value === null || providedEmptyOption) {
27530               removeUnknownOption();
27531               renderEmptyOption();
27532             } else {
27533               removeEmptyOption();
27534               renderUnknownOption();
27535             }
27536           }
27537         };
27538
27539         selectCtrl.readValue = function readNgOptionsValue() {
27540
27541           var selectedOption = options.selectValueMap[selectElement.val()];
27542
27543           if (selectedOption && !selectedOption.disabled) {
27544             removeEmptyOption();
27545             removeUnknownOption();
27546             return options.getViewValueFromOption(selectedOption);
27547           }
27548           return null;
27549         };
27550
27551         // If we are using `track by` then we must watch the tracked value on the model
27552         // since ngModel only watches for object identity change
27553         if (ngOptions.trackBy) {
27554           scope.$watch(
27555             function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
27556             function() { ngModelCtrl.$render(); }
27557           );
27558         }
27559
27560       } else {
27561
27562         ngModelCtrl.$isEmpty = function(value) {
27563           return !value || value.length === 0;
27564         };
27565
27566
27567         selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
27568           options.items.forEach(function(option) {
27569             option.element.selected = false;
27570           });
27571
27572           if (value) {
27573             value.forEach(function(item) {
27574               var option = options.getOptionFromViewValue(item);
27575               if (option && !option.disabled) option.element.selected = true;
27576             });
27577           }
27578         };
27579
27580
27581         selectCtrl.readValue = function readNgOptionsMultiple() {
27582           var selectedValues = selectElement.val() || [],
27583               selections = [];
27584
27585           forEach(selectedValues, function(value) {
27586             var option = options.selectValueMap[value];
27587             if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
27588           });
27589
27590           return selections;
27591         };
27592
27593         // If we are using `track by` then we must watch these tracked values on the model
27594         // since ngModel only watches for object identity change
27595         if (ngOptions.trackBy) {
27596
27597           scope.$watchCollection(function() {
27598             if (isArray(ngModelCtrl.$viewValue)) {
27599               return ngModelCtrl.$viewValue.map(function(value) {
27600                 return ngOptions.getTrackByValue(value);
27601               });
27602             }
27603           }, function() {
27604             ngModelCtrl.$render();
27605           });
27606
27607         }
27608       }
27609
27610
27611       if (providedEmptyOption) {
27612
27613         // we need to remove it before calling selectElement.empty() because otherwise IE will
27614         // remove the label from the element. wtf?
27615         emptyOption.remove();
27616
27617         // compile the element since there might be bindings in it
27618         $compile(emptyOption)(scope);
27619
27620         // remove the class, which is added automatically because we recompile the element and it
27621         // becomes the compilation root
27622         emptyOption.removeClass('ng-scope');
27623       } else {
27624         emptyOption = jqLite(optionTemplate.cloneNode(false));
27625       }
27626
27627       // We need to do this here to ensure that the options object is defined
27628       // when we first hit it in writeNgOptionsValue
27629       updateOptions();
27630
27631       // We will re-render the option elements if the option values or labels change
27632       scope.$watchCollection(ngOptions.getWatchables, updateOptions);
27633
27634       // ------------------------------------------------------------------ //
27635
27636
27637       function updateOptionElement(option, element) {
27638         option.element = element;
27639         element.disabled = option.disabled;
27640         // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
27641         // selects in certain circumstances when multiple selects are next to each other and display
27642         // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
27643         // See https://github.com/angular/angular.js/issues/11314 for more info.
27644         // This is unfortunately untestable with unit / e2e tests
27645         if (option.label !== element.label) {
27646           element.label = option.label;
27647           element.textContent = option.label;
27648         }
27649         if (option.value !== element.value) element.value = option.selectValue;
27650       }
27651
27652       function addOrReuseElement(parent, current, type, templateElement) {
27653         var element;
27654         // Check whether we can reuse the next element
27655         if (current && lowercase(current.nodeName) === type) {
27656           // The next element is the right type so reuse it
27657           element = current;
27658         } else {
27659           // The next element is not the right type so create a new one
27660           element = templateElement.cloneNode(false);
27661           if (!current) {
27662             // There are no more elements so just append it to the select
27663             parent.appendChild(element);
27664           } else {
27665             // The next element is not a group so insert the new one
27666             parent.insertBefore(element, current);
27667           }
27668         }
27669         return element;
27670       }
27671
27672
27673       function removeExcessElements(current) {
27674         var next;
27675         while (current) {
27676           next = current.nextSibling;
27677           jqLiteRemove(current);
27678           current = next;
27679         }
27680       }
27681
27682
27683       function skipEmptyAndUnknownOptions(current) {
27684         var emptyOption_ = emptyOption && emptyOption[0];
27685         var unknownOption_ = unknownOption && unknownOption[0];
27686
27687         // We cannot rely on the extracted empty option being the same as the compiled empty option,
27688         // because the compiled empty option might have been replaced by a comment because
27689         // it had an "element" transclusion directive on it (such as ngIf)
27690         if (emptyOption_ || unknownOption_) {
27691           while (current &&
27692                 (current === emptyOption_ ||
27693                 current === unknownOption_ ||
27694                 current.nodeType === NODE_TYPE_COMMENT ||
27695                 (nodeName_(current) === 'option' && current.value === ''))) {
27696             current = current.nextSibling;
27697           }
27698         }
27699         return current;
27700       }
27701
27702
27703       function updateOptions() {
27704
27705         var previousValue = options && selectCtrl.readValue();
27706
27707         options = ngOptions.getOptions();
27708
27709         var groupMap = {};
27710         var currentElement = selectElement[0].firstChild;
27711
27712         // Ensure that the empty option is always there if it was explicitly provided
27713         if (providedEmptyOption) {
27714           selectElement.prepend(emptyOption);
27715         }
27716
27717         currentElement = skipEmptyAndUnknownOptions(currentElement);
27718
27719         options.items.forEach(function updateOption(option) {
27720           var group;
27721           var groupElement;
27722           var optionElement;
27723
27724           if (isDefined(option.group)) {
27725
27726             // This option is to live in a group
27727             // See if we have already created this group
27728             group = groupMap[option.group];
27729
27730             if (!group) {
27731
27732               // We have not already created this group
27733               groupElement = addOrReuseElement(selectElement[0],
27734                                                currentElement,
27735                                                'optgroup',
27736                                                optGroupTemplate);
27737               // Move to the next element
27738               currentElement = groupElement.nextSibling;
27739
27740               // Update the label on the group element
27741               groupElement.label = option.group;
27742
27743               // Store it for use later
27744               group = groupMap[option.group] = {
27745                 groupElement: groupElement,
27746                 currentOptionElement: groupElement.firstChild
27747               };
27748
27749             }
27750
27751             // So now we have a group for this option we add the option to the group
27752             optionElement = addOrReuseElement(group.groupElement,
27753                                               group.currentOptionElement,
27754                                               'option',
27755                                               optionTemplate);
27756             updateOptionElement(option, optionElement);
27757             // Move to the next element
27758             group.currentOptionElement = optionElement.nextSibling;
27759
27760           } else {
27761
27762             // This option is not in a group
27763             optionElement = addOrReuseElement(selectElement[0],
27764                                               currentElement,
27765                                               'option',
27766                                               optionTemplate);
27767             updateOptionElement(option, optionElement);
27768             // Move to the next element
27769             currentElement = optionElement.nextSibling;
27770           }
27771         });
27772
27773
27774         // Now remove all excess options and group
27775         Object.keys(groupMap).forEach(function(key) {
27776           removeExcessElements(groupMap[key].currentOptionElement);
27777         });
27778         removeExcessElements(currentElement);
27779
27780         ngModelCtrl.$render();
27781
27782         // Check to see if the value has changed due to the update to the options
27783         if (!ngModelCtrl.$isEmpty(previousValue)) {
27784           var nextValue = selectCtrl.readValue();
27785           var isNotPrimitive = ngOptions.trackBy || multiple;
27786           if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
27787             ngModelCtrl.$setViewValue(nextValue);
27788             ngModelCtrl.$render();
27789           }
27790         }
27791
27792       }
27793   }
27794
27795   return {
27796     restrict: 'A',
27797     terminal: true,
27798     require: ['select', 'ngModel'],
27799     link: {
27800       pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
27801         // Deactivate the SelectController.register method to prevent
27802         // option directives from accidentally registering themselves
27803         // (and unwanted $destroy handlers etc.)
27804         ctrls[0].registerOption = noop;
27805       },
27806       post: ngOptionsPostLink
27807     }
27808   };
27809 }];
27810
27811 /**
27812  * @ngdoc directive
27813  * @name ngPluralize
27814  * @restrict EA
27815  *
27816  * @description
27817  * `ngPluralize` is a directive that displays messages according to en-US localization rules.
27818  * These rules are bundled with angular.js, but can be overridden
27819  * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
27820  * by specifying the mappings between
27821  * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
27822  * and the strings to be displayed.
27823  *
27824  * # Plural categories and explicit number rules
27825  * There are two
27826  * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
27827  * in Angular's default en-US locale: "one" and "other".
27828  *
27829  * While a plural category may match many numbers (for example, in en-US locale, "other" can match
27830  * any number that is not 1), an explicit number rule can only match one number. For example, the
27831  * explicit number rule for "3" matches the number 3. There are examples of plural categories
27832  * and explicit number rules throughout the rest of this documentation.
27833  *
27834  * # Configuring ngPluralize
27835  * You configure ngPluralize by providing 2 attributes: `count` and `when`.
27836  * You can also provide an optional attribute, `offset`.
27837  *
27838  * The value of the `count` attribute can be either a string or an {@link guide/expression
27839  * Angular expression}; these are evaluated on the current scope for its bound value.
27840  *
27841  * The `when` attribute specifies the mappings between plural categories and the actual
27842  * string to be displayed. The value of the attribute should be a JSON object.
27843  *
27844  * The following example shows how to configure ngPluralize:
27845  *
27846  * ```html
27847  * <ng-pluralize count="personCount"
27848                  when="{'0': 'Nobody is viewing.',
27849  *                      'one': '1 person is viewing.',
27850  *                      'other': '{} people are viewing.'}">
27851  * </ng-pluralize>
27852  *```
27853  *
27854  * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
27855  * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
27856  * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
27857  * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
27858  * show "a dozen people are viewing".
27859  *
27860  * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
27861  * into pluralized strings. In the previous example, Angular will replace `{}` with
27862  * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
27863  * for <span ng-non-bindable>{{numberExpression}}</span>.
27864  *
27865  * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
27866  * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
27867  *
27868  * # Configuring ngPluralize with offset
27869  * The `offset` attribute allows further customization of pluralized text, which can result in
27870  * a better user experience. For example, instead of the message "4 people are viewing this document",
27871  * you might display "John, Kate and 2 others are viewing this document".
27872  * The offset attribute allows you to offset a number by any desired value.
27873  * Let's take a look at an example:
27874  *
27875  * ```html
27876  * <ng-pluralize count="personCount" offset=2
27877  *               when="{'0': 'Nobody is viewing.',
27878  *                      '1': '{{person1}} is viewing.',
27879  *                      '2': '{{person1}} and {{person2}} are viewing.',
27880  *                      'one': '{{person1}}, {{person2}} and one other person are viewing.',
27881  *                      'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
27882  * </ng-pluralize>
27883  * ```
27884  *
27885  * Notice that we are still using two plural categories(one, other), but we added
27886  * three explicit number rules 0, 1 and 2.
27887  * When one person, perhaps John, views the document, "John is viewing" will be shown.
27888  * When three people view the document, no explicit number rule is found, so
27889  * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
27890  * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
27891  * is shown.
27892  *
27893  * Note that when you specify offsets, you must provide explicit number rules for
27894  * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
27895  * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
27896  * plural categories "one" and "other".
27897  *
27898  * @param {string|expression} count The variable to be bound to.
27899  * @param {string} when The mapping between plural category to its corresponding strings.
27900  * @param {number=} offset Offset to deduct from the total number.
27901  *
27902  * @example
27903     <example module="pluralizeExample">
27904       <file name="index.html">
27905         <script>
27906           angular.module('pluralizeExample', [])
27907             .controller('ExampleController', ['$scope', function($scope) {
27908               $scope.person1 = 'Igor';
27909               $scope.person2 = 'Misko';
27910               $scope.personCount = 1;
27911             }]);
27912         </script>
27913         <div ng-controller="ExampleController">
27914           <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
27915           <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
27916           <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
27917
27918           <!--- Example with simple pluralization rules for en locale --->
27919           Without Offset:
27920           <ng-pluralize count="personCount"
27921                         when="{'0': 'Nobody is viewing.',
27922                                'one': '1 person is viewing.',
27923                                'other': '{} people are viewing.'}">
27924           </ng-pluralize><br>
27925
27926           <!--- Example with offset --->
27927           With Offset(2):
27928           <ng-pluralize count="personCount" offset=2
27929                         when="{'0': 'Nobody is viewing.',
27930                                '1': '{{person1}} is viewing.',
27931                                '2': '{{person1}} and {{person2}} are viewing.',
27932                                'one': '{{person1}}, {{person2}} and one other person are viewing.',
27933                                'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
27934           </ng-pluralize>
27935         </div>
27936       </file>
27937       <file name="protractor.js" type="protractor">
27938         it('should show correct pluralized string', function() {
27939           var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
27940           var withOffset = element.all(by.css('ng-pluralize')).get(1);
27941           var countInput = element(by.model('personCount'));
27942
27943           expect(withoutOffset.getText()).toEqual('1 person is viewing.');
27944           expect(withOffset.getText()).toEqual('Igor is viewing.');
27945
27946           countInput.clear();
27947           countInput.sendKeys('0');
27948
27949           expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
27950           expect(withOffset.getText()).toEqual('Nobody is viewing.');
27951
27952           countInput.clear();
27953           countInput.sendKeys('2');
27954
27955           expect(withoutOffset.getText()).toEqual('2 people are viewing.');
27956           expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
27957
27958           countInput.clear();
27959           countInput.sendKeys('3');
27960
27961           expect(withoutOffset.getText()).toEqual('3 people are viewing.');
27962           expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
27963
27964           countInput.clear();
27965           countInput.sendKeys('4');
27966
27967           expect(withoutOffset.getText()).toEqual('4 people are viewing.');
27968           expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
27969         });
27970         it('should show data-bound names', function() {
27971           var withOffset = element.all(by.css('ng-pluralize')).get(1);
27972           var personCount = element(by.model('personCount'));
27973           var person1 = element(by.model('person1'));
27974           var person2 = element(by.model('person2'));
27975           personCount.clear();
27976           personCount.sendKeys('4');
27977           person1.clear();
27978           person1.sendKeys('Di');
27979           person2.clear();
27980           person2.sendKeys('Vojta');
27981           expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
27982         });
27983       </file>
27984     </example>
27985  */
27986 var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
27987   var BRACE = /{}/g,
27988       IS_WHEN = /^when(Minus)?(.+)$/;
27989
27990   return {
27991     link: function(scope, element, attr) {
27992       var numberExp = attr.count,
27993           whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
27994           offset = attr.offset || 0,
27995           whens = scope.$eval(whenExp) || {},
27996           whensExpFns = {},
27997           startSymbol = $interpolate.startSymbol(),
27998           endSymbol = $interpolate.endSymbol(),
27999           braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
28000           watchRemover = angular.noop,
28001           lastCount;
28002
28003       forEach(attr, function(expression, attributeName) {
28004         var tmpMatch = IS_WHEN.exec(attributeName);
28005         if (tmpMatch) {
28006           var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
28007           whens[whenKey] = element.attr(attr.$attr[attributeName]);
28008         }
28009       });
28010       forEach(whens, function(expression, key) {
28011         whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
28012
28013       });
28014
28015       scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
28016         var count = parseFloat(newVal);
28017         var countIsNaN = isNaN(count);
28018
28019         if (!countIsNaN && !(count in whens)) {
28020           // If an explicit number rule such as 1, 2, 3... is defined, just use it.
28021           // Otherwise, check it against pluralization rules in $locale service.
28022           count = $locale.pluralCat(count - offset);
28023         }
28024
28025         // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
28026         // In JS `NaN !== NaN`, so we have to explicitly check.
28027         if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
28028           watchRemover();
28029           var whenExpFn = whensExpFns[count];
28030           if (isUndefined(whenExpFn)) {
28031             if (newVal != null) {
28032               $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
28033             }
28034             watchRemover = noop;
28035             updateElementText();
28036           } else {
28037             watchRemover = scope.$watch(whenExpFn, updateElementText);
28038           }
28039           lastCount = count;
28040         }
28041       });
28042
28043       function updateElementText(newText) {
28044         element.text(newText || '');
28045       }
28046     }
28047   };
28048 }];
28049
28050 /**
28051  * @ngdoc directive
28052  * @name ngRepeat
28053  * @multiElement
28054  *
28055  * @description
28056  * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
28057  * instance gets its own scope, where the given loop variable is set to the current collection item,
28058  * and `$index` is set to the item index or key.
28059  *
28060  * Special properties are exposed on the local scope of each template instance, including:
28061  *
28062  * | Variable  | Type            | Details                                                                     |
28063  * |-----------|-----------------|-----------------------------------------------------------------------------|
28064  * | `$index`  | {@type number}  | iterator offset of the repeated element (0..length-1)                       |
28065  * | `$first`  | {@type boolean} | true if the repeated element is first in the iterator.                      |
28066  * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
28067  * | `$last`   | {@type boolean} | true if the repeated element is last in the iterator.                       |
28068  * | `$even`   | {@type boolean} | true if the iterator position `$index` is even (otherwise false).           |
28069  * | `$odd`    | {@type boolean} | true if the iterator position `$index` is odd (otherwise false).            |
28070  *
28071  * <div class="alert alert-info">
28072  *   Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
28073  *   This may be useful when, for instance, nesting ngRepeats.
28074  * </div>
28075  *
28076  *
28077  * # Iterating over object properties
28078  *
28079  * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
28080  * syntax:
28081  *
28082  * ```js
28083  * <div ng-repeat="(key, value) in myObj"> ... </div>
28084  * ```
28085  *
28086  * You need to be aware that the JavaScript specification does not define the order of keys
28087  * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
28088  * used to sort the keys alphabetically.)
28089  *
28090  * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
28091  * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
28092  * keys in the order in which they were defined, although there are exceptions when keys are deleted
28093  * 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).
28094  *
28095  * If this is not desired, the recommended workaround is to convert your object into an array
28096  * that is sorted into the order that you prefer before providing it to `ngRepeat`.  You could
28097  * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
28098  * or implement a `$watch` on the object yourself.
28099  *
28100  *
28101  * # Tracking and Duplicates
28102  *
28103  * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
28104  * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
28105  *
28106  * * When an item is added, a new instance of the template is added to the DOM.
28107  * * When an item is removed, its template instance is removed from the DOM.
28108  * * When items are reordered, their respective templates are reordered in the DOM.
28109  *
28110  * To minimize creation of DOM elements, `ngRepeat` uses a function
28111  * to "keep track" of all items in the collection and their corresponding DOM elements.
28112  * For example, if an item is added to the collection, ngRepeat will know that all other items
28113  * already have DOM elements, and will not re-render them.
28114  *
28115  * The default tracking function (which tracks items by their identity) does not allow
28116  * duplicate items in arrays. This is because when there are duplicates, it is not possible
28117  * to maintain a one-to-one mapping between collection items and DOM elements.
28118  *
28119  * If you do need to repeat duplicate items, you can substitute the default tracking behavior
28120  * with your own using the `track by` expression.
28121  *
28122  * For example, you may track items by the index of each item in the collection, using the
28123  * special scope property `$index`:
28124  * ```html
28125  *    <div ng-repeat="n in [42, 42, 43, 43] track by $index">
28126  *      {{n}}
28127  *    </div>
28128  * ```
28129  *
28130  * You may also use arbitrary expressions in `track by`, including references to custom functions
28131  * on the scope:
28132  * ```html
28133  *    <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
28134  *      {{n}}
28135  *    </div>
28136  * ```
28137  *
28138  * <div class="alert alert-success">
28139  * If you are working with objects that have an identifier property, you should track
28140  * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
28141  * will not have to rebuild the DOM elements for items it has already rendered, even if the
28142  * JavaScript objects in the collection have been substituted for new ones. For large collections,
28143  * this significantly improves rendering performance. If you don't have a unique identifier,
28144  * `track by $index` can also provide a performance boost.
28145  * </div>
28146  * ```html
28147  *    <div ng-repeat="model in collection track by model.id">
28148  *      {{model.name}}
28149  *    </div>
28150  * ```
28151  *
28152  * When no `track by` expression is provided, it is equivalent to tracking by the built-in
28153  * `$id` function, which tracks items by their identity:
28154  * ```html
28155  *    <div ng-repeat="obj in collection track by $id(obj)">
28156  *      {{obj.prop}}
28157  *    </div>
28158  * ```
28159  *
28160  * <div class="alert alert-warning">
28161  * **Note:** `track by` must always be the last expression:
28162  * </div>
28163  * ```
28164  * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
28165  *     {{model.name}}
28166  * </div>
28167  * ```
28168  *
28169  * # Special repeat start and end points
28170  * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
28171  * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
28172  * 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)
28173  * up to and including the ending HTML tag where **ng-repeat-end** is placed.
28174  *
28175  * The example below makes use of this feature:
28176  * ```html
28177  *   <header ng-repeat-start="item in items">
28178  *     Header {{ item }}
28179  *   </header>
28180  *   <div class="body">
28181  *     Body {{ item }}
28182  *   </div>
28183  *   <footer ng-repeat-end>
28184  *     Footer {{ item }}
28185  *   </footer>
28186  * ```
28187  *
28188  * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
28189  * ```html
28190  *   <header>
28191  *     Header A
28192  *   </header>
28193  *   <div class="body">
28194  *     Body A
28195  *   </div>
28196  *   <footer>
28197  *     Footer A
28198  *   </footer>
28199  *   <header>
28200  *     Header B
28201  *   </header>
28202  *   <div class="body">
28203  *     Body B
28204  *   </div>
28205  *   <footer>
28206  *     Footer B
28207  *   </footer>
28208  * ```
28209  *
28210  * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
28211  * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
28212  *
28213  * @animations
28214  * **.enter** - when a new item is added to the list or when an item is revealed after a filter
28215  *
28216  * **.leave** - when an item is removed from the list or when an item is filtered out
28217  *
28218  * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
28219  *
28220  * See the example below for defining CSS animations with ngRepeat.
28221  *
28222  * @element ANY
28223  * @scope
28224  * @priority 1000
28225  * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
28226  *   formats are currently supported:
28227  *
28228  *   * `variable in expression` – where variable is the user defined loop variable and `expression`
28229  *     is a scope expression giving the collection to enumerate.
28230  *
28231  *     For example: `album in artist.albums`.
28232  *
28233  *   * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
28234  *     and `expression` is the scope expression giving the collection to enumerate.
28235  *
28236  *     For example: `(name, age) in {'adam':10, 'amalie':12}`.
28237  *
28238  *   * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
28239  *     which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
28240  *     is specified, ng-repeat associates elements by identity. It is an error to have
28241  *     more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
28242  *     mapped to the same DOM element, which is not possible.)
28243  *
28244  *     Note that the tracking expression must come last, after any filters, and the alias expression.
28245  *
28246  *     For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
28247  *     will be associated by item identity in the array.
28248  *
28249  *     For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
28250  *     `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
28251  *     with the corresponding item in the array by identity. Moving the same object in array would move the DOM
28252  *     element in the same way in the DOM.
28253  *
28254  *     For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
28255  *     case the object identity does not matter. Two objects are considered equivalent as long as their `id`
28256  *     property is same.
28257  *
28258  *     For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
28259  *     to items in conjunction with a tracking expression.
28260  *
28261  *   * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
28262  *     intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
28263  *     when a filter is active on the repeater, but the filtered result set is empty.
28264  *
28265  *     For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
28266  *     the items have been processed through the filter.
28267  *
28268  *     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
28269  *     (and not as operator, inside an expression).
28270  *
28271  *     For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
28272  *
28273  * @example
28274  * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
28275  * results by name. New (entering) and removed (leaving) items are animated.
28276   <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
28277     <file name="index.html">
28278       <div ng-controller="repeatController">
28279         I have {{friends.length}} friends. They are:
28280         <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
28281         <ul class="example-animate-container">
28282           <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
28283             [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
28284           </li>
28285           <li class="animate-repeat" ng-if="results.length == 0">
28286             <strong>No results found...</strong>
28287           </li>
28288         </ul>
28289       </div>
28290     </file>
28291     <file name="script.js">
28292       angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
28293         $scope.friends = [
28294           {name:'John', age:25, gender:'boy'},
28295           {name:'Jessie', age:30, gender:'girl'},
28296           {name:'Johanna', age:28, gender:'girl'},
28297           {name:'Joy', age:15, gender:'girl'},
28298           {name:'Mary', age:28, gender:'girl'},
28299           {name:'Peter', age:95, gender:'boy'},
28300           {name:'Sebastian', age:50, gender:'boy'},
28301           {name:'Erika', age:27, gender:'girl'},
28302           {name:'Patrick', age:40, gender:'boy'},
28303           {name:'Samantha', age:60, gender:'girl'}
28304         ];
28305       });
28306     </file>
28307     <file name="animations.css">
28308       .example-animate-container {
28309         background:white;
28310         border:1px solid black;
28311         list-style:none;
28312         margin:0;
28313         padding:0 10px;
28314       }
28315
28316       .animate-repeat {
28317         line-height:30px;
28318         list-style:none;
28319         box-sizing:border-box;
28320       }
28321
28322       .animate-repeat.ng-move,
28323       .animate-repeat.ng-enter,
28324       .animate-repeat.ng-leave {
28325         transition:all linear 0.5s;
28326       }
28327
28328       .animate-repeat.ng-leave.ng-leave-active,
28329       .animate-repeat.ng-move,
28330       .animate-repeat.ng-enter {
28331         opacity:0;
28332         max-height:0;
28333       }
28334
28335       .animate-repeat.ng-leave,
28336       .animate-repeat.ng-move.ng-move-active,
28337       .animate-repeat.ng-enter.ng-enter-active {
28338         opacity:1;
28339         max-height:30px;
28340       }
28341     </file>
28342     <file name="protractor.js" type="protractor">
28343       var friends = element.all(by.repeater('friend in friends'));
28344
28345       it('should render initial data set', function() {
28346         expect(friends.count()).toBe(10);
28347         expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
28348         expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
28349         expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
28350         expect(element(by.binding('friends.length')).getText())
28351             .toMatch("I have 10 friends. They are:");
28352       });
28353
28354        it('should update repeater when filter predicate changes', function() {
28355          expect(friends.count()).toBe(10);
28356
28357          element(by.model('q')).sendKeys('ma');
28358
28359          expect(friends.count()).toBe(2);
28360          expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
28361          expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
28362        });
28363       </file>
28364     </example>
28365  */
28366 var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
28367   var NG_REMOVED = '$$NG_REMOVED';
28368   var ngRepeatMinErr = minErr('ngRepeat');
28369
28370   var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
28371     // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
28372     scope[valueIdentifier] = value;
28373     if (keyIdentifier) scope[keyIdentifier] = key;
28374     scope.$index = index;
28375     scope.$first = (index === 0);
28376     scope.$last = (index === (arrayLength - 1));
28377     scope.$middle = !(scope.$first || scope.$last);
28378     // jshint bitwise: false
28379     scope.$odd = !(scope.$even = (index&1) === 0);
28380     // jshint bitwise: true
28381   };
28382
28383   var getBlockStart = function(block) {
28384     return block.clone[0];
28385   };
28386
28387   var getBlockEnd = function(block) {
28388     return block.clone[block.clone.length - 1];
28389   };
28390
28391
28392   return {
28393     restrict: 'A',
28394     multiElement: true,
28395     transclude: 'element',
28396     priority: 1000,
28397     terminal: true,
28398     $$tlb: true,
28399     compile: function ngRepeatCompile($element, $attr) {
28400       var expression = $attr.ngRepeat;
28401       var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
28402
28403       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*$/);
28404
28405       if (!match) {
28406         throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
28407             expression);
28408       }
28409
28410       var lhs = match[1];
28411       var rhs = match[2];
28412       var aliasAs = match[3];
28413       var trackByExp = match[4];
28414
28415       match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
28416
28417       if (!match) {
28418         throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
28419             lhs);
28420       }
28421       var valueIdentifier = match[3] || match[1];
28422       var keyIdentifier = match[2];
28423
28424       if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
28425           /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
28426         throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
28427           aliasAs);
28428       }
28429
28430       var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
28431       var hashFnLocals = {$id: hashKey};
28432
28433       if (trackByExp) {
28434         trackByExpGetter = $parse(trackByExp);
28435       } else {
28436         trackByIdArrayFn = function(key, value) {
28437           return hashKey(value);
28438         };
28439         trackByIdObjFn = function(key) {
28440           return key;
28441         };
28442       }
28443
28444       return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
28445
28446         if (trackByExpGetter) {
28447           trackByIdExpFn = function(key, value, index) {
28448             // assign key, value, and $index to the locals so that they can be used in hash functions
28449             if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
28450             hashFnLocals[valueIdentifier] = value;
28451             hashFnLocals.$index = index;
28452             return trackByExpGetter($scope, hashFnLocals);
28453           };
28454         }
28455
28456         // Store a list of elements from previous run. This is a hash where key is the item from the
28457         // iterator, and the value is objects with following properties.
28458         //   - scope: bound scope
28459         //   - element: previous element.
28460         //   - index: position
28461         //
28462         // We are using no-proto object so that we don't need to guard against inherited props via
28463         // hasOwnProperty.
28464         var lastBlockMap = createMap();
28465
28466         //watch props
28467         $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
28468           var index, length,
28469               previousNode = $element[0],     // node that cloned nodes should be inserted after
28470                                               // initialized to the comment node anchor
28471               nextNode,
28472               // Same as lastBlockMap but it has the current state. It will become the
28473               // lastBlockMap on the next iteration.
28474               nextBlockMap = createMap(),
28475               collectionLength,
28476               key, value, // key/value of iteration
28477               trackById,
28478               trackByIdFn,
28479               collectionKeys,
28480               block,       // last object information {scope, element, id}
28481               nextBlockOrder,
28482               elementsToRemove;
28483
28484           if (aliasAs) {
28485             $scope[aliasAs] = collection;
28486           }
28487
28488           if (isArrayLike(collection)) {
28489             collectionKeys = collection;
28490             trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
28491           } else {
28492             trackByIdFn = trackByIdExpFn || trackByIdObjFn;
28493             // if object, extract keys, in enumeration order, unsorted
28494             collectionKeys = [];
28495             for (var itemKey in collection) {
28496               if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
28497                 collectionKeys.push(itemKey);
28498               }
28499             }
28500           }
28501
28502           collectionLength = collectionKeys.length;
28503           nextBlockOrder = new Array(collectionLength);
28504
28505           // locate existing items
28506           for (index = 0; index < collectionLength; index++) {
28507             key = (collection === collectionKeys) ? index : collectionKeys[index];
28508             value = collection[key];
28509             trackById = trackByIdFn(key, value, index);
28510             if (lastBlockMap[trackById]) {
28511               // found previously seen block
28512               block = lastBlockMap[trackById];
28513               delete lastBlockMap[trackById];
28514               nextBlockMap[trackById] = block;
28515               nextBlockOrder[index] = block;
28516             } else if (nextBlockMap[trackById]) {
28517               // if collision detected. restore lastBlockMap and throw an error
28518               forEach(nextBlockOrder, function(block) {
28519                 if (block && block.scope) lastBlockMap[block.id] = block;
28520               });
28521               throw ngRepeatMinErr('dupes',
28522                   "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
28523                   expression, trackById, value);
28524             } else {
28525               // new never before seen block
28526               nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
28527               nextBlockMap[trackById] = true;
28528             }
28529           }
28530
28531           // remove leftover items
28532           for (var blockKey in lastBlockMap) {
28533             block = lastBlockMap[blockKey];
28534             elementsToRemove = getBlockNodes(block.clone);
28535             $animate.leave(elementsToRemove);
28536             if (elementsToRemove[0].parentNode) {
28537               // if the element was not removed yet because of pending animation, mark it as deleted
28538               // so that we can ignore it later
28539               for (index = 0, length = elementsToRemove.length; index < length; index++) {
28540                 elementsToRemove[index][NG_REMOVED] = true;
28541               }
28542             }
28543             block.scope.$destroy();
28544           }
28545
28546           // we are not using forEach for perf reasons (trying to avoid #call)
28547           for (index = 0; index < collectionLength; index++) {
28548             key = (collection === collectionKeys) ? index : collectionKeys[index];
28549             value = collection[key];
28550             block = nextBlockOrder[index];
28551
28552             if (block.scope) {
28553               // if we have already seen this object, then we need to reuse the
28554               // associated scope/element
28555
28556               nextNode = previousNode;
28557
28558               // skip nodes that are already pending removal via leave animation
28559               do {
28560                 nextNode = nextNode.nextSibling;
28561               } while (nextNode && nextNode[NG_REMOVED]);
28562
28563               if (getBlockStart(block) != nextNode) {
28564                 // existing item which got moved
28565                 $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
28566               }
28567               previousNode = getBlockEnd(block);
28568               updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
28569             } else {
28570               // new item which we don't know about
28571               $transclude(function ngRepeatTransclude(clone, scope) {
28572                 block.scope = scope;
28573                 // http://jsperf.com/clone-vs-createcomment
28574                 var endNode = ngRepeatEndComment.cloneNode(false);
28575                 clone[clone.length++] = endNode;
28576
28577                 // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
28578                 $animate.enter(clone, null, jqLite(previousNode));
28579                 previousNode = endNode;
28580                 // Note: We only need the first/last node of the cloned nodes.
28581                 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
28582                 // by a directive with templateUrl when its template arrives.
28583                 block.clone = clone;
28584                 nextBlockMap[block.id] = block;
28585                 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
28586               });
28587             }
28588           }
28589           lastBlockMap = nextBlockMap;
28590         });
28591       };
28592     }
28593   };
28594 }];
28595
28596 var NG_HIDE_CLASS = 'ng-hide';
28597 var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
28598 /**
28599  * @ngdoc directive
28600  * @name ngShow
28601  * @multiElement
28602  *
28603  * @description
28604  * The `ngShow` directive shows or hides the given HTML element based on the expression
28605  * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
28606  * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
28607  * in AngularJS and sets the display style to none (using an !important flag).
28608  * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
28609  *
28610  * ```html
28611  * <!-- when $scope.myValue is truthy (element is visible) -->
28612  * <div ng-show="myValue"></div>
28613  *
28614  * <!-- when $scope.myValue is falsy (element is hidden) -->
28615  * <div ng-show="myValue" class="ng-hide"></div>
28616  * ```
28617  *
28618  * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
28619  * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
28620  * from the element causing the element not to appear hidden.
28621  *
28622  * ## Why is !important used?
28623  *
28624  * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
28625  * can be easily overridden by heavier selectors. For example, something as simple
28626  * as changing the display style on a HTML list item would make hidden elements appear visible.
28627  * This also becomes a bigger issue when dealing with CSS frameworks.
28628  *
28629  * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
28630  * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
28631  * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
28632  *
28633  * ### Overriding `.ng-hide`
28634  *
28635  * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
28636  * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
28637  * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
28638  * with extra animation classes that can be added.
28639  *
28640  * ```css
28641  * .ng-hide:not(.ng-hide-animate) {
28642  *   /&#42; this is just another form of hiding an element &#42;/
28643  *   display: block!important;
28644  *   position: absolute;
28645  *   top: -9999px;
28646  *   left: -9999px;
28647  * }
28648  * ```
28649  *
28650  * By default you don't need to override in CSS anything and the animations will work around the display style.
28651  *
28652  * ## A note about animations with `ngShow`
28653  *
28654  * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
28655  * is true and false. This system works like the animation system present with ngClass except that
28656  * you must also include the !important flag to override the display property
28657  * so that you can perform an animation when the element is hidden during the time of the animation.
28658  *
28659  * ```css
28660  * //
28661  * //a working example can be found at the bottom of this page
28662  * //
28663  * .my-element.ng-hide-add, .my-element.ng-hide-remove {
28664  *   /&#42; this is required as of 1.3x to properly
28665  *      apply all styling in a show/hide animation &#42;/
28666  *   transition: 0s linear all;
28667  * }
28668  *
28669  * .my-element.ng-hide-add-active,
28670  * .my-element.ng-hide-remove-active {
28671  *   /&#42; the transition is defined in the active class &#42;/
28672  *   transition: 1s linear all;
28673  * }
28674  *
28675  * .my-element.ng-hide-add { ... }
28676  * .my-element.ng-hide-add.ng-hide-add-active { ... }
28677  * .my-element.ng-hide-remove { ... }
28678  * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
28679  * ```
28680  *
28681  * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
28682  * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
28683  *
28684  * @animations
28685  * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
28686  * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
28687  *
28688  * @element ANY
28689  * @param {expression} ngShow If the {@link guide/expression expression} is truthy
28690  *     then the element is shown or hidden respectively.
28691  *
28692  * @example
28693   <example module="ngAnimate" deps="angular-animate.js" animations="true">
28694     <file name="index.html">
28695       Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
28696       <div>
28697         Show:
28698         <div class="check-element animate-show" ng-show="checked">
28699           <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
28700         </div>
28701       </div>
28702       <div>
28703         Hide:
28704         <div class="check-element animate-show" ng-hide="checked">
28705           <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
28706         </div>
28707       </div>
28708     </file>
28709     <file name="glyphicons.css">
28710       @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
28711     </file>
28712     <file name="animations.css">
28713       .animate-show {
28714         line-height: 20px;
28715         opacity: 1;
28716         padding: 10px;
28717         border: 1px solid black;
28718         background: white;
28719       }
28720
28721       .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
28722         transition: all linear 0.5s;
28723       }
28724
28725       .animate-show.ng-hide {
28726         line-height: 0;
28727         opacity: 0;
28728         padding: 0 10px;
28729       }
28730
28731       .check-element {
28732         padding: 10px;
28733         border: 1px solid black;
28734         background: white;
28735       }
28736     </file>
28737     <file name="protractor.js" type="protractor">
28738       var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
28739       var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
28740
28741       it('should check ng-show / ng-hide', function() {
28742         expect(thumbsUp.isDisplayed()).toBeFalsy();
28743         expect(thumbsDown.isDisplayed()).toBeTruthy();
28744
28745         element(by.model('checked')).click();
28746
28747         expect(thumbsUp.isDisplayed()).toBeTruthy();
28748         expect(thumbsDown.isDisplayed()).toBeFalsy();
28749       });
28750     </file>
28751   </example>
28752  */
28753 var ngShowDirective = ['$animate', function($animate) {
28754   return {
28755     restrict: 'A',
28756     multiElement: true,
28757     link: function(scope, element, attr) {
28758       scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
28759         // we're adding a temporary, animation-specific class for ng-hide since this way
28760         // we can control when the element is actually displayed on screen without having
28761         // to have a global/greedy CSS selector that breaks when other animations are run.
28762         // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
28763         $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
28764           tempClasses: NG_HIDE_IN_PROGRESS_CLASS
28765         });
28766       });
28767     }
28768   };
28769 }];
28770
28771
28772 /**
28773  * @ngdoc directive
28774  * @name ngHide
28775  * @multiElement
28776  *
28777  * @description
28778  * The `ngHide` directive shows or hides the given HTML element based on the expression
28779  * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
28780  * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
28781  * in AngularJS and sets the display style to none (using an !important flag).
28782  * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
28783  *
28784  * ```html
28785  * <!-- when $scope.myValue is truthy (element is hidden) -->
28786  * <div ng-hide="myValue" class="ng-hide"></div>
28787  *
28788  * <!-- when $scope.myValue is falsy (element is visible) -->
28789  * <div ng-hide="myValue"></div>
28790  * ```
28791  *
28792  * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
28793  * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
28794  * from the element causing the element not to appear hidden.
28795  *
28796  * ## Why is !important used?
28797  *
28798  * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
28799  * can be easily overridden by heavier selectors. For example, something as simple
28800  * as changing the display style on a HTML list item would make hidden elements appear visible.
28801  * This also becomes a bigger issue when dealing with CSS frameworks.
28802  *
28803  * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
28804  * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
28805  * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
28806  *
28807  * ### Overriding `.ng-hide`
28808  *
28809  * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
28810  * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
28811  * class in CSS:
28812  *
28813  * ```css
28814  * .ng-hide {
28815  *   /&#42; this is just another form of hiding an element &#42;/
28816  *   display: block!important;
28817  *   position: absolute;
28818  *   top: -9999px;
28819  *   left: -9999px;
28820  * }
28821  * ```
28822  *
28823  * By default you don't need to override in CSS anything and the animations will work around the display style.
28824  *
28825  * ## A note about animations with `ngHide`
28826  *
28827  * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
28828  * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
28829  * CSS class is added and removed for you instead of your own CSS class.
28830  *
28831  * ```css
28832  * //
28833  * //a working example can be found at the bottom of this page
28834  * //
28835  * .my-element.ng-hide-add, .my-element.ng-hide-remove {
28836  *   transition: 0.5s linear all;
28837  * }
28838  *
28839  * .my-element.ng-hide-add { ... }
28840  * .my-element.ng-hide-add.ng-hide-add-active { ... }
28841  * .my-element.ng-hide-remove { ... }
28842  * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
28843  * ```
28844  *
28845  * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
28846  * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
28847  *
28848  * @animations
28849  * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
28850  * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
28851  *
28852  * @element ANY
28853  * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
28854  *     the element is shown or hidden respectively.
28855  *
28856  * @example
28857   <example module="ngAnimate" deps="angular-animate.js" animations="true">
28858     <file name="index.html">
28859       Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
28860       <div>
28861         Show:
28862         <div class="check-element animate-hide" ng-show="checked">
28863           <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
28864         </div>
28865       </div>
28866       <div>
28867         Hide:
28868         <div class="check-element animate-hide" ng-hide="checked">
28869           <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
28870         </div>
28871       </div>
28872     </file>
28873     <file name="glyphicons.css">
28874       @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
28875     </file>
28876     <file name="animations.css">
28877       .animate-hide {
28878         transition: all linear 0.5s;
28879         line-height: 20px;
28880         opacity: 1;
28881         padding: 10px;
28882         border: 1px solid black;
28883         background: white;
28884       }
28885
28886       .animate-hide.ng-hide {
28887         line-height: 0;
28888         opacity: 0;
28889         padding: 0 10px;
28890       }
28891
28892       .check-element {
28893         padding: 10px;
28894         border: 1px solid black;
28895         background: white;
28896       }
28897     </file>
28898     <file name="protractor.js" type="protractor">
28899       var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
28900       var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
28901
28902       it('should check ng-show / ng-hide', function() {
28903         expect(thumbsUp.isDisplayed()).toBeFalsy();
28904         expect(thumbsDown.isDisplayed()).toBeTruthy();
28905
28906         element(by.model('checked')).click();
28907
28908         expect(thumbsUp.isDisplayed()).toBeTruthy();
28909         expect(thumbsDown.isDisplayed()).toBeFalsy();
28910       });
28911     </file>
28912   </example>
28913  */
28914 var ngHideDirective = ['$animate', function($animate) {
28915   return {
28916     restrict: 'A',
28917     multiElement: true,
28918     link: function(scope, element, attr) {
28919       scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
28920         // The comment inside of the ngShowDirective explains why we add and
28921         // remove a temporary class for the show/hide animation
28922         $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
28923           tempClasses: NG_HIDE_IN_PROGRESS_CLASS
28924         });
28925       });
28926     }
28927   };
28928 }];
28929
28930 /**
28931  * @ngdoc directive
28932  * @name ngStyle
28933  * @restrict AC
28934  *
28935  * @description
28936  * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
28937  *
28938  * @element ANY
28939  * @param {expression} ngStyle
28940  *
28941  * {@link guide/expression Expression} which evals to an
28942  * object whose keys are CSS style names and values are corresponding values for those CSS
28943  * keys.
28944  *
28945  * Since some CSS style names are not valid keys for an object, they must be quoted.
28946  * See the 'background-color' style in the example below.
28947  *
28948  * @example
28949    <example>
28950      <file name="index.html">
28951         <input type="button" value="set color" ng-click="myStyle={color:'red'}">
28952         <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
28953         <input type="button" value="clear" ng-click="myStyle={}">
28954         <br/>
28955         <span ng-style="myStyle">Sample Text</span>
28956         <pre>myStyle={{myStyle}}</pre>
28957      </file>
28958      <file name="style.css">
28959        span {
28960          color: black;
28961        }
28962      </file>
28963      <file name="protractor.js" type="protractor">
28964        var colorSpan = element(by.css('span'));
28965
28966        it('should check ng-style', function() {
28967          expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
28968          element(by.css('input[value=\'set color\']')).click();
28969          expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
28970          element(by.css('input[value=clear]')).click();
28971          expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
28972        });
28973      </file>
28974    </example>
28975  */
28976 var ngStyleDirective = ngDirective(function(scope, element, attr) {
28977   scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
28978     if (oldStyles && (newStyles !== oldStyles)) {
28979       forEach(oldStyles, function(val, style) { element.css(style, '');});
28980     }
28981     if (newStyles) element.css(newStyles);
28982   }, true);
28983 });
28984
28985 /**
28986  * @ngdoc directive
28987  * @name ngSwitch
28988  * @restrict EA
28989  *
28990  * @description
28991  * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
28992  * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
28993  * as specified in the template.
28994  *
28995  * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
28996  * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
28997  * matches the value obtained from the evaluated expression. In other words, you define a container element
28998  * (where you place the directive), place an expression on the **`on="..."` attribute**
28999  * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
29000  * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
29001  * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
29002  * attribute is displayed.
29003  *
29004  * <div class="alert alert-info">
29005  * Be aware that the attribute values to match against cannot be expressions. They are interpreted
29006  * as literal string values to match against.
29007  * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
29008  * value of the expression `$scope.someVal`.
29009  * </div>
29010
29011  * @animations
29012  * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
29013  * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
29014  *
29015  * @usage
29016  *
29017  * ```
29018  * <ANY ng-switch="expression">
29019  *   <ANY ng-switch-when="matchValue1">...</ANY>
29020  *   <ANY ng-switch-when="matchValue2">...</ANY>
29021  *   <ANY ng-switch-default>...</ANY>
29022  * </ANY>
29023  * ```
29024  *
29025  *
29026  * @scope
29027  * @priority 1200
29028  * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
29029  * On child elements add:
29030  *
29031  * * `ngSwitchWhen`: the case statement to match against. If match then this
29032  *   case will be displayed. If the same match appears multiple times, all the
29033  *   elements will be displayed.
29034  * * `ngSwitchDefault`: the default case when no other case match. If there
29035  *   are multiple default cases, all of them will be displayed when no other
29036  *   case match.
29037  *
29038  *
29039  * @example
29040   <example module="switchExample" deps="angular-animate.js" animations="true">
29041     <file name="index.html">
29042       <div ng-controller="ExampleController">
29043         <select ng-model="selection" ng-options="item for item in items">
29044         </select>
29045         <code>selection={{selection}}</code>
29046         <hr/>
29047         <div class="animate-switch-container"
29048           ng-switch on="selection">
29049             <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
29050             <div class="animate-switch" ng-switch-when="home">Home Span</div>
29051             <div class="animate-switch" ng-switch-default>default</div>
29052         </div>
29053       </div>
29054     </file>
29055     <file name="script.js">
29056       angular.module('switchExample', ['ngAnimate'])
29057         .controller('ExampleController', ['$scope', function($scope) {
29058           $scope.items = ['settings', 'home', 'other'];
29059           $scope.selection = $scope.items[0];
29060         }]);
29061     </file>
29062     <file name="animations.css">
29063       .animate-switch-container {
29064         position:relative;
29065         background:white;
29066         border:1px solid black;
29067         height:40px;
29068         overflow:hidden;
29069       }
29070
29071       .animate-switch {
29072         padding:10px;
29073       }
29074
29075       .animate-switch.ng-animate {
29076         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
29077
29078         position:absolute;
29079         top:0;
29080         left:0;
29081         right:0;
29082         bottom:0;
29083       }
29084
29085       .animate-switch.ng-leave.ng-leave-active,
29086       .animate-switch.ng-enter {
29087         top:-50px;
29088       }
29089       .animate-switch.ng-leave,
29090       .animate-switch.ng-enter.ng-enter-active {
29091         top:0;
29092       }
29093     </file>
29094     <file name="protractor.js" type="protractor">
29095       var switchElem = element(by.css('[ng-switch]'));
29096       var select = element(by.model('selection'));
29097
29098       it('should start in settings', function() {
29099         expect(switchElem.getText()).toMatch(/Settings Div/);
29100       });
29101       it('should change to home', function() {
29102         select.all(by.css('option')).get(1).click();
29103         expect(switchElem.getText()).toMatch(/Home Span/);
29104       });
29105       it('should select default', function() {
29106         select.all(by.css('option')).get(2).click();
29107         expect(switchElem.getText()).toMatch(/default/);
29108       });
29109     </file>
29110   </example>
29111  */
29112 var ngSwitchDirective = ['$animate', function($animate) {
29113   return {
29114     require: 'ngSwitch',
29115
29116     // asks for $scope to fool the BC controller module
29117     controller: ['$scope', function ngSwitchController() {
29118      this.cases = {};
29119     }],
29120     link: function(scope, element, attr, ngSwitchController) {
29121       var watchExpr = attr.ngSwitch || attr.on,
29122           selectedTranscludes = [],
29123           selectedElements = [],
29124           previousLeaveAnimations = [],
29125           selectedScopes = [];
29126
29127       var spliceFactory = function(array, index) {
29128           return function() { array.splice(index, 1); };
29129       };
29130
29131       scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
29132         var i, ii;
29133         for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
29134           $animate.cancel(previousLeaveAnimations[i]);
29135         }
29136         previousLeaveAnimations.length = 0;
29137
29138         for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
29139           var selected = getBlockNodes(selectedElements[i].clone);
29140           selectedScopes[i].$destroy();
29141           var promise = previousLeaveAnimations[i] = $animate.leave(selected);
29142           promise.then(spliceFactory(previousLeaveAnimations, i));
29143         }
29144
29145         selectedElements.length = 0;
29146         selectedScopes.length = 0;
29147
29148         if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
29149           forEach(selectedTranscludes, function(selectedTransclude) {
29150             selectedTransclude.transclude(function(caseElement, selectedScope) {
29151               selectedScopes.push(selectedScope);
29152               var anchor = selectedTransclude.element;
29153               caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
29154               var block = { clone: caseElement };
29155
29156               selectedElements.push(block);
29157               $animate.enter(caseElement, anchor.parent(), anchor);
29158             });
29159           });
29160         }
29161       });
29162     }
29163   };
29164 }];
29165
29166 var ngSwitchWhenDirective = ngDirective({
29167   transclude: 'element',
29168   priority: 1200,
29169   require: '^ngSwitch',
29170   multiElement: true,
29171   link: function(scope, element, attrs, ctrl, $transclude) {
29172     ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
29173     ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
29174   }
29175 });
29176
29177 var ngSwitchDefaultDirective = ngDirective({
29178   transclude: 'element',
29179   priority: 1200,
29180   require: '^ngSwitch',
29181   multiElement: true,
29182   link: function(scope, element, attr, ctrl, $transclude) {
29183     ctrl.cases['?'] = (ctrl.cases['?'] || []);
29184     ctrl.cases['?'].push({ transclude: $transclude, element: element });
29185    }
29186 });
29187
29188 /**
29189  * @ngdoc directive
29190  * @name ngTransclude
29191  * @restrict EAC
29192  *
29193  * @description
29194  * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
29195  *
29196  * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
29197  * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
29198  *
29199  * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
29200  * content of this element will be removed before the transcluded content is inserted.
29201  * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
29202  * that no transcluded content is provided.
29203  *
29204  * @element ANY
29205  *
29206  * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
29207  *                                               or its value is the same as the name of the attribute then the default slot is used.
29208  *
29209  * @example
29210  * ### Basic transclusion
29211  * This example demonstrates basic transclusion of content into a component directive.
29212  * <example name="simpleTranscludeExample" module="transcludeExample">
29213  *   <file name="index.html">
29214  *     <script>
29215  *       angular.module('transcludeExample', [])
29216  *        .directive('pane', function(){
29217  *           return {
29218  *             restrict: 'E',
29219  *             transclude: true,
29220  *             scope: { title:'@' },
29221  *             template: '<div style="border: 1px solid black;">' +
29222  *                         '<div style="background-color: gray">{{title}}</div>' +
29223  *                         '<ng-transclude></ng-transclude>' +
29224  *                       '</div>'
29225  *           };
29226  *       })
29227  *       .controller('ExampleController', ['$scope', function($scope) {
29228  *         $scope.title = 'Lorem Ipsum';
29229  *         $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
29230  *       }]);
29231  *     </script>
29232  *     <div ng-controller="ExampleController">
29233  *       <input ng-model="title" aria-label="title"> <br/>
29234  *       <textarea ng-model="text" aria-label="text"></textarea> <br/>
29235  *       <pane title="{{title}}">{{text}}</pane>
29236  *     </div>
29237  *   </file>
29238  *   <file name="protractor.js" type="protractor">
29239  *      it('should have transcluded', function() {
29240  *        var titleElement = element(by.model('title'));
29241  *        titleElement.clear();
29242  *        titleElement.sendKeys('TITLE');
29243  *        var textElement = element(by.model('text'));
29244  *        textElement.clear();
29245  *        textElement.sendKeys('TEXT');
29246  *        expect(element(by.binding('title')).getText()).toEqual('TITLE');
29247  *        expect(element(by.binding('text')).getText()).toEqual('TEXT');
29248  *      });
29249  *   </file>
29250  * </example>
29251  *
29252  * @example
29253  * ### Transclude fallback content
29254  * This example shows how to use `NgTransclude` with fallback content, that
29255  * is displayed if no transcluded content is provided.
29256  *
29257  * <example module="transcludeFallbackContentExample">
29258  * <file name="index.html">
29259  * <script>
29260  * angular.module('transcludeFallbackContentExample', [])
29261  * .directive('myButton', function(){
29262  *             return {
29263  *               restrict: 'E',
29264  *               transclude: true,
29265  *               scope: true,
29266  *               template: '<button style="cursor: pointer;">' +
29267  *                           '<ng-transclude>' +
29268  *                             '<b style="color: red;">Button1</b>' +
29269  *                           '</ng-transclude>' +
29270  *                         '</button>'
29271  *             };
29272  *         });
29273  * </script>
29274  * <!-- fallback button content -->
29275  * <my-button id="fallback"></my-button>
29276  * <!-- modified button content -->
29277  * <my-button id="modified">
29278  *   <i style="color: green;">Button2</i>
29279  * </my-button>
29280  * </file>
29281  * <file name="protractor.js" type="protractor">
29282  * it('should have different transclude element content', function() {
29283  *          expect(element(by.id('fallback')).getText()).toBe('Button1');
29284  *          expect(element(by.id('modified')).getText()).toBe('Button2');
29285  *        });
29286  * </file>
29287  * </example>
29288  *
29289  * @example
29290  * ### Multi-slot transclusion
29291  * This example demonstrates using multi-slot transclusion in a component directive.
29292  * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
29293  *   <file name="index.html">
29294  *    <style>
29295  *      .title, .footer {
29296  *        background-color: gray
29297  *      }
29298  *    </style>
29299  *    <div ng-controller="ExampleController">
29300  *      <input ng-model="title" aria-label="title"> <br/>
29301  *      <textarea ng-model="text" aria-label="text"></textarea> <br/>
29302  *      <pane>
29303  *        <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
29304  *        <pane-body><p>{{text}}</p></pane-body>
29305  *      </pane>
29306  *    </div>
29307  *   </file>
29308  *   <file name="app.js">
29309  *    angular.module('multiSlotTranscludeExample', [])
29310  *     .directive('pane', function(){
29311  *        return {
29312  *          restrict: 'E',
29313  *          transclude: {
29314  *            'title': '?paneTitle',
29315  *            'body': 'paneBody',
29316  *            'footer': '?paneFooter'
29317  *          },
29318  *          template: '<div style="border: 1px solid black;">' +
29319  *                      '<div class="title" ng-transclude="title">Fallback Title</div>' +
29320  *                      '<div ng-transclude="body"></div>' +
29321  *                      '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
29322  *                    '</div>'
29323  *        };
29324  *    })
29325  *    .controller('ExampleController', ['$scope', function($scope) {
29326  *      $scope.title = 'Lorem Ipsum';
29327  *      $scope.link = "https://google.com";
29328  *      $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
29329  *    }]);
29330  *   </file>
29331  *   <file name="protractor.js" type="protractor">
29332  *      it('should have transcluded the title and the body', function() {
29333  *        var titleElement = element(by.model('title'));
29334  *        titleElement.clear();
29335  *        titleElement.sendKeys('TITLE');
29336  *        var textElement = element(by.model('text'));
29337  *        textElement.clear();
29338  *        textElement.sendKeys('TEXT');
29339  *        expect(element(by.css('.title')).getText()).toEqual('TITLE');
29340  *        expect(element(by.binding('text')).getText()).toEqual('TEXT');
29341  *        expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
29342  *      });
29343  *   </file>
29344  * </example>
29345  */
29346 var ngTranscludeMinErr = minErr('ngTransclude');
29347 var ngTranscludeDirective = ngDirective({
29348   restrict: 'EAC',
29349   link: function($scope, $element, $attrs, controller, $transclude) {
29350
29351     if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
29352       // If the attribute is of the form: `ng-transclude="ng-transclude"`
29353       // then treat it like the default
29354       $attrs.ngTransclude = '';
29355     }
29356
29357     function ngTranscludeCloneAttachFn(clone) {
29358       if (clone.length) {
29359         $element.empty();
29360         $element.append(clone);
29361       }
29362     }
29363
29364     if (!$transclude) {
29365       throw ngTranscludeMinErr('orphan',
29366        'Illegal use of ngTransclude directive in the template! ' +
29367        'No parent directive that requires a transclusion found. ' +
29368        'Element: {0}',
29369        startingTag($element));
29370     }
29371
29372     // If there is no slot name defined or the slot name is not optional
29373     // then transclude the slot
29374     var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
29375     $transclude(ngTranscludeCloneAttachFn, null, slotName);
29376   }
29377 });
29378
29379 /**
29380  * @ngdoc directive
29381  * @name script
29382  * @restrict E
29383  *
29384  * @description
29385  * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
29386  * template can be used by {@link ng.directive:ngInclude `ngInclude`},
29387  * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
29388  * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
29389  * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
29390  *
29391  * @param {string} type Must be set to `'text/ng-template'`.
29392  * @param {string} id Cache name of the template.
29393  *
29394  * @example
29395   <example>
29396     <file name="index.html">
29397       <script type="text/ng-template" id="/tpl.html">
29398         Content of the template.
29399       </script>
29400
29401       <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
29402       <div id="tpl-content" ng-include src="currentTpl"></div>
29403     </file>
29404     <file name="protractor.js" type="protractor">
29405       it('should load template defined inside script tag', function() {
29406         element(by.css('#tpl-link')).click();
29407         expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
29408       });
29409     </file>
29410   </example>
29411  */
29412 var scriptDirective = ['$templateCache', function($templateCache) {
29413   return {
29414     restrict: 'E',
29415     terminal: true,
29416     compile: function(element, attr) {
29417       if (attr.type == 'text/ng-template') {
29418         var templateUrl = attr.id,
29419             text = element[0].text;
29420
29421         $templateCache.put(templateUrl, text);
29422       }
29423     }
29424   };
29425 }];
29426
29427 var noopNgModelController = { $setViewValue: noop, $render: noop };
29428
29429 function chromeHack(optionElement) {
29430   // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
29431   // Adding an <option selected="selected"> element to a <select required="required"> should
29432   // automatically select the new element
29433   if (optionElement[0].hasAttribute('selected')) {
29434     optionElement[0].selected = true;
29435   }
29436 }
29437
29438 /**
29439  * @ngdoc type
29440  * @name  select.SelectController
29441  * @description
29442  * The controller for the `<select>` directive. This provides support for reading
29443  * and writing the selected value(s) of the control and also coordinates dynamically
29444  * added `<option>` elements, perhaps by an `ngRepeat` directive.
29445  */
29446 var SelectController =
29447         ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
29448
29449   var self = this,
29450       optionsMap = new HashMap();
29451
29452   // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
29453   self.ngModelCtrl = noopNgModelController;
29454
29455   // The "unknown" option is one that is prepended to the list if the viewValue
29456   // does not match any of the options. When it is rendered the value of the unknown
29457   // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
29458   //
29459   // We can't just jqLite('<option>') since jqLite is not smart enough
29460   // to create it in <select> and IE barfs otherwise.
29461   self.unknownOption = jqLite(document.createElement('option'));
29462   self.renderUnknownOption = function(val) {
29463     var unknownVal = '? ' + hashKey(val) + ' ?';
29464     self.unknownOption.val(unknownVal);
29465     $element.prepend(self.unknownOption);
29466     $element.val(unknownVal);
29467   };
29468
29469   $scope.$on('$destroy', function() {
29470     // disable unknown option so that we don't do work when the whole select is being destroyed
29471     self.renderUnknownOption = noop;
29472   });
29473
29474   self.removeUnknownOption = function() {
29475     if (self.unknownOption.parent()) self.unknownOption.remove();
29476   };
29477
29478
29479   // Read the value of the select control, the implementation of this changes depending
29480   // upon whether the select can have multiple values and whether ngOptions is at work.
29481   self.readValue = function readSingleValue() {
29482     self.removeUnknownOption();
29483     return $element.val();
29484   };
29485
29486
29487   // Write the value to the select control, the implementation of this changes depending
29488   // upon whether the select can have multiple values and whether ngOptions is at work.
29489   self.writeValue = function writeSingleValue(value) {
29490     if (self.hasOption(value)) {
29491       self.removeUnknownOption();
29492       $element.val(value);
29493       if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
29494     } else {
29495       if (value == null && self.emptyOption) {
29496         self.removeUnknownOption();
29497         $element.val('');
29498       } else {
29499         self.renderUnknownOption(value);
29500       }
29501     }
29502   };
29503
29504
29505   // Tell the select control that an option, with the given value, has been added
29506   self.addOption = function(value, element) {
29507     // Skip comment nodes, as they only pollute the `optionsMap`
29508     if (element[0].nodeType === NODE_TYPE_COMMENT) return;
29509
29510     assertNotHasOwnProperty(value, '"option value"');
29511     if (value === '') {
29512       self.emptyOption = element;
29513     }
29514     var count = optionsMap.get(value) || 0;
29515     optionsMap.put(value, count + 1);
29516     self.ngModelCtrl.$render();
29517     chromeHack(element);
29518   };
29519
29520   // Tell the select control that an option, with the given value, has been removed
29521   self.removeOption = function(value) {
29522     var count = optionsMap.get(value);
29523     if (count) {
29524       if (count === 1) {
29525         optionsMap.remove(value);
29526         if (value === '') {
29527           self.emptyOption = undefined;
29528         }
29529       } else {
29530         optionsMap.put(value, count - 1);
29531       }
29532     }
29533   };
29534
29535   // Check whether the select control has an option matching the given value
29536   self.hasOption = function(value) {
29537     return !!optionsMap.get(value);
29538   };
29539
29540
29541   self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
29542
29543     if (interpolateValueFn) {
29544       // The value attribute is interpolated
29545       var oldVal;
29546       optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
29547         if (isDefined(oldVal)) {
29548           self.removeOption(oldVal);
29549         }
29550         oldVal = newVal;
29551         self.addOption(newVal, optionElement);
29552       });
29553     } else if (interpolateTextFn) {
29554       // The text content is interpolated
29555       optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
29556         optionAttrs.$set('value', newVal);
29557         if (oldVal !== newVal) {
29558           self.removeOption(oldVal);
29559         }
29560         self.addOption(newVal, optionElement);
29561       });
29562     } else {
29563       // The value attribute is static
29564       self.addOption(optionAttrs.value, optionElement);
29565     }
29566
29567     optionElement.on('$destroy', function() {
29568       self.removeOption(optionAttrs.value);
29569       self.ngModelCtrl.$render();
29570     });
29571   };
29572 }];
29573
29574 /**
29575  * @ngdoc directive
29576  * @name select
29577  * @restrict E
29578  *
29579  * @description
29580  * HTML `SELECT` element with angular data-binding.
29581  *
29582  * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
29583  * between the scope and the `<select>` control (including setting default values).
29584  * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
29585  * {@link ngOptions `ngOptions`} directives.
29586  *
29587  * When an item in the `<select>` menu is selected, the value of the selected option will be bound
29588  * to the model identified by the `ngModel` directive. With static or repeated options, this is
29589  * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
29590  * If you want dynamic value attributes, you can use interpolation inside the value attribute.
29591  *
29592  * <div class="alert alert-warning">
29593  * Note that the value of a `select` directive used without `ngOptions` is always a string.
29594  * When the model needs to be bound to a non-string value, you must either explicitly convert it
29595  * using a directive (see example below) or use `ngOptions` to specify the set of options.
29596  * This is because an option element can only be bound to string values at present.
29597  * </div>
29598  *
29599  * If the viewValue of `ngModel` does not match any of the options, then the control
29600  * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
29601  *
29602  * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
29603  * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
29604  * option. See example below for demonstration.
29605  *
29606  * <div class="alert alert-info">
29607  * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
29608  * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
29609  * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
29610  * comprehension expression, and additionally in reducing memory and increasing speed by not creating
29611  * a new scope for each repeated instance.
29612  * </div>
29613  *
29614  *
29615  * @param {string} ngModel Assignable angular expression to data-bind to.
29616  * @param {string=} name Property name of the form under which the control is published.
29617  * @param {string=} multiple Allows multiple options to be selected. The selected values will be
29618  *     bound to the model as an array.
29619  * @param {string=} required Sets `required` validation error key if the value is not entered.
29620  * @param {string=} ngRequired Adds required attribute and required validation constraint to
29621  * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
29622  * when you want to data-bind to the required attribute.
29623  * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
29624  *    interaction with the select element.
29625  * @param {string=} ngOptions sets the options that the select is populated with and defines what is
29626  * set on the model on selection. See {@link ngOptions `ngOptions`}.
29627  *
29628  * @example
29629  * ### Simple `select` elements with static options
29630  *
29631  * <example name="static-select" module="staticSelect">
29632  * <file name="index.html">
29633  * <div ng-controller="ExampleController">
29634  *   <form name="myForm">
29635  *     <label for="singleSelect"> Single select: </label><br>
29636  *     <select name="singleSelect" ng-model="data.singleSelect">
29637  *       <option value="option-1">Option 1</option>
29638  *       <option value="option-2">Option 2</option>
29639  *     </select><br>
29640  *
29641  *     <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
29642  *     <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
29643  *       <option value="">---Please select---</option> <!-- not selected / blank option -->
29644  *       <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
29645  *       <option value="option-2">Option 2</option>
29646  *     </select><br>
29647  *     <button ng-click="forceUnknownOption()">Force unknown option</button><br>
29648  *     <tt>singleSelect = {{data.singleSelect}}</tt>
29649  *
29650  *     <hr>
29651  *     <label for="multipleSelect"> Multiple select: </label><br>
29652  *     <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
29653  *       <option value="option-1">Option 1</option>
29654  *       <option value="option-2">Option 2</option>
29655  *       <option value="option-3">Option 3</option>
29656  *     </select><br>
29657  *     <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
29658  *   </form>
29659  * </div>
29660  * </file>
29661  * <file name="app.js">
29662  *  angular.module('staticSelect', [])
29663  *    .controller('ExampleController', ['$scope', function($scope) {
29664  *      $scope.data = {
29665  *       singleSelect: null,
29666  *       multipleSelect: [],
29667  *       option1: 'option-1',
29668  *      };
29669  *
29670  *      $scope.forceUnknownOption = function() {
29671  *        $scope.data.singleSelect = 'nonsense';
29672  *      };
29673  *   }]);
29674  * </file>
29675  *</example>
29676  *
29677  * ### Using `ngRepeat` to generate `select` options
29678  * <example name="ngrepeat-select" module="ngrepeatSelect">
29679  * <file name="index.html">
29680  * <div ng-controller="ExampleController">
29681  *   <form name="myForm">
29682  *     <label for="repeatSelect"> Repeat select: </label>
29683  *     <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
29684  *       <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
29685  *     </select>
29686  *   </form>
29687  *   <hr>
29688  *   <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
29689  * </div>
29690  * </file>
29691  * <file name="app.js">
29692  *  angular.module('ngrepeatSelect', [])
29693  *    .controller('ExampleController', ['$scope', function($scope) {
29694  *      $scope.data = {
29695  *       repeatSelect: null,
29696  *       availableOptions: [
29697  *         {id: '1', name: 'Option A'},
29698  *         {id: '2', name: 'Option B'},
29699  *         {id: '3', name: 'Option C'}
29700  *       ],
29701  *      };
29702  *   }]);
29703  * </file>
29704  *</example>
29705  *
29706  *
29707  * ### Using `select` with `ngOptions` and setting a default value
29708  * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
29709  *
29710  * <example name="select-with-default-values" module="defaultValueSelect">
29711  * <file name="index.html">
29712  * <div ng-controller="ExampleController">
29713  *   <form name="myForm">
29714  *     <label for="mySelect">Make a choice:</label>
29715  *     <select name="mySelect" id="mySelect"
29716  *       ng-options="option.name for option in data.availableOptions track by option.id"
29717  *       ng-model="data.selectedOption"></select>
29718  *   </form>
29719  *   <hr>
29720  *   <tt>option = {{data.selectedOption}}</tt><br/>
29721  * </div>
29722  * </file>
29723  * <file name="app.js">
29724  *  angular.module('defaultValueSelect', [])
29725  *    .controller('ExampleController', ['$scope', function($scope) {
29726  *      $scope.data = {
29727  *       availableOptions: [
29728  *         {id: '1', name: 'Option A'},
29729  *         {id: '2', name: 'Option B'},
29730  *         {id: '3', name: 'Option C'}
29731  *       ],
29732  *       selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
29733  *       };
29734  *   }]);
29735  * </file>
29736  *</example>
29737  *
29738  *
29739  * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
29740  *
29741  * <example name="select-with-non-string-options" module="nonStringSelect">
29742  *   <file name="index.html">
29743  *     <select ng-model="model.id" convert-to-number>
29744  *       <option value="0">Zero</option>
29745  *       <option value="1">One</option>
29746  *       <option value="2">Two</option>
29747  *     </select>
29748  *     {{ model }}
29749  *   </file>
29750  *   <file name="app.js">
29751  *     angular.module('nonStringSelect', [])
29752  *       .run(function($rootScope) {
29753  *         $rootScope.model = { id: 2 };
29754  *       })
29755  *       .directive('convertToNumber', function() {
29756  *         return {
29757  *           require: 'ngModel',
29758  *           link: function(scope, element, attrs, ngModel) {
29759  *             ngModel.$parsers.push(function(val) {
29760  *               return parseInt(val, 10);
29761  *             });
29762  *             ngModel.$formatters.push(function(val) {
29763  *               return '' + val;
29764  *             });
29765  *           }
29766  *         };
29767  *       });
29768  *   </file>
29769  *   <file name="protractor.js" type="protractor">
29770  *     it('should initialize to model', function() {
29771  *       var select = element(by.css('select'));
29772  *       expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
29773  *     });
29774  *   </file>
29775  * </example>
29776  *
29777  */
29778 var selectDirective = function() {
29779
29780   return {
29781     restrict: 'E',
29782     require: ['select', '?ngModel'],
29783     controller: SelectController,
29784     priority: 1,
29785     link: {
29786       pre: selectPreLink,
29787       post: selectPostLink
29788     }
29789   };
29790
29791   function selectPreLink(scope, element, attr, ctrls) {
29792
29793       // if ngModel is not defined, we don't need to do anything
29794       var ngModelCtrl = ctrls[1];
29795       if (!ngModelCtrl) return;
29796
29797       var selectCtrl = ctrls[0];
29798
29799       selectCtrl.ngModelCtrl = ngModelCtrl;
29800
29801       // When the selected item(s) changes we delegate getting the value of the select control
29802       // to the `readValue` method, which can be changed if the select can have multiple
29803       // selected values or if the options are being generated by `ngOptions`
29804       element.on('change', function() {
29805         scope.$apply(function() {
29806           ngModelCtrl.$setViewValue(selectCtrl.readValue());
29807         });
29808       });
29809
29810       // If the select allows multiple values then we need to modify how we read and write
29811       // values from and to the control; also what it means for the value to be empty and
29812       // we have to add an extra watch since ngModel doesn't work well with arrays - it
29813       // doesn't trigger rendering if only an item in the array changes.
29814       if (attr.multiple) {
29815
29816         // Read value now needs to check each option to see if it is selected
29817         selectCtrl.readValue = function readMultipleValue() {
29818           var array = [];
29819           forEach(element.find('option'), function(option) {
29820             if (option.selected) {
29821               array.push(option.value);
29822             }
29823           });
29824           return array;
29825         };
29826
29827         // Write value now needs to set the selected property of each matching option
29828         selectCtrl.writeValue = function writeMultipleValue(value) {
29829           var items = new HashMap(value);
29830           forEach(element.find('option'), function(option) {
29831             option.selected = isDefined(items.get(option.value));
29832           });
29833         };
29834
29835         // we have to do it on each watch since ngModel watches reference, but
29836         // we need to work of an array, so we need to see if anything was inserted/removed
29837         var lastView, lastViewRef = NaN;
29838         scope.$watch(function selectMultipleWatch() {
29839           if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
29840             lastView = shallowCopy(ngModelCtrl.$viewValue);
29841             ngModelCtrl.$render();
29842           }
29843           lastViewRef = ngModelCtrl.$viewValue;
29844         });
29845
29846         // If we are a multiple select then value is now a collection
29847         // so the meaning of $isEmpty changes
29848         ngModelCtrl.$isEmpty = function(value) {
29849           return !value || value.length === 0;
29850         };
29851
29852       }
29853     }
29854
29855     function selectPostLink(scope, element, attrs, ctrls) {
29856       // if ngModel is not defined, we don't need to do anything
29857       var ngModelCtrl = ctrls[1];
29858       if (!ngModelCtrl) return;
29859
29860       var selectCtrl = ctrls[0];
29861
29862       // We delegate rendering to the `writeValue` method, which can be changed
29863       // if the select can have multiple selected values or if the options are being
29864       // generated by `ngOptions`.
29865       // This must be done in the postLink fn to prevent $render to be called before
29866       // all nodes have been linked correctly.
29867       ngModelCtrl.$render = function() {
29868         selectCtrl.writeValue(ngModelCtrl.$viewValue);
29869       };
29870     }
29871 };
29872
29873
29874 // The option directive is purely designed to communicate the existence (or lack of)
29875 // of dynamically created (and destroyed) option elements to their containing select
29876 // directive via its controller.
29877 var optionDirective = ['$interpolate', function($interpolate) {
29878   return {
29879     restrict: 'E',
29880     priority: 100,
29881     compile: function(element, attr) {
29882       if (isDefined(attr.value)) {
29883         // If the value attribute is defined, check if it contains an interpolation
29884         var interpolateValueFn = $interpolate(attr.value, true);
29885       } else {
29886         // If the value attribute is not defined then we fall back to the
29887         // text content of the option element, which may be interpolated
29888         var interpolateTextFn = $interpolate(element.text(), true);
29889         if (!interpolateTextFn) {
29890           attr.$set('value', element.text());
29891         }
29892       }
29893
29894       return function(scope, element, attr) {
29895         // This is an optimization over using ^^ since we don't want to have to search
29896         // all the way to the root of the DOM for every single option element
29897         var selectCtrlName = '$selectController',
29898             parent = element.parent(),
29899             selectCtrl = parent.data(selectCtrlName) ||
29900               parent.parent().data(selectCtrlName); // in case we are in optgroup
29901
29902         if (selectCtrl) {
29903           selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
29904         }
29905       };
29906     }
29907   };
29908 }];
29909
29910 var styleDirective = valueFn({
29911   restrict: 'E',
29912   terminal: false
29913 });
29914
29915 /**
29916  * @ngdoc directive
29917  * @name ngRequired
29918  *
29919  * @description
29920  *
29921  * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
29922  * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
29923  * applied to custom controls.
29924  *
29925  * The directive sets the `required` attribute on the element if the Angular expression inside
29926  * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
29927  * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
29928  * for more info.
29929  *
29930  * The validator will set the `required` error key to true if the `required` attribute is set and
29931  * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
29932  * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
29933  * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
29934  * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
29935  *
29936  * @example
29937  * <example name="ngRequiredDirective" module="ngRequiredExample">
29938  *   <file name="index.html">
29939  *     <script>
29940  *       angular.module('ngRequiredExample', [])
29941  *         .controller('ExampleController', ['$scope', function($scope) {
29942  *           $scope.required = true;
29943  *         }]);
29944  *     </script>
29945  *     <div ng-controller="ExampleController">
29946  *       <form name="form">
29947  *         <label for="required">Toggle required: </label>
29948  *         <input type="checkbox" ng-model="required" id="required" />
29949  *         <br>
29950  *         <label for="input">This input must be filled if `required` is true: </label>
29951  *         <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
29952  *         <hr>
29953  *         required error set? = <code>{{form.input.$error.required}}</code><br>
29954  *         model = <code>{{model}}</code>
29955  *       </form>
29956  *     </div>
29957  *   </file>
29958  *   <file name="protractor.js" type="protractor">
29959        var required = element(by.binding('form.input.$error.required'));
29960        var model = element(by.binding('model'));
29961        var input = element(by.id('input'));
29962
29963        it('should set the required error', function() {
29964          expect(required.getText()).toContain('true');
29965
29966          input.sendKeys('123');
29967          expect(required.getText()).not.toContain('true');
29968          expect(model.getText()).toContain('123');
29969        });
29970  *   </file>
29971  * </example>
29972  */
29973 var requiredDirective = function() {
29974   return {
29975     restrict: 'A',
29976     require: '?ngModel',
29977     link: function(scope, elm, attr, ctrl) {
29978       if (!ctrl) return;
29979       attr.required = true; // force truthy in case we are on non input element
29980
29981       ctrl.$validators.required = function(modelValue, viewValue) {
29982         return !attr.required || !ctrl.$isEmpty(viewValue);
29983       };
29984
29985       attr.$observe('required', function() {
29986         ctrl.$validate();
29987       });
29988     }
29989   };
29990 };
29991
29992 /**
29993  * @ngdoc directive
29994  * @name ngPattern
29995  *
29996  * @description
29997  *
29998  * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
29999  * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
30000  *
30001  * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
30002  * does not match a RegExp which is obtained by evaluating the Angular expression given in the
30003  * `ngPattern` attribute value:
30004  * * If the expression evaluates to a RegExp object, then this is used directly.
30005  * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
30006  * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
30007  *
30008  * <div class="alert alert-info">
30009  * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
30010  * start at the index of the last search's match, thus not taking the whole input value into
30011  * account.
30012  * </div>
30013  *
30014  * <div class="alert alert-info">
30015  * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
30016  * differences:
30017  * <ol>
30018  *   <li>
30019  *     `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
30020  *     not available.
30021  *   </li>
30022  *   <li>
30023  *     The `ngPattern` attribute must be an expression, while the `pattern` value must be
30024  *     interpolated.
30025  *   </li>
30026  * </ol>
30027  * </div>
30028  *
30029  * @example
30030  * <example name="ngPatternDirective" module="ngPatternExample">
30031  *   <file name="index.html">
30032  *     <script>
30033  *       angular.module('ngPatternExample', [])
30034  *         .controller('ExampleController', ['$scope', function($scope) {
30035  *           $scope.regex = '\\d+';
30036  *         }]);
30037  *     </script>
30038  *     <div ng-controller="ExampleController">
30039  *       <form name="form">
30040  *         <label for="regex">Set a pattern (regex string): </label>
30041  *         <input type="text" ng-model="regex" id="regex" />
30042  *         <br>
30043  *         <label for="input">This input is restricted by the current pattern: </label>
30044  *         <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
30045  *         <hr>
30046  *         input valid? = <code>{{form.input.$valid}}</code><br>
30047  *         model = <code>{{model}}</code>
30048  *       </form>
30049  *     </div>
30050  *   </file>
30051  *   <file name="protractor.js" type="protractor">
30052        var model = element(by.binding('model'));
30053        var input = element(by.id('input'));
30054
30055        it('should validate the input with the default pattern', function() {
30056          input.sendKeys('aaa');
30057          expect(model.getText()).not.toContain('aaa');
30058
30059          input.clear().then(function() {
30060            input.sendKeys('123');
30061            expect(model.getText()).toContain('123');
30062          });
30063        });
30064  *   </file>
30065  * </example>
30066  */
30067 var patternDirective = function() {
30068   return {
30069     restrict: 'A',
30070     require: '?ngModel',
30071     link: function(scope, elm, attr, ctrl) {
30072       if (!ctrl) return;
30073
30074       var regexp, patternExp = attr.ngPattern || attr.pattern;
30075       attr.$observe('pattern', function(regex) {
30076         if (isString(regex) && regex.length > 0) {
30077           regex = new RegExp('^' + regex + '$');
30078         }
30079
30080         if (regex && !regex.test) {
30081           throw minErr('ngPattern')('noregexp',
30082             'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
30083             regex, startingTag(elm));
30084         }
30085
30086         regexp = regex || undefined;
30087         ctrl.$validate();
30088       });
30089
30090       ctrl.$validators.pattern = function(modelValue, viewValue) {
30091         // HTML5 pattern constraint validates the input value, so we validate the viewValue
30092         return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
30093       };
30094     }
30095   };
30096 };
30097
30098 /**
30099  * @ngdoc directive
30100  * @name ngMaxlength
30101  *
30102  * @description
30103  *
30104  * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
30105  * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
30106  *
30107  * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
30108  * is longer than the integer obtained by evaluating the Angular expression given in the
30109  * `ngMaxlength` attribute value.
30110  *
30111  * <div class="alert alert-info">
30112  * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
30113  * differences:
30114  * <ol>
30115  *   <li>
30116  *     `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
30117  *     validation is not available.
30118  *   </li>
30119  *   <li>
30120  *     The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
30121  *     interpolated.
30122  *   </li>
30123  * </ol>
30124  * </div>
30125  *
30126  * @example
30127  * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
30128  *   <file name="index.html">
30129  *     <script>
30130  *       angular.module('ngMaxlengthExample', [])
30131  *         .controller('ExampleController', ['$scope', function($scope) {
30132  *           $scope.maxlength = 5;
30133  *         }]);
30134  *     </script>
30135  *     <div ng-controller="ExampleController">
30136  *       <form name="form">
30137  *         <label for="maxlength">Set a maxlength: </label>
30138  *         <input type="number" ng-model="maxlength" id="maxlength" />
30139  *         <br>
30140  *         <label for="input">This input is restricted by the current maxlength: </label>
30141  *         <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
30142  *         <hr>
30143  *         input valid? = <code>{{form.input.$valid}}</code><br>
30144  *         model = <code>{{model}}</code>
30145  *       </form>
30146  *     </div>
30147  *   </file>
30148  *   <file name="protractor.js" type="protractor">
30149        var model = element(by.binding('model'));
30150        var input = element(by.id('input'));
30151
30152        it('should validate the input with the default maxlength', function() {
30153          input.sendKeys('abcdef');
30154          expect(model.getText()).not.toContain('abcdef');
30155
30156          input.clear().then(function() {
30157            input.sendKeys('abcde');
30158            expect(model.getText()).toContain('abcde');
30159          });
30160        });
30161  *   </file>
30162  * </example>
30163  */
30164 var maxlengthDirective = function() {
30165   return {
30166     restrict: 'A',
30167     require: '?ngModel',
30168     link: function(scope, elm, attr, ctrl) {
30169       if (!ctrl) return;
30170
30171       var maxlength = -1;
30172       attr.$observe('maxlength', function(value) {
30173         var intVal = toInt(value);
30174         maxlength = isNaN(intVal) ? -1 : intVal;
30175         ctrl.$validate();
30176       });
30177       ctrl.$validators.maxlength = function(modelValue, viewValue) {
30178         return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
30179       };
30180     }
30181   };
30182 };
30183
30184 /**
30185  * @ngdoc directive
30186  * @name ngMinlength
30187  *
30188  * @description
30189  *
30190  * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
30191  * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
30192  *
30193  * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
30194  * is shorter than the integer obtained by evaluating the Angular expression given in the
30195  * `ngMinlength` attribute value.
30196  *
30197  * <div class="alert alert-info">
30198  * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
30199  * differences:
30200  * <ol>
30201  *   <li>
30202  *     `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
30203  *     validation is not available.
30204  *   </li>
30205  *   <li>
30206  *     The `ngMinlength` value must be an expression, while the `minlength` value must be
30207  *     interpolated.
30208  *   </li>
30209  * </ol>
30210  * </div>
30211  *
30212  * @example
30213  * <example name="ngMinlengthDirective" module="ngMinlengthExample">
30214  *   <file name="index.html">
30215  *     <script>
30216  *       angular.module('ngMinlengthExample', [])
30217  *         .controller('ExampleController', ['$scope', function($scope) {
30218  *           $scope.minlength = 3;
30219  *         }]);
30220  *     </script>
30221  *     <div ng-controller="ExampleController">
30222  *       <form name="form">
30223  *         <label for="minlength">Set a minlength: </label>
30224  *         <input type="number" ng-model="minlength" id="minlength" />
30225  *         <br>
30226  *         <label for="input">This input is restricted by the current minlength: </label>
30227  *         <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
30228  *         <hr>
30229  *         input valid? = <code>{{form.input.$valid}}</code><br>
30230  *         model = <code>{{model}}</code>
30231  *       </form>
30232  *     </div>
30233  *   </file>
30234  *   <file name="protractor.js" type="protractor">
30235        var model = element(by.binding('model'));
30236        var input = element(by.id('input'));
30237
30238        it('should validate the input with the default minlength', function() {
30239          input.sendKeys('ab');
30240          expect(model.getText()).not.toContain('ab');
30241
30242          input.sendKeys('abc');
30243          expect(model.getText()).toContain('abc');
30244        });
30245  *   </file>
30246  * </example>
30247  */
30248 var minlengthDirective = function() {
30249   return {
30250     restrict: 'A',
30251     require: '?ngModel',
30252     link: function(scope, elm, attr, ctrl) {
30253       if (!ctrl) return;
30254
30255       var minlength = 0;
30256       attr.$observe('minlength', function(value) {
30257         minlength = toInt(value) || 0;
30258         ctrl.$validate();
30259       });
30260       ctrl.$validators.minlength = function(modelValue, viewValue) {
30261         return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
30262       };
30263     }
30264   };
30265 };
30266
30267 if (window.angular.bootstrap) {
30268   //AngularJS is already loaded, so we can return here...
30269   console.log('WARNING: Tried to load angular more than once.');
30270   return;
30271 }
30272
30273 //try to bind to jquery now so that one can write jqLite(document).ready()
30274 //but we will rebind on bootstrap again.
30275 bindJQuery();
30276
30277 publishExternalAPI(angular);
30278
30279 angular.module("ngLocale", [], ["$provide", function($provide) {
30280 var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
30281 function getDecimals(n) {
30282   n = n + '';
30283   var i = n.indexOf('.');
30284   return (i == -1) ? 0 : n.length - i - 1;
30285 }
30286
30287 function getVF(n, opt_precision) {
30288   var v = opt_precision;
30289
30290   if (undefined === v) {
30291     v = Math.min(getDecimals(n), 3);
30292   }
30293
30294   var base = Math.pow(10, v);
30295   var f = ((n * base) | 0) % base;
30296   return {v: v, f: f};
30297 }
30298
30299 $provide.value("$locale", {
30300   "DATETIME_FORMATS": {
30301     "AMPMS": [
30302       "AM",
30303       "PM"
30304     ],
30305     "DAY": [
30306       "Sunday",
30307       "Monday",
30308       "Tuesday",
30309       "Wednesday",
30310       "Thursday",
30311       "Friday",
30312       "Saturday"
30313     ],
30314     "ERANAMES": [
30315       "Before Christ",
30316       "Anno Domini"
30317     ],
30318     "ERAS": [
30319       "BC",
30320       "AD"
30321     ],
30322     "FIRSTDAYOFWEEK": 6,
30323     "MONTH": [
30324       "January",
30325       "February",
30326       "March",
30327       "April",
30328       "May",
30329       "June",
30330       "July",
30331       "August",
30332       "September",
30333       "October",
30334       "November",
30335       "December"
30336     ],
30337     "SHORTDAY": [
30338       "Sun",
30339       "Mon",
30340       "Tue",
30341       "Wed",
30342       "Thu",
30343       "Fri",
30344       "Sat"
30345     ],
30346     "SHORTMONTH": [
30347       "Jan",
30348       "Feb",
30349       "Mar",
30350       "Apr",
30351       "May",
30352       "Jun",
30353       "Jul",
30354       "Aug",
30355       "Sep",
30356       "Oct",
30357       "Nov",
30358       "Dec"
30359     ],
30360     "STANDALONEMONTH": [
30361       "January",
30362       "February",
30363       "March",
30364       "April",
30365       "May",
30366       "June",
30367       "July",
30368       "August",
30369       "September",
30370       "October",
30371       "November",
30372       "December"
30373     ],
30374     "WEEKENDRANGE": [
30375       5,
30376       6
30377     ],
30378     "fullDate": "EEEE, MMMM d, y",
30379     "longDate": "MMMM d, y",
30380     "medium": "MMM d, y h:mm:ss a",
30381     "mediumDate": "MMM d, y",
30382     "mediumTime": "h:mm:ss a",
30383     "short": "M/d/yy h:mm a",
30384     "shortDate": "M/d/yy",
30385     "shortTime": "h:mm a"
30386   },
30387   "NUMBER_FORMATS": {
30388     "CURRENCY_SYM": "$",
30389     "DECIMAL_SEP": ".",
30390     "GROUP_SEP": ",",
30391     "PATTERNS": [
30392       {
30393         "gSize": 3,
30394         "lgSize": 3,
30395         "maxFrac": 3,
30396         "minFrac": 0,
30397         "minInt": 1,
30398         "negPre": "-",
30399         "negSuf": "",
30400         "posPre": "",
30401         "posSuf": ""
30402       },
30403       {
30404         "gSize": 3,
30405         "lgSize": 3,
30406         "maxFrac": 2,
30407         "minFrac": 2,
30408         "minInt": 1,
30409         "negPre": "-\u00a4",
30410         "negSuf": "",
30411         "posPre": "\u00a4",
30412         "posSuf": ""
30413       }
30414     ]
30415   },
30416   "id": "en-us",
30417   "localeID": "en_US",
30418   "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;}
30419 });
30420 }]);
30421
30422   jqLite(document).ready(function() {
30423     angularInit(document, bootstrap);
30424   });
30425
30426 })(window, document);
30427
30428 !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>');