socketioMEANseed/www/bower_components/angular/angular.js
www/bower_components/angular/angular.jsRaw
1/**
2 * @license AngularJS v1.6.1
3 * (c) 2010-2016 Google, Inc. http://angularjs.org
4 * License: MIT
5 */
6(function(window) {'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
38function 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.6.1/' +
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 ESLint what variables are being exported */
73/* exported
74 angular,
75 msie,
76 jqLite,
77 jQuery,
78 slice,
79 splice,
80 push,
81 toString,
82 ngMinErr,
83 angularModule,
84 uid,
85 REGEX_STRING_REGEXP,
86 VALIDITY_STATE_PROPERTY,
87
88 lowercase,
89 uppercase,
90 manualLowercase,
91 manualUppercase,
92 nodeName_,
93 isArrayLike,
94 forEach,
95 forEachSorted,
96 reverseParams,
97 nextUid,
98 setHashKey,
99 extend,
100 toInt,
101 inherit,
102 merge,
103 noop,
104 identity,
105 valueFn,
106 isUndefined,
107 isDefined,
108 isObject,
109 isBlankObject,
110 isString,
111 isNumber,
112 isNumberNaN,
113 isDate,
114 isArray,
115 isFunction,
116 isRegExp,
117 isWindow,
118 isScope,
119 isFile,
120 isFormData,
121 isBlob,
122 isBoolean,
123 isPromiseLike,
124 trim,
125 escapeForRegexp,
126 isElement,
127 makeMap,
128 includes,
129 arrayRemove,
130 copy,
131 equals,
132 csp,
133 jq,
134 concat,
135 sliceArgs,
136 bind,
137 toJsonReplacer,
138 toJson,
139 fromJson,
140 convertTimezoneToLocal,
141 timezoneToOffset,
142 startingTag,
143 tryDecodeURIComponent,
144 parseKeyValue,
145 toKeyValue,
146 encodeUriSegment,
147 encodeUriQuery,
148 angularInit,
149 bootstrap,
150 getTestability,
151 snake_case,
152 bindJQuery,
153 assertArg,
154 assertArgFn,
155 assertNotHasOwnProperty,
156 getter,
157 getBlockNodes,
158 hasOwnProperty,
159 createMap,
160 stringify,
161
162 NODE_TYPE_ELEMENT,
163 NODE_TYPE_ATTRIBUTE,
164 NODE_TYPE_TEXT,
165 NODE_TYPE_COMMENT,
166 NODE_TYPE_DOCUMENT,
167 NODE_TYPE_DOCUMENT_FRAGMENT
168*/
169
170////////////////////////////////////
171
172/**
173 * @ngdoc module
174 * @name ng
175 * @module ng
176 * @installation
177 * @description
178 *
179 * # ng (core module)
180 * The ng module is loaded by default when an AngularJS application is started. The module itself
181 * contains the essential components for an AngularJS application to function. The table below
182 * lists a high level breakdown of each of the services/factories, filters, directives and testing
183 * components available within this core module.
184 *
185 * <div doc-module-components="ng"></div>
186 */
187
188var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
189
190// The name of a form control's ValidityState property.
191// This is used so that it's possible for internal tests to create mock ValidityStates.
192var VALIDITY_STATE_PROPERTY = 'validity';
193
194
195var hasOwnProperty = Object.prototype.hasOwnProperty;
196
197/**
198 * @ngdoc function
199 * @name angular.lowercase
200 * @module ng
201 * @kind function
202 *
203 * @deprecated
204 * sinceVersion="1.5.0"
205 * removeVersion="1.7.0"
206 * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.
207 *
208 * @description Converts the specified string to lowercase.
209 * @param {string} string String to be converted to lowercase.
210 * @returns {string} Lowercased string.
211 */
212var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
213
214/**
215 * @ngdoc function
216 * @name angular.uppercase
217 * @module ng
218 * @kind function
219 *
220 * @deprecated
221 * sinceVersion="1.5.0"
222 * removeVersion="1.7.0"
223 * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.
224 *
225 * @description Converts the specified string to uppercase.
226 * @param {string} string String to be converted to uppercase.
227 * @returns {string} Uppercased string.
228 */
229var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
230
231
232var manualLowercase = function(s) {
233 /* eslint-disable no-bitwise */
234 return isString(s)
235 ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
236 : s;
237 /* eslint-enable */
238};
239var manualUppercase = function(s) {
240 /* eslint-disable no-bitwise */
241 return isString(s)
242 ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
243 : s;
244 /* eslint-enable */
245};
246
247
248// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
249// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
250// with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
251if ('i' !== 'I'.toLowerCase()) {
252 lowercase = manualLowercase;
253 uppercase = manualUppercase;
254}
255
256
257var
258 msie, // holds major version number for IE, or NaN if UA is not IE.
259 jqLite, // delay binding since jQuery could be loaded after us.
260 jQuery, // delay binding
261 slice = [].slice,
262 splice = [].splice,
263 push = [].push,
264 toString = Object.prototype.toString,
265 getPrototypeOf = Object.getPrototypeOf,
266 ngMinErr = minErr('ng'),
267
268 /** @name angular */
269 angular = window.angular || (window.angular = {}),
270 angularModule,
271 uid = 0;
272
273// Support: IE 9-11 only
274/**
275 * documentMode is an IE-only property
276 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
277 */
278msie = window.document.documentMode;
279
280
281/**
282 * @private
283 * @param {*} obj
284 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
285 * String ...)
286 */
287function isArrayLike(obj) {
288
289 // `null`, `undefined` and `window` are not array-like
290 if (obj == null || isWindow(obj)) return false;
291
292 // arrays, strings and jQuery/jqLite objects are array like
293 // * jqLite is either the jQuery or jqLite constructor function
294 // * we have to check the existence of jqLite first as this method is called
295 // via the forEach method when constructing the jqLite object in the first place
296 if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
297
298 // Support: iOS 8.2 (not reproducible in simulator)
299 // "length" in obj used to prevent JIT error (gh-11508)
300 var length = 'length' in Object(obj) && obj.length;
301
302 // NodeList objects (with `item` method) and
303 // other objects with suitable length characteristics are array-like
304 return isNumber(length) &&
305 (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
306
307}
308
309/**
310 * @ngdoc function
311 * @name angular.forEach
312 * @module ng
313 * @kind function
314 *
315 * @description
316 * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
317 * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
318 * is the value of an object property or an array element, `key` is the object property key or
319 * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
320 *
321 * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
322 * using the `hasOwnProperty` method.
323 *
324 * Unlike ES262's
325 * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
326 * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
327 * return the value provided.
328 *
329 ```js
330 var values = {name: 'misko', gender: 'male'};
331 var log = [];
332 angular.forEach(values, function(value, key) {
333 this.push(key + ': ' + value);
334 }, log);
335 expect(log).toEqual(['name: misko', 'gender: male']);
336 ```
337 *
338 * @param {Object|Array} obj Object to iterate over.
339 * @param {Function} iterator Iterator function.
340 * @param {Object=} context Object to become context (`this`) for the iterator function.
341 * @returns {Object|Array} Reference to `obj`.
342 */
343
344function forEach(obj, iterator, context) {
345 var key, length;
346 if (obj) {
347 if (isFunction(obj)) {
348 for (key in obj) {
349 if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
350 iterator.call(context, obj[key], key, obj);
351 }
352 }
353 } else if (isArray(obj) || isArrayLike(obj)) {
354 var isPrimitive = typeof obj !== 'object';
355 for (key = 0, length = obj.length; key < length; key++) {
356 if (isPrimitive || key in obj) {
357 iterator.call(context, obj[key], key, obj);
358 }
359 }
360 } else if (obj.forEach && obj.forEach !== forEach) {
361 obj.forEach(iterator, context, obj);
362 } else if (isBlankObject(obj)) {
363 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
364 for (key in obj) {
365 iterator.call(context, obj[key], key, obj);
366 }
367 } else if (typeof obj.hasOwnProperty === 'function') {
368 // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
369 for (key in obj) {
370 if (obj.hasOwnProperty(key)) {
371 iterator.call(context, obj[key], key, obj);
372 }
373 }
374 } else {
375 // Slow path for objects which do not have a method `hasOwnProperty`
376 for (key in obj) {
377 if (hasOwnProperty.call(obj, key)) {
378 iterator.call(context, obj[key], key, obj);
379 }
380 }
381 }
382 }
383 return obj;
384}
385
386function forEachSorted(obj, iterator, context) {
387 var keys = Object.keys(obj).sort();
388 for (var i = 0; i < keys.length; i++) {
389 iterator.call(context, obj[keys[i]], keys[i]);
390 }
391 return keys;
392}
393
394
395/**
396 * when using forEach the params are value, key, but it is often useful to have key, value.
397 * @param {function(string, *)} iteratorFn
398 * @returns {function(*, string)}
399 */
400function reverseParams(iteratorFn) {
401 return function(value, key) {iteratorFn(key, value);};
402}
403
404/**
405 * A consistent way of creating unique IDs in angular.
406 *
407 * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
408 * we hit number precision issues in JavaScript.
409 *
410 * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
411 *
412 * @returns {number} an unique alpha-numeric string
413 */
414function nextUid() {
415 return ++uid;
416}
417
418
419/**
420 * Set or clear the hashkey for an object.
421 * @param obj object
422 * @param h the hashkey (!truthy to delete the hashkey)
423 */
424function setHashKey(obj, h) {
425 if (h) {
426 obj.$$hashKey = h;
427 } else {
428 delete obj.$$hashKey;
429 }
430}
431
432
433function baseExtend(dst, objs, deep) {
434 var h = dst.$$hashKey;
435
436 for (var i = 0, ii = objs.length; i < ii; ++i) {
437 var obj = objs[i];
438 if (!isObject(obj) && !isFunction(obj)) continue;
439 var keys = Object.keys(obj);
440 for (var j = 0, jj = keys.length; j < jj; j++) {
441 var key = keys[j];
442 var src = obj[key];
443
444 if (deep && isObject(src)) {
445 if (isDate(src)) {
446 dst[key] = new Date(src.valueOf());
447 } else if (isRegExp(src)) {
448 dst[key] = new RegExp(src);
449 } else if (src.nodeName) {
450 dst[key] = src.cloneNode(true);
451 } else if (isElement(src)) {
452 dst[key] = src.clone();
453 } else {
454 if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
455 baseExtend(dst[key], [src], true);
456 }
457 } else {
458 dst[key] = src;
459 }
460 }
461 }
462
463 setHashKey(dst, h);
464 return dst;
465}
466
467/**
468 * @ngdoc function
469 * @name angular.extend
470 * @module ng
471 * @kind function
472 *
473 * @description
474 * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
475 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
476 * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
477 *
478 * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
479 * {@link angular.merge} for this.
480 *
481 * @param {Object} dst Destination object.
482 * @param {...Object} src Source object(s).
483 * @returns {Object} Reference to `dst`.
484 */
485function extend(dst) {
486 return baseExtend(dst, slice.call(arguments, 1), false);
487}
488
489
490/**
491* @ngdoc function
492* @name angular.merge
493* @module ng
494* @kind function
495*
496* @description
497* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
498* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
499* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
500*
501* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
502* objects, performing a deep copy.
503*
504* @param {Object} dst Destination object.
505* @param {...Object} src Source object(s).
506* @returns {Object} Reference to `dst`.
507*/
508function merge(dst) {
509 return baseExtend(dst, slice.call(arguments, 1), true);
510}
511
512
513
514function toInt(str) {
515 return parseInt(str, 10);
516}
517
518var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
519 // eslint-disable-next-line no-self-compare
520 return num !== num;
521};
522
523
524function inherit(parent, extra) {
525 return extend(Object.create(parent), extra);
526}
527
528/**
529 * @ngdoc function
530 * @name angular.noop
531 * @module ng
532 * @kind function
533 *
534 * @description
535 * A function that performs no operations. This function can be useful when writing code in the
536 * functional style.
537 ```js
538 function foo(callback) {
539 var result = calculateResult();
540 (callback || angular.noop)(result);
541 }
542 ```
543 */
544function noop() {}
545noop.$inject = [];
546
547
548/**
549 * @ngdoc function
550 * @name angular.identity
551 * @module ng
552 * @kind function
553 *
554 * @description
555 * A function that returns its first argument. This function is useful when writing code in the
556 * functional style.
557 *
558 ```js
559 function transformer(transformationFn, value) {
560 return (transformationFn || angular.identity)(value);
561 };
562
563 // E.g.
564 function getResult(fn, input) {
565 return (fn || angular.identity)(input);
566 };
567
568 getResult(function(n) { return n * 2; }, 21); // returns 42
569 getResult(null, 21); // returns 21
570 getResult(undefined, 21); // returns 21
571 ```
572 *
573 * @param {*} value to be returned.
574 * @returns {*} the value passed in.
575 */
576function identity($) {return $;}
577identity.$inject = [];
578
579
580function valueFn(value) {return function valueRef() {return value;};}
581
582function hasCustomToString(obj) {
583 return isFunction(obj.toString) && obj.toString !== toString;
584}
585
586
587/**
588 * @ngdoc function
589 * @name angular.isUndefined
590 * @module ng
591 * @kind function
592 *
593 * @description
594 * Determines if a reference is undefined.
595 *
596 * @param {*} value Reference to check.
597 * @returns {boolean} True if `value` is undefined.
598 */
599function isUndefined(value) {return typeof value === 'undefined';}
600
601
602/**
603 * @ngdoc function
604 * @name angular.isDefined
605 * @module ng
606 * @kind function
607 *
608 * @description
609 * Determines if a reference is defined.
610 *
611 * @param {*} value Reference to check.
612 * @returns {boolean} True if `value` is defined.
613 */
614function isDefined(value) {return typeof value !== 'undefined';}
615
616
617/**
618 * @ngdoc function
619 * @name angular.isObject
620 * @module ng
621 * @kind function
622 *
623 * @description
624 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
625 * considered to be objects. Note that JavaScript arrays are objects.
626 *
627 * @param {*} value Reference to check.
628 * @returns {boolean} True if `value` is an `Object` but not `null`.
629 */
630function isObject(value) {
631 // http://jsperf.com/isobject4
632 return value !== null && typeof value === 'object';
633}
634
635
636/**
637 * Determine if a value is an object with a null prototype
638 *
639 * @returns {boolean} True if `value` is an `Object` with a null prototype
640 */
641function isBlankObject(value) {
642 return value !== null && typeof value === 'object' && !getPrototypeOf(value);
643}
644
645
646/**
647 * @ngdoc function
648 * @name angular.isString
649 * @module ng
650 * @kind function
651 *
652 * @description
653 * Determines if a reference is a `String`.
654 *
655 * @param {*} value Reference to check.
656 * @returns {boolean} True if `value` is a `String`.
657 */
658function isString(value) {return typeof value === 'string';}
659
660
661/**
662 * @ngdoc function
663 * @name angular.isNumber
664 * @module ng
665 * @kind function
666 *
667 * @description
668 * Determines if a reference is a `Number`.
669 *
670 * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
671 *
672 * If you wish to exclude these then you can use the native
673 * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
674 * method.
675 *
676 * @param {*} value Reference to check.
677 * @returns {boolean} True if `value` is a `Number`.
678 */
679function isNumber(value) {return typeof value === 'number';}
680
681
682/**
683 * @ngdoc function
684 * @name angular.isDate
685 * @module ng
686 * @kind function
687 *
688 * @description
689 * Determines if a value is a date.
690 *
691 * @param {*} value Reference to check.
692 * @returns {boolean} True if `value` is a `Date`.
693 */
694function isDate(value) {
695 return toString.call(value) === '[object Date]';
696}
697
698
699/**
700 * @ngdoc function
701 * @name angular.isArray
702 * @module ng
703 * @kind function
704 *
705 * @description
706 * Determines if a reference is an `Array`. Alias of Array.isArray.
707 *
708 * @param {*} value Reference to check.
709 * @returns {boolean} True if `value` is an `Array`.
710 */
711var isArray = Array.isArray;
712
713/**
714 * @ngdoc function
715 * @name angular.isFunction
716 * @module ng
717 * @kind function
718 *
719 * @description
720 * Determines if a reference is a `Function`.
721 *
722 * @param {*} value Reference to check.
723 * @returns {boolean} True if `value` is a `Function`.
724 */
725function isFunction(value) {return typeof value === 'function';}
726
727
728/**
729 * Determines if a value is a regular expression object.
730 *
731 * @private
732 * @param {*} value Reference to check.
733 * @returns {boolean} True if `value` is a `RegExp`.
734 */
735function isRegExp(value) {
736 return toString.call(value) === '[object RegExp]';
737}
738
739
740/**
741 * Checks if `obj` is a window object.
742 *
743 * @private
744 * @param {*} obj Object to check
745 * @returns {boolean} True if `obj` is a window obj.
746 */
747function isWindow(obj) {
748 return obj && obj.window === obj;
749}
750
751
752function isScope(obj) {
753 return obj && obj.$evalAsync && obj.$watch;
754}
755
756
757function isFile(obj) {
758 return toString.call(obj) === '[object File]';
759}
760
761
762function isFormData(obj) {
763 return toString.call(obj) === '[object FormData]';
764}
765
766
767function isBlob(obj) {
768 return toString.call(obj) === '[object Blob]';
769}
770
771
772function isBoolean(value) {
773 return typeof value === 'boolean';
774}
775
776
777function isPromiseLike(obj) {
778 return obj && isFunction(obj.then);
779}
780
781
782var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
783function isTypedArray(value) {
784 return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
785}
786
787function isArrayBuffer(obj) {
788 return toString.call(obj) === '[object ArrayBuffer]';
789}
790
791
792var trim = function(value) {
793 return isString(value) ? value.trim() : value;
794};
795
796// Copied from:
797// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
798// Prereq: s is a string.
799var escapeForRegexp = function(s) {
800 return s
801 .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
802 // eslint-disable-next-line no-control-regex
803 .replace(/\x08/g, '\\x08');
804};
805
806
807/**
808 * @ngdoc function
809 * @name angular.isElement
810 * @module ng
811 * @kind function
812 *
813 * @description
814 * Determines if a reference is a DOM element (or wrapped jQuery element).
815 *
816 * @param {*} value Reference to check.
817 * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
818 */
819function isElement(node) {
820 return !!(node &&
821 (node.nodeName // We are a direct element.
822 || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
823}
824
825/**
826 * @param str 'key1,key2,...'
827 * @returns {object} in the form of {key1:true, key2:true, ...}
828 */
829function makeMap(str) {
830 var obj = {}, items = str.split(','), i;
831 for (i = 0; i < items.length; i++) {
832 obj[items[i]] = true;
833 }
834 return obj;
835}
836
837
838function nodeName_(element) {
839 return lowercase(element.nodeName || (element[0] && element[0].nodeName));
840}
841
842function includes(array, obj) {
843 return Array.prototype.indexOf.call(array, obj) !== -1;
844}
845
846function arrayRemove(array, value) {
847 var index = array.indexOf(value);
848 if (index >= 0) {
849 array.splice(index, 1);
850 }
851 return index;
852}
853
854/**
855 * @ngdoc function
856 * @name angular.copy
857 * @module ng
858 * @kind function
859 *
860 * @description
861 * Creates a deep copy of `source`, which should be an object or an array.
862 *
863 * * If no destination is supplied, a copy of the object or array is created.
864 * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
865 * are deleted and then all elements/properties from the source are copied to it.
866 * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
867 * * If `source` is identical to `destination` an exception will be thrown.
868 *
869 * <br />
870 * <div class="alert alert-warning">
871 * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
872 * and on `destination`) will be ignored.
873 * </div>
874 *
875 * @param {*} source The source that will be used to make a copy.
876 * Can be any type, including primitives, `null`, and `undefined`.
877 * @param {(Object|Array)=} destination Destination into which the source is copied. If
878 * provided, must be of the same type as `source`.
879 * @returns {*} The copy or updated `destination`, if `destination` was specified.
880 *
881 * @example
882 <example module="copyExample" name="angular-copy">
883 <file name="index.html">
884 <div ng-controller="ExampleController">
885 <form novalidate class="simple-form">
886 <label>Name: <input type="text" ng-model="user.name" /></label><br />
887 <label>Age: <input type="number" ng-model="user.age" /></label><br />
888 Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
889 <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
890 <button ng-click="reset()">RESET</button>
891 <button ng-click="update(user)">SAVE</button>
892 </form>
893 <pre>form = {{user | json}}</pre>
894 <pre>master = {{master | json}}</pre>
895 </div>
896 </file>
897 <file name="script.js">
898 // Module: copyExample
899 angular.
900 module('copyExample', []).
901 controller('ExampleController', ['$scope', function($scope) {
902 $scope.master = {};
903
904 $scope.reset = function() {
905 // Example with 1 argument
906 $scope.user = angular.copy($scope.master);
907 };
908
909 $scope.update = function(user) {
910 // Example with 2 arguments
911 angular.copy(user, $scope.master);
912 };
913
914 $scope.reset();
915 }]);
916 </file>
917 </example>
918 */
919function copy(source, destination) {
920 var stackSource = [];
921 var stackDest = [];
922
923 if (destination) {
924 if (isTypedArray(destination) || isArrayBuffer(destination)) {
925 throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
926 }
927 if (source === destination) {
928 throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
929 }
930
931 // Empty the destination object
932 if (isArray(destination)) {
933 destination.length = 0;
934 } else {
935 forEach(destination, function(value, key) {
936 if (key !== '$$hashKey') {
937 delete destination[key];
938 }
939 });
940 }
941
942 stackSource.push(source);
943 stackDest.push(destination);
944 return copyRecurse(source, destination);
945 }
946
947 return copyElement(source);
948
949 function copyRecurse(source, destination) {
950 var h = destination.$$hashKey;
951 var key;
952 if (isArray(source)) {
953 for (var i = 0, ii = source.length; i < ii; i++) {
954 destination.push(copyElement(source[i]));
955 }
956 } else if (isBlankObject(source)) {
957 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
958 for (key in source) {
959 destination[key] = copyElement(source[key]);
960 }
961 } else if (source && typeof source.hasOwnProperty === 'function') {
962 // Slow path, which must rely on hasOwnProperty
963 for (key in source) {
964 if (source.hasOwnProperty(key)) {
965 destination[key] = copyElement(source[key]);
966 }
967 }
968 } else {
969 // Slowest path --- hasOwnProperty can't be called as a method
970 for (key in source) {
971 if (hasOwnProperty.call(source, key)) {
972 destination[key] = copyElement(source[key]);
973 }
974 }
975 }
976 setHashKey(destination, h);
977 return destination;
978 }
979
980 function copyElement(source) {
981 // Simple values
982 if (!isObject(source)) {
983 return source;
984 }
985
986 // Already copied values
987 var index = stackSource.indexOf(source);
988 if (index !== -1) {
989 return stackDest[index];
990 }
991
992 if (isWindow(source) || isScope(source)) {
993 throw ngMinErr('cpws',
994 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
995 }
996
997 var needsRecurse = false;
998 var destination = copyType(source);
999
1000 if (destination === undefined) {
1001 destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
1002 needsRecurse = true;
1003 }
1004
1005 stackSource.push(source);
1006 stackDest.push(destination);
1007
1008 return needsRecurse
1009 ? copyRecurse(source, destination)
1010 : destination;
1011 }
1012
1013 function copyType(source) {
1014 switch (toString.call(source)) {
1015 case '[object Int8Array]':
1016 case '[object Int16Array]':
1017 case '[object Int32Array]':
1018 case '[object Float32Array]':
1019 case '[object Float64Array]':
1020 case '[object Uint8Array]':
1021 case '[object Uint8ClampedArray]':
1022 case '[object Uint16Array]':
1023 case '[object Uint32Array]':
1024 return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
1025
1026 case '[object ArrayBuffer]':
1027 // Support: IE10
1028 if (!source.slice) {
1029 // If we're in this case we know the environment supports ArrayBuffer
1030 /* eslint-disable no-undef */
1031 var copied = new ArrayBuffer(source.byteLength);
1032 new Uint8Array(copied).set(new Uint8Array(source));
1033 /* eslint-enable */
1034 return copied;
1035 }
1036 return source.slice(0);
1037
1038 case '[object Boolean]':
1039 case '[object Number]':
1040 case '[object String]':
1041 case '[object Date]':
1042 return new source.constructor(source.valueOf());
1043
1044 case '[object RegExp]':
1045 var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
1046 re.lastIndex = source.lastIndex;
1047 return re;
1048
1049 case '[object Blob]':
1050 return new source.constructor([source], {type: source.type});
1051 }
1052
1053 if (isFunction(source.cloneNode)) {
1054 return source.cloneNode(true);
1055 }
1056 }
1057}
1058
1059
1060/**
1061 * @ngdoc function
1062 * @name angular.equals
1063 * @module ng
1064 * @kind function
1065 *
1066 * @description
1067 * Determines if two objects or two values are equivalent. Supports value types, regular
1068 * expressions, arrays and objects.
1069 *
1070 * Two objects or values are considered equivalent if at least one of the following is true:
1071 *
1072 * * Both objects or values pass `===` comparison.
1073 * * Both objects or values are of the same type and all of their properties are equal by
1074 * comparing them with `angular.equals`.
1075 * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
1076 * * Both values represent the same regular expression (In JavaScript,
1077 * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
1078 * representation matches).
1079 *
1080 * During a property comparison, properties of `function` type and properties with names
1081 * that begin with `$` are ignored.
1082 *
1083 * Scope and DOMWindow objects are being compared only by identify (`===`).
1084 *
1085 * @param {*} o1 Object or value to compare.
1086 * @param {*} o2 Object or value to compare.
1087 * @returns {boolean} True if arguments are equal.
1088 *
1089 * @example
1090 <example module="equalsExample" name="equalsExample">
1091 <file name="index.html">
1092 <div ng-controller="ExampleController">
1093 <form novalidate>
1094 <h3>User 1</h3>
1095 Name: <input type="text" ng-model="user1.name">
1096 Age: <input type="number" ng-model="user1.age">
1097
1098 <h3>User 2</h3>
1099 Name: <input type="text" ng-model="user2.name">
1100 Age: <input type="number" ng-model="user2.age">
1101
1102 <div>
1103 <br/>
1104 <input type="button" value="Compare" ng-click="compare()">
1105 </div>
1106 User 1: <pre>{{user1 | json}}</pre>
1107 User 2: <pre>{{user2 | json}}</pre>
1108 Equal: <pre>{{result}}</pre>
1109 </form>
1110 </div>
1111 </file>
1112 <file name="script.js">
1113 angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
1114 $scope.user1 = {};
1115 $scope.user2 = {};
1116 $scope.compare = function() {
1117 $scope.result = angular.equals($scope.user1, $scope.user2);
1118 };
1119 }]);
1120 </file>
1121 </example>
1122 */
1123function equals(o1, o2) {
1124 if (o1 === o2) return true;
1125 if (o1 === null || o2 === null) return false;
1126 // eslint-disable-next-line no-self-compare
1127 if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
1128 var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
1129 if (t1 === t2 && t1 === 'object') {
1130 if (isArray(o1)) {
1131 if (!isArray(o2)) return false;
1132 if ((length = o1.length) === o2.length) {
1133 for (key = 0; key < length; key++) {
1134 if (!equals(o1[key], o2[key])) return false;
1135 }
1136 return true;
1137 }
1138 } else if (isDate(o1)) {
1139 if (!isDate(o2)) return false;
1140 return equals(o1.getTime(), o2.getTime());
1141 } else if (isRegExp(o1)) {
1142 if (!isRegExp(o2)) return false;
1143 return o1.toString() === o2.toString();
1144 } else {
1145 if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
1146 isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
1147 keySet = createMap();
1148 for (key in o1) {
1149 if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
1150 if (!equals(o1[key], o2[key])) return false;
1151 keySet[key] = true;
1152 }
1153 for (key in o2) {
1154 if (!(key in keySet) &&
1155 key.charAt(0) !== '$' &&
1156 isDefined(o2[key]) &&
1157 !isFunction(o2[key])) return false;
1158 }
1159 return true;
1160 }
1161 }
1162 return false;
1163}
1164
1165var csp = function() {
1166 if (!isDefined(csp.rules)) {
1167
1168
1169 var ngCspElement = (window.document.querySelector('[ng-csp]') ||
1170 window.document.querySelector('[data-ng-csp]'));
1171
1172 if (ngCspElement) {
1173 var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
1174 ngCspElement.getAttribute('data-ng-csp');
1175 csp.rules = {
1176 noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
1177 noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
1178 };
1179 } else {
1180 csp.rules = {
1181 noUnsafeEval: noUnsafeEval(),
1182 noInlineStyle: false
1183 };
1184 }
1185 }
1186
1187 return csp.rules;
1188
1189 function noUnsafeEval() {
1190 try {
1191 // eslint-disable-next-line no-new, no-new-func
1192 new Function('');
1193 return false;
1194 } catch (e) {
1195 return true;
1196 }
1197 }
1198};
1199
1200/**
1201 * @ngdoc directive
1202 * @module ng
1203 * @name ngJq
1204 *
1205 * @element ANY
1206 * @param {string=} ngJq the name of the library available under `window`
1207 * to be used for angular.element
1208 * @description
1209 * Use this directive to force the angular.element library. This should be
1210 * used to force either jqLite by leaving ng-jq blank or setting the name of
1211 * the jquery variable under window (eg. jQuery).
1212 *
1213 * Since angular looks for this directive when it is loaded (doesn't wait for the
1214 * DOMContentLoaded event), it must be placed on an element that comes before the script
1215 * which loads angular. Also, only the first instance of `ng-jq` will be used and all
1216 * others ignored.
1217 *
1218 * @example
1219 * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
1220 ```html
1221 <!doctype html>
1222 <html ng-app ng-jq>
1223 ...
1224 ...
1225 </html>
1226 ```
1227 * @example
1228 * This example shows how to use a jQuery based library of a different name.
1229 * The library name must be available at the top most 'window'.
1230 ```html
1231 <!doctype html>
1232 <html ng-app ng-jq="jQueryLib">
1233 ...
1234 ...
1235 </html>
1236 ```
1237 */
1238var jq = function() {
1239 if (isDefined(jq.name_)) return jq.name_;
1240 var el;
1241 var i, ii = ngAttrPrefixes.length, prefix, name;
1242 for (i = 0; i < ii; ++i) {
1243 prefix = ngAttrPrefixes[i];
1244 el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
1245 if (el) {
1246 name = el.getAttribute(prefix + 'jq');
1247 break;
1248 }
1249 }
1250
1251 return (jq.name_ = name);
1252};
1253
1254function concat(array1, array2, index) {
1255 return array1.concat(slice.call(array2, index));
1256}
1257
1258function sliceArgs(args, startIndex) {
1259 return slice.call(args, startIndex || 0);
1260}
1261
1262
1263/**
1264 * @ngdoc function
1265 * @name angular.bind
1266 * @module ng
1267 * @kind function
1268 *
1269 * @description
1270 * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
1271 * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
1272 * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
1273 * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
1274 *
1275 * @param {Object} self Context which `fn` should be evaluated in.
1276 * @param {function()} fn Function to be bound.
1277 * @param {...*} args Optional arguments to be prebound to the `fn` function call.
1278 * @returns {function()} Function that wraps the `fn` with all the specified bindings.
1279 */
1280function bind(self, fn) {
1281 var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
1282 if (isFunction(fn) && !(fn instanceof RegExp)) {
1283 return curryArgs.length
1284 ? function() {
1285 return arguments.length
1286 ? fn.apply(self, concat(curryArgs, arguments, 0))
1287 : fn.apply(self, curryArgs);
1288 }
1289 : function() {
1290 return arguments.length
1291 ? fn.apply(self, arguments)
1292 : fn.call(self);
1293 };
1294 } else {
1295 // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
1296 return fn;
1297 }
1298}
1299
1300
1301function toJsonReplacer(key, value) {
1302 var val = value;
1303
1304 if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
1305 val = undefined;
1306 } else if (isWindow(value)) {
1307 val = '$WINDOW';
1308 } else if (value && window.document === value) {
1309 val = '$DOCUMENT';
1310 } else if (isScope(value)) {
1311 val = '$SCOPE';
1312 }
1313
1314 return val;
1315}
1316
1317
1318/**
1319 * @ngdoc function
1320 * @name angular.toJson
1321 * @module ng
1322 * @kind function
1323 *
1324 * @description
1325 * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
1326 * stripped since angular uses this notation internally.
1327 *
1328 * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
1329 * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
1330 * If set to an integer, the JSON output will contain that many spaces per indentation.
1331 * @returns {string|undefined} JSON-ified string representing `obj`.
1332 * @knownIssue
1333 *
1334 * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
1335 * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
1336 * `Date.prototype.toJSON` method as follows:
1337 *
1338 * ```
1339 * var _DatetoJSON = Date.prototype.toJSON;
1340 * Date.prototype.toJSON = function() {
1341 * try {
1342 * return _DatetoJSON.call(this);
1343 * } catch(e) {
1344 * if (e instanceof RangeError) {
1345 * return null;
1346 * }
1347 * throw e;
1348 * }
1349 * };
1350 * ```
1351 *
1352 * See https://github.com/angular/angular.js/pull/14221 for more information.
1353 */
1354function toJson(obj, pretty) {
1355 if (isUndefined(obj)) return undefined;
1356 if (!isNumber(pretty)) {
1357 pretty = pretty ? 2 : null;
1358 }
1359 return JSON.stringify(obj, toJsonReplacer, pretty);
1360}
1361
1362
1363/**
1364 * @ngdoc function
1365 * @name angular.fromJson
1366 * @module ng
1367 * @kind function
1368 *
1369 * @description
1370 * Deserializes a JSON string.
1371 *
1372 * @param {string} json JSON string to deserialize.
1373 * @returns {Object|Array|string|number} Deserialized JSON string.
1374 */
1375function fromJson(json) {
1376 return isString(json)
1377 ? JSON.parse(json)
1378 : json;
1379}
1380
1381
1382var ALL_COLONS = /:/g;
1383function timezoneToOffset(timezone, fallback) {
1384 // Support: IE 9-11 only, Edge 13-14+
1385 // IE/Edge do not "understand" colon (`:`) in timezone
1386 timezone = timezone.replace(ALL_COLONS, '');
1387 var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
1388 return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
1389}
1390
1391
1392function addDateMinutes(date, minutes) {
1393 date = new Date(date.getTime());
1394 date.setMinutes(date.getMinutes() + minutes);
1395 return date;
1396}
1397
1398
1399function convertTimezoneToLocal(date, timezone, reverse) {
1400 reverse = reverse ? -1 : 1;
1401 var dateTimezoneOffset = date.getTimezoneOffset();
1402 var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
1403 return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
1404}
1405
1406
1407/**
1408 * @returns {string} Returns the string representation of the element.
1409 */
1410function startingTag(element) {
1411 element = jqLite(element).clone();
1412 try {
1413 // turns out IE does not let you set .html() on elements which
1414 // are not allowed to have children. So we just ignore it.
1415 element.empty();
1416 } catch (e) { /* empty */ }
1417 var elemHtml = jqLite('<div>').append(element).html();
1418 try {
1419 return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
1420 elemHtml.
1421 match(/^(<[^>]+>)/)[1].
1422 replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
1423 } catch (e) {
1424 return lowercase(elemHtml);
1425 }
1426
1427}
1428
1429
1430/////////////////////////////////////////////////
1431
1432/**
1433 * Tries to decode the URI component without throwing an exception.
1434 *
1435 * @private
1436 * @param str value potential URI component to check.
1437 * @returns {boolean} True if `value` can be decoded
1438 * with the decodeURIComponent function.
1439 */
1440function tryDecodeURIComponent(value) {
1441 try {
1442 return decodeURIComponent(value);
1443 } catch (e) {
1444 // Ignore any invalid uri component.
1445 }
1446}
1447
1448
1449/**
1450 * Parses an escaped url query string into key-value pairs.
1451 * @returns {Object.<string,boolean|Array>}
1452 */
1453function parseKeyValue(/**string*/keyValue) {
1454 var obj = {};
1455 forEach((keyValue || '').split('&'), function(keyValue) {
1456 var splitPoint, key, val;
1457 if (keyValue) {
1458 key = keyValue = keyValue.replace(/\+/g,'%20');
1459 splitPoint = keyValue.indexOf('=');
1460 if (splitPoint !== -1) {
1461 key = keyValue.substring(0, splitPoint);
1462 val = keyValue.substring(splitPoint + 1);
1463 }
1464 key = tryDecodeURIComponent(key);
1465 if (isDefined(key)) {
1466 val = isDefined(val) ? tryDecodeURIComponent(val) : true;
1467 if (!hasOwnProperty.call(obj, key)) {
1468 obj[key] = val;
1469 } else if (isArray(obj[key])) {
1470 obj[key].push(val);
1471 } else {
1472 obj[key] = [obj[key],val];
1473 }
1474 }
1475 }
1476 });
1477 return obj;
1478}
1479
1480function toKeyValue(obj) {
1481 var parts = [];
1482 forEach(obj, function(value, key) {
1483 if (isArray(value)) {
1484 forEach(value, function(arrayValue) {
1485 parts.push(encodeUriQuery(key, true) +
1486 (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
1487 });
1488 } else {
1489 parts.push(encodeUriQuery(key, true) +
1490 (value === true ? '' : '=' + encodeUriQuery(value, true)));
1491 }
1492 });
1493 return parts.length ? parts.join('&') : '';
1494}
1495
1496
1497/**
1498 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
1499 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
1500 * segments:
1501 * segment = *pchar
1502 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
1503 * pct-encoded = "%" HEXDIG HEXDIG
1504 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
1505 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
1506 * / "*" / "+" / "," / ";" / "="
1507 */
1508function encodeUriSegment(val) {
1509 return encodeUriQuery(val, true).
1510 replace(/%26/gi, '&').
1511 replace(/%3D/gi, '=').
1512 replace(/%2B/gi, '+');
1513}
1514
1515
1516/**
1517 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
1518 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
1519 * encoded per http://tools.ietf.org/html/rfc3986:
1520 * query = *( pchar / "/" / "?" )
1521 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
1522 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
1523 * pct-encoded = "%" HEXDIG HEXDIG
1524 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
1525 * / "*" / "+" / "," / ";" / "="
1526 */
1527function encodeUriQuery(val, pctEncodeSpaces) {
1528 return encodeURIComponent(val).
1529 replace(/%40/gi, '@').
1530 replace(/%3A/gi, ':').
1531 replace(/%24/g, '$').
1532 replace(/%2C/gi, ',').
1533 replace(/%3B/gi, ';').
1534 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
1535}
1536
1537var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
1538
1539function getNgAttribute(element, ngAttr) {
1540 var attr, i, ii = ngAttrPrefixes.length;
1541 for (i = 0; i < ii; ++i) {
1542 attr = ngAttrPrefixes[i] + ngAttr;
1543 if (isString(attr = element.getAttribute(attr))) {
1544 return attr;
1545 }
1546 }
1547 return null;
1548}
1549
1550function allowAutoBootstrap(document) {
1551 if (!document.currentScript) {
1552 return true;
1553 }
1554 var src = document.currentScript.getAttribute('src');
1555 var link = document.createElement('a');
1556 link.href = src;
1557 if (document.location.origin === link.origin) {
1558 // Same-origin resources are always allowed, even for non-whitelisted schemes.
1559 return true;
1560 }
1561 // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
1562 // This is to prevent angular.js bundled with browser extensions from being used to bypass the
1563 // content security policy in web pages and other browser extensions.
1564 switch (link.protocol) {
1565 case 'http:':
1566 case 'https:':
1567 case 'ftp:':
1568 case 'blob:':
1569 case 'file:':
1570 case 'data:':
1571 return true;
1572 default:
1573 return false;
1574 }
1575}
1576
1577// Cached as it has to run during loading so that document.currentScript is available.
1578var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
1579
1580/**
1581 * @ngdoc directive
1582 * @name ngApp
1583 * @module ng
1584 *
1585 * @element ANY
1586 * @param {angular.Module} ngApp an optional application
1587 * {@link angular.module module} name to load.
1588 * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
1589 * created in "strict-di" mode. This means that the application will fail to invoke functions which
1590 * do not use explicit function annotation (and are thus unsuitable for minification), as described
1591 * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
1592 * tracking down the root of these bugs.
1593 *
1594 * @description
1595 *
1596 * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
1597 * designates the **root element** of the application and is typically placed near the root element
1598 * of the page - e.g. on the `<body>` or `<html>` tags.
1599 *
1600 * There are a few things to keep in mind when using `ngApp`:
1601 * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
1602 * found in the document will be used to define the root element to auto-bootstrap as an
1603 * application. To run multiple applications in an HTML document you must manually bootstrap them using
1604 * {@link angular.bootstrap} instead.
1605 * - AngularJS applications cannot be nested within each other.
1606 * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
1607 * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
1608 * {@link ngRoute.ngView `ngView`}.
1609 * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
1610 * causing animations to stop working and making the injector inaccessible from outside the app.
1611 *
1612 * You can specify an **AngularJS module** to be used as the root module for the application. This
1613 * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
1614 * should contain the application code needed or have dependencies on other modules that will
1615 * contain the code. See {@link angular.module} for more information.
1616 *
1617 * In the example below if the `ngApp` directive were not placed on the `html` element then the
1618 * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
1619 * would not be resolved to `3`.
1620 *
1621 * `ngApp` is the easiest, and most common way to bootstrap an application.
1622 *
1623 <example module="ngAppDemo" name="ng-app">
1624 <file name="index.html">
1625 <div ng-controller="ngAppDemoController">
1626 I can add: {{a}} + {{b}} = {{ a+b }}
1627 </div>
1628 </file>
1629 <file name="script.js">
1630 angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
1631 $scope.a = 1;
1632 $scope.b = 2;
1633 });
1634 </file>
1635 </example>
1636 *
1637 * Using `ngStrictDi`, you would see something like this:
1638 *
1639 <example ng-app-included="true" name="strict-di">
1640 <file name="index.html">
1641 <div ng-app="ngAppStrictDemo" ng-strict-di>
1642 <div ng-controller="GoodController1">
1643 I can add: {{a}} + {{b}} = {{ a+b }}
1644
1645 <p>This renders because the controller does not fail to
1646 instantiate, by using explicit annotation style (see
1647 script.js for details)
1648 </p>
1649 </div>
1650
1651 <div ng-controller="GoodController2">
1652 Name: <input ng-model="name"><br />
1653 Hello, {{name}}!
1654
1655 <p>This renders because the controller does not fail to
1656 instantiate, by using explicit annotation style
1657 (see script.js for details)
1658 </p>
1659 </div>
1660
1661 <div ng-controller="BadController">
1662 I can add: {{a}} + {{b}} = {{ a+b }}
1663
1664 <p>The controller could not be instantiated, due to relying
1665 on automatic function annotations (which are disabled in
1666 strict mode). As such, the content of this section is not
1667 interpolated, and there should be an error in your web console.
1668 </p>
1669 </div>
1670 </div>
1671 </file>
1672 <file name="script.js">
1673 angular.module('ngAppStrictDemo', [])
1674 // BadController will fail to instantiate, due to relying on automatic function annotation,
1675 // rather than an explicit annotation
1676 .controller('BadController', function($scope) {
1677 $scope.a = 1;
1678 $scope.b = 2;
1679 })
1680 // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
1681 // due to using explicit annotations using the array style and $inject property, respectively.
1682 .controller('GoodController1', ['$scope', function($scope) {
1683 $scope.a = 1;
1684 $scope.b = 2;
1685 }])
1686 .controller('GoodController2', GoodController2);
1687 function GoodController2($scope) {
1688 $scope.name = 'World';
1689 }
1690 GoodController2.$inject = ['$scope'];
1691 </file>
1692 <file name="style.css">
1693 div[ng-controller] {
1694 margin-bottom: 1em;
1695 -webkit-border-radius: 4px;
1696 border-radius: 4px;
1697 border: 1px solid;
1698 padding: .5em;
1699 }
1700 div[ng-controller^=Good] {
1701 border-color: #d6e9c6;
1702 background-color: #dff0d8;
1703 color: #3c763d;
1704 }
1705 div[ng-controller^=Bad] {
1706 border-color: #ebccd1;
1707 background-color: #f2dede;
1708 color: #a94442;
1709 margin-bottom: 0;
1710 }
1711 </file>
1712 </example>
1713 */
1714function angularInit(element, bootstrap) {
1715 var appElement,
1716 module,
1717 config = {};
1718
1719 // The element `element` has priority over any other element.
1720 forEach(ngAttrPrefixes, function(prefix) {
1721 var name = prefix + 'app';
1722
1723 if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
1724 appElement = element;
1725 module = element.getAttribute(name);
1726 }
1727 });
1728 forEach(ngAttrPrefixes, function(prefix) {
1729 var name = prefix + 'app';
1730 var candidate;
1731
1732 if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
1733 appElement = candidate;
1734 module = candidate.getAttribute(name);
1735 }
1736 });
1737 if (appElement) {
1738 if (!isAutoBootstrapAllowed) {
1739 window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
1740 'an extension, document.location.href does not match.');
1741 return;
1742 }
1743 config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
1744 bootstrap(appElement, module ? [module] : [], config);
1745 }
1746}
1747
1748/**
1749 * @ngdoc function
1750 * @name angular.bootstrap
1751 * @module ng
1752 * @description
1753 * Use this function to manually start up angular application.
1754 *
1755 * For more information, see the {@link guide/bootstrap Bootstrap guide}.
1756 *
1757 * Angular will detect if it has been loaded into the browser more than once and only allow the
1758 * first loaded script to be bootstrapped and will report a warning to the browser console for
1759 * each of the subsequent scripts. This prevents strange results in applications, where otherwise
1760 * multiple instances of Angular try to work on the DOM.
1761 *
1762 * <div class="alert alert-warning">
1763 * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
1764 * They must use {@link ng.directive:ngApp ngApp}.
1765 * </div>
1766 *
1767 * <div class="alert alert-warning">
1768 * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
1769 * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
1770 * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
1771 * causing animations to stop working and making the injector inaccessible from outside the app.
1772 * </div>
1773 *
1774 * ```html
1775 * <!doctype html>
1776 * <html>
1777 * <body>
1778 * <div ng-controller="WelcomeController">
1779 * {{greeting}}
1780 * </div>
1781 *
1782 * <script src="angular.js"></script>
1783 * <script>
1784 * var app = angular.module('demo', [])
1785 * .controller('WelcomeController', function($scope) {
1786 * $scope.greeting = 'Welcome!';
1787 * });
1788 * angular.bootstrap(document, ['demo']);
1789 * </script>
1790 * </body>
1791 * </html>
1792 * ```
1793 *
1794 * @param {DOMElement} element DOM element which is the root of angular application.
1795 * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
1796 * Each item in the array should be the name of a predefined module or a (DI annotated)
1797 * function that will be invoked by the injector as a `config` block.
1798 * See: {@link angular.module modules}
1799 * @param {Object=} config an object for defining configuration options for the application. The
1800 * following keys are supported:
1801 *
1802 * * `strictDi` - disable automatic function annotation for the application. This is meant to
1803 * assist in finding bugs which break minified code. Defaults to `false`.
1804 *
1805 * @returns {auto.$injector} Returns the newly created injector for this app.
1806 */
1807function bootstrap(element, modules, config) {
1808 if (!isObject(config)) config = {};
1809 var defaultConfig = {
1810 strictDi: false
1811 };
1812 config = extend(defaultConfig, config);
1813 var doBootstrap = function() {
1814 element = jqLite(element);
1815
1816 if (element.injector()) {
1817 var tag = (element[0] === window.document) ? 'document' : startingTag(element);
1818 // Encode angle brackets to prevent input from being sanitized to empty string #8683.
1819 throw ngMinErr(
1820 'btstrpd',
1821 'App already bootstrapped with this element \'{0}\'',
1822 tag.replace(/</,'<').replace(/>/,'>'));
1823 }
1824
1825 modules = modules || [];
1826 modules.unshift(['$provide', function($provide) {
1827 $provide.value('$rootElement', element);
1828 }]);
1829
1830 if (config.debugInfoEnabled) {
1831 // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
1832 modules.push(['$compileProvider', function($compileProvider) {
1833 $compileProvider.debugInfoEnabled(true);
1834 }]);
1835 }
1836
1837 modules.unshift('ng');
1838 var injector = createInjector(modules, config.strictDi);
1839 injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
1840 function bootstrapApply(scope, element, compile, injector) {
1841 scope.$apply(function() {
1842 element.data('$injector', injector);
1843 compile(element)(scope);
1844 });
1845 }]
1846 );
1847 return injector;
1848 };
1849
1850 var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
1851 var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
1852
1853 if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
1854 config.debugInfoEnabled = true;
1855 window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
1856 }
1857
1858 if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
1859 return doBootstrap();
1860 }
1861
1862 window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
1863 angular.resumeBootstrap = function(extraModules) {
1864 forEach(extraModules, function(module) {
1865 modules.push(module);
1866 });
1867 return doBootstrap();
1868 };
1869
1870 if (isFunction(angular.resumeDeferredBootstrap)) {
1871 angular.resumeDeferredBootstrap();
1872 }
1873}
1874
1875/**
1876 * @ngdoc function
1877 * @name angular.reloadWithDebugInfo
1878 * @module ng
1879 * @description
1880 * Use this function to reload the current application with debug information turned on.
1881 * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
1882 *
1883 * See {@link ng.$compileProvider#debugInfoEnabled} for more.
1884 */
1885function reloadWithDebugInfo() {
1886 window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
1887 window.location.reload();
1888}
1889
1890/**
1891 * @name angular.getTestability
1892 * @module ng
1893 * @description
1894 * Get the testability service for the instance of Angular on the given
1895 * element.
1896 * @param {DOMElement} element DOM element which is the root of angular application.
1897 */
1898function getTestability(rootElement) {
1899 var injector = angular.element(rootElement).injector();
1900 if (!injector) {
1901 throw ngMinErr('test',
1902 'no injector found for element argument to getTestability');
1903 }
1904 return injector.get('$$testability');
1905}
1906
1907var SNAKE_CASE_REGEXP = /[A-Z]/g;
1908function snake_case(name, separator) {
1909 separator = separator || '_';
1910 return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
1911 return (pos ? separator : '') + letter.toLowerCase();
1912 });
1913}
1914
1915var bindJQueryFired = false;
1916function bindJQuery() {
1917 var originalCleanData;
1918
1919 if (bindJQueryFired) {
1920 return;
1921 }
1922
1923 // bind to jQuery if present;
1924 var jqName = jq();
1925 jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
1926 !jqName ? undefined : // use jqLite
1927 window[jqName]; // use jQuery specified by `ngJq`
1928
1929 // Use jQuery if it exists with proper functionality, otherwise default to us.
1930 // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
1931 // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
1932 // versions. It will not work for sure with jQuery <1.7, though.
1933 if (jQuery && jQuery.fn.on) {
1934 jqLite = jQuery;
1935 extend(jQuery.fn, {
1936 scope: JQLitePrototype.scope,
1937 isolateScope: JQLitePrototype.isolateScope,
1938 controller: JQLitePrototype.controller,
1939 injector: JQLitePrototype.injector,
1940 inheritedData: JQLitePrototype.inheritedData
1941 });
1942
1943 // All nodes removed from the DOM via various jQuery APIs like .remove()
1944 // are passed through jQuery.cleanData. Monkey-patch this method to fire
1945 // the $destroy event on all removed nodes.
1946 originalCleanData = jQuery.cleanData;
1947 jQuery.cleanData = function(elems) {
1948 var events;
1949 for (var i = 0, elem; (elem = elems[i]) != null; i++) {
1950 events = jQuery._data(elem, 'events');
1951 if (events && events.$destroy) {
1952 jQuery(elem).triggerHandler('$destroy');
1953 }
1954 }
1955 originalCleanData(elems);
1956 };
1957 } else {
1958 jqLite = JQLite;
1959 }
1960
1961 angular.element = jqLite;
1962
1963 // Prevent double-proxying.
1964 bindJQueryFired = true;
1965}
1966
1967/**
1968 * throw error if the argument is falsy.
1969 */
1970function assertArg(arg, name, reason) {
1971 if (!arg) {
1972 throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
1973 }
1974 return arg;
1975}
1976
1977function assertArgFn(arg, name, acceptArrayAnnotation) {
1978 if (acceptArrayAnnotation && isArray(arg)) {
1979 arg = arg[arg.length - 1];
1980 }
1981
1982 assertArg(isFunction(arg), name, 'not a function, got ' +
1983 (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
1984 return arg;
1985}
1986
1987/**
1988 * throw error if the name given is hasOwnProperty
1989 * @param {String} name the name to test
1990 * @param {String} context the context in which the name is used, such as module or directive
1991 */
1992function assertNotHasOwnProperty(name, context) {
1993 if (name === 'hasOwnProperty') {
1994 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
1995 }
1996}
1997
1998/**
1999 * Return the value accessible from the object by path. Any undefined traversals are ignored
2000 * @param {Object} obj starting object
2001 * @param {String} path path to traverse
2002 * @param {boolean} [bindFnToScope=true]
2003 * @returns {Object} value as accessible by path
2004 */
2005//TODO(misko): this function needs to be removed
2006function getter(obj, path, bindFnToScope) {
2007 if (!path) return obj;
2008 var keys = path.split('.');
2009 var key;
2010 var lastInstance = obj;
2011 var len = keys.length;
2012
2013 for (var i = 0; i < len; i++) {
2014 key = keys[i];
2015 if (obj) {
2016 obj = (lastInstance = obj)[key];
2017 }
2018 }
2019 if (!bindFnToScope && isFunction(obj)) {
2020 return bind(lastInstance, obj);
2021 }
2022 return obj;
2023}
2024
2025/**
2026 * Return the DOM siblings between the first and last node in the given array.
2027 * @param {Array} array like object
2028 * @returns {Array} the inputted object or a jqLite collection containing the nodes
2029 */
2030function getBlockNodes(nodes) {
2031 // TODO(perf): update `nodes` instead of creating a new object?
2032 var node = nodes[0];
2033 var endNode = nodes[nodes.length - 1];
2034 var blockNodes;
2035
2036 for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
2037 if (blockNodes || nodes[i] !== node) {
2038 if (!blockNodes) {
2039 blockNodes = jqLite(slice.call(nodes, 0, i));
2040 }
2041 blockNodes.push(node);
2042 }
2043 }
2044
2045 return blockNodes || nodes;
2046}
2047
2048
2049/**
2050 * Creates a new object without a prototype. This object is useful for lookup without having to
2051 * guard against prototypically inherited properties via hasOwnProperty.
2052 *
2053 * Related micro-benchmarks:
2054 * - http://jsperf.com/object-create2
2055 * - http://jsperf.com/proto-map-lookup/2
2056 * - http://jsperf.com/for-in-vs-object-keys2
2057 *
2058 * @returns {Object}
2059 */
2060function createMap() {
2061 return Object.create(null);
2062}
2063
2064function stringify(value) {
2065 if (value == null) { // null || undefined
2066 return '';
2067 }
2068 switch (typeof value) {
2069 case 'string':
2070 break;
2071 case 'number':
2072 value = '' + value;
2073 break;
2074 default:
2075 if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
2076 value = value.toString();
2077 } else {
2078 value = toJson(value);
2079 }
2080 }
2081
2082 return value;
2083}
2084
2085var NODE_TYPE_ELEMENT = 1;
2086var NODE_TYPE_ATTRIBUTE = 2;
2087var NODE_TYPE_TEXT = 3;
2088var NODE_TYPE_COMMENT = 8;
2089var NODE_TYPE_DOCUMENT = 9;
2090var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
2091
2092/**
2093 * @ngdoc type
2094 * @name angular.Module
2095 * @module ng
2096 * @description
2097 *
2098 * Interface for configuring angular {@link angular.module modules}.
2099 */
2100
2101function setupModuleLoader(window) {
2102
2103 var $injectorMinErr = minErr('$injector');
2104 var ngMinErr = minErr('ng');
2105
2106 function ensure(obj, name, factory) {
2107 return obj[name] || (obj[name] = factory());
2108 }
2109
2110 var angular = ensure(window, 'angular', Object);
2111
2112 // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
2113 angular.$$minErr = angular.$$minErr || minErr;
2114
2115 return ensure(angular, 'module', function() {
2116 /** @type {Object.<string, angular.Module>} */
2117 var modules = {};
2118
2119 /**
2120 * @ngdoc function
2121 * @name angular.module
2122 * @module ng
2123 * @description
2124 *
2125 * The `angular.module` is a global place for creating, registering and retrieving Angular
2126 * modules.
2127 * All modules (angular core or 3rd party) that should be available to an application must be
2128 * registered using this mechanism.
2129 *
2130 * Passing one argument retrieves an existing {@link angular.Module},
2131 * whereas passing more than one argument creates a new {@link angular.Module}
2132 *
2133 *
2134 * # Module
2135 *
2136 * A module is a collection of services, directives, controllers, filters, and configuration information.
2137 * `angular.module` is used to configure the {@link auto.$injector $injector}.
2138 *
2139 * ```js
2140 * // Create a new module
2141 * var myModule = angular.module('myModule', []);
2142 *
2143 * // register a new service
2144 * myModule.value('appName', 'MyCoolApp');
2145 *
2146 * // configure existing services inside initialization blocks.
2147 * myModule.config(['$locationProvider', function($locationProvider) {
2148 * // Configure existing providers
2149 * $locationProvider.hashPrefix('!');
2150 * }]);
2151 * ```
2152 *
2153 * Then you can create an injector and load your modules like this:
2154 *
2155 * ```js
2156 * var injector = angular.injector(['ng', 'myModule'])
2157 * ```
2158 *
2159 * However it's more likely that you'll just use
2160 * {@link ng.directive:ngApp ngApp} or
2161 * {@link angular.bootstrap} to simplify this process for you.
2162 *
2163 * @param {!string} name The name of the module to create or retrieve.
2164 * @param {!Array.<string>=} requires If specified then new module is being created. If
2165 * unspecified then the module is being retrieved for further configuration.
2166 * @param {Function=} configFn Optional configuration function for the module. Same as
2167 * {@link angular.Module#config Module#config()}.
2168 * @returns {angular.Module} new module with the {@link angular.Module} api.
2169 */
2170 return function module(name, requires, configFn) {
2171 var assertNotHasOwnProperty = function(name, context) {
2172 if (name === 'hasOwnProperty') {
2173 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
2174 }
2175 };
2176
2177 assertNotHasOwnProperty(name, 'module');
2178 if (requires && modules.hasOwnProperty(name)) {
2179 modules[name] = null;
2180 }
2181 return ensure(modules, name, function() {
2182 if (!requires) {
2183 throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
2184 'the module name or forgot to load it. If registering a module ensure that you ' +
2185 'specify the dependencies as the second argument.', name);
2186 }
2187
2188 /** @type {!Array.<Array.<*>>} */
2189 var invokeQueue = [];
2190
2191 /** @type {!Array.<Function>} */
2192 var configBlocks = [];
2193
2194 /** @type {!Array.<Function>} */
2195 var runBlocks = [];
2196
2197 var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
2198
2199 /** @type {angular.Module} */
2200 var moduleInstance = {
2201 // Private state
2202 _invokeQueue: invokeQueue,
2203 _configBlocks: configBlocks,
2204 _runBlocks: runBlocks,
2205
2206 /**
2207 * @ngdoc property
2208 * @name angular.Module#requires
2209 * @module ng
2210 *
2211 * @description
2212 * Holds the list of modules which the injector will load before the current module is
2213 * loaded.
2214 */
2215 requires: requires,
2216
2217 /**
2218 * @ngdoc property
2219 * @name angular.Module#name
2220 * @module ng
2221 *
2222 * @description
2223 * Name of the module.
2224 */
2225 name: name,
2226
2227
2228 /**
2229 * @ngdoc method
2230 * @name angular.Module#provider
2231 * @module ng
2232 * @param {string} name service name
2233 * @param {Function} providerType Construction function for creating new instance of the
2234 * service.
2235 * @description
2236 * See {@link auto.$provide#provider $provide.provider()}.
2237 */
2238 provider: invokeLaterAndSetModuleName('$provide', 'provider'),
2239
2240 /**
2241 * @ngdoc method
2242 * @name angular.Module#factory
2243 * @module ng
2244 * @param {string} name service name
2245 * @param {Function} providerFunction Function for creating new instance of the service.
2246 * @description
2247 * See {@link auto.$provide#factory $provide.factory()}.
2248 */
2249 factory: invokeLaterAndSetModuleName('$provide', 'factory'),
2250
2251 /**
2252 * @ngdoc method
2253 * @name angular.Module#service
2254 * @module ng
2255 * @param {string} name service name
2256 * @param {Function} constructor A constructor function that will be instantiated.
2257 * @description
2258 * See {@link auto.$provide#service $provide.service()}.
2259 */
2260 service: invokeLaterAndSetModuleName('$provide', 'service'),
2261
2262 /**
2263 * @ngdoc method
2264 * @name angular.Module#value
2265 * @module ng
2266 * @param {string} name service name
2267 * @param {*} object Service instance object.
2268 * @description
2269 * See {@link auto.$provide#value $provide.value()}.
2270 */
2271 value: invokeLater('$provide', 'value'),
2272
2273 /**
2274 * @ngdoc method
2275 * @name angular.Module#constant
2276 * @module ng
2277 * @param {string} name constant name
2278 * @param {*} object Constant value.
2279 * @description
2280 * Because the constants are fixed, they get applied before other provide methods.
2281 * See {@link auto.$provide#constant $provide.constant()}.
2282 */
2283 constant: invokeLater('$provide', 'constant', 'unshift'),
2284
2285 /**
2286 * @ngdoc method
2287 * @name angular.Module#decorator
2288 * @module ng
2289 * @param {string} name The name of the service to decorate.
2290 * @param {Function} decorFn This function will be invoked when the service needs to be
2291 * instantiated and should return the decorated service instance.
2292 * @description
2293 * See {@link auto.$provide#decorator $provide.decorator()}.
2294 */
2295 decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
2296
2297 /**
2298 * @ngdoc method
2299 * @name angular.Module#animation
2300 * @module ng
2301 * @param {string} name animation name
2302 * @param {Function} animationFactory Factory function for creating new instance of an
2303 * animation.
2304 * @description
2305 *
2306 * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
2307 *
2308 *
2309 * Defines an animation hook that can be later used with
2310 * {@link $animate $animate} service and directives that use this service.
2311 *
2312 * ```js
2313 * module.animation('.animation-name', function($inject1, $inject2) {
2314 * return {
2315 * eventName : function(element, done) {
2316 * //code to run the animation
2317 * //once complete, then run done()
2318 * return function cancellationFunction(element) {
2319 * //code to cancel the animation
2320 * }
2321 * }
2322 * }
2323 * })
2324 * ```
2325 *
2326 * See {@link ng.$animateProvider#register $animateProvider.register()} and
2327 * {@link ngAnimate ngAnimate module} for more information.
2328 */
2329 animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
2330
2331 /**
2332 * @ngdoc method
2333 * @name angular.Module#filter
2334 * @module ng
2335 * @param {string} name Filter name - this must be a valid angular expression identifier
2336 * @param {Function} filterFactory Factory function for creating new instance of filter.
2337 * @description
2338 * See {@link ng.$filterProvider#register $filterProvider.register()}.
2339 *
2340 * <div class="alert alert-warning">
2341 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
2342 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
2343 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
2344 * (`myapp_subsection_filterx`).
2345 * </div>
2346 */
2347 filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
2348
2349 /**
2350 * @ngdoc method
2351 * @name angular.Module#controller
2352 * @module ng
2353 * @param {string|Object} name Controller name, or an object map of controllers where the
2354 * keys are the names and the values are the constructors.
2355 * @param {Function} constructor Controller constructor function.
2356 * @description
2357 * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
2358 */
2359 controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
2360
2361 /**
2362 * @ngdoc method
2363 * @name angular.Module#directive
2364 * @module ng
2365 * @param {string|Object} name Directive name, or an object map of directives where the
2366 * keys are the names and the values are the factories.
2367 * @param {Function} directiveFactory Factory function for creating new instance of
2368 * directives.
2369 * @description
2370 * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
2371 */
2372 directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
2373
2374 /**
2375 * @ngdoc method
2376 * @name angular.Module#component
2377 * @module ng
2378 * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
2379 * @param {Object} options Component definition object (a simplified
2380 * {@link ng.$compile#directive-definition-object directive definition object})
2381 *
2382 * @description
2383 * See {@link ng.$compileProvider#component $compileProvider.component()}.
2384 */
2385 component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
2386
2387 /**
2388 * @ngdoc method
2389 * @name angular.Module#config
2390 * @module ng
2391 * @param {Function} configFn Execute this function on module load. Useful for service
2392 * configuration.
2393 * @description
2394 * Use this method to register work which needs to be performed on module loading.
2395 * For more about how to configure services, see
2396 * {@link providers#provider-recipe Provider Recipe}.
2397 */
2398 config: config,
2399
2400 /**
2401 * @ngdoc method
2402 * @name angular.Module#run
2403 * @module ng
2404 * @param {Function} initializationFn Execute this function after injector creation.
2405 * Useful for application initialization.
2406 * @description
2407 * Use this method to register work which should be performed when the injector is done
2408 * loading all modules.
2409 */
2410 run: function(block) {
2411 runBlocks.push(block);
2412 return this;
2413 }
2414 };
2415
2416 if (configFn) {
2417 config(configFn);
2418 }
2419
2420 return moduleInstance;
2421
2422 /**
2423 * @param {string} provider
2424 * @param {string} method
2425 * @param {String=} insertMethod
2426 * @returns {angular.Module}
2427 */
2428 function invokeLater(provider, method, insertMethod, queue) {
2429 if (!queue) queue = invokeQueue;
2430 return function() {
2431 queue[insertMethod || 'push']([provider, method, arguments]);
2432 return moduleInstance;
2433 };
2434 }
2435
2436 /**
2437 * @param {string} provider
2438 * @param {string} method
2439 * @returns {angular.Module}
2440 */
2441 function invokeLaterAndSetModuleName(provider, method, queue) {
2442 if (!queue) queue = invokeQueue;
2443 return function(recipeName, factoryFunction) {
2444 if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
2445 queue.push([provider, method, arguments]);
2446 return moduleInstance;
2447 };
2448 }
2449 });
2450 };
2451 });
2452
2453}
2454
2455/* global shallowCopy: true */
2456
2457/**
2458 * Creates a shallow copy of an object, an array or a primitive.
2459 *
2460 * Assumes that there are no proto properties for objects.
2461 */
2462function shallowCopy(src, dst) {
2463 if (isArray(src)) {
2464 dst = dst || [];
2465
2466 for (var i = 0, ii = src.length; i < ii; i++) {
2467 dst[i] = src[i];
2468 }
2469 } else if (isObject(src)) {
2470 dst = dst || {};
2471
2472 for (var key in src) {
2473 if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
2474 dst[key] = src[key];
2475 }
2476 }
2477 }
2478
2479 return dst || src;
2480}
2481
2482/* global toDebugString: true */
2483
2484function serializeObject(obj) {
2485 var seen = [];
2486
2487 return JSON.stringify(obj, function(key, val) {
2488 val = toJsonReplacer(key, val);
2489 if (isObject(val)) {
2490
2491 if (seen.indexOf(val) >= 0) return '...';
2492
2493 seen.push(val);
2494 }
2495 return val;
2496 });
2497}
2498
2499function toDebugString(obj) {
2500 if (typeof obj === 'function') {
2501 return obj.toString().replace(/ \{[\s\S]*$/, '');
2502 } else if (isUndefined(obj)) {
2503 return 'undefined';
2504 } else if (typeof obj !== 'string') {
2505 return serializeObject(obj);
2506 }
2507 return obj;
2508}
2509
2510/* global angularModule: true,
2511 version: true,
2512
2513 $CompileProvider,
2514
2515 htmlAnchorDirective,
2516 inputDirective,
2517 inputDirective,
2518 formDirective,
2519 scriptDirective,
2520 selectDirective,
2521 optionDirective,
2522 ngBindDirective,
2523 ngBindHtmlDirective,
2524 ngBindTemplateDirective,
2525 ngClassDirective,
2526 ngClassEvenDirective,
2527 ngClassOddDirective,
2528 ngCloakDirective,
2529 ngControllerDirective,
2530 ngFormDirective,
2531 ngHideDirective,
2532 ngIfDirective,
2533 ngIncludeDirective,
2534 ngIncludeFillContentDirective,
2535 ngInitDirective,
2536 ngNonBindableDirective,
2537 ngPluralizeDirective,
2538 ngRepeatDirective,
2539 ngShowDirective,
2540 ngStyleDirective,
2541 ngSwitchDirective,
2542 ngSwitchWhenDirective,
2543 ngSwitchDefaultDirective,
2544 ngOptionsDirective,
2545 ngTranscludeDirective,
2546 ngModelDirective,
2547 ngListDirective,
2548 ngChangeDirective,
2549 patternDirective,
2550 patternDirective,
2551 requiredDirective,
2552 requiredDirective,
2553 minlengthDirective,
2554 minlengthDirective,
2555 maxlengthDirective,
2556 maxlengthDirective,
2557 ngValueDirective,
2558 ngModelOptionsDirective,
2559 ngAttributeAliasDirectives,
2560 ngEventDirectives,
2561
2562 $AnchorScrollProvider,
2563 $AnimateProvider,
2564 $CoreAnimateCssProvider,
2565 $$CoreAnimateJsProvider,
2566 $$CoreAnimateQueueProvider,
2567 $$AnimateRunnerFactoryProvider,
2568 $$AnimateAsyncRunFactoryProvider,
2569 $BrowserProvider,
2570 $CacheFactoryProvider,
2571 $ControllerProvider,
2572 $DateProvider,
2573 $DocumentProvider,
2574 $$IsDocumentHiddenProvider,
2575 $ExceptionHandlerProvider,
2576 $FilterProvider,
2577 $$ForceReflowProvider,
2578 $InterpolateProvider,
2579 $IntervalProvider,
2580 $$HashMapProvider,
2581 $HttpProvider,
2582 $HttpParamSerializerProvider,
2583 $HttpParamSerializerJQLikeProvider,
2584 $HttpBackendProvider,
2585 $xhrFactoryProvider,
2586 $jsonpCallbacksProvider,
2587 $LocationProvider,
2588 $LogProvider,
2589 $ParseProvider,
2590 $RootScopeProvider,
2591 $QProvider,
2592 $$QProvider,
2593 $$SanitizeUriProvider,
2594 $SceProvider,
2595 $SceDelegateProvider,
2596 $SnifferProvider,
2597 $TemplateCacheProvider,
2598 $TemplateRequestProvider,
2599 $$TestabilityProvider,
2600 $TimeoutProvider,
2601 $$RAFProvider,
2602 $WindowProvider,
2603 $$jqLiteProvider,
2604 $$CookieReaderProvider
2605*/
2606
2607
2608/**
2609 * @ngdoc object
2610 * @name angular.version
2611 * @module ng
2612 * @description
2613 * An object that contains information about the current AngularJS version.
2614 *
2615 * This object has the following properties:
2616 *
2617 * - `full` – `{string}` – Full version string, such as "0.9.18".
2618 * - `major` – `{number}` – Major version number, such as "0".
2619 * - `minor` – `{number}` – Minor version number, such as "9".
2620 * - `dot` – `{number}` – Dot version number, such as "18".
2621 * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
2622 */
2623var version = {
2624 // These placeholder strings will be replaced by grunt's `build` task.
2625 // They need to be double- or single-quoted.
2626 full: '1.6.1',
2627 major: 1,
2628 minor: 6,
2629 dot: 1,
2630 codeName: 'promise-rectification'
2631};
2632
2633
2634function publishExternalAPI(angular) {
2635 extend(angular, {
2636 'bootstrap': bootstrap,
2637 'copy': copy,
2638 'extend': extend,
2639 'merge': merge,
2640 'equals': equals,
2641 'element': jqLite,
2642 'forEach': forEach,
2643 'injector': createInjector,
2644 'noop': noop,
2645 'bind': bind,
2646 'toJson': toJson,
2647 'fromJson': fromJson,
2648 'identity': identity,
2649 'isUndefined': isUndefined,
2650 'isDefined': isDefined,
2651 'isString': isString,
2652 'isFunction': isFunction,
2653 'isObject': isObject,
2654 'isNumber': isNumber,
2655 'isElement': isElement,
2656 'isArray': isArray,
2657 'version': version,
2658 'isDate': isDate,
2659 'lowercase': lowercase,
2660 'uppercase': uppercase,
2661 'callbacks': {$$counter: 0},
2662 'getTestability': getTestability,
2663 'reloadWithDebugInfo': reloadWithDebugInfo,
2664 '$$minErr': minErr,
2665 '$$csp': csp,
2666 '$$encodeUriSegment': encodeUriSegment,
2667 '$$encodeUriQuery': encodeUriQuery,
2668 '$$stringify': stringify
2669 });
2670
2671 angularModule = setupModuleLoader(window);
2672
2673 angularModule('ng', ['ngLocale'], ['$provide',
2674 function ngModule($provide) {
2675 // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
2676 $provide.provider({
2677 $$sanitizeUri: $$SanitizeUriProvider
2678 });
2679 $provide.provider('$compile', $CompileProvider).
2680 directive({
2681 a: htmlAnchorDirective,
2682 input: inputDirective,
2683 textarea: inputDirective,
2684 form: formDirective,
2685 script: scriptDirective,
2686 select: selectDirective,
2687 option: optionDirective,
2688 ngBind: ngBindDirective,
2689 ngBindHtml: ngBindHtmlDirective,
2690 ngBindTemplate: ngBindTemplateDirective,
2691 ngClass: ngClassDirective,
2692 ngClassEven: ngClassEvenDirective,
2693 ngClassOdd: ngClassOddDirective,
2694 ngCloak: ngCloakDirective,
2695 ngController: ngControllerDirective,
2696 ngForm: ngFormDirective,
2697 ngHide: ngHideDirective,
2698 ngIf: ngIfDirective,
2699 ngInclude: ngIncludeDirective,
2700 ngInit: ngInitDirective,
2701 ngNonBindable: ngNonBindableDirective,
2702 ngPluralize: ngPluralizeDirective,
2703 ngRepeat: ngRepeatDirective,
2704 ngShow: ngShowDirective,
2705 ngStyle: ngStyleDirective,
2706 ngSwitch: ngSwitchDirective,
2707 ngSwitchWhen: ngSwitchWhenDirective,
2708 ngSwitchDefault: ngSwitchDefaultDirective,
2709 ngOptions: ngOptionsDirective,
2710 ngTransclude: ngTranscludeDirective,
2711 ngModel: ngModelDirective,
2712 ngList: ngListDirective,
2713 ngChange: ngChangeDirective,
2714 pattern: patternDirective,
2715 ngPattern: patternDirective,
2716 required: requiredDirective,
2717 ngRequired: requiredDirective,
2718 minlength: minlengthDirective,
2719 ngMinlength: minlengthDirective,
2720 maxlength: maxlengthDirective,
2721 ngMaxlength: maxlengthDirective,
2722 ngValue: ngValueDirective,
2723 ngModelOptions: ngModelOptionsDirective
2724 }).
2725 directive({
2726 ngInclude: ngIncludeFillContentDirective
2727 }).
2728 directive(ngAttributeAliasDirectives).
2729 directive(ngEventDirectives);
2730 $provide.provider({
2731 $anchorScroll: $AnchorScrollProvider,
2732 $animate: $AnimateProvider,
2733 $animateCss: $CoreAnimateCssProvider,
2734 $$animateJs: $$CoreAnimateJsProvider,
2735 $$animateQueue: $$CoreAnimateQueueProvider,
2736 $$AnimateRunner: $$AnimateRunnerFactoryProvider,
2737 $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
2738 $browser: $BrowserProvider,
2739 $cacheFactory: $CacheFactoryProvider,
2740 $controller: $ControllerProvider,
2741 $document: $DocumentProvider,
2742 $$isDocumentHidden: $$IsDocumentHiddenProvider,
2743 $exceptionHandler: $ExceptionHandlerProvider,
2744 $filter: $FilterProvider,
2745 $$forceReflow: $$ForceReflowProvider,
2746 $interpolate: $InterpolateProvider,
2747 $interval: $IntervalProvider,
2748 $http: $HttpProvider,
2749 $httpParamSerializer: $HttpParamSerializerProvider,
2750 $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
2751 $httpBackend: $HttpBackendProvider,
2752 $xhrFactory: $xhrFactoryProvider,
2753 $jsonpCallbacks: $jsonpCallbacksProvider,
2754 $location: $LocationProvider,
2755 $log: $LogProvider,
2756 $parse: $ParseProvider,
2757 $rootScope: $RootScopeProvider,
2758 $q: $QProvider,
2759 $$q: $$QProvider,
2760 $sce: $SceProvider,
2761 $sceDelegate: $SceDelegateProvider,
2762 $sniffer: $SnifferProvider,
2763 $templateCache: $TemplateCacheProvider,
2764 $templateRequest: $TemplateRequestProvider,
2765 $$testability: $$TestabilityProvider,
2766 $timeout: $TimeoutProvider,
2767 $window: $WindowProvider,
2768 $$rAF: $$RAFProvider,
2769 $$jqLite: $$jqLiteProvider,
2770 $$HashMap: $$HashMapProvider,
2771 $$cookieReader: $$CookieReaderProvider
2772 });
2773 }
2774 ]);
2775}
2776
2777/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2778 * Any commits to this file should be reviewed with security in mind. *
2779 * Changes to this file can potentially create security vulnerabilities. *
2780 * An approval from 2 Core members with history of modifying *
2781 * this file is required. *
2782 * *
2783 * Does the change somehow allow for arbitrary javascript to be executed? *
2784 * Or allows for someone to change the prototype of built-in objects? *
2785 * Or gives undesired access to variables likes document or window? *
2786 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2787
2788/* global
2789 JQLitePrototype: true,
2790 BOOLEAN_ATTR: true,
2791 ALIASED_ATTR: true
2792*/
2793
2794//////////////////////////////////
2795//JQLite
2796//////////////////////////////////
2797
2798/**
2799 * @ngdoc function
2800 * @name angular.element
2801 * @module ng
2802 * @kind function
2803 *
2804 * @description
2805 * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
2806 *
2807 * If jQuery is available, `angular.element` is an alias for the
2808 * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
2809 * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
2810 *
2811 * jqLite is a tiny, API-compatible subset of jQuery that allows
2812 * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
2813 * commonly needed functionality with the goal of having a very small footprint.
2814 *
2815 * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
2816 * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
2817 * specific version of jQuery if multiple versions exist on the page.
2818 *
2819 * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
2820 * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
2821 *
2822 * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
2823 * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
2824 * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
2825 *
2826 * ## Angular's jqLite
2827 * jqLite provides only the following jQuery methods:
2828 *
2829 * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
2830 * - [`after()`](http://api.jquery.com/after/)
2831 * - [`append()`](http://api.jquery.com/append/)
2832 * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
2833 * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
2834 * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
2835 * - [`clone()`](http://api.jquery.com/clone/)
2836 * - [`contents()`](http://api.jquery.com/contents/)
2837 * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
2838 * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
2839 * - [`data()`](http://api.jquery.com/data/)
2840 * - [`detach()`](http://api.jquery.com/detach/)
2841 * - [`empty()`](http://api.jquery.com/empty/)
2842 * - [`eq()`](http://api.jquery.com/eq/)
2843 * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
2844 * - [`hasClass()`](http://api.jquery.com/hasClass/)
2845 * - [`html()`](http://api.jquery.com/html/)
2846 * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
2847 * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
2848 * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
2849 * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
2850 * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
2851 * - [`prepend()`](http://api.jquery.com/prepend/)
2852 * - [`prop()`](http://api.jquery.com/prop/)
2853 * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
2854 * - [`remove()`](http://api.jquery.com/remove/)
2855 * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
2856 * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
2857 * - [`removeData()`](http://api.jquery.com/removeData/)
2858 * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
2859 * - [`text()`](http://api.jquery.com/text/)
2860 * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
2861 * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
2862 * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
2863 * - [`val()`](http://api.jquery.com/val/)
2864 * - [`wrap()`](http://api.jquery.com/wrap/)
2865 *
2866 * ## jQuery/jqLite Extras
2867 * Angular also provides the following additional methods and events to both jQuery and jqLite:
2868 *
2869 * ### Events
2870 * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
2871 * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
2872 * element before it is removed.
2873 *
2874 * ### Methods
2875 * - `controller(name)` - retrieves the controller of the current element or its parent. By default
2876 * retrieves controller associated with the `ngController` directive. If `name` is provided as
2877 * camelCase directive name, then the controller for this directive will be retrieved (e.g.
2878 * `'ngModel'`).
2879 * - `injector()` - retrieves the injector of the current element or its parent.
2880 * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
2881 * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
2882 * be enabled.
2883 * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
2884 * current element. This getter should be used only on elements that contain a directive which starts a new isolate
2885 * scope. Calling `scope()` on this element always returns the original non-isolate scope.
2886 * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
2887 * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
2888 * parent element is reached.
2889 *
2890 * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
2891 * https://github.com/angular/angular.js/issues/14251 for more information.
2892 *
2893 * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
2894 * @returns {Object} jQuery object.
2895 */
2896
2897JQLite.expando = 'ng339';
2898
2899var jqCache = JQLite.cache = {},
2900 jqId = 1;
2901
2902/*
2903 * !!! This is an undocumented "private" function !!!
2904 */
2905JQLite._data = function(node) {
2906 //jQuery always returns an object on cache miss
2907 return this.cache[node[this.expando]] || {};
2908};
2909
2910function jqNextId() { return ++jqId; }
2911
2912
2913var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
2914var MS_HACK_REGEXP = /^-ms-/;
2915var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
2916var jqLiteMinErr = minErr('jqLite');
2917
2918/**
2919 * Converts kebab-case to camelCase.
2920 * There is also a special case for the ms prefix starting with a lowercase letter.
2921 * @param name Name to normalize
2922 */
2923function cssKebabToCamel(name) {
2924 return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
2925}
2926
2927function fnCamelCaseReplace(all, letter) {
2928 return letter.toUpperCase();
2929}
2930
2931/**
2932 * Converts kebab-case to camelCase.
2933 * @param name Name to normalize
2934 */
2935function kebabToCamel(name) {
2936 return name
2937 .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
2938}
2939
2940var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
2941var HTML_REGEXP = /<|&#?\w+;/;
2942var TAG_NAME_REGEXP = /<([\w:-]+)/;
2943var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
2944
2945var wrapMap = {
2946 'option': [1, '<select multiple="multiple">', '</select>'],
2947
2948 'thead': [1, '<table>', '</table>'],
2949 'col': [2, '<table><colgroup>', '</colgroup></table>'],
2950 'tr': [2, '<table><tbody>', '</tbody></table>'],
2951 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
2952 '_default': [0, '', '']
2953};
2954
2955wrapMap.optgroup = wrapMap.option;
2956wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
2957wrapMap.th = wrapMap.td;
2958
2959
2960function jqLiteIsTextNode(html) {
2961 return !HTML_REGEXP.test(html);
2962}
2963
2964function jqLiteAcceptsData(node) {
2965 // The window object can accept data but has no nodeType
2966 // Otherwise we are only interested in elements (1) and documents (9)
2967 var nodeType = node.nodeType;
2968 return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
2969}
2970
2971function jqLiteHasData(node) {
2972 for (var key in jqCache[node.ng339]) {
2973 return true;
2974 }
2975 return false;
2976}
2977
2978function jqLiteCleanData(nodes) {
2979 for (var i = 0, ii = nodes.length; i < ii; i++) {
2980 jqLiteRemoveData(nodes[i]);
2981 }
2982}
2983
2984function jqLiteBuildFragment(html, context) {
2985 var tmp, tag, wrap,
2986 fragment = context.createDocumentFragment(),
2987 nodes = [], i;
2988
2989 if (jqLiteIsTextNode(html)) {
2990 // Convert non-html into a text node
2991 nodes.push(context.createTextNode(html));
2992 } else {
2993 // Convert html into DOM nodes
2994 tmp = fragment.appendChild(context.createElement('div'));
2995 tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
2996 wrap = wrapMap[tag] || wrapMap._default;
2997 tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
2998
2999 // Descend through wrappers to the right content
3000 i = wrap[0];
3001 while (i--) {
3002 tmp = tmp.lastChild;
3003 }
3004
3005 nodes = concat(nodes, tmp.childNodes);
3006
3007 tmp = fragment.firstChild;
3008 tmp.textContent = '';
3009 }
3010
3011 // Remove wrapper from fragment
3012 fragment.textContent = '';
3013 fragment.innerHTML = ''; // Clear inner HTML
3014 forEach(nodes, function(node) {
3015 fragment.appendChild(node);
3016 });
3017
3018 return fragment;
3019}
3020
3021function jqLiteParseHTML(html, context) {
3022 context = context || window.document;
3023 var parsed;
3024
3025 if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
3026 return [context.createElement(parsed[1])];
3027 }
3028
3029 if ((parsed = jqLiteBuildFragment(html, context))) {
3030 return parsed.childNodes;
3031 }
3032
3033 return [];
3034}
3035
3036function jqLiteWrapNode(node, wrapper) {
3037 var parent = node.parentNode;
3038
3039 if (parent) {
3040 parent.replaceChild(wrapper, node);
3041 }
3042
3043 wrapper.appendChild(node);
3044}
3045
3046
3047// IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
3048var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
3049 // eslint-disable-next-line no-bitwise
3050 return !!(this.compareDocumentPosition(arg) & 16);
3051};
3052
3053/////////////////////////////////////////////
3054function JQLite(element) {
3055 if (element instanceof JQLite) {
3056 return element;
3057 }
3058
3059 var argIsString;
3060
3061 if (isString(element)) {
3062 element = trim(element);
3063 argIsString = true;
3064 }
3065 if (!(this instanceof JQLite)) {
3066 if (argIsString && element.charAt(0) !== '<') {
3067 throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
3068 }
3069 return new JQLite(element);
3070 }
3071
3072 if (argIsString) {
3073 jqLiteAddNodes(this, jqLiteParseHTML(element));
3074 } else if (isFunction(element)) {
3075 jqLiteReady(element);
3076 } else {
3077 jqLiteAddNodes(this, element);
3078 }
3079}
3080
3081function jqLiteClone(element) {
3082 return element.cloneNode(true);
3083}
3084
3085function jqLiteDealoc(element, onlyDescendants) {
3086 if (!onlyDescendants) jqLiteRemoveData(element);
3087
3088 if (element.querySelectorAll) {
3089 var descendants = element.querySelectorAll('*');
3090 for (var i = 0, l = descendants.length; i < l; i++) {
3091 jqLiteRemoveData(descendants[i]);
3092 }
3093 }
3094}
3095
3096function jqLiteOff(element, type, fn, unsupported) {
3097 if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
3098
3099 var expandoStore = jqLiteExpandoStore(element);
3100 var events = expandoStore && expandoStore.events;
3101 var handle = expandoStore && expandoStore.handle;
3102
3103 if (!handle) return; //no listeners registered
3104
3105 if (!type) {
3106 for (type in events) {
3107 if (type !== '$destroy') {
3108 element.removeEventListener(type, handle);
3109 }
3110 delete events[type];
3111 }
3112 } else {
3113
3114 var removeHandler = function(type) {
3115 var listenerFns = events[type];
3116 if (isDefined(fn)) {
3117 arrayRemove(listenerFns || [], fn);
3118 }
3119 if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
3120 element.removeEventListener(type, handle);
3121 delete events[type];
3122 }
3123 };
3124
3125 forEach(type.split(' '), function(type) {
3126 removeHandler(type);
3127 if (MOUSE_EVENT_MAP[type]) {
3128 removeHandler(MOUSE_EVENT_MAP[type]);
3129 }
3130 });
3131 }
3132}
3133
3134function jqLiteRemoveData(element, name) {
3135 var expandoId = element.ng339;
3136 var expandoStore = expandoId && jqCache[expandoId];
3137
3138 if (expandoStore) {
3139 if (name) {
3140 delete expandoStore.data[name];
3141 return;
3142 }
3143
3144 if (expandoStore.handle) {
3145 if (expandoStore.events.$destroy) {
3146 expandoStore.handle({}, '$destroy');
3147 }
3148 jqLiteOff(element);
3149 }
3150 delete jqCache[expandoId];
3151 element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
3152 }
3153}
3154
3155
3156function jqLiteExpandoStore(element, createIfNecessary) {
3157 var expandoId = element.ng339,
3158 expandoStore = expandoId && jqCache[expandoId];
3159
3160 if (createIfNecessary && !expandoStore) {
3161 element.ng339 = expandoId = jqNextId();
3162 expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
3163 }
3164
3165 return expandoStore;
3166}
3167
3168
3169function jqLiteData(element, key, value) {
3170 if (jqLiteAcceptsData(element)) {
3171 var prop;
3172
3173 var isSimpleSetter = isDefined(value);
3174 var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
3175 var massGetter = !key;
3176 var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
3177 var data = expandoStore && expandoStore.data;
3178
3179 if (isSimpleSetter) { // data('key', value)
3180 data[kebabToCamel(key)] = value;
3181 } else {
3182 if (massGetter) { // data()
3183 return data;
3184 } else {
3185 if (isSimpleGetter) { // data('key')
3186 // don't force creation of expandoStore if it doesn't exist yet
3187 return data && data[kebabToCamel(key)];
3188 } else { // mass-setter: data({key1: val1, key2: val2})
3189 for (prop in key) {
3190 data[kebabToCamel(prop)] = key[prop];
3191 }
3192 }
3193 }
3194 }
3195 }
3196}
3197
3198function jqLiteHasClass(element, selector) {
3199 if (!element.getAttribute) return false;
3200 return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
3201 indexOf(' ' + selector + ' ') > -1);
3202}
3203
3204function jqLiteRemoveClass(element, cssClasses) {
3205 if (cssClasses && element.setAttribute) {
3206 forEach(cssClasses.split(' '), function(cssClass) {
3207 element.setAttribute('class', trim(
3208 (' ' + (element.getAttribute('class') || '') + ' ')
3209 .replace(/[\n\t]/g, ' ')
3210 .replace(' ' + trim(cssClass) + ' ', ' '))
3211 );
3212 });
3213 }
3214}
3215
3216function jqLiteAddClass(element, cssClasses) {
3217 if (cssClasses && element.setAttribute) {
3218 var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
3219 .replace(/[\n\t]/g, ' ');
3220
3221 forEach(cssClasses.split(' '), function(cssClass) {
3222 cssClass = trim(cssClass);
3223 if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
3224 existingClasses += cssClass + ' ';
3225 }
3226 });
3227
3228 element.setAttribute('class', trim(existingClasses));
3229 }
3230}
3231
3232
3233function jqLiteAddNodes(root, elements) {
3234 // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
3235
3236 if (elements) {
3237
3238 // if a Node (the most common case)
3239 if (elements.nodeType) {
3240 root[root.length++] = elements;
3241 } else {
3242 var length = elements.length;
3243
3244 // if an Array or NodeList and not a Window
3245 if (typeof length === 'number' && elements.window !== elements) {
3246 if (length) {
3247 for (var i = 0; i < length; i++) {
3248 root[root.length++] = elements[i];
3249 }
3250 }
3251 } else {
3252 root[root.length++] = elements;
3253 }
3254 }
3255 }
3256}
3257
3258
3259function jqLiteController(element, name) {
3260 return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
3261}
3262
3263function jqLiteInheritedData(element, name, value) {
3264 // if element is the document object work with the html element instead
3265 // this makes $(document).scope() possible
3266 if (element.nodeType === NODE_TYPE_DOCUMENT) {
3267 element = element.documentElement;
3268 }
3269 var names = isArray(name) ? name : [name];
3270
3271 while (element) {
3272 for (var i = 0, ii = names.length; i < ii; i++) {
3273 if (isDefined(value = jqLite.data(element, names[i]))) return value;
3274 }
3275
3276 // If dealing with a document fragment node with a host element, and no parent, use the host
3277 // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
3278 // to lookup parent controllers.
3279 element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
3280 }
3281}
3282
3283function jqLiteEmpty(element) {
3284 jqLiteDealoc(element, true);
3285 while (element.firstChild) {
3286 element.removeChild(element.firstChild);
3287 }
3288}
3289
3290function jqLiteRemove(element, keepData) {
3291 if (!keepData) jqLiteDealoc(element);
3292 var parent = element.parentNode;
3293 if (parent) parent.removeChild(element);
3294}
3295
3296
3297function jqLiteDocumentLoaded(action, win) {
3298 win = win || window;
3299 if (win.document.readyState === 'complete') {
3300 // Force the action to be run async for consistent behavior
3301 // from the action's point of view
3302 // i.e. it will definitely not be in a $apply
3303 win.setTimeout(action);
3304 } else {
3305 // No need to unbind this handler as load is only ever called once
3306 jqLite(win).on('load', action);
3307 }
3308}
3309
3310function jqLiteReady(fn) {
3311 function trigger() {
3312 window.document.removeEventListener('DOMContentLoaded', trigger);
3313 window.removeEventListener('load', trigger);
3314 fn();
3315 }
3316
3317 // check if document is already loaded
3318 if (window.document.readyState === 'complete') {
3319 window.setTimeout(fn);
3320 } else {
3321 // We can not use jqLite since we are not done loading and jQuery could be loaded later.
3322
3323 // Works for modern browsers and IE9
3324 window.document.addEventListener('DOMContentLoaded', trigger);
3325
3326 // Fallback to window.onload for others
3327 window.addEventListener('load', trigger);
3328 }
3329}
3330
3331//////////////////////////////////////////
3332// Functions which are declared directly.
3333//////////////////////////////////////////
3334var JQLitePrototype = JQLite.prototype = {
3335 ready: jqLiteReady,
3336 toString: function() {
3337 var value = [];
3338 forEach(this, function(e) { value.push('' + e);});
3339 return '[' + value.join(', ') + ']';
3340 },
3341
3342 eq: function(index) {
3343 return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
3344 },
3345
3346 length: 0,
3347 push: push,
3348 sort: [].sort,
3349 splice: [].splice
3350};
3351
3352//////////////////////////////////////////
3353// Functions iterating getter/setters.
3354// these functions return self on setter and
3355// value on get.
3356//////////////////////////////////////////
3357var BOOLEAN_ATTR = {};
3358forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
3359 BOOLEAN_ATTR[lowercase(value)] = value;
3360});
3361var BOOLEAN_ELEMENTS = {};
3362forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
3363 BOOLEAN_ELEMENTS[value] = true;
3364});
3365var ALIASED_ATTR = {
3366 'ngMinlength': 'minlength',
3367 'ngMaxlength': 'maxlength',
3368 'ngMin': 'min',
3369 'ngMax': 'max',
3370 'ngPattern': 'pattern',
3371 'ngStep': 'step'
3372};
3373
3374function getBooleanAttrName(element, name) {
3375 // check dom last since we will most likely fail on name
3376 var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
3377
3378 // booleanAttr is here twice to minimize DOM access
3379 return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
3380}
3381
3382function getAliasedAttrName(name) {
3383 return ALIASED_ATTR[name];
3384}
3385
3386forEach({
3387 data: jqLiteData,
3388 removeData: jqLiteRemoveData,
3389 hasData: jqLiteHasData,
3390 cleanData: jqLiteCleanData
3391}, function(fn, name) {
3392 JQLite[name] = fn;
3393});
3394
3395forEach({
3396 data: jqLiteData,
3397 inheritedData: jqLiteInheritedData,
3398
3399 scope: function(element) {
3400 // Can't use jqLiteData here directly so we stay compatible with jQuery!
3401 return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
3402 },
3403
3404 isolateScope: function(element) {
3405 // Can't use jqLiteData here directly so we stay compatible with jQuery!
3406 return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
3407 },
3408
3409 controller: jqLiteController,
3410
3411 injector: function(element) {
3412 return jqLiteInheritedData(element, '$injector');
3413 },
3414
3415 removeAttr: function(element, name) {
3416 element.removeAttribute(name);
3417 },
3418
3419 hasClass: jqLiteHasClass,
3420
3421 css: function(element, name, value) {
3422 name = cssKebabToCamel(name);
3423
3424 if (isDefined(value)) {
3425 element.style[name] = value;
3426 } else {
3427 return element.style[name];
3428 }
3429 },
3430
3431 attr: function(element, name, value) {
3432 var ret;
3433 var nodeType = element.nodeType;
3434 if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
3435 !element.getAttribute) {
3436 return;
3437 }
3438
3439 var lowercasedName = lowercase(name);
3440 var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
3441
3442 if (isDefined(value)) {
3443 // setter
3444
3445 if (value === null || (value === false && isBooleanAttr)) {
3446 element.removeAttribute(name);
3447 } else {
3448 element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
3449 }
3450 } else {
3451 // getter
3452
3453 ret = element.getAttribute(name);
3454
3455 if (isBooleanAttr && ret !== null) {
3456 ret = lowercasedName;
3457 }
3458 // Normalize non-existing attributes to undefined (as jQuery).
3459 return ret === null ? undefined : ret;
3460 }
3461 },
3462
3463 prop: function(element, name, value) {
3464 if (isDefined(value)) {
3465 element[name] = value;
3466 } else {
3467 return element[name];
3468 }
3469 },
3470
3471 text: (function() {
3472 getText.$dv = '';
3473 return getText;
3474
3475 function getText(element, value) {
3476 if (isUndefined(value)) {
3477 var nodeType = element.nodeType;
3478 return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
3479 }
3480 element.textContent = value;
3481 }
3482 })(),
3483
3484 val: function(element, value) {
3485 if (isUndefined(value)) {
3486 if (element.multiple && nodeName_(element) === 'select') {
3487 var result = [];
3488 forEach(element.options, function(option) {
3489 if (option.selected) {
3490 result.push(option.value || option.text);
3491 }
3492 });
3493 return result;
3494 }
3495 return element.value;
3496 }
3497 element.value = value;
3498 },
3499
3500 html: function(element, value) {
3501 if (isUndefined(value)) {
3502 return element.innerHTML;
3503 }
3504 jqLiteDealoc(element, true);
3505 element.innerHTML = value;
3506 },
3507
3508 empty: jqLiteEmpty
3509}, function(fn, name) {
3510 /**
3511 * Properties: writes return selection, reads return first value
3512 */
3513 JQLite.prototype[name] = function(arg1, arg2) {
3514 var i, key;
3515 var nodeCount = this.length;
3516
3517 // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
3518 // in a way that survives minification.
3519 // jqLiteEmpty takes no arguments but is a setter.
3520 if (fn !== jqLiteEmpty &&
3521 (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
3522 if (isObject(arg1)) {
3523
3524 // we are a write, but the object properties are the key/values
3525 for (i = 0; i < nodeCount; i++) {
3526 if (fn === jqLiteData) {
3527 // data() takes the whole object in jQuery
3528 fn(this[i], arg1);
3529 } else {
3530 for (key in arg1) {
3531 fn(this[i], key, arg1[key]);
3532 }
3533 }
3534 }
3535 // return self for chaining
3536 return this;
3537 } else {
3538 // we are a read, so read the first child.
3539 // TODO: do we still need this?
3540 var value = fn.$dv;
3541 // Only if we have $dv do we iterate over all, otherwise it is just the first element.
3542 var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
3543 for (var j = 0; j < jj; j++) {
3544 var nodeValue = fn(this[j], arg1, arg2);
3545 value = value ? value + nodeValue : nodeValue;
3546 }
3547 return value;
3548 }
3549 } else {
3550 // we are a write, so apply to all children
3551 for (i = 0; i < nodeCount; i++) {
3552 fn(this[i], arg1, arg2);
3553 }
3554 // return self for chaining
3555 return this;
3556 }
3557 };
3558});
3559
3560function createEventHandler(element, events) {
3561 var eventHandler = function(event, type) {
3562 // jQuery specific api
3563 event.isDefaultPrevented = function() {
3564 return event.defaultPrevented;
3565 };
3566
3567 var eventFns = events[type || event.type];
3568 var eventFnsLength = eventFns ? eventFns.length : 0;
3569
3570 if (!eventFnsLength) return;
3571
3572 if (isUndefined(event.immediatePropagationStopped)) {
3573 var originalStopImmediatePropagation = event.stopImmediatePropagation;
3574 event.stopImmediatePropagation = function() {
3575 event.immediatePropagationStopped = true;
3576
3577 if (event.stopPropagation) {
3578 event.stopPropagation();
3579 }
3580
3581 if (originalStopImmediatePropagation) {
3582 originalStopImmediatePropagation.call(event);
3583 }
3584 };
3585 }
3586
3587 event.isImmediatePropagationStopped = function() {
3588 return event.immediatePropagationStopped === true;
3589 };
3590
3591 // Some events have special handlers that wrap the real handler
3592 var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
3593
3594 // Copy event handlers in case event handlers array is modified during execution.
3595 if ((eventFnsLength > 1)) {
3596 eventFns = shallowCopy(eventFns);
3597 }
3598
3599 for (var i = 0; i < eventFnsLength; i++) {
3600 if (!event.isImmediatePropagationStopped()) {
3601 handlerWrapper(element, event, eventFns[i]);
3602 }
3603 }
3604 };
3605
3606 // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
3607 // events on `element`
3608 eventHandler.elem = element;
3609 return eventHandler;
3610}
3611
3612function defaultHandlerWrapper(element, event, handler) {
3613 handler.call(element, event);
3614}
3615
3616function specialMouseHandlerWrapper(target, event, handler) {
3617 // Refer to jQuery's implementation of mouseenter & mouseleave
3618 // Read about mouseenter and mouseleave:
3619 // http://www.quirksmode.org/js/events_mouse.html#link8
3620 var related = event.relatedTarget;
3621 // For mousenter/leave call the handler if related is outside the target.
3622 // NB: No relatedTarget if the mouse left/entered the browser window
3623 if (!related || (related !== target && !jqLiteContains.call(target, related))) {
3624 handler.call(target, event);
3625 }
3626}
3627
3628//////////////////////////////////////////
3629// Functions iterating traversal.
3630// These functions chain results into a single
3631// selector.
3632//////////////////////////////////////////
3633forEach({
3634 removeData: jqLiteRemoveData,
3635
3636 on: function jqLiteOn(element, type, fn, unsupported) {
3637 if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
3638
3639 // Do not add event handlers to non-elements because they will not be cleaned up.
3640 if (!jqLiteAcceptsData(element)) {
3641 return;
3642 }
3643
3644 var expandoStore = jqLiteExpandoStore(element, true);
3645 var events = expandoStore.events;
3646 var handle = expandoStore.handle;
3647
3648 if (!handle) {
3649 handle = expandoStore.handle = createEventHandler(element, events);
3650 }
3651
3652 // http://jsperf.com/string-indexof-vs-split
3653 var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
3654 var i = types.length;
3655
3656 var addHandler = function(type, specialHandlerWrapper, noEventListener) {
3657 var eventFns = events[type];
3658
3659 if (!eventFns) {
3660 eventFns = events[type] = [];
3661 eventFns.specialHandlerWrapper = specialHandlerWrapper;
3662 if (type !== '$destroy' && !noEventListener) {
3663 element.addEventListener(type, handle);
3664 }
3665 }
3666
3667 eventFns.push(fn);
3668 };
3669
3670 while (i--) {
3671 type = types[i];
3672 if (MOUSE_EVENT_MAP[type]) {
3673 addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
3674 addHandler(type, undefined, true);
3675 } else {
3676 addHandler(type);
3677 }
3678 }
3679 },
3680
3681 off: jqLiteOff,
3682
3683 one: function(element, type, fn) {
3684 element = jqLite(element);
3685
3686 //add the listener twice so that when it is called
3687 //you can remove the original function and still be
3688 //able to call element.off(ev, fn) normally
3689 element.on(type, function onFn() {
3690 element.off(type, fn);
3691 element.off(type, onFn);
3692 });
3693 element.on(type, fn);
3694 },
3695
3696 replaceWith: function(element, replaceNode) {
3697 var index, parent = element.parentNode;
3698 jqLiteDealoc(element);
3699 forEach(new JQLite(replaceNode), function(node) {
3700 if (index) {
3701 parent.insertBefore(node, index.nextSibling);
3702 } else {
3703 parent.replaceChild(node, element);
3704 }
3705 index = node;
3706 });
3707 },
3708
3709 children: function(element) {
3710 var children = [];
3711 forEach(element.childNodes, function(element) {
3712 if (element.nodeType === NODE_TYPE_ELEMENT) {
3713 children.push(element);
3714 }
3715 });
3716 return children;
3717 },
3718
3719 contents: function(element) {
3720 return element.contentDocument || element.childNodes || [];
3721 },
3722
3723 append: function(element, node) {
3724 var nodeType = element.nodeType;
3725 if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
3726
3727 node = new JQLite(node);
3728
3729 for (var i = 0, ii = node.length; i < ii; i++) {
3730 var child = node[i];
3731 element.appendChild(child);
3732 }
3733 },
3734
3735 prepend: function(element, node) {
3736 if (element.nodeType === NODE_TYPE_ELEMENT) {
3737 var index = element.firstChild;
3738 forEach(new JQLite(node), function(child) {
3739 element.insertBefore(child, index);
3740 });
3741 }
3742 },
3743
3744 wrap: function(element, wrapNode) {
3745 jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
3746 },
3747
3748 remove: jqLiteRemove,
3749
3750 detach: function(element) {
3751 jqLiteRemove(element, true);
3752 },
3753
3754 after: function(element, newElement) {
3755 var index = element, parent = element.parentNode;
3756
3757 if (parent) {
3758 newElement = new JQLite(newElement);
3759
3760 for (var i = 0, ii = newElement.length; i < ii; i++) {
3761 var node = newElement[i];
3762 parent.insertBefore(node, index.nextSibling);
3763 index = node;
3764 }
3765 }
3766 },
3767
3768 addClass: jqLiteAddClass,
3769 removeClass: jqLiteRemoveClass,
3770
3771 toggleClass: function(element, selector, condition) {
3772 if (selector) {
3773 forEach(selector.split(' '), function(className) {
3774 var classCondition = condition;
3775 if (isUndefined(classCondition)) {
3776 classCondition = !jqLiteHasClass(element, className);
3777 }
3778 (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
3779 });
3780 }
3781 },
3782
3783 parent: function(element) {
3784 var parent = element.parentNode;
3785 return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
3786 },
3787
3788 next: function(element) {
3789 return element.nextElementSibling;
3790 },
3791
3792 find: function(element, selector) {
3793 if (element.getElementsByTagName) {
3794 return element.getElementsByTagName(selector);
3795 } else {
3796 return [];
3797 }
3798 },
3799
3800 clone: jqLiteClone,
3801
3802 triggerHandler: function(element, event, extraParameters) {
3803
3804 var dummyEvent, eventFnsCopy, handlerArgs;
3805 var eventName = event.type || event;
3806 var expandoStore = jqLiteExpandoStore(element);
3807 var events = expandoStore && expandoStore.events;
3808 var eventFns = events && events[eventName];
3809
3810 if (eventFns) {
3811 // Create a dummy event to pass to the handlers
3812 dummyEvent = {
3813 preventDefault: function() { this.defaultPrevented = true; },
3814 isDefaultPrevented: function() { return this.defaultPrevented === true; },
3815 stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
3816 isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
3817 stopPropagation: noop,
3818 type: eventName,
3819 target: element
3820 };
3821
3822 // If a custom event was provided then extend our dummy event with it
3823 if (event.type) {
3824 dummyEvent = extend(dummyEvent, event);
3825 }
3826
3827 // Copy event handlers in case event handlers array is modified during execution.
3828 eventFnsCopy = shallowCopy(eventFns);
3829 handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
3830
3831 forEach(eventFnsCopy, function(fn) {
3832 if (!dummyEvent.isImmediatePropagationStopped()) {
3833 fn.apply(element, handlerArgs);
3834 }
3835 });
3836 }
3837 }
3838}, function(fn, name) {
3839 /**
3840 * chaining functions
3841 */
3842 JQLite.prototype[name] = function(arg1, arg2, arg3) {
3843 var value;
3844
3845 for (var i = 0, ii = this.length; i < ii; i++) {
3846 if (isUndefined(value)) {
3847 value = fn(this[i], arg1, arg2, arg3);
3848 if (isDefined(value)) {
3849 // any function which returns a value needs to be wrapped
3850 value = jqLite(value);
3851 }
3852 } else {
3853 jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
3854 }
3855 }
3856 return isDefined(value) ? value : this;
3857 };
3858});
3859
3860// bind legacy bind/unbind to on/off
3861JQLite.prototype.bind = JQLite.prototype.on;
3862JQLite.prototype.unbind = JQLite.prototype.off;
3863
3864
3865// Provider for private $$jqLite service
3866/** @this */
3867function $$jqLiteProvider() {
3868 this.$get = function $$jqLite() {
3869 return extend(JQLite, {
3870 hasClass: function(node, classes) {
3871 if (node.attr) node = node[0];
3872 return jqLiteHasClass(node, classes);
3873 },
3874 addClass: function(node, classes) {
3875 if (node.attr) node = node[0];
3876 return jqLiteAddClass(node, classes);
3877 },
3878 removeClass: function(node, classes) {
3879 if (node.attr) node = node[0];
3880 return jqLiteRemoveClass(node, classes);
3881 }
3882 });
3883 };
3884}
3885
3886/**
3887 * Computes a hash of an 'obj'.
3888 * Hash of a:
3889 * string is string
3890 * number is number as string
3891 * object is either result of calling $$hashKey function on the object or uniquely generated id,
3892 * that is also assigned to the $$hashKey property of the object.
3893 *
3894 * @param obj
3895 * @returns {string} hash string such that the same input will have the same hash string.
3896 * The resulting string key is in 'type:hashKey' format.
3897 */
3898function hashKey(obj, nextUidFn) {
3899 var key = obj && obj.$$hashKey;
3900
3901 if (key) {
3902 if (typeof key === 'function') {
3903 key = obj.$$hashKey();
3904 }
3905 return key;
3906 }
3907
3908 var objType = typeof obj;
3909 if (objType === 'function' || (objType === 'object' && obj !== null)) {
3910 key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
3911 } else {
3912 key = objType + ':' + obj;
3913 }
3914
3915 return key;
3916}
3917
3918/**
3919 * HashMap which can use objects as keys
3920 */
3921function HashMap(array, isolatedUid) {
3922 if (isolatedUid) {
3923 var uid = 0;
3924 this.nextUid = function() {
3925 return ++uid;
3926 };
3927 }
3928 forEach(array, this.put, this);
3929}
3930HashMap.prototype = {
3931 /**
3932 * Store key value pair
3933 * @param key key to store can be any type
3934 * @param value value to store can be any type
3935 */
3936 put: function(key, value) {
3937 this[hashKey(key, this.nextUid)] = value;
3938 },
3939
3940 /**
3941 * @param key
3942 * @returns {Object} the value for the key
3943 */
3944 get: function(key) {
3945 return this[hashKey(key, this.nextUid)];
3946 },
3947
3948 /**
3949 * Remove the key/value pair
3950 * @param key
3951 */
3952 remove: function(key) {
3953 var value = this[key = hashKey(key, this.nextUid)];
3954 delete this[key];
3955 return value;
3956 }
3957};
3958
3959var $$HashMapProvider = [/** @this */function() {
3960 this.$get = [function() {
3961 return HashMap;
3962 }];
3963}];
3964
3965/**
3966 * @ngdoc function
3967 * @module ng
3968 * @name angular.injector
3969 * @kind function
3970 *
3971 * @description
3972 * Creates an injector object that can be used for retrieving services as well as for
3973 * dependency injection (see {@link guide/di dependency injection}).
3974 *
3975 * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
3976 * {@link angular.module}. The `ng` module must be explicitly added.
3977 * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
3978 * disallows argument name annotation inference.
3979 * @returns {injector} Injector object. See {@link auto.$injector $injector}.
3980 *
3981 * @example
3982 * Typical usage
3983 * ```js
3984 * // create an injector
3985 * var $injector = angular.injector(['ng']);
3986 *
3987 * // use the injector to kick off your application
3988 * // use the type inference to auto inject arguments, or use implicit injection
3989 * $injector.invoke(function($rootScope, $compile, $document) {
3990 * $compile($document)($rootScope);
3991 * $rootScope.$digest();
3992 * });
3993 * ```
3994 *
3995 * Sometimes you want to get access to the injector of a currently running Angular app
3996 * from outside Angular. Perhaps, you want to inject and compile some markup after the
3997 * application has been bootstrapped. You can do this using the extra `injector()` added
3998 * to JQuery/jqLite elements. See {@link angular.element}.
3999 *
4000 * *This is fairly rare but could be the case if a third party library is injecting the
4001 * markup.*
4002 *
4003 * In the following example a new block of HTML containing a `ng-controller`
4004 * directive is added to the end of the document body by JQuery. We then compile and link
4005 * it into the current AngularJS scope.
4006 *
4007 * ```js
4008 * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
4009 * $(document.body).append($div);
4010 *
4011 * angular.element(document).injector().invoke(function($compile) {
4012 * var scope = angular.element($div).scope();
4013 * $compile($div)(scope);
4014 * });
4015 * ```
4016 */
4017
4018
4019/**
4020 * @ngdoc module
4021 * @name auto
4022 * @installation
4023 * @description
4024 *
4025 * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
4026 */
4027
4028var ARROW_ARG = /^([^(]+?)=>/;
4029var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
4030var FN_ARG_SPLIT = /,/;
4031var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
4032var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
4033var $injectorMinErr = minErr('$injector');
4034
4035function stringifyFn(fn) {
4036 // Support: Chrome 50-51 only
4037 // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51
4038 // (See https://github.com/angular/angular.js/issues/14487.)
4039 // TODO (gkalpak): Remove workaround when Chrome v52 is released
4040 return Function.prototype.toString.call(fn) + ' ';
4041}
4042
4043function extractArgs(fn) {
4044 var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
4045 args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
4046 return args;
4047}
4048
4049function anonFn(fn) {
4050 // For anonymous functions, showing at the very least the function signature can help in
4051 // debugging.
4052 var args = extractArgs(fn);
4053 if (args) {
4054 return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
4055 }
4056 return 'fn';
4057}
4058
4059function annotate(fn, strictDi, name) {
4060 var $inject,
4061 argDecl,
4062 last;
4063
4064 if (typeof fn === 'function') {
4065 if (!($inject = fn.$inject)) {
4066 $inject = [];
4067 if (fn.length) {
4068 if (strictDi) {
4069 if (!isString(name) || !name) {
4070 name = fn.name || anonFn(fn);
4071 }
4072 throw $injectorMinErr('strictdi',
4073 '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
4074 }
4075 argDecl = extractArgs(fn);
4076 forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
4077 arg.replace(FN_ARG, function(all, underscore, name) {
4078 $inject.push(name);
4079 });
4080 });
4081 }
4082 fn.$inject = $inject;
4083 }
4084 } else if (isArray(fn)) {
4085 last = fn.length - 1;
4086 assertArgFn(fn[last], 'fn');
4087 $inject = fn.slice(0, last);
4088 } else {
4089 assertArgFn(fn, 'fn', true);
4090 }
4091 return $inject;
4092}
4093
4094///////////////////////////////////////
4095
4096/**
4097 * @ngdoc service
4098 * @name $injector
4099 *
4100 * @description
4101 *
4102 * `$injector` is used to retrieve object instances as defined by
4103 * {@link auto.$provide provider}, instantiate types, invoke methods,
4104 * and load modules.
4105 *
4106 * The following always holds true:
4107 *
4108 * ```js
4109 * var $injector = angular.injector();
4110 * expect($injector.get('$injector')).toBe($injector);
4111 * expect($injector.invoke(function($injector) {
4112 * return $injector;
4113 * })).toBe($injector);
4114 * ```
4115 *
4116 * # Injection Function Annotation
4117 *
4118 * JavaScript does not have annotations, and annotations are needed for dependency injection. The
4119 * following are all valid ways of annotating function with injection arguments and are equivalent.
4120 *
4121 * ```js
4122 * // inferred (only works if code not minified/obfuscated)
4123 * $injector.invoke(function(serviceA){});
4124 *
4125 * // annotated
4126 * function explicit(serviceA) {};
4127 * explicit.$inject = ['serviceA'];
4128 * $injector.invoke(explicit);
4129 *
4130 * // inline
4131 * $injector.invoke(['serviceA', function(serviceA){}]);
4132 * ```
4133 *
4134 * ## Inference
4135 *
4136 * In JavaScript calling `toString()` on a function returns the function definition. The definition
4137 * can then be parsed and the function arguments can be extracted. This method of discovering
4138 * annotations is disallowed when the injector is in strict mode.
4139 * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
4140 * argument names.
4141 *
4142 * ## `$inject` Annotation
4143 * By adding an `$inject` property onto a function the injection parameters can be specified.
4144 *
4145 * ## Inline
4146 * As an array of injection names, where the last item in the array is the function to call.
4147 */
4148
4149/**
4150 * @ngdoc method
4151 * @name $injector#get
4152 *
4153 * @description
4154 * Return an instance of the service.
4155 *
4156 * @param {string} name The name of the instance to retrieve.
4157 * @param {string=} caller An optional string to provide the origin of the function call for error messages.
4158 * @return {*} The instance.
4159 */
4160
4161/**
4162 * @ngdoc method
4163 * @name $injector#invoke
4164 *
4165 * @description
4166 * Invoke the method and supply the method arguments from the `$injector`.
4167 *
4168 * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
4169 * injected according to the {@link guide/di $inject Annotation} rules.
4170 * @param {Object=} self The `this` for the invoked method.
4171 * @param {Object=} locals Optional object. If preset then any argument names are read from this
4172 * object first, before the `$injector` is consulted.
4173 * @returns {*} the value returned by the invoked `fn` function.
4174 */
4175
4176/**
4177 * @ngdoc method
4178 * @name $injector#has
4179 *
4180 * @description
4181 * Allows the user to query if the particular service exists.
4182 *
4183 * @param {string} name Name of the service to query.
4184 * @returns {boolean} `true` if injector has given service.
4185 */
4186
4187/**
4188 * @ngdoc method
4189 * @name $injector#instantiate
4190 * @description
4191 * Create a new instance of JS type. The method takes a constructor function, invokes the new
4192 * operator, and supplies all of the arguments to the constructor function as specified by the
4193 * constructor annotation.
4194 *
4195 * @param {Function} Type Annotated constructor function.
4196 * @param {Object=} locals Optional object. If preset then any argument names are read from this
4197 * object first, before the `$injector` is consulted.
4198 * @returns {Object} new instance of `Type`.
4199 */
4200
4201/**
4202 * @ngdoc method
4203 * @name $injector#annotate
4204 *
4205 * @description
4206 * Returns an array of service names which the function is requesting for injection. This API is
4207 * used by the injector to determine which services need to be injected into the function when the
4208 * function is invoked. There are three ways in which the function can be annotated with the needed
4209 * dependencies.
4210 *
4211 * # Argument names
4212 *
4213 * The simplest form is to extract the dependencies from the arguments of the function. This is done
4214 * by converting the function into a string using `toString()` method and extracting the argument
4215 * names.
4216 * ```js
4217 * // Given
4218 * function MyController($scope, $route) {
4219 * // ...
4220 * }
4221 *
4222 * // Then
4223 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
4224 * ```
4225 *
4226 * You can disallow this method by using strict injection mode.
4227 *
4228 * This method does not work with code minification / obfuscation. For this reason the following
4229 * annotation strategies are supported.
4230 *
4231 * # The `$inject` property
4232 *
4233 * If a function has an `$inject` property and its value is an array of strings, then the strings
4234 * represent names of services to be injected into the function.
4235 * ```js
4236 * // Given
4237 * var MyController = function(obfuscatedScope, obfuscatedRoute) {
4238 * // ...
4239 * }
4240 * // Define function dependencies
4241 * MyController['$inject'] = ['$scope', '$route'];
4242 *
4243 * // Then
4244 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
4245 * ```
4246 *
4247 * # The array notation
4248 *
4249 * It is often desirable to inline Injected functions and that's when setting the `$inject` property
4250 * is very inconvenient. In these situations using the array notation to specify the dependencies in
4251 * a way that survives minification is a better choice:
4252 *
4253 * ```js
4254 * // We wish to write this (not minification / obfuscation safe)
4255 * injector.invoke(function($compile, $rootScope) {
4256 * // ...
4257 * });
4258 *
4259 * // We are forced to write break inlining
4260 * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
4261 * // ...
4262 * };
4263 * tmpFn.$inject = ['$compile', '$rootScope'];
4264 * injector.invoke(tmpFn);
4265 *
4266 * // To better support inline function the inline annotation is supported
4267 * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
4268 * // ...
4269 * }]);
4270 *
4271 * // Therefore
4272 * expect(injector.annotate(
4273 * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
4274 * ).toEqual(['$compile', '$rootScope']);
4275 * ```
4276 *
4277 * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
4278 * be retrieved as described above.
4279 *
4280 * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
4281 *
4282 * @returns {Array.<string>} The names of the services which the function requires.
4283 */
4284
4285
4286
4287/**
4288 * @ngdoc service
4289 * @name $provide
4290 *
4291 * @description
4292 *
4293 * The {@link auto.$provide $provide} service has a number of methods for registering components
4294 * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
4295 * {@link angular.Module}.
4296 *
4297 * An Angular **service** is a singleton object created by a **service factory**. These **service
4298 * factories** are functions which, in turn, are created by a **service provider**.
4299 * The **service providers** are constructor functions. When instantiated they must contain a
4300 * property called `$get`, which holds the **service factory** function.
4301 *
4302 * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
4303 * correct **service provider**, instantiating it and then calling its `$get` **service factory**
4304 * function to get the instance of the **service**.
4305 *
4306 * Often services have no configuration options and there is no need to add methods to the service
4307 * provider. The provider will be no more than a constructor function with a `$get` property. For
4308 * these cases the {@link auto.$provide $provide} service has additional helper methods to register
4309 * services without specifying a provider.
4310 *
4311 * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
4312 * {@link auto.$injector $injector}
4313 * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
4314 * providers and services.
4315 * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
4316 * services, not providers.
4317 * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
4318 * that will be wrapped in a **service provider** object, whose `$get` property will contain the
4319 * given factory function.
4320 * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
4321 * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
4322 * a new object using the given constructor function.
4323 * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
4324 * will be able to modify or replace the implementation of another service.
4325 *
4326 * See the individual methods for more information and examples.
4327 */
4328
4329/**
4330 * @ngdoc method
4331 * @name $provide#provider
4332 * @description
4333 *
4334 * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
4335 * are constructor functions, whose instances are responsible for "providing" a factory for a
4336 * service.
4337 *
4338 * Service provider names start with the name of the service they provide followed by `Provider`.
4339 * For example, the {@link ng.$log $log} service has a provider called
4340 * {@link ng.$logProvider $logProvider}.
4341 *
4342 * Service provider objects can have additional methods which allow configuration of the provider
4343 * and its service. Importantly, you can configure what kind of service is created by the `$get`
4344 * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
4345 * method {@link ng.$logProvider#debugEnabled debugEnabled}
4346 * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
4347 * console or not.
4348 *
4349 * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
4350 'Provider'` key.
4351 * @param {(Object|function())} provider If the provider is:
4352 *
4353 * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
4354 * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
4355 * - `Constructor`: a new instance of the provider will be created using
4356 * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
4357 *
4358 * @returns {Object} registered provider instance
4359
4360 * @example
4361 *
4362 * The following example shows how to create a simple event tracking service and register it using
4363 * {@link auto.$provide#provider $provide.provider()}.
4364 *
4365 * ```js
4366 * // Define the eventTracker provider
4367 * function EventTrackerProvider() {
4368 * var trackingUrl = '/track';
4369 *
4370 * // A provider method for configuring where the tracked events should been saved
4371 * this.setTrackingUrl = function(url) {
4372 * trackingUrl = url;
4373 * };
4374 *
4375 * // The service factory function
4376 * this.$get = ['$http', function($http) {
4377 * var trackedEvents = {};
4378 * return {
4379 * // Call this to track an event
4380 * event: function(event) {
4381 * var count = trackedEvents[event] || 0;
4382 * count += 1;
4383 * trackedEvents[event] = count;
4384 * return count;
4385 * },
4386 * // Call this to save the tracked events to the trackingUrl
4387 * save: function() {
4388 * $http.post(trackingUrl, trackedEvents);
4389 * }
4390 * };
4391 * }];
4392 * }
4393 *
4394 * describe('eventTracker', function() {
4395 * var postSpy;
4396 *
4397 * beforeEach(module(function($provide) {
4398 * // Register the eventTracker provider
4399 * $provide.provider('eventTracker', EventTrackerProvider);
4400 * }));
4401 *
4402 * beforeEach(module(function(eventTrackerProvider) {
4403 * // Configure eventTracker provider
4404 * eventTrackerProvider.setTrackingUrl('/custom-track');
4405 * }));
4406 *
4407 * it('tracks events', inject(function(eventTracker) {
4408 * expect(eventTracker.event('login')).toEqual(1);
4409 * expect(eventTracker.event('login')).toEqual(2);
4410 * }));
4411 *
4412 * it('saves to the tracking url', inject(function(eventTracker, $http) {
4413 * postSpy = spyOn($http, 'post');
4414 * eventTracker.event('login');
4415 * eventTracker.save();
4416 * expect(postSpy).toHaveBeenCalled();
4417 * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
4418 * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
4419 * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
4420 * }));
4421 * });
4422 * ```
4423 */
4424
4425/**
4426 * @ngdoc method
4427 * @name $provide#factory
4428 * @description
4429 *
4430 * Register a **service factory**, which will be called to return the service instance.
4431 * This is short for registering a service where its provider consists of only a `$get` property,
4432 * which is the given service factory function.
4433 * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
4434 * configure your service in a provider.
4435 *
4436 * @param {string} name The name of the instance.
4437 * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
4438 * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
4439 * @returns {Object} registered provider instance
4440 *
4441 * @example
4442 * Here is an example of registering a service
4443 * ```js
4444 * $provide.factory('ping', ['$http', function($http) {
4445 * return function ping() {
4446 * return $http.send('/ping');
4447 * };
4448 * }]);
4449 * ```
4450 * You would then inject and use this service like this:
4451 * ```js
4452 * someModule.controller('Ctrl', ['ping', function(ping) {
4453 * ping();
4454 * }]);
4455 * ```
4456 */
4457
4458
4459/**
4460 * @ngdoc method
4461 * @name $provide#service
4462 * @description
4463 *
4464 * Register a **service constructor**, which will be invoked with `new` to create the service
4465 * instance.
4466 * This is short for registering a service where its provider's `$get` property is a factory
4467 * function that returns an instance instantiated by the injector from the service constructor
4468 * function.
4469 *
4470 * Internally it looks a bit like this:
4471 *
4472 * ```
4473 * {
4474 * $get: function() {
4475 * return $injector.instantiate(constructor);
4476 * }
4477 * }
4478 * ```
4479 *
4480 *
4481 * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
4482 * as a type/class.
4483 *
4484 * @param {string} name The name of the instance.
4485 * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
4486 * that will be instantiated.
4487 * @returns {Object} registered provider instance
4488 *
4489 * @example
4490 * Here is an example of registering a service using
4491 * {@link auto.$provide#service $provide.service(class)}.
4492 * ```js
4493 * var Ping = function($http) {
4494 * this.$http = $http;
4495 * };
4496 *
4497 * Ping.$inject = ['$http'];
4498 *
4499 * Ping.prototype.send = function() {
4500 * return this.$http.get('/ping');
4501 * };
4502 * $provide.service('ping', Ping);
4503 * ```
4504 * You would then inject and use this service like this:
4505 * ```js
4506 * someModule.controller('Ctrl', ['ping', function(ping) {
4507 * ping.send();
4508 * }]);
4509 * ```
4510 */
4511
4512
4513/**
4514 * @ngdoc method
4515 * @name $provide#value
4516 * @description
4517 *
4518 * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
4519 * number, an array, an object or a function. This is short for registering a service where its
4520 * provider's `$get` property is a factory function that takes no arguments and returns the **value
4521 * service**. That also means it is not possible to inject other services into a value service.
4522 *
4523 * Value services are similar to constant services, except that they cannot be injected into a
4524 * module configuration function (see {@link angular.Module#config}) but they can be overridden by
4525 * an Angular {@link auto.$provide#decorator decorator}.
4526 *
4527 * @param {string} name The name of the instance.
4528 * @param {*} value The value.
4529 * @returns {Object} registered provider instance
4530 *
4531 * @example
4532 * Here are some examples of creating value services.
4533 * ```js
4534 * $provide.value('ADMIN_USER', 'admin');
4535 *
4536 * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
4537 *
4538 * $provide.value('halfOf', function(value) {
4539 * return value / 2;
4540 * });
4541 * ```
4542 */
4543
4544
4545/**
4546 * @ngdoc method
4547 * @name $provide#constant
4548 * @description
4549 *
4550 * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
4551 * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
4552 * possible to inject other services into a constant.
4553 *
4554 * But unlike {@link auto.$provide#value value}, a constant can be
4555 * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
4556 * be overridden by an Angular {@link auto.$provide#decorator decorator}.
4557 *
4558 * @param {string} name The name of the constant.
4559 * @param {*} value The constant value.
4560 * @returns {Object} registered instance
4561 *
4562 * @example
4563 * Here a some examples of creating constants:
4564 * ```js
4565 * $provide.constant('SHARD_HEIGHT', 306);
4566 *
4567 * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
4568 *
4569 * $provide.constant('double', function(value) {
4570 * return value * 2;
4571 * });
4572 * ```
4573 */
4574
4575
4576/**
4577 * @ngdoc method
4578 * @name $provide#decorator
4579 * @description
4580 *
4581 * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
4582 * intercepts the creation of a service, allowing it to override or modify the behavior of the
4583 * service. The return value of the decorator function may be the original service, or a new service
4584 * that replaces (or wraps and delegates to) the original service.
4585 *
4586 * You can find out more about using decorators in the {@link guide/decorators} guide.
4587 *
4588 * @param {string} name The name of the service to decorate.
4589 * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
4590 * provided and should return the decorated service instance. The function is called using
4591 * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
4592 * Local injection arguments:
4593 *
4594 * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
4595 * decorated or delegated to.
4596 *
4597 * @example
4598 * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
4599 * calls to {@link ng.$log#error $log.warn()}.
4600 * ```js
4601 * $provide.decorator('$log', ['$delegate', function($delegate) {
4602 * $delegate.warn = $delegate.error;
4603 * return $delegate;
4604 * }]);
4605 * ```
4606 */
4607
4608
4609function createInjector(modulesToLoad, strictDi) {
4610 strictDi = (strictDi === true);
4611 var INSTANTIATING = {},
4612 providerSuffix = 'Provider',
4613 path = [],
4614 loadedModules = new HashMap([], true),
4615 providerCache = {
4616 $provide: {
4617 provider: supportObject(provider),
4618 factory: supportObject(factory),
4619 service: supportObject(service),
4620 value: supportObject(value),
4621 constant: supportObject(constant),
4622 decorator: decorator
4623 }
4624 },
4625 providerInjector = (providerCache.$injector =
4626 createInternalInjector(providerCache, function(serviceName, caller) {
4627 if (angular.isString(caller)) {
4628 path.push(caller);
4629 }
4630 throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
4631 })),
4632 instanceCache = {},
4633 protoInstanceInjector =
4634 createInternalInjector(instanceCache, function(serviceName, caller) {
4635 var provider = providerInjector.get(serviceName + providerSuffix, caller);
4636 return instanceInjector.invoke(
4637 provider.$get, provider, undefined, serviceName);
4638 }),
4639 instanceInjector = protoInstanceInjector;
4640
4641 providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
4642 var runBlocks = loadModules(modulesToLoad);
4643 instanceInjector = protoInstanceInjector.get('$injector');
4644 instanceInjector.strictDi = strictDi;
4645 forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
4646
4647 return instanceInjector;
4648
4649 ////////////////////////////////////
4650 // $provider
4651 ////////////////////////////////////
4652
4653 function supportObject(delegate) {
4654 return function(key, value) {
4655 if (isObject(key)) {
4656 forEach(key, reverseParams(delegate));
4657 } else {
4658 return delegate(key, value);
4659 }
4660 };
4661 }
4662
4663 function provider(name, provider_) {
4664 assertNotHasOwnProperty(name, 'service');
4665 if (isFunction(provider_) || isArray(provider_)) {
4666 provider_ = providerInjector.instantiate(provider_);
4667 }
4668 if (!provider_.$get) {
4669 throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
4670 }
4671 return (providerCache[name + providerSuffix] = provider_);
4672 }
4673
4674 function enforceReturnValue(name, factory) {
4675 return /** @this */ function enforcedReturnValue() {
4676 var result = instanceInjector.invoke(factory, this);
4677 if (isUndefined(result)) {
4678 throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
4679 }
4680 return result;
4681 };
4682 }
4683
4684 function factory(name, factoryFn, enforce) {
4685 return provider(name, {
4686 $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
4687 });
4688 }
4689
4690 function service(name, constructor) {
4691 return factory(name, ['$injector', function($injector) {
4692 return $injector.instantiate(constructor);
4693 }]);
4694 }
4695
4696 function value(name, val) { return factory(name, valueFn(val), false); }
4697
4698 function constant(name, value) {
4699 assertNotHasOwnProperty(name, 'constant');
4700 providerCache[name] = value;
4701 instanceCache[name] = value;
4702 }
4703
4704 function decorator(serviceName, decorFn) {
4705 var origProvider = providerInjector.get(serviceName + providerSuffix),
4706 orig$get = origProvider.$get;
4707
4708 origProvider.$get = function() {
4709 var origInstance = instanceInjector.invoke(orig$get, origProvider);
4710 return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
4711 };
4712 }
4713
4714 ////////////////////////////////////
4715 // Module Loading
4716 ////////////////////////////////////
4717 function loadModules(modulesToLoad) {
4718 assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
4719 var runBlocks = [], moduleFn;
4720 forEach(modulesToLoad, function(module) {
4721 if (loadedModules.get(module)) return;
4722 loadedModules.put(module, true);
4723
4724 function runInvokeQueue(queue) {
4725 var i, ii;
4726 for (i = 0, ii = queue.length; i < ii; i++) {
4727 var invokeArgs = queue[i],
4728 provider = providerInjector.get(invokeArgs[0]);
4729
4730 provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
4731 }
4732 }
4733
4734 try {
4735 if (isString(module)) {
4736 moduleFn = angularModule(module);
4737 runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
4738 runInvokeQueue(moduleFn._invokeQueue);
4739 runInvokeQueue(moduleFn._configBlocks);
4740 } else if (isFunction(module)) {
4741 runBlocks.push(providerInjector.invoke(module));
4742 } else if (isArray(module)) {
4743 runBlocks.push(providerInjector.invoke(module));
4744 } else {
4745 assertArgFn(module, 'module');
4746 }
4747 } catch (e) {
4748 if (isArray(module)) {
4749 module = module[module.length - 1];
4750 }
4751 if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
4752 // Safari & FF's stack traces don't contain error.message content
4753 // unlike those of Chrome and IE
4754 // So if stack doesn't contain message, we create a new string that contains both.
4755 // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
4756 // eslint-disable-next-line no-ex-assign
4757 e = e.message + '\n' + e.stack;
4758 }
4759 throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
4760 module, e.stack || e.message || e);
4761 }
4762 });
4763 return runBlocks;
4764 }
4765
4766 ////////////////////////////////////
4767 // internal Injector
4768 ////////////////////////////////////
4769
4770 function createInternalInjector(cache, factory) {
4771
4772 function getService(serviceName, caller) {
4773 if (cache.hasOwnProperty(serviceName)) {
4774 if (cache[serviceName] === INSTANTIATING) {
4775 throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
4776 serviceName + ' <- ' + path.join(' <- '));
4777 }
4778 return cache[serviceName];
4779 } else {
4780 try {
4781 path.unshift(serviceName);
4782 cache[serviceName] = INSTANTIATING;
4783 cache[serviceName] = factory(serviceName, caller);
4784 return cache[serviceName];
4785 } catch (err) {
4786 if (cache[serviceName] === INSTANTIATING) {
4787 delete cache[serviceName];
4788 }
4789 throw err;
4790 } finally {
4791 path.shift();
4792 }
4793 }
4794 }
4795
4796
4797 function injectionArgs(fn, locals, serviceName) {
4798 var args = [],
4799 $inject = createInjector.$$annotate(fn, strictDi, serviceName);
4800
4801 for (var i = 0, length = $inject.length; i < length; i++) {
4802 var key = $inject[i];
4803 if (typeof key !== 'string') {
4804 throw $injectorMinErr('itkn',
4805 'Incorrect injection token! Expected service name as string, got {0}', key);
4806 }
4807 args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
4808 getService(key, serviceName));
4809 }
4810 return args;
4811 }
4812
4813 function isClass(func) {
4814 // Support: IE 9-11 only
4815 // IE 9-11 do not support classes and IE9 leaks with the code below.
4816 if (msie || typeof func !== 'function') {
4817 return false;
4818 }
4819 var result = func.$$ngIsClass;
4820 if (!isBoolean(result)) {
4821 // Support: Edge 12-13 only
4822 // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
4823 result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
4824 }
4825 return result;
4826 }
4827
4828 function invoke(fn, self, locals, serviceName) {
4829 if (typeof locals === 'string') {
4830 serviceName = locals;
4831 locals = null;
4832 }
4833
4834 var args = injectionArgs(fn, locals, serviceName);
4835 if (isArray(fn)) {
4836 fn = fn[fn.length - 1];
4837 }
4838
4839 if (!isClass(fn)) {
4840 // http://jsperf.com/angularjs-invoke-apply-vs-switch
4841 // #5388
4842 return fn.apply(self, args);
4843 } else {
4844 args.unshift(null);
4845 return new (Function.prototype.bind.apply(fn, args))();
4846 }
4847 }
4848
4849
4850 function instantiate(Type, locals, serviceName) {
4851 // Check if Type is annotated and use just the given function at n-1 as parameter
4852 // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
4853 var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
4854 var args = injectionArgs(Type, locals, serviceName);
4855 // Empty object at position 0 is ignored for invocation with `new`, but required.
4856 args.unshift(null);
4857 return new (Function.prototype.bind.apply(ctor, args))();
4858 }
4859
4860
4861 return {
4862 invoke: invoke,
4863 instantiate: instantiate,
4864 get: getService,
4865 annotate: createInjector.$$annotate,
4866 has: function(name) {
4867 return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
4868 }
4869 };
4870 }
4871}
4872
4873createInjector.$$annotate = annotate;
4874
4875/**
4876 * @ngdoc provider
4877 * @name $anchorScrollProvider
4878 * @this
4879 *
4880 * @description
4881 * Use `$anchorScrollProvider` to disable automatic scrolling whenever
4882 * {@link ng.$location#hash $location.hash()} changes.
4883 */
4884function $AnchorScrollProvider() {
4885
4886 var autoScrollingEnabled = true;
4887
4888 /**
4889 * @ngdoc method
4890 * @name $anchorScrollProvider#disableAutoScrolling
4891 *
4892 * @description
4893 * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
4894 * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
4895 * Use this method to disable automatic scrolling.
4896 *
4897 * If automatic scrolling is disabled, one must explicitly call
4898 * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
4899 * current hash.
4900 */
4901 this.disableAutoScrolling = function() {
4902 autoScrollingEnabled = false;
4903 };
4904
4905 /**
4906 * @ngdoc service
4907 * @name $anchorScroll
4908 * @kind function
4909 * @requires $window
4910 * @requires $location
4911 * @requires $rootScope
4912 *
4913 * @description
4914 * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
4915 * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
4916 * in the
4917 * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
4918 *
4919 * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
4920 * match any anchor whenever it changes. This can be disabled by calling
4921 * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
4922 *
4923 * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
4924 * vertical scroll-offset (either fixed or dynamic).
4925 *
4926 * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
4927 * {@link ng.$location#hash $location.hash()} will be used.
4928 *
4929 * @property {(number|function|jqLite)} yOffset
4930 * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
4931 * positioned elements at the top of the page, such as navbars, headers etc.
4932 *
4933 * `yOffset` can be specified in various ways:
4934 * - **number**: A fixed number of pixels to be used as offset.<br /><br />
4935 * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
4936 * a number representing the offset (in pixels).<br /><br />
4937 * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
4938 * the top of the page to the element's bottom will be used as offset.<br />
4939 * **Note**: The element will be taken into account only as long as its `position` is set to
4940 * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
4941 * their height and/or positioning according to the viewport's size.
4942 *
4943 * <br />
4944 * <div class="alert alert-warning">
4945 * In order for `yOffset` to work properly, scrolling should take place on the document's root and
4946 * not some child element.
4947 * </div>
4948 *
4949 * @example
4950 <example module="anchorScrollExample" name="anchor-scroll">
4951 <file name="index.html">
4952 <div id="scrollArea" ng-controller="ScrollController">
4953 <a ng-click="gotoBottom()">Go to bottom</a>
4954 <a id="bottom"></a> You're at the bottom!
4955 </div>
4956 </file>
4957 <file name="script.js">
4958 angular.module('anchorScrollExample', [])
4959 .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
4960 function($scope, $location, $anchorScroll) {
4961 $scope.gotoBottom = function() {
4962 // set the location.hash to the id of
4963 // the element you wish to scroll to.
4964 $location.hash('bottom');
4965
4966 // call $anchorScroll()
4967 $anchorScroll();
4968 };
4969 }]);
4970 </file>
4971 <file name="style.css">
4972 #scrollArea {
4973 height: 280px;
4974 overflow: auto;
4975 }
4976
4977 #bottom {
4978 display: block;
4979 margin-top: 2000px;
4980 }
4981 </file>
4982 </example>
4983 *
4984 * <hr />
4985 * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
4986 * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
4987 *
4988 * @example
4989 <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
4990 <file name="index.html">
4991 <div class="fixed-header" ng-controller="headerCtrl">
4992 <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
4993 Go to anchor {{x}}
4994 </a>
4995 </div>
4996 <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
4997 Anchor {{x}} of 5
4998 </div>
4999 </file>
5000 <file name="script.js">
5001 angular.module('anchorScrollOffsetExample', [])
5002 .run(['$anchorScroll', function($anchorScroll) {
5003 $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
5004 }])
5005 .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
5006 function($anchorScroll, $location, $scope) {
5007 $scope.gotoAnchor = function(x) {
5008 var newHash = 'anchor' + x;
5009 if ($location.hash() !== newHash) {
5010 // set the $location.hash to `newHash` and
5011 // $anchorScroll will automatically scroll to it
5012 $location.hash('anchor' + x);
5013 } else {
5014 // call $anchorScroll() explicitly,
5015 // since $location.hash hasn't changed
5016 $anchorScroll();
5017 }
5018 };
5019 }
5020 ]);
5021 </file>
5022 <file name="style.css">
5023 body {
5024 padding-top: 50px;
5025 }
5026
5027 .anchor {
5028 border: 2px dashed DarkOrchid;
5029 padding: 10px 10px 200px 10px;
5030 }
5031
5032 .fixed-header {
5033 background-color: rgba(0, 0, 0, 0.2);
5034 height: 50px;
5035 position: fixed;
5036 top: 0; left: 0; right: 0;
5037 }
5038
5039 .fixed-header > a {
5040 display: inline-block;
5041 margin: 5px 15px;
5042 }
5043 </file>
5044 </example>
5045 */
5046 this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
5047 var document = $window.document;
5048
5049 // Helper function to get first anchor from a NodeList
5050 // (using `Array#some()` instead of `angular#forEach()` since it's more performant
5051 // and working in all supported browsers.)
5052 function getFirstAnchor(list) {
5053 var result = null;
5054 Array.prototype.some.call(list, function(element) {
5055 if (nodeName_(element) === 'a') {
5056 result = element;
5057 return true;
5058 }
5059 });
5060 return result;
5061 }
5062
5063 function getYOffset() {
5064
5065 var offset = scroll.yOffset;
5066
5067 if (isFunction(offset)) {
5068 offset = offset();
5069 } else if (isElement(offset)) {
5070 var elem = offset[0];
5071 var style = $window.getComputedStyle(elem);
5072 if (style.position !== 'fixed') {
5073 offset = 0;
5074 } else {
5075 offset = elem.getBoundingClientRect().bottom;
5076 }
5077 } else if (!isNumber(offset)) {
5078 offset = 0;
5079 }
5080
5081 return offset;
5082 }
5083
5084 function scrollTo(elem) {
5085 if (elem) {
5086 elem.scrollIntoView();
5087
5088 var offset = getYOffset();
5089
5090 if (offset) {
5091 // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
5092 // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
5093 // top of the viewport.
5094 //
5095 // IF the number of pixels from the top of `elem` to the end of the page's content is less
5096 // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
5097 // way down the page.
5098 //
5099 // This is often the case for elements near the bottom of the page.
5100 //
5101 // In such cases we do not need to scroll the whole `offset` up, just the difference between
5102 // the top of the element and the offset, which is enough to align the top of `elem` at the
5103 // desired position.
5104 var elemTop = elem.getBoundingClientRect().top;
5105 $window.scrollBy(0, elemTop - offset);
5106 }
5107 } else {
5108 $window.scrollTo(0, 0);
5109 }
5110 }
5111
5112 function scroll(hash) {
5113 // Allow numeric hashes
5114 hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
5115 var elm;
5116
5117 // empty hash, scroll to the top of the page
5118 if (!hash) scrollTo(null);
5119
5120 // element with given id
5121 else if ((elm = document.getElementById(hash))) scrollTo(elm);
5122
5123 // first anchor with given name :-D
5124 else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
5125
5126 // no element and hash === 'top', scroll to the top of the page
5127 else if (hash === 'top') scrollTo(null);
5128 }
5129
5130 // does not scroll when user clicks on anchor link that is currently on
5131 // (no url change, no $location.hash() change), browser native does scroll
5132 if (autoScrollingEnabled) {
5133 $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
5134 function autoScrollWatchAction(newVal, oldVal) {
5135 // skip the initial scroll if $location.hash is empty
5136 if (newVal === oldVal && newVal === '') return;
5137
5138 jqLiteDocumentLoaded(function() {
5139 $rootScope.$evalAsync(scroll);
5140 });
5141 });
5142 }
5143
5144 return scroll;
5145 }];
5146}
5147
5148var $animateMinErr = minErr('$animate');
5149var ELEMENT_NODE = 1;
5150var NG_ANIMATE_CLASSNAME = 'ng-animate';
5151
5152function mergeClasses(a,b) {
5153 if (!a && !b) return '';
5154 if (!a) return b;
5155 if (!b) return a;
5156 if (isArray(a)) a = a.join(' ');
5157 if (isArray(b)) b = b.join(' ');
5158 return a + ' ' + b;
5159}
5160
5161function extractElementNode(element) {
5162 for (var i = 0; i < element.length; i++) {
5163 var elm = element[i];
5164 if (elm.nodeType === ELEMENT_NODE) {
5165 return elm;
5166 }
5167 }
5168}
5169
5170function splitClasses(classes) {
5171 if (isString(classes)) {
5172 classes = classes.split(' ');
5173 }
5174
5175 // Use createMap() to prevent class assumptions involving property names in
5176 // Object.prototype
5177 var obj = createMap();
5178 forEach(classes, function(klass) {
5179 // sometimes the split leaves empty string values
5180 // incase extra spaces were applied to the options
5181 if (klass.length) {
5182 obj[klass] = true;
5183 }
5184 });
5185 return obj;
5186}
5187
5188// if any other type of options value besides an Object value is
5189// passed into the $animate.method() animation then this helper code
5190// will be run which will ignore it. While this patch is not the
5191// greatest solution to this, a lot of existing plugins depend on
5192// $animate to either call the callback (< 1.2) or return a promise
5193// that can be changed. This helper function ensures that the options
5194// are wiped clean incase a callback function is provided.
5195function prepareAnimateOptions(options) {
5196 return isObject(options)
5197 ? options
5198 : {};
5199}
5200
5201var $$CoreAnimateJsProvider = /** @this */ function() {
5202 this.$get = noop;
5203};
5204
5205// this is prefixed with Core since it conflicts with
5206// the animateQueueProvider defined in ngAnimate/animateQueue.js
5207var $$CoreAnimateQueueProvider = /** @this */ function() {
5208 var postDigestQueue = new HashMap();
5209 var postDigestElements = [];
5210
5211 this.$get = ['$$AnimateRunner', '$rootScope',
5212 function($$AnimateRunner, $rootScope) {
5213 return {
5214 enabled: noop,
5215 on: noop,
5216 off: noop,
5217 pin: noop,
5218
5219 push: function(element, event, options, domOperation) {
5220 if (domOperation) {
5221 domOperation();
5222 }
5223
5224 options = options || {};
5225 if (options.from) {
5226 element.css(options.from);
5227 }
5228 if (options.to) {
5229 element.css(options.to);
5230 }
5231
5232 if (options.addClass || options.removeClass) {
5233 addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
5234 }
5235
5236 var runner = new $$AnimateRunner();
5237
5238 // since there are no animations to run the runner needs to be
5239 // notified that the animation call is complete.
5240 runner.complete();
5241 return runner;
5242 }
5243 };
5244
5245
5246 function updateData(data, classes, value) {
5247 var changed = false;
5248 if (classes) {
5249 classes = isString(classes) ? classes.split(' ') :
5250 isArray(classes) ? classes : [];
5251 forEach(classes, function(className) {
5252 if (className) {
5253 changed = true;
5254 data[className] = value;
5255 }
5256 });
5257 }
5258 return changed;
5259 }
5260
5261 function handleCSSClassChanges() {
5262 forEach(postDigestElements, function(element) {
5263 var data = postDigestQueue.get(element);
5264 if (data) {
5265 var existing = splitClasses(element.attr('class'));
5266 var toAdd = '';
5267 var toRemove = '';
5268 forEach(data, function(status, className) {
5269 var hasClass = !!existing[className];
5270 if (status !== hasClass) {
5271 if (status) {
5272 toAdd += (toAdd.length ? ' ' : '') + className;
5273 } else {
5274 toRemove += (toRemove.length ? ' ' : '') + className;
5275 }
5276 }
5277 });
5278
5279 forEach(element, function(elm) {
5280 if (toAdd) {
5281 jqLiteAddClass(elm, toAdd);
5282 }
5283 if (toRemove) {
5284 jqLiteRemoveClass(elm, toRemove);
5285 }
5286 });
5287 postDigestQueue.remove(element);
5288 }
5289 });
5290 postDigestElements.length = 0;
5291 }
5292
5293
5294 function addRemoveClassesPostDigest(element, add, remove) {
5295 var data = postDigestQueue.get(element) || {};
5296
5297 var classesAdded = updateData(data, add, true);
5298 var classesRemoved = updateData(data, remove, false);
5299
5300 if (classesAdded || classesRemoved) {
5301
5302 postDigestQueue.put(element, data);
5303 postDigestElements.push(element);
5304
5305 if (postDigestElements.length === 1) {
5306 $rootScope.$$postDigest(handleCSSClassChanges);
5307 }
5308 }
5309 }
5310 }];
5311};
5312
5313/**
5314 * @ngdoc provider
5315 * @name $animateProvider
5316 *
5317 * @description
5318 * Default implementation of $animate that doesn't perform any animations, instead just
5319 * synchronously performs DOM updates and resolves the returned runner promise.
5320 *
5321 * In order to enable animations the `ngAnimate` module has to be loaded.
5322 *
5323 * To see the functional implementation check out `src/ngAnimate/animate.js`.
5324 */
5325var $AnimateProvider = ['$provide', /** @this */ function($provide) {
5326 var provider = this;
5327
5328 this.$$registeredAnimations = Object.create(null);
5329
5330 /**
5331 * @ngdoc method
5332 * @name $animateProvider#register
5333 *
5334 * @description
5335 * Registers a new injectable animation factory function. The factory function produces the
5336 * animation object which contains callback functions for each event that is expected to be
5337 * animated.
5338 *
5339 * * `eventFn`: `function(element, ... , doneFunction, options)`
5340 * The element to animate, the `doneFunction` and the options fed into the animation. Depending
5341 * on the type of animation additional arguments will be injected into the animation function. The
5342 * list below explains the function signatures for the different animation methods:
5343 *
5344 * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
5345 * - addClass: function(element, addedClasses, doneFunction, options)
5346 * - removeClass: function(element, removedClasses, doneFunction, options)
5347 * - enter, leave, move: function(element, doneFunction, options)
5348 * - animate: function(element, fromStyles, toStyles, doneFunction, options)
5349 *
5350 * Make sure to trigger the `doneFunction` once the animation is fully complete.
5351 *
5352 * ```js
5353 * return {
5354 * //enter, leave, move signature
5355 * eventFn : function(element, done, options) {
5356 * //code to run the animation
5357 * //once complete, then run done()
5358 * return function endFunction(wasCancelled) {
5359 * //code to cancel the animation
5360 * }
5361 * }
5362 * }
5363 * ```
5364 *
5365 * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
5366 * @param {Function} factory The factory function that will be executed to return the animation
5367 * object.
5368 */
5369 this.register = function(name, factory) {
5370 if (name && name.charAt(0) !== '.') {
5371 throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
5372 }
5373
5374 var key = name + '-animation';
5375 provider.$$registeredAnimations[name.substr(1)] = key;
5376 $provide.factory(key, factory);
5377 };
5378
5379 /**
5380 * @ngdoc method
5381 * @name $animateProvider#classNameFilter
5382 *
5383 * @description
5384 * Sets and/or returns the CSS class regular expression that is checked when performing
5385 * an animation. Upon bootstrap the classNameFilter value is not set at all and will
5386 * therefore enable $animate to attempt to perform an animation on any element that is triggered.
5387 * When setting the `classNameFilter` value, animations will only be performed on elements
5388 * that successfully match the filter expression. This in turn can boost performance
5389 * for low-powered devices as well as applications containing a lot of structural operations.
5390 * @param {RegExp=} expression The className expression which will be checked against all animations
5391 * @return {RegExp} The current CSS className expression value. If null then there is no expression value
5392 */
5393 this.classNameFilter = function(expression) {
5394 if (arguments.length === 1) {
5395 this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
5396 if (this.$$classNameFilter) {
5397 var reservedRegex = new RegExp('(\\s+|\\/)' + NG_ANIMATE_CLASSNAME + '(\\s+|\\/)');
5398 if (reservedRegex.test(this.$$classNameFilter.toString())) {
5399 throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
5400 }
5401 }
5402 }
5403 return this.$$classNameFilter;
5404 };
5405
5406 this.$get = ['$$animateQueue', function($$animateQueue) {
5407 function domInsert(element, parentElement, afterElement) {
5408 // if for some reason the previous element was removed
5409 // from the dom sometime before this code runs then let's
5410 // just stick to using the parent element as the anchor
5411 if (afterElement) {
5412 var afterNode = extractElementNode(afterElement);
5413 if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
5414 afterElement = null;
5415 }
5416 }
5417 if (afterElement) {
5418 afterElement.after(element);
5419 } else {
5420 parentElement.prepend(element);
5421 }
5422 }
5423
5424 /**
5425 * @ngdoc service
5426 * @name $animate
5427 * @description The $animate service exposes a series of DOM utility methods that provide support
5428 * for animation hooks. The default behavior is the application of DOM operations, however,
5429 * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
5430 * to ensure that animation runs with the triggered DOM operation.
5431 *
5432 * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
5433 * included and only when it is active then the animation hooks that `$animate` triggers will be
5434 * functional. Once active then all structural `ng-` directives will trigger animations as they perform
5435 * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
5436 * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
5437 *
5438 * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
5439 *
5440 * To learn more about enabling animation support, click here to visit the
5441 * {@link ngAnimate ngAnimate module page}.
5442 */
5443 return {
5444 // we don't call it directly since non-existant arguments may
5445 // be interpreted as null within the sub enabled function
5446
5447 /**
5448 *
5449 * @ngdoc method
5450 * @name $animate#on
5451 * @kind function
5452 * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
5453 * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
5454 * is fired with the following params:
5455 *
5456 * ```js
5457 * $animate.on('enter', container,
5458 * function callback(element, phase) {
5459 * // cool we detected an enter animation within the container
5460 * }
5461 * );
5462 * ```
5463 *
5464 * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
5465 * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
5466 * as well as among its children
5467 * @param {Function} callback the callback function that will be fired when the listener is triggered
5468 *
5469 * The arguments present in the callback function are:
5470 * * `element` - The captured DOM element that the animation was fired on.
5471 * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
5472 */
5473 on: $$animateQueue.on,
5474
5475 /**
5476 *
5477 * @ngdoc method
5478 * @name $animate#off
5479 * @kind function
5480 * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
5481 * can be used in three different ways depending on the arguments:
5482 *
5483 * ```js
5484 * // remove all the animation event listeners listening for `enter`
5485 * $animate.off('enter');
5486 *
5487 * // remove listeners for all animation events from the container element
5488 * $animate.off(container);
5489 *
5490 * // remove all the animation event listeners listening for `enter` on the given element and its children
5491 * $animate.off('enter', container);
5492 *
5493 * // remove the event listener function provided by `callback` that is set
5494 * // to listen for `enter` on the given `container` as well as its children
5495 * $animate.off('enter', container, callback);
5496 * ```
5497 *
5498 * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
5499 * addClass, removeClass, etc...), or the container element. If it is the element, all other
5500 * arguments are ignored.
5501 * @param {DOMElement=} container the container element the event listener was placed on
5502 * @param {Function=} callback the callback function that was registered as the listener
5503 */
5504 off: $$animateQueue.off,
5505
5506 /**
5507 * @ngdoc method
5508 * @name $animate#pin
5509 * @kind function
5510 * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
5511 * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
5512 * element despite being outside the realm of the application or within another application. Say for example if the application
5513 * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
5514 * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
5515 * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
5516 *
5517 * Note that this feature is only active when the `ngAnimate` module is used.
5518 *
5519 * @param {DOMElement} element the external element that will be pinned
5520 * @param {DOMElement} parentElement the host parent element that will be associated with the external element
5521 */
5522 pin: $$animateQueue.pin,
5523
5524 /**
5525 *
5526 * @ngdoc method
5527 * @name $animate#enabled
5528 * @kind function
5529 * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
5530 * function can be called in four ways:
5531 *
5532 * ```js
5533 * // returns true or false
5534 * $animate.enabled();
5535 *
5536 * // changes the enabled state for all animations
5537 * $animate.enabled(false);
5538 * $animate.enabled(true);
5539 *
5540 * // returns true or false if animations are enabled for an element
5541 * $animate.enabled(element);
5542 *
5543 * // changes the enabled state for an element and its children
5544 * $animate.enabled(element, true);
5545 * $animate.enabled(element, false);
5546 * ```
5547 *
5548 * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
5549 * @param {boolean=} enabled whether or not the animations will be enabled for the element
5550 *
5551 * @return {boolean} whether or not animations are enabled
5552 */
5553 enabled: $$animateQueue.enabled,
5554
5555 /**
5556 * @ngdoc method
5557 * @name $animate#cancel
5558 * @kind function
5559 * @description Cancels the provided animation.
5560 *
5561 * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
5562 */
5563 cancel: function(runner) {
5564 if (runner.end) {
5565 runner.end();
5566 }
5567 },
5568
5569 /**
5570 *
5571 * @ngdoc method
5572 * @name $animate#enter
5573 * @kind function
5574 * @description Inserts the element into the DOM either after the `after` element (if provided) or
5575 * as the first child within the `parent` element and then triggers an animation.
5576 * A promise is returned that will be resolved during the next digest once the animation
5577 * has completed.
5578 *
5579 * @param {DOMElement} element the element which will be inserted into the DOM
5580 * @param {DOMElement} parent the parent element which will append the element as
5581 * a child (so long as the after element is not present)
5582 * @param {DOMElement=} after the sibling element after which the element will be appended
5583 * @param {object=} options an optional collection of options/styles that will be applied to the element.
5584 * The object can have the following properties:
5585 *
5586 * - **addClass** - `{string}` - space-separated CSS classes to add to element
5587 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
5588 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
5589 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
5590 *
5591 * @return {Promise} the animation callback promise
5592 */
5593 enter: function(element, parent, after, options) {
5594 parent = parent && jqLite(parent);
5595 after = after && jqLite(after);
5596 parent = parent || after.parent();
5597 domInsert(element, parent, after);
5598 return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
5599 },
5600
5601 /**
5602 *
5603 * @ngdoc method
5604 * @name $animate#move
5605 * @kind function
5606 * @description Inserts (moves) the element into its new position in the DOM either after
5607 * the `after` element (if provided) or as the first child within the `parent` element
5608 * and then triggers an animation. A promise is returned that will be resolved
5609 * during the next digest once the animation has completed.
5610 *
5611 * @param {DOMElement} element the element which will be moved into the new DOM position
5612 * @param {DOMElement} parent the parent element which will append the element as
5613 * a child (so long as the after element is not present)
5614 * @param {DOMElement=} after the sibling element after which the element will be appended
5615 * @param {object=} options an optional collection of options/styles that will be applied to the element.
5616 * The object can have the following properties:
5617 *
5618 * - **addClass** - `{string}` - space-separated CSS classes to add to element
5619 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
5620 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
5621 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
5622 *
5623 * @return {Promise} the animation callback promise
5624 */
5625 move: function(element, parent, after, options) {
5626 parent = parent && jqLite(parent);
5627 after = after && jqLite(after);
5628 parent = parent || after.parent();
5629 domInsert(element, parent, after);
5630 return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
5631 },
5632
5633 /**
5634 * @ngdoc method
5635 * @name $animate#leave
5636 * @kind function
5637 * @description Triggers an animation and then removes the element from the DOM.
5638 * When the function is called a promise is returned that will be resolved during the next
5639 * digest once the animation has completed.
5640 *
5641 * @param {DOMElement} element the element which will be removed from the DOM
5642 * @param {object=} options an optional collection of options/styles that will be applied to the element.
5643 * The object can have the following properties:
5644 *
5645 * - **addClass** - `{string}` - space-separated CSS classes to add to element
5646 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
5647 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
5648 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
5649 *
5650 * @return {Promise} the animation callback promise
5651 */
5652 leave: function(element, options) {
5653 return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
5654 element.remove();
5655 });
5656 },
5657
5658 /**
5659 * @ngdoc method
5660 * @name $animate#addClass
5661 * @kind function
5662 *
5663 * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
5664 * execution, the addClass operation will only be handled after the next digest and it will not trigger an
5665 * animation if element already contains the CSS class or if the class is removed at a later step.
5666 * Note that class-based animations are treated differently compared to structural animations
5667 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5668 * depending if CSS or JavaScript animations are used.
5669 *
5670 * @param {DOMElement} element the element which the CSS classes will be applied to
5671 * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
5672 * @param {object=} options an optional collection of options/styles that will be applied to the element.
5673 * The object can have the following properties:
5674 *
5675 * - **addClass** - `{string}` - space-separated CSS classes to add to element
5676 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
5677 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
5678 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
5679 *
5680 * @return {Promise} the animation callback promise
5681 */
5682 addClass: function(element, className, options) {
5683 options = prepareAnimateOptions(options);
5684 options.addClass = mergeClasses(options.addclass, className);
5685 return $$animateQueue.push(element, 'addClass', options);
5686 },
5687
5688 /**
5689 * @ngdoc method
5690 * @name $animate#removeClass
5691 * @kind function
5692 *
5693 * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
5694 * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
5695 * animation if element does not contain the CSS class or if the class is added at a later step.
5696 * Note that class-based animations are treated differently compared to structural animations
5697 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5698 * depending if CSS or JavaScript animations are used.
5699 *
5700 * @param {DOMElement} element the element which the CSS classes will be applied to
5701 * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
5702 * @param {object=} options an optional collection of options/styles that will be applied to the element.
5703 * The object can have the following properties:
5704 *
5705 * - **addClass** - `{string}` - space-separated CSS classes to add to element
5706 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
5707 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
5708 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
5709 *
5710 * @return {Promise} the animation callback promise
5711 */
5712 removeClass: function(element, className, options) {
5713 options = prepareAnimateOptions(options);
5714 options.removeClass = mergeClasses(options.removeClass, className);
5715 return $$animateQueue.push(element, 'removeClass', options);
5716 },
5717
5718 /**
5719 * @ngdoc method
5720 * @name $animate#setClass
5721 * @kind function
5722 *
5723 * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
5724 * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
5725 * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
5726 * passed. Note that class-based animations are treated differently compared to structural animations
5727 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5728 * depending if CSS or JavaScript animations are used.
5729 *
5730 * @param {DOMElement} element the element which the CSS classes will be applied to
5731 * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
5732 * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
5733 * @param {object=} options an optional collection of options/styles that will be applied to the element.
5734 * The object can have the following properties:
5735 *
5736 * - **addClass** - `{string}` - space-separated CSS classes to add to element
5737 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
5738 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
5739 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
5740 *
5741 * @return {Promise} the animation callback promise
5742 */
5743 setClass: function(element, add, remove, options) {
5744 options = prepareAnimateOptions(options);
5745 options.addClass = mergeClasses(options.addClass, add);
5746 options.removeClass = mergeClasses(options.removeClass, remove);
5747 return $$animateQueue.push(element, 'setClass', options);
5748 },
5749
5750 /**
5751 * @ngdoc method
5752 * @name $animate#animate
5753 * @kind function
5754 *
5755 * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
5756 * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
5757 * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
5758 * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
5759 * style in `to`, the style in `from` is applied immediately, and no animation is run.
5760 * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
5761 * method (or as part of the `options` parameter):
5762 *
5763 * ```js
5764 * ngModule.animation('.my-inline-animation', function() {
5765 * return {
5766 * animate : function(element, from, to, done, options) {
5767 * //animation
5768 * done();
5769 * }
5770 * }
5771 * });
5772 * ```
5773 *
5774 * @param {DOMElement} element the element which the CSS styles will be applied to
5775 * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
5776 * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
5777 * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
5778 * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
5779 * (Note that if no animation is detected then this value will not be applied to the element.)
5780 * @param {object=} options an optional collection of options/styles that will be applied to the element.
5781 * The object can have the following properties:
5782 *
5783 * - **addClass** - `{string}` - space-separated CSS classes to add to element
5784 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
5785 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
5786 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
5787 *
5788 * @return {Promise} the animation callback promise
5789 */
5790 animate: function(element, from, to, className, options) {
5791 options = prepareAnimateOptions(options);
5792 options.from = options.from ? extend(options.from, from) : from;
5793 options.to = options.to ? extend(options.to, to) : to;
5794
5795 className = className || 'ng-inline-animate';
5796 options.tempClasses = mergeClasses(options.tempClasses, className);
5797 return $$animateQueue.push(element, 'animate', options);
5798 }
5799 };
5800 }];
5801}];
5802
5803var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
5804 this.$get = ['$$rAF', function($$rAF) {
5805 var waitQueue = [];
5806
5807 function waitForTick(fn) {
5808 waitQueue.push(fn);
5809 if (waitQueue.length > 1) return;
5810 $$rAF(function() {
5811 for (var i = 0; i < waitQueue.length; i++) {
5812 waitQueue[i]();
5813 }
5814 waitQueue = [];
5815 });
5816 }
5817
5818 return function() {
5819 var passed = false;
5820 waitForTick(function() {
5821 passed = true;
5822 });
5823 return function(callback) {
5824 if (passed) {
5825 callback();
5826 } else {
5827 waitForTick(callback);
5828 }
5829 };
5830 };
5831 }];
5832};
5833
5834var $$AnimateRunnerFactoryProvider = /** @this */ function() {
5835 this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
5836 function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
5837
5838 var INITIAL_STATE = 0;
5839 var DONE_PENDING_STATE = 1;
5840 var DONE_COMPLETE_STATE = 2;
5841
5842 AnimateRunner.chain = function(chain, callback) {
5843 var index = 0;
5844
5845 next();
5846 function next() {
5847 if (index === chain.length) {
5848 callback(true);
5849 return;
5850 }
5851
5852 chain[index](function(response) {
5853 if (response === false) {
5854 callback(false);
5855 return;
5856 }
5857 index++;
5858 next();
5859 });
5860 }
5861 };
5862
5863 AnimateRunner.all = function(runners, callback) {
5864 var count = 0;
5865 var status = true;
5866 forEach(runners, function(runner) {
5867 runner.done(onProgress);
5868 });
5869
5870 function onProgress(response) {
5871 status = status && response;
5872 if (++count === runners.length) {
5873 callback(status);
5874 }
5875 }
5876 };
5877
5878 function AnimateRunner(host) {
5879 this.setHost(host);
5880
5881 var rafTick = $$animateAsyncRun();
5882 var timeoutTick = function(fn) {
5883 $timeout(fn, 0, false);
5884 };
5885
5886 this._doneCallbacks = [];
5887 this._tick = function(fn) {
5888 if ($$isDocumentHidden()) {
5889 timeoutTick(fn);
5890 } else {
5891 rafTick(fn);
5892 }
5893 };
5894 this._state = 0;
5895 }
5896
5897 AnimateRunner.prototype = {
5898 setHost: function(host) {
5899 this.host = host || {};
5900 },
5901
5902 done: function(fn) {
5903 if (this._state === DONE_COMPLETE_STATE) {
5904 fn();
5905 } else {
5906 this._doneCallbacks.push(fn);
5907 }
5908 },
5909
5910 progress: noop,
5911
5912 getPromise: function() {
5913 if (!this.promise) {
5914 var self = this;
5915 this.promise = $q(function(resolve, reject) {
5916 self.done(function(status) {
5917 if (status === false) {
5918 reject();
5919 } else {
5920 resolve();
5921 }
5922 });
5923 });
5924 }
5925 return this.promise;
5926 },
5927
5928 then: function(resolveHandler, rejectHandler) {
5929 return this.getPromise().then(resolveHandler, rejectHandler);
5930 },
5931
5932 'catch': function(handler) {
5933 return this.getPromise()['catch'](handler);
5934 },
5935
5936 'finally': function(handler) {
5937 return this.getPromise()['finally'](handler);
5938 },
5939
5940 pause: function() {
5941 if (this.host.pause) {
5942 this.host.pause();
5943 }
5944 },
5945
5946 resume: function() {
5947 if (this.host.resume) {
5948 this.host.resume();
5949 }
5950 },
5951
5952 end: function() {
5953 if (this.host.end) {
5954 this.host.end();
5955 }
5956 this._resolve(true);
5957 },
5958
5959 cancel: function() {
5960 if (this.host.cancel) {
5961 this.host.cancel();
5962 }
5963 this._resolve(false);
5964 },
5965
5966 complete: function(response) {
5967 var self = this;
5968 if (self._state === INITIAL_STATE) {
5969 self._state = DONE_PENDING_STATE;
5970 self._tick(function() {
5971 self._resolve(response);
5972 });
5973 }
5974 },
5975
5976 _resolve: function(response) {
5977 if (this._state !== DONE_COMPLETE_STATE) {
5978 forEach(this._doneCallbacks, function(fn) {
5979 fn(response);
5980 });
5981 this._doneCallbacks.length = 0;
5982 this._state = DONE_COMPLETE_STATE;
5983 }
5984 }
5985 };
5986
5987 return AnimateRunner;
5988 }];
5989};
5990
5991/* exported $CoreAnimateCssProvider */
5992
5993/**
5994 * @ngdoc service
5995 * @name $animateCss
5996 * @kind object
5997 * @this
5998 *
5999 * @description
6000 * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
6001 * then the `$animateCss` service will actually perform animations.
6002 *
6003 * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
6004 */
6005var $CoreAnimateCssProvider = function() {
6006 this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
6007
6008 return function(element, initialOptions) {
6009 // all of the animation functions should create
6010 // a copy of the options data, however, if a
6011 // parent service has already created a copy then
6012 // we should stick to using that
6013 var options = initialOptions || {};
6014 if (!options.$$prepared) {
6015 options = copy(options);
6016 }
6017
6018 // there is no point in applying the styles since
6019 // there is no animation that goes on at all in
6020 // this version of $animateCss.
6021 if (options.cleanupStyles) {
6022 options.from = options.to = null;
6023 }
6024
6025 if (options.from) {
6026 element.css(options.from);
6027 options.from = null;
6028 }
6029
6030 var closed, runner = new $$AnimateRunner();
6031 return {
6032 start: run,
6033 end: run
6034 };
6035
6036 function run() {
6037 $$rAF(function() {
6038 applyAnimationContents();
6039 if (!closed) {
6040 runner.complete();
6041 }
6042 closed = true;
6043 });
6044 return runner;
6045 }
6046
6047 function applyAnimationContents() {
6048 if (options.addClass) {
6049 element.addClass(options.addClass);
6050 options.addClass = null;
6051 }
6052 if (options.removeClass) {
6053 element.removeClass(options.removeClass);
6054 options.removeClass = null;
6055 }
6056 if (options.to) {
6057 element.css(options.to);
6058 options.to = null;
6059 }
6060 }
6061 };
6062 }];
6063};
6064
6065/* global stripHash: true */
6066
6067/**
6068 * ! This is a private undocumented service !
6069 *
6070 * @name $browser
6071 * @requires $log
6072 * @description
6073 * This object has two goals:
6074 *
6075 * - hide all the global state in the browser caused by the window object
6076 * - abstract away all the browser specific features and inconsistencies
6077 *
6078 * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
6079 * service, which can be used for convenient testing of the application without the interaction with
6080 * the real browser apis.
6081 */
6082/**
6083 * @param {object} window The global window object.
6084 * @param {object} document jQuery wrapped document.
6085 * @param {object} $log window.console or an object with the same interface.
6086 * @param {object} $sniffer $sniffer service
6087 */
6088function Browser(window, document, $log, $sniffer) {
6089 var self = this,
6090 location = window.location,
6091 history = window.history,
6092 setTimeout = window.setTimeout,
6093 clearTimeout = window.clearTimeout,
6094 pendingDeferIds = {};
6095
6096 self.isMock = false;
6097
6098 var outstandingRequestCount = 0;
6099 var outstandingRequestCallbacks = [];
6100
6101 // TODO(vojta): remove this temporary api
6102 self.$$completeOutstandingRequest = completeOutstandingRequest;
6103 self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
6104
6105 /**
6106 * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
6107 * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
6108 */
6109 function completeOutstandingRequest(fn) {
6110 try {
6111 fn.apply(null, sliceArgs(arguments, 1));
6112 } finally {
6113 outstandingRequestCount--;
6114 if (outstandingRequestCount === 0) {
6115 while (outstandingRequestCallbacks.length) {
6116 try {
6117 outstandingRequestCallbacks.pop()();
6118 } catch (e) {
6119 $log.error(e);
6120 }
6121 }
6122 }
6123 }
6124 }
6125
6126 function getHash(url) {
6127 var index = url.indexOf('#');
6128 return index === -1 ? '' : url.substr(index);
6129 }
6130
6131 /**
6132 * @private
6133 * Note: this method is used only by scenario runner
6134 * TODO(vojta): prefix this method with $$ ?
6135 * @param {function()} callback Function that will be called when no outstanding request
6136 */
6137 self.notifyWhenNoOutstandingRequests = function(callback) {
6138 if (outstandingRequestCount === 0) {
6139 callback();
6140 } else {
6141 outstandingRequestCallbacks.push(callback);
6142 }
6143 };
6144
6145 //////////////////////////////////////////////////////////////
6146 // URL API
6147 //////////////////////////////////////////////////////////////
6148
6149 var cachedState, lastHistoryState,
6150 lastBrowserUrl = location.href,
6151 baseElement = document.find('base'),
6152 pendingLocation = null,
6153 getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
6154 try {
6155 return history.state;
6156 } catch (e) {
6157 // MSIE can reportedly throw when there is no state (UNCONFIRMED).
6158 }
6159 };
6160
6161 cacheState();
6162 lastHistoryState = cachedState;
6163
6164 /**
6165 * @name $browser#url
6166 *
6167 * @description
6168 * GETTER:
6169 * Without any argument, this method just returns current value of location.href.
6170 *
6171 * SETTER:
6172 * With at least one argument, this method sets url to new value.
6173 * If html5 history api supported, pushState/replaceState is used, otherwise
6174 * location.href/location.replace is used.
6175 * Returns its own instance to allow chaining
6176 *
6177 * NOTE: this api is intended for use only by the $location service. Please use the
6178 * {@link ng.$location $location service} to change url.
6179 *
6180 * @param {string} url New url (when used as setter)
6181 * @param {boolean=} replace Should new url replace current history record?
6182 * @param {object=} state object to use with pushState/replaceState
6183 */
6184 self.url = function(url, replace, state) {
6185 // In modern browsers `history.state` is `null` by default; treating it separately
6186 // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
6187 // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
6188 if (isUndefined(state)) {
6189 state = null;
6190 }
6191
6192 // Android Browser BFCache causes location, history reference to become stale.
6193 if (location !== window.location) location = window.location;
6194 if (history !== window.history) history = window.history;
6195
6196 // setter
6197 if (url) {
6198 var sameState = lastHistoryState === state;
6199
6200 // Don't change anything if previous and current URLs and states match. This also prevents
6201 // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
6202 // See https://github.com/angular/angular.js/commit/ffb2701
6203 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
6204 return self;
6205 }
6206 var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
6207 lastBrowserUrl = url;
6208 lastHistoryState = state;
6209 // Don't use history API if only the hash changed
6210 // due to a bug in IE10/IE11 which leads
6211 // to not firing a `hashchange` nor `popstate` event
6212 // in some cases (see #9143).
6213 if ($sniffer.history && (!sameBase || !sameState)) {
6214 history[replace ? 'replaceState' : 'pushState'](state, '', url);
6215 cacheState();
6216 // Do the assignment again so that those two variables are referentially identical.
6217 lastHistoryState = cachedState;
6218 } else {
6219 if (!sameBase) {
6220 pendingLocation = url;
6221 }
6222 if (replace) {
6223 location.replace(url);
6224 } else if (!sameBase) {
6225 location.href = url;
6226 } else {
6227 location.hash = getHash(url);
6228 }
6229 if (location.href !== url) {
6230 pendingLocation = url;
6231 }
6232 }
6233 if (pendingLocation) {
6234 pendingLocation = url;
6235 }
6236 return self;
6237 // getter
6238 } else {
6239 // - pendingLocation is needed as browsers don't allow to read out
6240 // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
6241 // https://openradar.appspot.com/22186109).
6242 // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
6243 return pendingLocation || location.href.replace(/%27/g,'\'');
6244 }
6245 };
6246
6247 /**
6248 * @name $browser#state
6249 *
6250 * @description
6251 * This method is a getter.
6252 *
6253 * Return history.state or null if history.state is undefined.
6254 *
6255 * @returns {object} state
6256 */
6257 self.state = function() {
6258 return cachedState;
6259 };
6260
6261 var urlChangeListeners = [],
6262 urlChangeInit = false;
6263
6264 function cacheStateAndFireUrlChange() {
6265 pendingLocation = null;
6266 cacheState();
6267 fireUrlChange();
6268 }
6269
6270 // This variable should be used *only* inside the cacheState function.
6271 var lastCachedState = null;
6272 function cacheState() {
6273 // This should be the only place in $browser where `history.state` is read.
6274 cachedState = getCurrentState();
6275 cachedState = isUndefined(cachedState) ? null : cachedState;
6276
6277 // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
6278 if (equals(cachedState, lastCachedState)) {
6279 cachedState = lastCachedState;
6280 }
6281 lastCachedState = cachedState;
6282 }
6283
6284 function fireUrlChange() {
6285 if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
6286 return;
6287 }
6288
6289 lastBrowserUrl = self.url();
6290 lastHistoryState = cachedState;
6291 forEach(urlChangeListeners, function(listener) {
6292 listener(self.url(), cachedState);
6293 });
6294 }
6295
6296 /**
6297 * @name $browser#onUrlChange
6298 *
6299 * @description
6300 * Register callback function that will be called, when url changes.
6301 *
6302 * It's only called when the url is changed from outside of angular:
6303 * - user types different url into address bar
6304 * - user clicks on history (forward/back) button
6305 * - user clicks on a link
6306 *
6307 * It's not called when url is changed by $browser.url() method
6308 *
6309 * The listener gets called with new url as parameter.
6310 *
6311 * NOTE: this api is intended for use only by the $location service. Please use the
6312 * {@link ng.$location $location service} to monitor url changes in angular apps.
6313 *
6314 * @param {function(string)} listener Listener function to be called when url changes.
6315 * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
6316 */
6317 self.onUrlChange = function(callback) {
6318 // TODO(vojta): refactor to use node's syntax for events
6319 if (!urlChangeInit) {
6320 // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
6321 // don't fire popstate when user change the address bar and don't fire hashchange when url
6322 // changed by push/replaceState
6323
6324 // html5 history api - popstate event
6325 if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
6326 // hashchange event
6327 jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
6328
6329 urlChangeInit = true;
6330 }
6331
6332 urlChangeListeners.push(callback);
6333 return callback;
6334 };
6335
6336 /**
6337 * @private
6338 * Remove popstate and hashchange handler from window.
6339 *
6340 * NOTE: this api is intended for use only by $rootScope.
6341 */
6342 self.$$applicationDestroyed = function() {
6343 jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
6344 };
6345
6346 /**
6347 * Checks whether the url has changed outside of Angular.
6348 * Needs to be exported to be able to check for changes that have been done in sync,
6349 * as hashchange/popstate events fire in async.
6350 */
6351 self.$$checkUrlChange = fireUrlChange;
6352
6353 //////////////////////////////////////////////////////////////
6354 // Misc API
6355 //////////////////////////////////////////////////////////////
6356
6357 /**
6358 * @name $browser#baseHref
6359 *
6360 * @description
6361 * Returns current <base href>
6362 * (always relative - without domain)
6363 *
6364 * @returns {string} The current base href
6365 */
6366 self.baseHref = function() {
6367 var href = baseElement.attr('href');
6368 return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
6369 };
6370
6371 /**
6372 * @name $browser#defer
6373 * @param {function()} fn A function, who's execution should be deferred.
6374 * @param {number=} [delay=0] of milliseconds to defer the function execution.
6375 * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
6376 *
6377 * @description
6378 * Executes a fn asynchronously via `setTimeout(fn, delay)`.
6379 *
6380 * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
6381 * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
6382 * via `$browser.defer.flush()`.
6383 *
6384 */
6385 self.defer = function(fn, delay) {
6386 var timeoutId;
6387 outstandingRequestCount++;
6388 timeoutId = setTimeout(function() {
6389 delete pendingDeferIds[timeoutId];
6390 completeOutstandingRequest(fn);
6391 }, delay || 0);
6392 pendingDeferIds[timeoutId] = true;
6393 return timeoutId;
6394 };
6395
6396
6397 /**
6398 * @name $browser#defer.cancel
6399 *
6400 * @description
6401 * Cancels a deferred task identified with `deferId`.
6402 *
6403 * @param {*} deferId Token returned by the `$browser.defer` function.
6404 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
6405 * canceled.
6406 */
6407 self.defer.cancel = function(deferId) {
6408 if (pendingDeferIds[deferId]) {
6409 delete pendingDeferIds[deferId];
6410 clearTimeout(deferId);
6411 completeOutstandingRequest(noop);
6412 return true;
6413 }
6414 return false;
6415 };
6416
6417}
6418
6419/** @this */
6420function $BrowserProvider() {
6421 this.$get = ['$window', '$log', '$sniffer', '$document',
6422 function($window, $log, $sniffer, $document) {
6423 return new Browser($window, $document, $log, $sniffer);
6424 }];
6425}
6426
6427/**
6428 * @ngdoc service
6429 * @name $cacheFactory
6430 * @this
6431 *
6432 * @description
6433 * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
6434 * them.
6435 *
6436 * ```js
6437 *
6438 * var cache = $cacheFactory('cacheId');
6439 * expect($cacheFactory.get('cacheId')).toBe(cache);
6440 * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
6441 *
6442 * cache.put("key", "value");
6443 * cache.put("another key", "another value");
6444 *
6445 * // We've specified no options on creation
6446 * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
6447 *
6448 * ```
6449 *
6450 *
6451 * @param {string} cacheId Name or id of the newly created cache.
6452 * @param {object=} options Options object that specifies the cache behavior. Properties:
6453 *
6454 * - `{number=}` `capacity` — turns the cache into LRU cache.
6455 *
6456 * @returns {object} Newly created cache object with the following set of methods:
6457 *
6458 * - `{object}` `info()` — Returns id, size, and options of cache.
6459 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
6460 * it.
6461 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
6462 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
6463 * - `{void}` `removeAll()` — Removes all cached values.
6464 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
6465 *
6466 * @example
6467 <example module="cacheExampleApp" name="cache-factory">
6468 <file name="index.html">
6469 <div ng-controller="CacheController">
6470 <input ng-model="newCacheKey" placeholder="Key">
6471 <input ng-model="newCacheValue" placeholder="Value">
6472 <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
6473
6474 <p ng-if="keys.length">Cached Values</p>
6475 <div ng-repeat="key in keys">
6476 <span ng-bind="key"></span>
6477 <span>: </span>
6478 <b ng-bind="cache.get(key)"></b>
6479 </div>
6480
6481 <p>Cache Info</p>
6482 <div ng-repeat="(key, value) in cache.info()">
6483 <span ng-bind="key"></span>
6484 <span>: </span>
6485 <b ng-bind="value"></b>
6486 </div>
6487 </div>
6488 </file>
6489 <file name="script.js">
6490 angular.module('cacheExampleApp', []).
6491 controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
6492 $scope.keys = [];
6493 $scope.cache = $cacheFactory('cacheId');
6494 $scope.put = function(key, value) {
6495 if (angular.isUndefined($scope.cache.get(key))) {
6496 $scope.keys.push(key);
6497 }
6498 $scope.cache.put(key, angular.isUndefined(value) ? null : value);
6499 };
6500 }]);
6501 </file>
6502 <file name="style.css">
6503 p {
6504 margin: 10px 0 3px;
6505 }
6506 </file>
6507 </example>
6508 */
6509function $CacheFactoryProvider() {
6510
6511 this.$get = function() {
6512 var caches = {};
6513
6514 function cacheFactory(cacheId, options) {
6515 if (cacheId in caches) {
6516 throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
6517 }
6518
6519 var size = 0,
6520 stats = extend({}, options, {id: cacheId}),
6521 data = createMap(),
6522 capacity = (options && options.capacity) || Number.MAX_VALUE,
6523 lruHash = createMap(),
6524 freshEnd = null,
6525 staleEnd = null;
6526
6527 /**
6528 * @ngdoc type
6529 * @name $cacheFactory.Cache
6530 *
6531 * @description
6532 * A cache object used to store and retrieve data, primarily used by
6533 * {@link $http $http} and the {@link ng.directive:script script} directive to cache
6534 * templates and other data.
6535 *
6536 * ```js
6537 * angular.module('superCache')
6538 * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
6539 * return $cacheFactory('super-cache');
6540 * }]);
6541 * ```
6542 *
6543 * Example test:
6544 *
6545 * ```js
6546 * it('should behave like a cache', inject(function(superCache) {
6547 * superCache.put('key', 'value');
6548 * superCache.put('another key', 'another value');
6549 *
6550 * expect(superCache.info()).toEqual({
6551 * id: 'super-cache',
6552 * size: 2
6553 * });
6554 *
6555 * superCache.remove('another key');
6556 * expect(superCache.get('another key')).toBeUndefined();
6557 *
6558 * superCache.removeAll();
6559 * expect(superCache.info()).toEqual({
6560 * id: 'super-cache',
6561 * size: 0
6562 * });
6563 * }));
6564 * ```
6565 */
6566 return (caches[cacheId] = {
6567
6568 /**
6569 * @ngdoc method
6570 * @name $cacheFactory.Cache#put
6571 * @kind function
6572 *
6573 * @description
6574 * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
6575 * retrieved later, and incrementing the size of the cache if the key was not already
6576 * present in the cache. If behaving like an LRU cache, it will also remove stale
6577 * entries from the set.
6578 *
6579 * It will not insert undefined values into the cache.
6580 *
6581 * @param {string} key the key under which the cached data is stored.
6582 * @param {*} value the value to store alongside the key. If it is undefined, the key
6583 * will not be stored.
6584 * @returns {*} the value stored.
6585 */
6586 put: function(key, value) {
6587 if (isUndefined(value)) return;
6588 if (capacity < Number.MAX_VALUE) {
6589 var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
6590
6591 refresh(lruEntry);
6592 }
6593
6594 if (!(key in data)) size++;
6595 data[key] = value;
6596
6597 if (size > capacity) {
6598 this.remove(staleEnd.key);
6599 }
6600
6601 return value;
6602 },
6603
6604 /**
6605 * @ngdoc method
6606 * @name $cacheFactory.Cache#get
6607 * @kind function
6608 *
6609 * @description
6610 * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
6611 *
6612 * @param {string} key the key of the data to be retrieved
6613 * @returns {*} the value stored.
6614 */
6615 get: function(key) {
6616 if (capacity < Number.MAX_VALUE) {
6617 var lruEntry = lruHash[key];
6618
6619 if (!lruEntry) return;
6620
6621 refresh(lruEntry);
6622 }
6623
6624 return data[key];
6625 },
6626
6627
6628 /**
6629 * @ngdoc method
6630 * @name $cacheFactory.Cache#remove
6631 * @kind function
6632 *
6633 * @description
6634 * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
6635 *
6636 * @param {string} key the key of the entry to be removed
6637 */
6638 remove: function(key) {
6639 if (capacity < Number.MAX_VALUE) {
6640 var lruEntry = lruHash[key];
6641
6642 if (!lruEntry) return;
6643
6644 if (lruEntry === freshEnd) freshEnd = lruEntry.p;
6645 if (lruEntry === staleEnd) staleEnd = lruEntry.n;
6646 link(lruEntry.n,lruEntry.p);
6647
6648 delete lruHash[key];
6649 }
6650
6651 if (!(key in data)) return;
6652
6653 delete data[key];
6654 size--;
6655 },
6656
6657
6658 /**
6659 * @ngdoc method
6660 * @name $cacheFactory.Cache#removeAll
6661 * @kind function
6662 *
6663 * @description
6664 * Clears the cache object of any entries.
6665 */
6666 removeAll: function() {
6667 data = createMap();
6668 size = 0;
6669 lruHash = createMap();
6670 freshEnd = staleEnd = null;
6671 },
6672
6673
6674 /**
6675 * @ngdoc method
6676 * @name $cacheFactory.Cache#destroy
6677 * @kind function
6678 *
6679 * @description
6680 * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
6681 * removing it from the {@link $cacheFactory $cacheFactory} set.
6682 */
6683 destroy: function() {
6684 data = null;
6685 stats = null;
6686 lruHash = null;
6687 delete caches[cacheId];
6688 },
6689
6690
6691 /**
6692 * @ngdoc method
6693 * @name $cacheFactory.Cache#info
6694 * @kind function
6695 *
6696 * @description
6697 * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
6698 *
6699 * @returns {object} an object with the following properties:
6700 * <ul>
6701 * <li>**id**: the id of the cache instance</li>
6702 * <li>**size**: the number of entries kept in the cache instance</li>
6703 * <li>**...**: any additional properties from the options object when creating the
6704 * cache.</li>
6705 * </ul>
6706 */
6707 info: function() {
6708 return extend({}, stats, {size: size});
6709 }
6710 });
6711
6712
6713 /**
6714 * makes the `entry` the freshEnd of the LRU linked list
6715 */
6716 function refresh(entry) {
6717 if (entry !== freshEnd) {
6718 if (!staleEnd) {
6719 staleEnd = entry;
6720 } else if (staleEnd === entry) {
6721 staleEnd = entry.n;
6722 }
6723
6724 link(entry.n, entry.p);
6725 link(entry, freshEnd);
6726 freshEnd = entry;
6727 freshEnd.n = null;
6728 }
6729 }
6730
6731
6732 /**
6733 * bidirectionally links two entries of the LRU linked list
6734 */
6735 function link(nextEntry, prevEntry) {
6736 if (nextEntry !== prevEntry) {
6737 if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
6738 if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
6739 }
6740 }
6741 }
6742
6743
6744 /**
6745 * @ngdoc method
6746 * @name $cacheFactory#info
6747 *
6748 * @description
6749 * Get information about all the caches that have been created
6750 *
6751 * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
6752 */
6753 cacheFactory.info = function() {
6754 var info = {};
6755 forEach(caches, function(cache, cacheId) {
6756 info[cacheId] = cache.info();
6757 });
6758 return info;
6759 };
6760
6761
6762 /**
6763 * @ngdoc method
6764 * @name $cacheFactory#get
6765 *
6766 * @description
6767 * Get access to a cache object by the `cacheId` used when it was created.
6768 *
6769 * @param {string} cacheId Name or id of a cache to access.
6770 * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
6771 */
6772 cacheFactory.get = function(cacheId) {
6773 return caches[cacheId];
6774 };
6775
6776
6777 return cacheFactory;
6778 };
6779}
6780
6781/**
6782 * @ngdoc service
6783 * @name $templateCache
6784 * @this
6785 *
6786 * @description
6787 * The first time a template is used, it is loaded in the template cache for quick retrieval. You
6788 * can load templates directly into the cache in a `script` tag, or by consuming the
6789 * `$templateCache` service directly.
6790 *
6791 * Adding via the `script` tag:
6792 *
6793 * ```html
6794 * <script type="text/ng-template" id="templateId.html">
6795 * <p>This is the content of the template</p>
6796 * </script>
6797 * ```
6798 *
6799 * **Note:** the `script` tag containing the template does not need to be included in the `head` of
6800 * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
6801 * element with ng-app attribute), otherwise the template will be ignored.
6802 *
6803 * Adding via the `$templateCache` service:
6804 *
6805 * ```js
6806 * var myApp = angular.module('myApp', []);
6807 * myApp.run(function($templateCache) {
6808 * $templateCache.put('templateId.html', 'This is the content of the template');
6809 * });
6810 * ```
6811 *
6812 * To retrieve the template later, simply use it in your component:
6813 * ```js
6814 * myApp.component('myComponent', {
6815 * templateUrl: 'templateId.html'
6816 * });
6817 * ```
6818 *
6819 * or get it via the `$templateCache` service:
6820 * ```js
6821 * $templateCache.get('templateId.html')
6822 * ```
6823 *
6824 * See {@link ng.$cacheFactory $cacheFactory}.
6825 *
6826 */
6827function $TemplateCacheProvider() {
6828 this.$get = ['$cacheFactory', function($cacheFactory) {
6829 return $cacheFactory('templates');
6830 }];
6831}
6832
6833/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
6834 * Any commits to this file should be reviewed with security in mind. *
6835 * Changes to this file can potentially create security vulnerabilities. *
6836 * An approval from 2 Core members with history of modifying *
6837 * this file is required. *
6838 * *
6839 * Does the change somehow allow for arbitrary javascript to be executed? *
6840 * Or allows for someone to change the prototype of built-in objects? *
6841 * Or gives undesired access to variables like document or window? *
6842 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
6843
6844/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
6845 *
6846 * DOM-related variables:
6847 *
6848 * - "node" - DOM Node
6849 * - "element" - DOM Element or Node
6850 * - "$node" or "$element" - jqLite-wrapped node or element
6851 *
6852 *
6853 * Compiler related stuff:
6854 *
6855 * - "linkFn" - linking fn of a single directive
6856 * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
6857 * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
6858 * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
6859 */
6860
6861
6862/**
6863 * @ngdoc service
6864 * @name $compile
6865 * @kind function
6866 *
6867 * @description
6868 * Compiles an HTML string or DOM into a template and produces a template function, which
6869 * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
6870 *
6871 * The compilation is a process of walking the DOM tree and matching DOM elements to
6872 * {@link ng.$compileProvider#directive directives}.
6873 *
6874 * <div class="alert alert-warning">
6875 * **Note:** This document is an in-depth reference of all directive options.
6876 * For a gentle introduction to directives with examples of common use cases,
6877 * see the {@link guide/directive directive guide}.
6878 * </div>
6879 *
6880 * ## Comprehensive Directive API
6881 *
6882 * There are many different options for a directive.
6883 *
6884 * The difference resides in the return value of the factory function.
6885 * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
6886 * that defines the directive properties, or just the `postLink` function (all other properties will have
6887 * the default values).
6888 *
6889 * <div class="alert alert-success">
6890 * **Best Practice:** It's recommended to use the "directive definition object" form.
6891 * </div>
6892 *
6893 * Here's an example directive declared with a Directive Definition Object:
6894 *
6895 * ```js
6896 * var myModule = angular.module(...);
6897 *
6898 * myModule.directive('directiveName', function factory(injectables) {
6899 * var directiveDefinitionObject = {
6900 * {@link $compile#-priority- priority}: 0,
6901 * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
6902 * // or
6903 * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
6904 * {@link $compile#-transclude- transclude}: false,
6905 * {@link $compile#-restrict- restrict}: 'A',
6906 * {@link $compile#-templatenamespace- templateNamespace}: 'html',
6907 * {@link $compile#-scope- scope}: false,
6908 * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
6909 * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
6910 * {@link $compile#-bindtocontroller- bindToController}: false,
6911 * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
6912 * {@link $compile#-multielement- multiElement}: false,
6913 * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
6914 * return {
6915 * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
6916 * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
6917 * }
6918 * // or
6919 * // return function postLink( ... ) { ... }
6920 * },
6921 * // or
6922 * // {@link $compile#-link- link}: {
6923 * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
6924 * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
6925 * // }
6926 * // or
6927 * // {@link $compile#-link- link}: function postLink( ... ) { ... }
6928 * };
6929 * return directiveDefinitionObject;
6930 * });
6931 * ```
6932 *
6933 * <div class="alert alert-warning">
6934 * **Note:** Any unspecified options will use the default value. You can see the default values below.
6935 * </div>
6936 *
6937 * Therefore the above can be simplified as:
6938 *
6939 * ```js
6940 * var myModule = angular.module(...);
6941 *
6942 * myModule.directive('directiveName', function factory(injectables) {
6943 * var directiveDefinitionObject = {
6944 * link: function postLink(scope, iElement, iAttrs) { ... }
6945 * };
6946 * return directiveDefinitionObject;
6947 * // or
6948 * // return function postLink(scope, iElement, iAttrs) { ... }
6949 * });
6950 * ```
6951 *
6952 * ### Life-cycle hooks
6953 * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
6954 * directive:
6955 * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
6956 * had their bindings initialized (and before the pre & post linking functions for the directives on
6957 * this element). This is a good place to put initialization code for your controller.
6958 * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
6959 * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
6960 * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
6961 * component such as cloning the bound value to prevent accidental mutation of the outer value.
6962 * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
6963 * changes. Any actions that you wish to take in response to the changes that you detect must be
6964 * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
6965 * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
6966 * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
6967 * if detecting changes, you must store the previous value(s) for comparison to the current values.
6968 * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
6969 * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
6970 * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
6971 * components will have their `$onDestroy()` hook called before child components.
6972 * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
6973 * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
6974 * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
6975 * they are waiting for their template to load asynchronously and their own compilation and linking has been
6976 * suspended until that occurs.
6977 *
6978 * #### Comparison with Angular 2 life-cycle hooks
6979 * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
6980 * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
6981 *
6982 * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
6983 * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
6984 * In Angular 2 you can only define hooks on the prototype of the Component class.
6985 * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
6986 * `ngDoCheck` in Angular 2
6987 * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
6988 * propagated throughout the application.
6989 * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
6990 * error or do nothing depending upon the state of `enableProdMode()`.
6991 *
6992 * #### Life-cycle hook examples
6993 *
6994 * This example shows how you can check for mutations to a Date object even though the identity of the object
6995 * has not changed.
6996 *
6997 * <example name="doCheckDateExample" module="do-check-module">
6998 * <file name="app.js">
6999 * angular.module('do-check-module', [])
7000 * .component('app', {
7001 * template:
7002 * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
7003 * 'Date: {{ $ctrl.date }}' +
7004 * '<test date="$ctrl.date"></test>',
7005 * controller: function() {
7006 * this.date = new Date();
7007 * this.month = this.date.getMonth();
7008 * this.updateDate = function() {
7009 * this.date.setMonth(this.month);
7010 * };
7011 * }
7012 * })
7013 * .component('test', {
7014 * bindings: { date: '<' },
7015 * template:
7016 * '<pre>{{ $ctrl.log | json }}</pre>',
7017 * controller: function() {
7018 * var previousValue;
7019 * this.log = [];
7020 * this.$doCheck = function() {
7021 * var currentValue = this.date && this.date.valueOf();
7022 * if (previousValue !== currentValue) {
7023 * this.log.push('doCheck: date mutated: ' + this.date);
7024 * previousValue = currentValue;
7025 * }
7026 * };
7027 * }
7028 * });
7029 * </file>
7030 * <file name="index.html">
7031 * <app></app>
7032 * </file>
7033 * </example>
7034 *
7035 * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
7036 * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
7037 * arrays or objects can have a negative impact on your application performance)
7038 *
7039 * <example name="doCheckArrayExample" module="do-check-module">
7040 * <file name="index.html">
7041 * <div ng-init="items = []">
7042 * <button ng-click="items.push(items.length)">Add Item</button>
7043 * <button ng-click="items = []">Reset Items</button>
7044 * <pre>{{ items }}</pre>
7045 * <test items="items"></test>
7046 * </div>
7047 * </file>
7048 * <file name="app.js">
7049 * angular.module('do-check-module', [])
7050 * .component('test', {
7051 * bindings: { items: '<' },
7052 * template:
7053 * '<pre>{{ $ctrl.log | json }}</pre>',
7054 * controller: function() {
7055 * this.log = [];
7056 *
7057 * this.$doCheck = function() {
7058 * if (this.items_ref !== this.items) {
7059 * this.log.push('doCheck: items changed');
7060 * this.items_ref = this.items;
7061 * }
7062 * if (!angular.equals(this.items_clone, this.items)) {
7063 * this.log.push('doCheck: items mutated');
7064 * this.items_clone = angular.copy(this.items);
7065 * }
7066 * };
7067 * }
7068 * });
7069 * </file>
7070 * </example>
7071 *
7072 *
7073 * ### Directive Definition Object
7074 *
7075 * The directive definition object provides instructions to the {@link ng.$compile
7076 * compiler}. The attributes are:
7077 *
7078 * #### `multiElement`
7079 * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
7080 * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
7081 * together as the directive elements. It is recommended that this feature be used on directives
7082 * which are not strictly behavioral (such as {@link ngClick}), and which
7083 * do not manipulate or replace child nodes (such as {@link ngInclude}).
7084 *
7085 * #### `priority`
7086 * When there are multiple directives defined on a single DOM element, sometimes it
7087 * is necessary to specify the order in which the directives are applied. The `priority` is used
7088 * to sort the directives before their `compile` functions get called. Priority is defined as a
7089 * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
7090 * are also run in priority order, but post-link functions are run in reverse order. The order
7091 * of directives with the same priority is undefined. The default priority is `0`.
7092 *
7093 * #### `terminal`
7094 * If set to true then the current `priority` will be the last set of directives
7095 * which will execute (any directives at the current priority will still execute
7096 * as the order of execution on same `priority` is undefined). Note that expressions
7097 * and other directives used in the directive's template will also be excluded from execution.
7098 *
7099 * #### `scope`
7100 * The scope property can be `false`, `true`, or an object:
7101 *
7102 * * **`false` (default):** No scope will be created for the directive. The directive will use its
7103 * parent's scope.
7104 *
7105 * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
7106 * the directive's element. If multiple directives on the same element request a new scope,
7107 * only one new scope is created.
7108 *
7109 * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
7110 * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
7111 * scope. This is useful when creating reusable components, which should not accidentally read or modify
7112 * data in the parent scope.
7113 *
7114 * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
7115 * directive's element. These local properties are useful for aliasing values for templates. The keys in
7116 * the object hash map to the name of the property on the isolate scope; the values define how the property
7117 * is bound to the parent scope, via matching attributes on the directive's element:
7118 *
7119 * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
7120 * always a string since DOM attributes are strings. If no `attr` name is specified then the
7121 * attribute name is assumed to be the same as the local name. Given `<my-component
7122 * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
7123 * the directive's scope property `localName` will reflect the interpolated value of `hello
7124 * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
7125 * scope. The `name` is read from the parent scope (not the directive's scope).
7126 *
7127 * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
7128 * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
7129 * If no `attr` name is specified then the attribute name is assumed to be the same as the local
7130 * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
7131 * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
7132 * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
7133 * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
7134 * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
7135 * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
7136 * will be thrown upon discovering changes to the local value, since it will be impossible to sync
7137 * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
7138 * method is used for tracking changes, and the equality check is based on object identity.
7139 * However, if an object literal or an array literal is passed as the binding expression, the
7140 * equality check is done by value (using the {@link angular.equals} function). It's also possible
7141 * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
7142 * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
7143 *
7144 * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
7145 * expression passed via the attribute `attr`. The expression is evaluated in the context of the
7146 * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
7147 * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
7148 *
7149 * For example, given `<my-component my-attr="parentModel">` and directive definition of
7150 * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
7151 * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
7152 * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
7153 * two caveats:
7154 * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
7155 * sets the same value. That means if your bound value is an object, changes to its properties
7156 * in the isolated scope will be reflected in the parent scope (because both reference the same object).
7157 * 2. one-way binding watches changes to the **identity** of the parent value. That means the
7158 * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
7159 * to the value has changed. In most cases, this should not be of concern, but can be important
7160 * to know if you one-way bind to an object, and then replace that object in the isolated scope.
7161 * If you now change a property of the object in your parent scope, the change will not be
7162 * propagated to the isolated scope, because the identity of the object on the parent scope
7163 * has not changed. Instead you must assign a new object.
7164 *
7165 * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
7166 * back to the parent. However, it does not make this completely impossible.
7167 *
7168 * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
7169 * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
7170 * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
7171 * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
7172 * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
7173 * via an expression to the parent scope. This can be done by passing a map of local variable names
7174 * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
7175 * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
7176 *
7177 * In general it's possible to apply more than one directive to one element, but there might be limitations
7178 * depending on the type of scope required by the directives. The following points will help explain these limitations.
7179 * For simplicity only two directives are taken into account, but it is also applicable for several directives:
7180 *
7181 * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
7182 * * **child scope** + **no scope** => Both directives will share one single child scope
7183 * * **child scope** + **child scope** => Both directives will share one single child scope
7184 * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
7185 * its parent's scope
7186 * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
7187 * be applied to the same element.
7188 * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
7189 * cannot be applied to the same element.
7190 *
7191 *
7192 * #### `bindToController`
7193 * This property is used to bind scope properties directly to the controller. It can be either
7194 * `true` or an object hash with the same format as the `scope` property.
7195 *
7196 * When an isolate scope is used for a directive (see above), `bindToController: true` will
7197 * allow a component to have its properties bound to the controller, rather than to scope.
7198 *
7199 * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
7200 * properties. You can access these bindings once they have been initialized by providing a controller method called
7201 * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
7202 * initialized.
7203 *
7204 * <div class="alert alert-warning">
7205 * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
7206 * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
7207 * code that relies upon bindings inside a `$onInit` method on the controller, instead.
7208 * </div>
7209 *
7210 * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
7211 * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
7212 * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
7213 * scope (useful for component directives).
7214 *
7215 * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
7216 *
7217 *
7218 * #### `controller`
7219 * Controller constructor function. The controller is instantiated before the
7220 * pre-linking phase and can be accessed by other directives (see
7221 * `require` attribute). This allows the directives to communicate with each other and augment
7222 * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
7223 *
7224 * * `$scope` - Current scope associated with the element
7225 * * `$element` - Current element
7226 * * `$attrs` - Current attributes object for the element
7227 * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
7228 * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
7229 * * `scope`: (optional) override the scope.
7230 * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
7231 * * `futureParentElement` (optional):
7232 * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
7233 * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
7234 * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
7235 * and when the `cloneLinkingFn` is passed,
7236 * as those elements need to created and cloned in a special way when they are defined outside their
7237 * usual containers (e.g. like `<svg>`).
7238 * * See also the `directive.templateNamespace` property.
7239 * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
7240 * then the default transclusion is provided.
7241 * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
7242 * `true` if the specified slot contains content (i.e. one or more DOM nodes).
7243 *
7244 * #### `require`
7245 * Require another directive and inject its controller as the fourth argument to the linking function. The
7246 * `require` property can be a string, an array or an object:
7247 * * a **string** containing the name of the directive to pass to the linking function
7248 * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
7249 * linking function will be an array of controllers in the same order as the names in the `require` property
7250 * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
7251 * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
7252 * controllers.
7253 *
7254 * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
7255 * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
7256 * have been constructed but before `$onInit` is called.
7257 * If the name of the required controller is the same as the local name (the key), the name can be
7258 * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
7259 * See the {@link $compileProvider#component} helper for an example of how this can be used.
7260 * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
7261 * raised (unless no link function is specified and the required controllers are not being bound to the directive
7262 * controller, in which case error checking is skipped). The name can be prefixed with:
7263 *
7264 * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
7265 * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
7266 * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
7267 * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
7268 * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
7269 * `null` to the `link` fn if not found.
7270 * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
7271 * `null` to the `link` fn if not found.
7272 *
7273 *
7274 * #### `controllerAs`
7275 * Identifier name for a reference to the controller in the directive's scope.
7276 * This allows the controller to be referenced from the directive template. This is especially
7277 * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
7278 * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
7279 * `controllerAs` reference might overwrite a property that already exists on the parent scope.
7280 *
7281 *
7282 * #### `restrict`
7283 * String of subset of `EACM` which restricts the directive to a specific directive
7284 * declaration style. If omitted, the defaults (elements and attributes) are used.
7285 *
7286 * * `E` - Element name (default): `<my-directive></my-directive>`
7287 * * `A` - Attribute (default): `<div my-directive="exp"></div>`
7288 * * `C` - Class: `<div class="my-directive: exp;"></div>`
7289 * * `M` - Comment: `<!-- directive: my-directive exp -->`
7290 *
7291 *
7292 * #### `templateNamespace`
7293 * String representing the document type used by the markup in the template.
7294 * AngularJS needs this information as those elements need to be created and cloned
7295 * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
7296 *
7297 * * `html` - All root nodes in the template are HTML. Root nodes may also be
7298 * top-level elements such as `<svg>` or `<math>`.
7299 * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
7300 * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
7301 *
7302 * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
7303 *
7304 * #### `template`
7305 * HTML markup that may:
7306 * * Replace the contents of the directive's element (default).
7307 * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
7308 * * Wrap the contents of the directive's element (if `transclude` is true).
7309 *
7310 * Value may be:
7311 *
7312 * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
7313 * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
7314 * function api below) and returns a string value.
7315 *
7316 *
7317 * #### `templateUrl`
7318 * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
7319 *
7320 * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
7321 * for later when the template has been resolved. In the meantime it will continue to compile and link
7322 * sibling and parent elements as though this element had not contained any directives.
7323 *
7324 * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
7325 * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
7326 * case when only one deeply nested directive has `templateUrl`.
7327 *
7328 * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
7329 *
7330 * You can specify `templateUrl` as a string representing the URL or as a function which takes two
7331 * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
7332 * a string value representing the url. In either case, the template URL is passed through {@link
7333 * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
7334 *
7335 *
7336 * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
7337 * specify what the template should replace. Defaults to `false`.
7338 *
7339 * * `true` - the template will replace the directive's element.
7340 * * `false` - the template will replace the contents of the directive's element.
7341 *
7342 * The replacement process migrates all of the attributes / classes from the old element to the new
7343 * one. See the {@link guide/directive#template-expanding-directive
7344 * Directives Guide} for an example.
7345 *
7346 * There are very few scenarios where element replacement is required for the application function,
7347 * the main one being reusable custom components that are used within SVG contexts
7348 * (because SVG doesn't work with custom elements in the DOM tree).
7349 *
7350 * #### `transclude`
7351 * Extract the contents of the element where the directive appears and make it available to the directive.
7352 * The contents are compiled and provided to the directive as a **transclusion function**. See the
7353 * {@link $compile#transclusion Transclusion} section below.
7354 *
7355 *
7356 * #### `compile`
7357 *
7358 * ```js
7359 * function compile(tElement, tAttrs, transclude) { ... }
7360 * ```
7361 *
7362 * The compile function deals with transforming the template DOM. Since most directives do not do
7363 * template transformation, it is not used often. The compile function takes the following arguments:
7364 *
7365 * * `tElement` - template element - The element where the directive has been declared. It is
7366 * safe to do template transformation on the element and child elements only.
7367 *
7368 * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
7369 * between all directive compile functions.
7370 *
7371 * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
7372 *
7373 * <div class="alert alert-warning">
7374 * **Note:** The template instance and the link instance may be different objects if the template has
7375 * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
7376 * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
7377 * should be done in a linking function rather than in a compile function.
7378 * </div>
7379
7380 * <div class="alert alert-warning">
7381 * **Note:** The compile function cannot handle directives that recursively use themselves in their
7382 * own templates or compile functions. Compiling these directives results in an infinite loop and
7383 * stack overflow errors.
7384 *
7385 * This can be avoided by manually using $compile in the postLink function to imperatively compile
7386 * a directive's template instead of relying on automatic template compilation via `template` or
7387 * `templateUrl` declaration or manual compilation inside the compile function.
7388 * </div>
7389 *
7390 * <div class="alert alert-danger">
7391 * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
7392 * e.g. does not know about the right outer scope. Please use the transclude function that is passed
7393 * to the link function instead.
7394 * </div>
7395
7396 * A compile function can have a return value which can be either a function or an object.
7397 *
7398 * * returning a (post-link) function - is equivalent to registering the linking function via the
7399 * `link` property of the config object when the compile function is empty.
7400 *
7401 * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
7402 * control when a linking function should be called during the linking phase. See info about
7403 * pre-linking and post-linking functions below.
7404 *
7405 *
7406 * #### `link`
7407 * This property is used only if the `compile` property is not defined.
7408 *
7409 * ```js
7410 * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
7411 * ```
7412 *
7413 * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
7414 * executed after the template has been cloned. This is where most of the directive logic will be
7415 * put.
7416 *
7417 * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
7418 * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
7419 *
7420 * * `iElement` - instance element - The element where the directive is to be used. It is safe to
7421 * manipulate the children of the element only in `postLink` function since the children have
7422 * already been linked.
7423 *
7424 * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
7425 * between all directive linking functions.
7426 *
7427 * * `controller` - the directive's required controller instance(s) - Instances are shared
7428 * among all directives, which allows the directives to use the controllers as a communication
7429 * channel. The exact value depends on the directive's `require` property:
7430 * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
7431 * * `string`: the controller instance
7432 * * `array`: array of controller instances
7433 *
7434 * If a required controller cannot be found, and it is optional, the instance is `null`,
7435 * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
7436 *
7437 * Note that you can also require the directive's own controller - it will be made available like
7438 * any other controller.
7439 *
7440 * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
7441 * This is the same as the `$transclude` parameter of directive controllers,
7442 * see {@link ng.$compile#-controller- the controller section for details}.
7443 * `function([scope], cloneLinkingFn, futureParentElement)`.
7444 *
7445 * #### Pre-linking function
7446 *
7447 * Executed before the child elements are linked. Not safe to do DOM transformation since the
7448 * compiler linking function will fail to locate the correct elements for linking.
7449 *
7450 * #### Post-linking function
7451 *
7452 * Executed after the child elements are linked.
7453 *
7454 * Note that child elements that contain `templateUrl` directives will not have been compiled
7455 * and linked since they are waiting for their template to load asynchronously and their own
7456 * compilation and linking has been suspended until that occurs.
7457 *
7458 * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
7459 * for their async templates to be resolved.
7460 *
7461 *
7462 * ### Transclusion
7463 *
7464 * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
7465 * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
7466 * scope from where they were taken.
7467 *
7468 * Transclusion is used (often with {@link ngTransclude}) to insert the
7469 * original contents of a directive's element into a specified place in the template of the directive.
7470 * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
7471 * content has access to the properties on the scope from which it was taken, even if the directive
7472 * has isolated scope.
7473 * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
7474 *
7475 * This makes it possible for the widget to have private state for its template, while the transcluded
7476 * content has access to its originating scope.
7477 *
7478 * <div class="alert alert-warning">
7479 * **Note:** When testing an element transclude directive you must not place the directive at the root of the
7480 * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
7481 * Testing Transclusion Directives}.
7482 * </div>
7483 *
7484 * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
7485 * directive's element, the entire element or multiple parts of the element contents:
7486 *
7487 * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
7488 * * `'element'` - transclude the whole of the directive's element including any directives on this
7489 * element that defined at a lower priority than this directive. When used, the `template`
7490 * property is ignored.
7491 * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
7492 *
7493 * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
7494 *
7495 * This object is a map where the keys are the name of the slot to fill and the value is an element selector
7496 * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
7497 * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
7498 *
7499 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
7500 *
7501 * If the element selector is prefixed with a `?` then that slot is optional.
7502 *
7503 * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
7504 * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
7505 *
7506 * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
7507 * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
7508 * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
7509 * injectable into the directive's controller.
7510 *
7511 *
7512 * #### Transclusion Functions
7513 *
7514 * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
7515 * function** to the directive's `link` function and `controller`. This transclusion function is a special
7516 * **linking function** that will return the compiled contents linked to a new transclusion scope.
7517 *
7518 * <div class="alert alert-info">
7519 * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
7520 * ngTransclude will deal with it for us.
7521 * </div>
7522 *
7523 * If you want to manually control the insertion and removal of the transcluded content in your directive
7524 * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
7525 * object that contains the compiled DOM, which is linked to the correct transclusion scope.
7526 *
7527 * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
7528 * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
7529 * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
7530 *
7531 * <div class="alert alert-info">
7532 * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
7533 * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
7534 * </div>
7535 *
7536 * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
7537 * attach function**:
7538 *
7539 * ```js
7540 * var transcludedContent, transclusionScope;
7541 *
7542 * $transclude(function(clone, scope) {
7543 * element.append(clone);
7544 * transcludedContent = clone;
7545 * transclusionScope = scope;
7546 * });
7547 * ```
7548 *
7549 * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
7550 * associated transclusion scope:
7551 *
7552 * ```js
7553 * transcludedContent.remove();
7554 * transclusionScope.$destroy();
7555 * ```
7556 *
7557 * <div class="alert alert-info">
7558 * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
7559 * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
7560 * then you are also responsible for calling `$destroy` on the transclusion scope.
7561 * </div>
7562 *
7563 * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
7564 * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
7565 * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
7566 *
7567 *
7568 * #### Transclusion Scopes
7569 *
7570 * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
7571 * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
7572 * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
7573 * was taken.
7574 *
7575 * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
7576 * like this:
7577 *
7578 * ```html
7579 * <div ng-app>
7580 * <div isolate>
7581 * <div transclusion>
7582 * </div>
7583 * </div>
7584 * </div>
7585 * ```
7586 *
7587 * The `$parent` scope hierarchy will look like this:
7588 *
7589 ```
7590 - $rootScope
7591 - isolate
7592 - transclusion
7593 ```
7594 *
7595 * but the scopes will inherit prototypically from different scopes to their `$parent`.
7596 *
7597 ```
7598 - $rootScope
7599 - transclusion
7600 - isolate
7601 ```
7602 *
7603 *
7604 * ### Attributes
7605 *
7606 * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
7607 * `link()` or `compile()` functions. It has a variety of uses.
7608 *
7609 * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
7610 * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
7611 * to the attributes.
7612 *
7613 * * *Directive inter-communication:* All directives share the same instance of the attributes
7614 * object which allows the directives to use the attributes object as inter directive
7615 * communication.
7616 *
7617 * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
7618 * allowing other directives to read the interpolated value.
7619 *
7620 * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
7621 * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
7622 * the only way to easily get the actual value because during the linking phase the interpolation
7623 * hasn't been evaluated yet and so the value is at this time set to `undefined`.
7624 *
7625 * ```js
7626 * function linkingFn(scope, elm, attrs, ctrl) {
7627 * // get the attribute value
7628 * console.log(attrs.ngModel);
7629 *
7630 * // change the attribute
7631 * attrs.$set('ngModel', 'new value');
7632 *
7633 * // observe changes to interpolated attribute
7634 * attrs.$observe('ngModel', function(value) {
7635 * console.log('ngModel has changed value to ' + value);
7636 * });
7637 * }
7638 * ```
7639 *
7640 * ## Example
7641 *
7642 * <div class="alert alert-warning">
7643 * **Note**: Typically directives are registered with `module.directive`. The example below is
7644 * to illustrate how `$compile` works.
7645 * </div>
7646 *
7647 <example module="compileExample" name="compile">
7648 <file name="index.html">
7649 <script>
7650 angular.module('compileExample', [], function($compileProvider) {
7651 // configure new 'compile' directive by passing a directive
7652 // factory function. The factory function injects the '$compile'
7653 $compileProvider.directive('compile', function($compile) {
7654 // directive factory creates a link function
7655 return function(scope, element, attrs) {
7656 scope.$watch(
7657 function(scope) {
7658 // watch the 'compile' expression for changes
7659 return scope.$eval(attrs.compile);
7660 },
7661 function(value) {
7662 // when the 'compile' expression changes
7663 // assign it into the current DOM
7664 element.html(value);
7665
7666 // compile the new DOM and link it to the current
7667 // scope.
7668 // NOTE: we only compile .childNodes so that
7669 // we don't get into infinite loop compiling ourselves
7670 $compile(element.contents())(scope);
7671 }
7672 );
7673 };
7674 });
7675 })
7676 .controller('GreeterController', ['$scope', function($scope) {
7677 $scope.name = 'Angular';
7678 $scope.html = 'Hello {{name}}';
7679 }]);
7680 </script>
7681 <div ng-controller="GreeterController">
7682 <input ng-model="name"> <br/>
7683 <textarea ng-model="html"></textarea> <br/>
7684 <div compile="html"></div>
7685 </div>
7686 </file>
7687 <file name="protractor.js" type="protractor">
7688 it('should auto compile', function() {
7689 var textarea = $('textarea');
7690 var output = $('div[compile]');
7691 // The initial state reads 'Hello Angular'.
7692 expect(output.getText()).toBe('Hello Angular');
7693 textarea.clear();
7694 textarea.sendKeys('{{name}}!');
7695 expect(output.getText()).toBe('Angular!');
7696 });
7697 </file>
7698 </example>
7699
7700 *
7701 *
7702 * @param {string|DOMElement} element Element or HTML string to compile into a template function.
7703 * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
7704 *
7705 * <div class="alert alert-danger">
7706 * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
7707 * e.g. will not use the right outer scope. Please pass the transclude function as a
7708 * `parentBoundTranscludeFn` to the link function instead.
7709 * </div>
7710 *
7711 * @param {number} maxPriority only apply directives lower than given priority (Only effects the
7712 * root element(s), not their children)
7713 * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
7714 * (a DOM element/tree) to a scope. Where:
7715 *
7716 * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
7717 * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
7718 * `template` and call the `cloneAttachFn` function allowing the caller to attach the
7719 * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
7720 * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
7721 *
7722 * * `clonedElement` - is a clone of the original `element` passed into the compiler.
7723 * * `scope` - is the current scope with which the linking function is working with.
7724 *
7725 * * `options` - An optional object hash with linking options. If `options` is provided, then the following
7726 * keys may be used to control linking behavior:
7727 *
7728 * * `parentBoundTranscludeFn` - the transclude function made available to
7729 * directives; if given, it will be passed through to the link functions of
7730 * directives found in `element` during compilation.
7731 * * `transcludeControllers` - an object hash with keys that map controller names
7732 * to a hash with the key `instance`, which maps to the controller instance;
7733 * if given, it will make the controllers available to directives on the compileNode:
7734 * ```
7735 * {
7736 * parent: {
7737 * instance: parentControllerInstance
7738 * }
7739 * }
7740 * ```
7741 * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
7742 * the cloned elements; only needed for transcludes that are allowed to contain non html
7743 * elements (e.g. SVG elements). See also the directive.controller property.
7744 *
7745 * Calling the linking function returns the element of the template. It is either the original
7746 * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
7747 *
7748 * After linking the view is not updated until after a call to $digest which typically is done by
7749 * Angular automatically.
7750 *
7751 * If you need access to the bound view, there are two ways to do it:
7752 *
7753 * - If you are not asking the linking function to clone the template, create the DOM element(s)
7754 * before you send them to the compiler and keep this reference around.
7755 * ```js
7756 * var element = $compile('<p>{{total}}</p>')(scope);
7757 * ```
7758 *
7759 * - if on the other hand, you need the element to be cloned, the view reference from the original
7760 * example would not point to the clone, but rather to the original template that was cloned. In
7761 * this case, you can access the clone via the cloneAttachFn:
7762 * ```js
7763 * var templateElement = angular.element('<p>{{total}}</p>'),
7764 * scope = ....;
7765 *
7766 * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
7767 * //attach the clone to DOM document at the right place
7768 * });
7769 *
7770 * //now we have reference to the cloned DOM via `clonedElement`
7771 * ```
7772 *
7773 *
7774 * For information on how the compiler works, see the
7775 * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
7776 *
7777 * @knownIssue
7778 *
7779 * ### Double Compilation
7780 *
7781 Double compilation occurs when an already compiled part of the DOM gets
7782 compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
7783 and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
7784 section on double compilation} for an in-depth explanation and ways to avoid it.
7785 *
7786 */
7787
7788var $compileMinErr = minErr('$compile');
7789
7790function UNINITIALIZED_VALUE() {}
7791var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
7792
7793/**
7794 * @ngdoc provider
7795 * @name $compileProvider
7796 *
7797 * @description
7798 */
7799$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
7800/** @this */
7801function $CompileProvider($provide, $$sanitizeUriProvider) {
7802 var hasDirectives = {},
7803 Suffix = 'Directive',
7804 COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
7805 CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
7806 ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
7807 REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
7808
7809 // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
7810 // The assumption is that future DOM event attribute names will begin with
7811 // 'on' and be composed of only English letters.
7812 var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
7813 var bindingCache = createMap();
7814
7815 function parseIsolateBindings(scope, directiveName, isController) {
7816 var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
7817
7818 var bindings = createMap();
7819
7820 forEach(scope, function(definition, scopeName) {
7821 if (definition in bindingCache) {
7822 bindings[scopeName] = bindingCache[definition];
7823 return;
7824 }
7825 var match = definition.match(LOCAL_REGEXP);
7826
7827 if (!match) {
7828 throw $compileMinErr('iscp',
7829 'Invalid {3} for directive \'{0}\'.' +
7830 ' Definition: {... {1}: \'{2}\' ...}',
7831 directiveName, scopeName, definition,
7832 (isController ? 'controller bindings definition' :
7833 'isolate scope definition'));
7834 }
7835
7836 bindings[scopeName] = {
7837 mode: match[1][0],
7838 collection: match[2] === '*',
7839 optional: match[3] === '?',
7840 attrName: match[4] || scopeName
7841 };
7842 if (match[4]) {
7843 bindingCache[definition] = bindings[scopeName];
7844 }
7845 });
7846
7847 return bindings;
7848 }
7849
7850 function parseDirectiveBindings(directive, directiveName) {
7851 var bindings = {
7852 isolateScope: null,
7853 bindToController: null
7854 };
7855 if (isObject(directive.scope)) {
7856 if (directive.bindToController === true) {
7857 bindings.bindToController = parseIsolateBindings(directive.scope,
7858 directiveName, true);
7859 bindings.isolateScope = {};
7860 } else {
7861 bindings.isolateScope = parseIsolateBindings(directive.scope,
7862 directiveName, false);
7863 }
7864 }
7865 if (isObject(directive.bindToController)) {
7866 bindings.bindToController =
7867 parseIsolateBindings(directive.bindToController, directiveName, true);
7868 }
7869 if (bindings.bindToController && !directive.controller) {
7870 // There is no controller
7871 throw $compileMinErr('noctrl',
7872 'Cannot bind to controller without directive \'{0}\'s controller.',
7873 directiveName);
7874 }
7875 return bindings;
7876 }
7877
7878 function assertValidDirectiveName(name) {
7879 var letter = name.charAt(0);
7880 if (!letter || letter !== lowercase(letter)) {
7881 throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
7882 }
7883 if (name !== name.trim()) {
7884 throw $compileMinErr('baddir',
7885 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
7886 name);
7887 }
7888 }
7889
7890 function getDirectiveRequire(directive) {
7891 var require = directive.require || (directive.controller && directive.name);
7892
7893 if (!isArray(require) && isObject(require)) {
7894 forEach(require, function(value, key) {
7895 var match = value.match(REQUIRE_PREFIX_REGEXP);
7896 var name = value.substring(match[0].length);
7897 if (!name) require[key] = match[0] + key;
7898 });
7899 }
7900
7901 return require;
7902 }
7903
7904 function getDirectiveRestrict(restrict, name) {
7905 if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
7906 throw $compileMinErr('badrestrict',
7907 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
7908 restrict,
7909 name);
7910 }
7911
7912 return restrict || 'EA';
7913 }
7914
7915 /**
7916 * @ngdoc method
7917 * @name $compileProvider#directive
7918 * @kind function
7919 *
7920 * @description
7921 * Register a new directive with the compiler.
7922 *
7923 * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
7924 * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
7925 * names and the values are the factories.
7926 * @param {Function|Array} directiveFactory An injectable directive factory function. See the
7927 * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
7928 * @returns {ng.$compileProvider} Self for chaining.
7929 */
7930 this.directive = function registerDirective(name, directiveFactory) {
7931 assertArg(name, 'name');
7932 assertNotHasOwnProperty(name, 'directive');
7933 if (isString(name)) {
7934 assertValidDirectiveName(name);
7935 assertArg(directiveFactory, 'directiveFactory');
7936 if (!hasDirectives.hasOwnProperty(name)) {
7937 hasDirectives[name] = [];
7938 $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
7939 function($injector, $exceptionHandler) {
7940 var directives = [];
7941 forEach(hasDirectives[name], function(directiveFactory, index) {
7942 try {
7943 var directive = $injector.invoke(directiveFactory);
7944 if (isFunction(directive)) {
7945 directive = { compile: valueFn(directive) };
7946 } else if (!directive.compile && directive.link) {
7947 directive.compile = valueFn(directive.link);
7948 }
7949 directive.priority = directive.priority || 0;
7950 directive.index = index;
7951 directive.name = directive.name || name;
7952 directive.require = getDirectiveRequire(directive);
7953 directive.restrict = getDirectiveRestrict(directive.restrict, name);
7954 directive.$$moduleName = directiveFactory.$$moduleName;
7955 directives.push(directive);
7956 } catch (e) {
7957 $exceptionHandler(e);
7958 }
7959 });
7960 return directives;
7961 }]);
7962 }
7963 hasDirectives[name].push(directiveFactory);
7964 } else {
7965 forEach(name, reverseParams(registerDirective));
7966 }
7967 return this;
7968 };
7969
7970 /**
7971 * @ngdoc method
7972 * @name $compileProvider#component
7973 * @module ng
7974 * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
7975 * @param {Object} options Component definition object (a simplified
7976 * {@link ng.$compile#directive-definition-object directive definition object}),
7977 * with the following properties (all optional):
7978 *
7979 * - `controller` – `{(string|function()=}` – controller constructor function that should be
7980 * associated with newly created scope or the name of a {@link ng.$compile#-controller-
7981 * registered controller} if passed as a string. An empty `noop` function by default.
7982 * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
7983 * If present, the controller will be published to scope under the `controllerAs` name.
7984 * If not present, this will default to be `$ctrl`.
7985 * - `template` – `{string=|function()=}` – html template as a string or a function that
7986 * returns an html template as a string which should be used as the contents of this component.
7987 * Empty string by default.
7988 *
7989 * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
7990 * the following locals:
7991 *
7992 * - `$element` - Current element
7993 * - `$attrs` - Current attributes object for the element
7994 *
7995 * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
7996 * template that should be used as the contents of this component.
7997 *
7998 * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
7999 * the following locals:
8000 *
8001 * - `$element` - Current element
8002 * - `$attrs` - Current attributes object for the element
8003 *
8004 * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
8005 * Component properties are always bound to the component controller and not to the scope.
8006 * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
8007 * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
8008 * Disabled by default.
8009 * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
8010 * this component's controller. The object keys specify the property names under which the required
8011 * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
8012 * - `$...` – additional properties to attach to the directive factory function and the controller
8013 * constructor function. (This is used by the component router to annotate)
8014 *
8015 * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
8016 * @description
8017 * Register a **component definition** with the compiler. This is a shorthand for registering a special
8018 * type of directive, which represents a self-contained UI component in your application. Such components
8019 * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
8020 *
8021 * Component definitions are very simple and do not require as much configuration as defining general
8022 * directives. Component definitions usually consist only of a template and a controller backing it.
8023 *
8024 * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
8025 * `bindToController`. They always have **isolate scope** and are restricted to elements.
8026 *
8027 * Here are a few examples of how you would usually define components:
8028 *
8029 * ```js
8030 * var myMod = angular.module(...);
8031 * myMod.component('myComp', {
8032 * template: '<div>My name is {{$ctrl.name}}</div>',
8033 * controller: function() {
8034 * this.name = 'shahar';
8035 * }
8036 * });
8037 *
8038 * myMod.component('myComp', {
8039 * template: '<div>My name is {{$ctrl.name}}</div>',
8040 * bindings: {name: '@'}
8041 * });
8042 *
8043 * myMod.component('myComp', {
8044 * templateUrl: 'views/my-comp.html',
8045 * controller: 'MyCtrl',
8046 * controllerAs: 'ctrl',
8047 * bindings: {name: '@'}
8048 * });
8049 *
8050 * ```
8051 * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
8052 *
8053 * <br />
8054 * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
8055 */
8056 this.component = function registerComponent(name, options) {
8057 var controller = options.controller || function() {};
8058
8059 function factory($injector) {
8060 function makeInjectable(fn) {
8061 if (isFunction(fn) || isArray(fn)) {
8062 return /** @this */ function(tElement, tAttrs) {
8063 return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
8064 };
8065 } else {
8066 return fn;
8067 }
8068 }
8069
8070 var template = (!options.template && !options.templateUrl ? '' : options.template);
8071 var ddo = {
8072 controller: controller,
8073 controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
8074 template: makeInjectable(template),
8075 templateUrl: makeInjectable(options.templateUrl),
8076 transclude: options.transclude,
8077 scope: {},
8078 bindToController: options.bindings || {},
8079 restrict: 'E',
8080 require: options.require
8081 };
8082
8083 // Copy annotations (starting with $) over to the DDO
8084 forEach(options, function(val, key) {
8085 if (key.charAt(0) === '$') ddo[key] = val;
8086 });
8087
8088 return ddo;
8089 }
8090
8091 // TODO(pete) remove the following `forEach` before we release 1.6.0
8092 // The component-router@0.2.0 looks for the annotations on the controller constructor
8093 // Nothing in Angular looks for annotations on the factory function but we can't remove
8094 // it from 1.5.x yet.
8095
8096 // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
8097 // These could be used by libraries such as the new component router
8098 forEach(options, function(val, key) {
8099 if (key.charAt(0) === '$') {
8100 factory[key] = val;
8101 // Don't try to copy over annotations to named controller
8102 if (isFunction(controller)) controller[key] = val;
8103 }
8104 });
8105
8106 factory.$inject = ['$injector'];
8107
8108 return this.directive(name, factory);
8109 };
8110
8111
8112 /**
8113 * @ngdoc method
8114 * @name $compileProvider#aHrefSanitizationWhitelist
8115 * @kind function
8116 *
8117 * @description
8118 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
8119 * urls during a[href] sanitization.
8120 *
8121 * The sanitization is a security measure aimed at preventing XSS attacks via html links.
8122 *
8123 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
8124 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
8125 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
8126 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
8127 *
8128 * @param {RegExp=} regexp New regexp to whitelist urls with.
8129 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
8130 * chaining otherwise.
8131 */
8132 this.aHrefSanitizationWhitelist = function(regexp) {
8133 if (isDefined(regexp)) {
8134 $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
8135 return this;
8136 } else {
8137 return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
8138 }
8139 };
8140
8141
8142 /**
8143 * @ngdoc method
8144 * @name $compileProvider#imgSrcSanitizationWhitelist
8145 * @kind function
8146 *
8147 * @description
8148 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
8149 * urls during img[src] sanitization.
8150 *
8151 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
8152 *
8153 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
8154 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
8155 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
8156 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
8157 *
8158 * @param {RegExp=} regexp New regexp to whitelist urls with.
8159 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
8160 * chaining otherwise.
8161 */
8162 this.imgSrcSanitizationWhitelist = function(regexp) {
8163 if (isDefined(regexp)) {
8164 $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
8165 return this;
8166 } else {
8167 return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
8168 }
8169 };
8170
8171 /**
8172 * @ngdoc method
8173 * @name $compileProvider#debugInfoEnabled
8174 *
8175 * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
8176 * current debugInfoEnabled state
8177 * @returns {*} current value if used as getter or itself (chaining) if used as setter
8178 *
8179 * @kind function
8180 *
8181 * @description
8182 * Call this method to enable/disable various debug runtime information in the compiler such as adding
8183 * binding information and a reference to the current scope on to DOM elements.
8184 * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
8185 * * `ng-binding` CSS class
8186 * * `$binding` data property containing an array of the binding expressions
8187 *
8188 * You may want to disable this in production for a significant performance boost. See
8189 * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
8190 *
8191 * The default value is true.
8192 */
8193 var debugInfoEnabled = true;
8194 this.debugInfoEnabled = function(enabled) {
8195 if (isDefined(enabled)) {
8196 debugInfoEnabled = enabled;
8197 return this;
8198 }
8199 return debugInfoEnabled;
8200 };
8201
8202 /**
8203 * @ngdoc method
8204 * @name $compileProvider#preAssignBindingsEnabled
8205 *
8206 * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
8207 * current preAssignBindingsEnabled state
8208 * @returns {*} current value if used as getter or itself (chaining) if used as setter
8209 *
8210 * @kind function
8211 *
8212 * @description
8213 * Call this method to enable/disable whether directive controllers are assigned bindings before
8214 * calling the controller's constructor.
8215 * If enabled (true), the compiler assigns the value of each of the bindings to the
8216 * properties of the controller object before the constructor of this object is called.
8217 *
8218 * If disabled (false), the compiler calls the constructor first before assigning bindings.
8219 *
8220 * The default value is true in Angular 1.5.x but will switch to false in Angular 1.6.x.
8221 */
8222 var preAssignBindingsEnabled = false;
8223 this.preAssignBindingsEnabled = function(enabled) {
8224 if (isDefined(enabled)) {
8225 preAssignBindingsEnabled = enabled;
8226 return this;
8227 }
8228 return preAssignBindingsEnabled;
8229 };
8230
8231
8232 var TTL = 10;
8233 /**
8234 * @ngdoc method
8235 * @name $compileProvider#onChangesTtl
8236 * @description
8237 *
8238 * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
8239 * assuming that the model is unstable.
8240 *
8241 * The current default is 10 iterations.
8242 *
8243 * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
8244 * in several iterations of calls to these hooks. However if an application needs more than the default 10
8245 * iterations to stabilize then you should investigate what is causing the model to continuously change during
8246 * the `$onChanges` hook execution.
8247 *
8248 * Increasing the TTL could have performance implications, so you should not change it without proper justification.
8249 *
8250 * @param {number} limit The number of `$onChanges` hook iterations.
8251 * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
8252 */
8253 this.onChangesTtl = function(value) {
8254 if (arguments.length) {
8255 TTL = value;
8256 return this;
8257 }
8258 return TTL;
8259 };
8260
8261 var commentDirectivesEnabledConfig = true;
8262 /**
8263 * @ngdoc method
8264 * @name $compileProvider#commentDirectivesEnabled
8265 * @description
8266 *
8267 * It indicates to the compiler
8268 * whether or not directives on comments should be compiled.
8269 * Defaults to `true`.
8270 *
8271 * Calling this function with false disables the compilation of directives
8272 * on comments for the whole application.
8273 * This results in a compilation performance gain,
8274 * as the compiler doesn't have to check comments when looking for directives.
8275 * This should however only be used if you are sure that no comment directives are used in
8276 * the application (including any 3rd party directives).
8277 *
8278 * @param {boolean} enabled `false` if the compiler may ignore directives on comments
8279 * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
8280 */
8281 this.commentDirectivesEnabled = function(value) {
8282 if (arguments.length) {
8283 commentDirectivesEnabledConfig = value;
8284 return this;
8285 }
8286 return commentDirectivesEnabledConfig;
8287 };
8288
8289
8290 var cssClassDirectivesEnabledConfig = true;
8291 /**
8292 * @ngdoc method
8293 * @name $compileProvider#cssClassDirectivesEnabled
8294 * @description
8295 *
8296 * It indicates to the compiler
8297 * whether or not directives on element classes should be compiled.
8298 * Defaults to `true`.
8299 *
8300 * Calling this function with false disables the compilation of directives
8301 * on element classes for the whole application.
8302 * This results in a compilation performance gain,
8303 * as the compiler doesn't have to check element classes when looking for directives.
8304 * This should however only be used if you are sure that no class directives are used in
8305 * the application (including any 3rd party directives).
8306 *
8307 * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
8308 * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
8309 */
8310 this.cssClassDirectivesEnabled = function(value) {
8311 if (arguments.length) {
8312 cssClassDirectivesEnabledConfig = value;
8313 return this;
8314 }
8315 return cssClassDirectivesEnabledConfig;
8316 };
8317
8318 this.$get = [
8319 '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
8320 '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
8321 function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
8322 $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
8323
8324 var SIMPLE_ATTR_NAME = /^\w/;
8325 var specialAttrHolder = window.document.createElement('div');
8326
8327
8328 var commentDirectivesEnabled = commentDirectivesEnabledConfig;
8329 var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
8330
8331
8332 var onChangesTtl = TTL;
8333 // The onChanges hooks should all be run together in a single digest
8334 // When changes occur, the call to trigger their hooks will be added to this queue
8335 var onChangesQueue;
8336
8337 // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
8338 function flushOnChangesQueue() {
8339 try {
8340 if (!(--onChangesTtl)) {
8341 // We have hit the TTL limit so reset everything
8342 onChangesQueue = undefined;
8343 throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
8344 }
8345 // We must run this hook in an apply since the $$postDigest runs outside apply
8346 $rootScope.$apply(function() {
8347 var errors = [];
8348 for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
8349 try {
8350 onChangesQueue[i]();
8351 } catch (e) {
8352 errors.push(e);
8353 }
8354 }
8355 // Reset the queue to trigger a new schedule next time there is a change
8356 onChangesQueue = undefined;
8357 if (errors.length) {
8358 throw errors;
8359 }
8360 });
8361 } finally {
8362 onChangesTtl++;
8363 }
8364 }
8365
8366
8367 function Attributes(element, attributesToCopy) {
8368 if (attributesToCopy) {
8369 var keys = Object.keys(attributesToCopy);
8370 var i, l, key;
8371
8372 for (i = 0, l = keys.length; i < l; i++) {
8373 key = keys[i];
8374 this[key] = attributesToCopy[key];
8375 }
8376 } else {
8377 this.$attr = {};
8378 }
8379
8380 this.$$element = element;
8381 }
8382
8383 Attributes.prototype = {
8384 /**
8385 * @ngdoc method
8386 * @name $compile.directive.Attributes#$normalize
8387 * @kind function
8388 *
8389 * @description
8390 * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
8391 * `data-`) to its normalized, camelCase form.
8392 *
8393 * Also there is special case for Moz prefix starting with upper case letter.
8394 *
8395 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
8396 *
8397 * @param {string} name Name to normalize
8398 */
8399 $normalize: directiveNormalize,
8400
8401
8402 /**
8403 * @ngdoc method
8404 * @name $compile.directive.Attributes#$addClass
8405 * @kind function
8406 *
8407 * @description
8408 * Adds the CSS class value specified by the classVal parameter to the element. If animations
8409 * are enabled then an animation will be triggered for the class addition.
8410 *
8411 * @param {string} classVal The className value that will be added to the element
8412 */
8413 $addClass: function(classVal) {
8414 if (classVal && classVal.length > 0) {
8415 $animate.addClass(this.$$element, classVal);
8416 }
8417 },
8418
8419 /**
8420 * @ngdoc method
8421 * @name $compile.directive.Attributes#$removeClass
8422 * @kind function
8423 *
8424 * @description
8425 * Removes the CSS class value specified by the classVal parameter from the element. If
8426 * animations are enabled then an animation will be triggered for the class removal.
8427 *
8428 * @param {string} classVal The className value that will be removed from the element
8429 */
8430 $removeClass: function(classVal) {
8431 if (classVal && classVal.length > 0) {
8432 $animate.removeClass(this.$$element, classVal);
8433 }
8434 },
8435
8436 /**
8437 * @ngdoc method
8438 * @name $compile.directive.Attributes#$updateClass
8439 * @kind function
8440 *
8441 * @description
8442 * Adds and removes the appropriate CSS class values to the element based on the difference
8443 * between the new and old CSS class values (specified as newClasses and oldClasses).
8444 *
8445 * @param {string} newClasses The current CSS className value
8446 * @param {string} oldClasses The former CSS className value
8447 */
8448 $updateClass: function(newClasses, oldClasses) {
8449 var toAdd = tokenDifference(newClasses, oldClasses);
8450 if (toAdd && toAdd.length) {
8451 $animate.addClass(this.$$element, toAdd);
8452 }
8453
8454 var toRemove = tokenDifference(oldClasses, newClasses);
8455 if (toRemove && toRemove.length) {
8456 $animate.removeClass(this.$$element, toRemove);
8457 }
8458 },
8459
8460 /**
8461 * Set a normalized attribute on the element in a way such that all directives
8462 * can share the attribute. This function properly handles boolean attributes.
8463 * @param {string} key Normalized key. (ie ngAttribute)
8464 * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
8465 * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
8466 * Defaults to true.
8467 * @param {string=} attrName Optional none normalized name. Defaults to key.
8468 */
8469 $set: function(key, value, writeAttr, attrName) {
8470 // TODO: decide whether or not to throw an error if "class"
8471 //is set through this function since it may cause $updateClass to
8472 //become unstable.
8473
8474 var node = this.$$element[0],
8475 booleanKey = getBooleanAttrName(node, key),
8476 aliasedKey = getAliasedAttrName(key),
8477 observer = key,
8478 nodeName;
8479
8480 if (booleanKey) {
8481 this.$$element.prop(key, value);
8482 attrName = booleanKey;
8483 } else if (aliasedKey) {
8484 this[aliasedKey] = value;
8485 observer = aliasedKey;
8486 }
8487
8488 this[key] = value;
8489
8490 // translate normalized key to actual key
8491 if (attrName) {
8492 this.$attr[key] = attrName;
8493 } else {
8494 attrName = this.$attr[key];
8495 if (!attrName) {
8496 this.$attr[key] = attrName = snake_case(key, '-');
8497 }
8498 }
8499
8500 nodeName = nodeName_(this.$$element);
8501
8502 if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
8503 (nodeName === 'img' && key === 'src')) {
8504 // sanitize a[href] and img[src] values
8505 this[key] = value = $$sanitizeUri(value, key === 'src');
8506 } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
8507 // sanitize img[srcset] values
8508 var result = '';
8509
8510 // first check if there are spaces because it's not the same pattern
8511 var trimmedSrcset = trim(value);
8512 // ( 999x ,| 999w ,| ,|, )
8513 var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
8514 var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
8515
8516 // split srcset into tuple of uri and descriptor except for the last item
8517 var rawUris = trimmedSrcset.split(pattern);
8518
8519 // for each tuples
8520 var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
8521 for (var i = 0; i < nbrUrisWith2parts; i++) {
8522 var innerIdx = i * 2;
8523 // sanitize the uri
8524 result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
8525 // add the descriptor
8526 result += (' ' + trim(rawUris[innerIdx + 1]));
8527 }
8528
8529 // split the last item into uri and descriptor
8530 var lastTuple = trim(rawUris[i * 2]).split(/\s/);
8531
8532 // sanitize the last uri
8533 result += $$sanitizeUri(trim(lastTuple[0]), true);
8534
8535 // and add the last descriptor if any
8536 if (lastTuple.length === 2) {
8537 result += (' ' + trim(lastTuple[1]));
8538 }
8539 this[key] = value = result;
8540 }
8541
8542 if (writeAttr !== false) {
8543 if (value === null || isUndefined(value)) {
8544 this.$$element.removeAttr(attrName);
8545 } else {
8546 if (SIMPLE_ATTR_NAME.test(attrName)) {
8547 this.$$element.attr(attrName, value);
8548 } else {
8549 setSpecialAttr(this.$$element[0], attrName, value);
8550 }
8551 }
8552 }
8553
8554 // fire observers
8555 var $$observers = this.$$observers;
8556 if ($$observers) {
8557 forEach($$observers[observer], function(fn) {
8558 try {
8559 fn(value);
8560 } catch (e) {
8561 $exceptionHandler(e);
8562 }
8563 });
8564 }
8565 },
8566
8567
8568 /**
8569 * @ngdoc method
8570 * @name $compile.directive.Attributes#$observe
8571 * @kind function
8572 *
8573 * @description
8574 * Observes an interpolated attribute.
8575 *
8576 * The observer function will be invoked once during the next `$digest` following
8577 * compilation. The observer is then invoked whenever the interpolated value
8578 * changes.
8579 *
8580 * @param {string} key Normalized key. (ie ngAttribute) .
8581 * @param {function(interpolatedValue)} fn Function that will be called whenever
8582 the interpolated value of the attribute changes.
8583 * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
8584 * guide} for more info.
8585 * @returns {function()} Returns a deregistration function for this observer.
8586 */
8587 $observe: function(key, fn) {
8588 var attrs = this,
8589 $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
8590 listeners = ($$observers[key] || ($$observers[key] = []));
8591
8592 listeners.push(fn);
8593 $rootScope.$evalAsync(function() {
8594 if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
8595 // no one registered attribute interpolation function, so lets call it manually
8596 fn(attrs[key]);
8597 }
8598 });
8599
8600 return function() {
8601 arrayRemove(listeners, fn);
8602 };
8603 }
8604 };
8605
8606 function setSpecialAttr(element, attrName, value) {
8607 // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
8608 // so we have to jump through some hoops to get such an attribute
8609 // https://github.com/angular/angular.js/pull/13318
8610 specialAttrHolder.innerHTML = '<span ' + attrName + '>';
8611 var attributes = specialAttrHolder.firstChild.attributes;
8612 var attribute = attributes[0];
8613 // We have to remove the attribute from its container element before we can add it to the destination element
8614 attributes.removeNamedItem(attribute.name);
8615 attribute.value = value;
8616 element.attributes.setNamedItem(attribute);
8617 }
8618
8619 function safeAddClass($element, className) {
8620 try {
8621 $element.addClass(className);
8622 } catch (e) {
8623 // ignore, since it means that we are trying to set class on
8624 // SVG element, where class name is read-only.
8625 }
8626 }
8627
8628
8629 var startSymbol = $interpolate.startSymbol(),
8630 endSymbol = $interpolate.endSymbol(),
8631 denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
8632 ? identity
8633 : function denormalizeTemplate(template) {
8634 return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
8635 },
8636 NG_ATTR_BINDING = /^ngAttr[A-Z]/;
8637 var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
8638
8639 compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
8640 var bindings = $element.data('$binding') || [];
8641
8642 if (isArray(binding)) {
8643 bindings = bindings.concat(binding);
8644 } else {
8645 bindings.push(binding);
8646 }
8647
8648 $element.data('$binding', bindings);
8649 } : noop;
8650
8651 compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
8652 safeAddClass($element, 'ng-binding');
8653 } : noop;
8654
8655 compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
8656 var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
8657 $element.data(dataName, scope);
8658 } : noop;
8659
8660 compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
8661 safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
8662 } : noop;
8663
8664 compile.$$createComment = function(directiveName, comment) {
8665 var content = '';
8666 if (debugInfoEnabled) {
8667 content = ' ' + (directiveName || '') + ': ';
8668 if (comment) content += comment + ' ';
8669 }
8670 return window.document.createComment(content);
8671 };
8672
8673 return compile;
8674
8675 //================================
8676
8677 function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
8678 previousCompileContext) {
8679 if (!($compileNodes instanceof jqLite)) {
8680 // jquery always rewraps, whereas we need to preserve the original selector so that we can
8681 // modify it.
8682 $compileNodes = jqLite($compileNodes);
8683 }
8684 var compositeLinkFn =
8685 compileNodes($compileNodes, transcludeFn, $compileNodes,
8686 maxPriority, ignoreDirective, previousCompileContext);
8687 compile.$$addScopeClass($compileNodes);
8688 var namespace = null;
8689 return function publicLinkFn(scope, cloneConnectFn, options) {
8690 if (!$compileNodes) {
8691 throw $compileMinErr('multilink', 'This element has already been linked.');
8692 }
8693 assertArg(scope, 'scope');
8694
8695 if (previousCompileContext && previousCompileContext.needsNewScope) {
8696 // A parent directive did a replace and a directive on this element asked
8697 // for transclusion, which caused us to lose a layer of element on which
8698 // we could hold the new transclusion scope, so we will create it manually
8699 // here.
8700 scope = scope.$parent.$new();
8701 }
8702
8703 options = options || {};
8704 var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
8705 transcludeControllers = options.transcludeControllers,
8706 futureParentElement = options.futureParentElement;
8707
8708 // When `parentBoundTranscludeFn` is passed, it is a
8709 // `controllersBoundTransclude` function (it was previously passed
8710 // as `transclude` to directive.link) so we must unwrap it to get
8711 // its `boundTranscludeFn`
8712 if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
8713 parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
8714 }
8715
8716 if (!namespace) {
8717 namespace = detectNamespaceForChildElements(futureParentElement);
8718 }
8719 var $linkNode;
8720 if (namespace !== 'html') {
8721 // When using a directive with replace:true and templateUrl the $compileNodes
8722 // (or a child element inside of them)
8723 // might change, so we need to recreate the namespace adapted compileNodes
8724 // for call to the link function.
8725 // Note: This will already clone the nodes...
8726 $linkNode = jqLite(
8727 wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
8728 );
8729 } else if (cloneConnectFn) {
8730 // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
8731 // and sometimes changes the structure of the DOM.
8732 $linkNode = JQLitePrototype.clone.call($compileNodes);
8733 } else {
8734 $linkNode = $compileNodes;
8735 }
8736
8737 if (transcludeControllers) {
8738 for (var controllerName in transcludeControllers) {
8739 $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
8740 }
8741 }
8742
8743 compile.$$addScopeInfo($linkNode, scope);
8744
8745 if (cloneConnectFn) cloneConnectFn($linkNode, scope);
8746 if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
8747
8748 if (!cloneConnectFn) {
8749 $compileNodes = compositeLinkFn = null;
8750 }
8751 return $linkNode;
8752 };
8753 }
8754
8755 function detectNamespaceForChildElements(parentElement) {
8756 // TODO: Make this detect MathML as well...
8757 var node = parentElement && parentElement[0];
8758 if (!node) {
8759 return 'html';
8760 } else {
8761 return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
8762 }
8763 }
8764
8765 /**
8766 * Compile function matches each node in nodeList against the directives. Once all directives
8767 * for a particular node are collected their compile functions are executed. The compile
8768 * functions return values - the linking functions - are combined into a composite linking
8769 * function, which is the a linking function for the node.
8770 *
8771 * @param {NodeList} nodeList an array of nodes or NodeList to compile
8772 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
8773 * scope argument is auto-generated to the new child of the transcluded parent scope.
8774 * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
8775 * the rootElement must be set the jqLite collection of the compile root. This is
8776 * needed so that the jqLite collection items can be replaced with widgets.
8777 * @param {number=} maxPriority Max directive priority.
8778 * @returns {Function} A composite linking function of all of the matched directives or null.
8779 */
8780 function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
8781 previousCompileContext) {
8782 var linkFns = [],
8783 // `nodeList` can be either an element's `.childNodes` (live NodeList)
8784 // or a jqLite/jQuery collection or an array
8785 notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
8786 attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
8787
8788
8789 for (var i = 0; i < nodeList.length; i++) {
8790 attrs = new Attributes();
8791
8792 // Support: IE 11 only
8793 // Workaround for #11781 and #14924
8794 if (msie === 11) {
8795 mergeConsecutiveTextNodes(nodeList, i, notLiveList);
8796 }
8797
8798 // We must always refer to `nodeList[i]` hereafter,
8799 // since the nodes can be replaced underneath us.
8800 directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
8801 ignoreDirective);
8802
8803 nodeLinkFn = (directives.length)
8804 ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
8805 null, [], [], previousCompileContext)
8806 : null;
8807
8808 if (nodeLinkFn && nodeLinkFn.scope) {
8809 compile.$$addScopeClass(attrs.$$element);
8810 }
8811
8812 childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
8813 !(childNodes = nodeList[i].childNodes) ||
8814 !childNodes.length)
8815 ? null
8816 : compileNodes(childNodes,
8817 nodeLinkFn ? (
8818 (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
8819 && nodeLinkFn.transclude) : transcludeFn);
8820
8821 if (nodeLinkFn || childLinkFn) {
8822 linkFns.push(i, nodeLinkFn, childLinkFn);
8823 linkFnFound = true;
8824 nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
8825 }
8826
8827 //use the previous context only for the first element in the virtual group
8828 previousCompileContext = null;
8829 }
8830
8831 // return a linking function if we have found anything, null otherwise
8832 return linkFnFound ? compositeLinkFn : null;
8833
8834 function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
8835 var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
8836 var stableNodeList;
8837
8838
8839 if (nodeLinkFnFound) {
8840 // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
8841 // offsets don't get screwed up
8842 var nodeListLength = nodeList.length;
8843 stableNodeList = new Array(nodeListLength);
8844
8845 // create a sparse array by only copying the elements which have a linkFn
8846 for (i = 0; i < linkFns.length; i += 3) {
8847 idx = linkFns[i];
8848 stableNodeList[idx] = nodeList[idx];
8849 }
8850 } else {
8851 stableNodeList = nodeList;
8852 }
8853
8854 for (i = 0, ii = linkFns.length; i < ii;) {
8855 node = stableNodeList[linkFns[i++]];
8856 nodeLinkFn = linkFns[i++];
8857 childLinkFn = linkFns[i++];
8858
8859 if (nodeLinkFn) {
8860 if (nodeLinkFn.scope) {
8861 childScope = scope.$new();
8862 compile.$$addScopeInfo(jqLite(node), childScope);
8863 } else {
8864 childScope = scope;
8865 }
8866
8867 if (nodeLinkFn.transcludeOnThisElement) {
8868 childBoundTranscludeFn = createBoundTranscludeFn(
8869 scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
8870
8871 } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
8872 childBoundTranscludeFn = parentBoundTranscludeFn;
8873
8874 } else if (!parentBoundTranscludeFn && transcludeFn) {
8875 childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
8876
8877 } else {
8878 childBoundTranscludeFn = null;
8879 }
8880
8881 nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
8882
8883 } else if (childLinkFn) {
8884 childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
8885 }
8886 }
8887 }
8888 }
8889
8890 function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
8891 var node = nodeList[idx];
8892 var parent = node.parentNode;
8893 var sibling;
8894
8895 if (node.nodeType !== NODE_TYPE_TEXT) {
8896 return;
8897 }
8898
8899 while (true) {
8900 sibling = parent ? node.nextSibling : nodeList[idx + 1];
8901 if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
8902 break;
8903 }
8904
8905 node.nodeValue = node.nodeValue + sibling.nodeValue;
8906
8907 if (sibling.parentNode) {
8908 sibling.parentNode.removeChild(sibling);
8909 }
8910 if (notLiveList && sibling === nodeList[idx + 1]) {
8911 nodeList.splice(idx + 1, 1);
8912 }
8913 }
8914 }
8915
8916 function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
8917 function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
8918
8919 if (!transcludedScope) {
8920 transcludedScope = scope.$new(false, containingScope);
8921 transcludedScope.$$transcluded = true;
8922 }
8923
8924 return transcludeFn(transcludedScope, cloneFn, {
8925 parentBoundTranscludeFn: previousBoundTranscludeFn,
8926 transcludeControllers: controllers,
8927 futureParentElement: futureParentElement
8928 });
8929 }
8930
8931 // We need to attach the transclusion slots onto the `boundTranscludeFn`
8932 // so that they are available inside the `controllersBoundTransclude` function
8933 var boundSlots = boundTranscludeFn.$$slots = createMap();
8934 for (var slotName in transcludeFn.$$slots) {
8935 if (transcludeFn.$$slots[slotName]) {
8936 boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
8937 } else {
8938 boundSlots[slotName] = null;
8939 }
8940 }
8941
8942 return boundTranscludeFn;
8943 }
8944
8945 /**
8946 * Looks for directives on the given node and adds them to the directive collection which is
8947 * sorted.
8948 *
8949 * @param node Node to search.
8950 * @param directives An array to which the directives are added to. This array is sorted before
8951 * the function returns.
8952 * @param attrs The shared attrs object which is used to populate the normalized attributes.
8953 * @param {number=} maxPriority Max directive priority.
8954 */
8955 function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
8956 var nodeType = node.nodeType,
8957 attrsMap = attrs.$attr,
8958 match,
8959 nodeName,
8960 className;
8961
8962 switch (nodeType) {
8963 case NODE_TYPE_ELEMENT: /* Element */
8964
8965 nodeName = nodeName_(node);
8966
8967 // use the node name: <directive>
8968 addDirective(directives,
8969 directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
8970
8971 // iterate over the attributes
8972 for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
8973 j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
8974 var attrStartName = false;
8975 var attrEndName = false;
8976
8977 attr = nAttrs[j];
8978 name = attr.name;
8979 value = attr.value;
8980
8981 // support ngAttr attribute binding
8982 ngAttrName = directiveNormalize(name);
8983 isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
8984 if (isNgAttr) {
8985 name = name.replace(PREFIX_REGEXP, '')
8986 .substr(8).replace(/_(.)/g, function(match, letter) {
8987 return letter.toUpperCase();
8988 });
8989 }
8990
8991 var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
8992 if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
8993 attrStartName = name;
8994 attrEndName = name.substr(0, name.length - 5) + 'end';
8995 name = name.substr(0, name.length - 6);
8996 }
8997
8998 nName = directiveNormalize(name.toLowerCase());
8999 attrsMap[nName] = name;
9000 if (isNgAttr || !attrs.hasOwnProperty(nName)) {
9001 attrs[nName] = value;
9002 if (getBooleanAttrName(node, nName)) {
9003 attrs[nName] = true; // presence means true
9004 }
9005 }
9006 addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
9007 addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
9008 attrEndName);
9009 }
9010
9011 if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
9012 // Hidden input elements can have strange behaviour when navigating back to the page
9013 // This tells the browser not to try to cache and reinstate previous values
9014 node.setAttribute('autocomplete', 'off');
9015 }
9016
9017 // use class as directive
9018 if (!cssClassDirectivesEnabled) break;
9019 className = node.className;
9020 if (isObject(className)) {
9021 // Maybe SVGAnimatedString
9022 className = className.animVal;
9023 }
9024 if (isString(className) && className !== '') {
9025 while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
9026 nName = directiveNormalize(match[2]);
9027 if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
9028 attrs[nName] = trim(match[3]);
9029 }
9030 className = className.substr(match.index + match[0].length);
9031 }
9032 }
9033 break;
9034 case NODE_TYPE_TEXT: /* Text Node */
9035 addTextInterpolateDirective(directives, node.nodeValue);
9036 break;
9037 case NODE_TYPE_COMMENT: /* Comment */
9038 if (!commentDirectivesEnabled) break;
9039 collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
9040 break;
9041 }
9042
9043 directives.sort(byPriority);
9044 return directives;
9045 }
9046
9047 function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
9048 // function created because of performance, try/catch disables
9049 // the optimization of the whole function #14848
9050 try {
9051 var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
9052 if (match) {
9053 var nName = directiveNormalize(match[1]);
9054 if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
9055 attrs[nName] = trim(match[2]);
9056 }
9057 }
9058 } catch (e) {
9059 // turns out that under some circumstances IE9 throws errors when one attempts to read
9060 // comment's node value.
9061 // Just ignore it and continue. (Can't seem to reproduce in test case.)
9062 }
9063 }
9064
9065 /**
9066 * Given a node with a directive-start it collects all of the siblings until it finds
9067 * directive-end.
9068 * @param node
9069 * @param attrStart
9070 * @param attrEnd
9071 * @returns {*}
9072 */
9073 function groupScan(node, attrStart, attrEnd) {
9074 var nodes = [];
9075 var depth = 0;
9076 if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
9077 do {
9078 if (!node) {
9079 throw $compileMinErr('uterdir',
9080 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
9081 attrStart, attrEnd);
9082 }
9083 if (node.nodeType === NODE_TYPE_ELEMENT) {
9084 if (node.hasAttribute(attrStart)) depth++;
9085 if (node.hasAttribute(attrEnd)) depth--;
9086 }
9087 nodes.push(node);
9088 node = node.nextSibling;
9089 } while (depth > 0);
9090 } else {
9091 nodes.push(node);
9092 }
9093
9094 return jqLite(nodes);
9095 }
9096
9097 /**
9098 * Wrapper for linking function which converts normal linking function into a grouped
9099 * linking function.
9100 * @param linkFn
9101 * @param attrStart
9102 * @param attrEnd
9103 * @returns {Function}
9104 */
9105 function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
9106 return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
9107 element = groupScan(element[0], attrStart, attrEnd);
9108 return linkFn(scope, element, attrs, controllers, transcludeFn);
9109 };
9110 }
9111
9112 /**
9113 * A function generator that is used to support both eager and lazy compilation
9114 * linking function.
9115 * @param eager
9116 * @param $compileNodes
9117 * @param transcludeFn
9118 * @param maxPriority
9119 * @param ignoreDirective
9120 * @param previousCompileContext
9121 * @returns {Function}
9122 */
9123 function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
9124 var compiled;
9125
9126 if (eager) {
9127 return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
9128 }
9129 return /** @this */ function lazyCompilation() {
9130 if (!compiled) {
9131 compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
9132
9133 // Null out all of these references in order to make them eligible for garbage collection
9134 // since this is a potentially long lived closure
9135 $compileNodes = transcludeFn = previousCompileContext = null;
9136 }
9137 return compiled.apply(this, arguments);
9138 };
9139 }
9140
9141 /**
9142 * Once the directives have been collected, their compile functions are executed. This method
9143 * is responsible for inlining directive templates as well as terminating the application
9144 * of the directives if the terminal directive has been reached.
9145 *
9146 * @param {Array} directives Array of collected directives to execute their compile function.
9147 * this needs to be pre-sorted by priority order.
9148 * @param {Node} compileNode The raw DOM node to apply the compile functions to
9149 * @param {Object} templateAttrs The shared attribute function
9150 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
9151 * scope argument is auto-generated to the new
9152 * child of the transcluded parent scope.
9153 * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
9154 * argument has the root jqLite array so that we can replace nodes
9155 * on it.
9156 * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
9157 * compiling the transclusion.
9158 * @param {Array.<Function>} preLinkFns
9159 * @param {Array.<Function>} postLinkFns
9160 * @param {Object} previousCompileContext Context used for previous compilation of the current
9161 * node
9162 * @returns {Function} linkFn
9163 */
9164 function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
9165 jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
9166 previousCompileContext) {
9167 previousCompileContext = previousCompileContext || {};
9168
9169 var terminalPriority = -Number.MAX_VALUE,
9170 newScopeDirective = previousCompileContext.newScopeDirective,
9171 controllerDirectives = previousCompileContext.controllerDirectives,
9172 newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
9173 templateDirective = previousCompileContext.templateDirective,
9174 nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
9175 hasTranscludeDirective = false,
9176 hasTemplate = false,
9177 hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
9178 $compileNode = templateAttrs.$$element = jqLite(compileNode),
9179 directive,
9180 directiveName,
9181 $template,
9182 replaceDirective = originalReplaceDirective,
9183 childTranscludeFn = transcludeFn,
9184 linkFn,
9185 didScanForMultipleTransclusion = false,
9186 mightHaveMultipleTransclusionError = false,
9187 directiveValue;
9188
9189 // executes all directives on the current element
9190 for (var i = 0, ii = directives.length; i < ii; i++) {
9191 directive = directives[i];
9192 var attrStart = directive.$$start;
9193 var attrEnd = directive.$$end;
9194
9195 // collect multiblock sections
9196 if (attrStart) {
9197 $compileNode = groupScan(compileNode, attrStart, attrEnd);
9198 }
9199 $template = undefined;
9200
9201 if (terminalPriority > directive.priority) {
9202 break; // prevent further processing of directives
9203 }
9204
9205 directiveValue = directive.scope;
9206
9207 if (directiveValue) {
9208
9209 // skip the check for directives with async templates, we'll check the derived sync
9210 // directive when the template arrives
9211 if (!directive.templateUrl) {
9212 if (isObject(directiveValue)) {
9213 // This directive is trying to add an isolated scope.
9214 // Check that there is no scope of any kind already
9215 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
9216 directive, $compileNode);
9217 newIsolateScopeDirective = directive;
9218 } else {
9219 // This directive is trying to add a child scope.
9220 // Check that there is no isolated scope already
9221 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
9222 $compileNode);
9223 }
9224 }
9225
9226 newScopeDirective = newScopeDirective || directive;
9227 }
9228
9229 directiveName = directive.name;
9230
9231 // If we encounter a condition that can result in transclusion on the directive,
9232 // then scan ahead in the remaining directives for others that may cause a multiple
9233 // transclusion error to be thrown during the compilation process. If a matching directive
9234 // is found, then we know that when we encounter a transcluded directive, we need to eagerly
9235 // compile the `transclude` function rather than doing it lazily in order to throw
9236 // exceptions at the correct time
9237 if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
9238 || (directive.transclude && !directive.$$tlb))) {
9239 var candidateDirective;
9240
9241 for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
9242 if ((candidateDirective.transclude && !candidateDirective.$$tlb)
9243 || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
9244 mightHaveMultipleTransclusionError = true;
9245 break;
9246 }
9247 }
9248
9249 didScanForMultipleTransclusion = true;
9250 }
9251
9252 if (!directive.templateUrl && directive.controller) {
9253 controllerDirectives = controllerDirectives || createMap();
9254 assertNoDuplicate('\'' + directiveName + '\' controller',
9255 controllerDirectives[directiveName], directive, $compileNode);
9256 controllerDirectives[directiveName] = directive;
9257 }
9258
9259 directiveValue = directive.transclude;
9260
9261 if (directiveValue) {
9262 hasTranscludeDirective = true;
9263
9264 // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
9265 // This option should only be used by directives that know how to safely handle element transclusion,
9266 // where the transcluded nodes are added or replaced after linking.
9267 if (!directive.$$tlb) {
9268 assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
9269 nonTlbTranscludeDirective = directive;
9270 }
9271
9272 if (directiveValue === 'element') {
9273 hasElementTranscludeDirective = true;
9274 terminalPriority = directive.priority;
9275 $template = $compileNode;
9276 $compileNode = templateAttrs.$$element =
9277 jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
9278 compileNode = $compileNode[0];
9279 replaceWith(jqCollection, sliceArgs($template), compileNode);
9280
9281 // Support: Chrome < 50
9282 // https://github.com/angular/angular.js/issues/14041
9283
9284 // In the versions of V8 prior to Chrome 50, the document fragment that is created
9285 // in the `replaceWith` function is improperly garbage collected despite still
9286 // being referenced by the `parentNode` property of all of the child nodes. By adding
9287 // a reference to the fragment via a different property, we can avoid that incorrect
9288 // behavior.
9289 // TODO: remove this line after Chrome 50 has been released
9290 $template[0].$$parentNode = $template[0].parentNode;
9291
9292 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
9293 replaceDirective && replaceDirective.name, {
9294 // Don't pass in:
9295 // - controllerDirectives - otherwise we'll create duplicates controllers
9296 // - newIsolateScopeDirective or templateDirective - combining templates with
9297 // element transclusion doesn't make sense.
9298 //
9299 // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
9300 // on the same element more than once.
9301 nonTlbTranscludeDirective: nonTlbTranscludeDirective
9302 });
9303 } else {
9304
9305 var slots = createMap();
9306
9307 if (!isObject(directiveValue)) {
9308 $template = jqLite(jqLiteClone(compileNode)).contents();
9309 } else {
9310
9311 // We have transclusion slots,
9312 // collect them up, compile them and store their transclusion functions
9313 $template = [];
9314
9315 var slotMap = createMap();
9316 var filledSlots = createMap();
9317
9318 // Parse the element selectors
9319 forEach(directiveValue, function(elementSelector, slotName) {
9320 // If an element selector starts with a ? then it is optional
9321 var optional = (elementSelector.charAt(0) === '?');
9322 elementSelector = optional ? elementSelector.substring(1) : elementSelector;
9323
9324 slotMap[elementSelector] = slotName;
9325
9326 // We explicitly assign `null` since this implies that a slot was defined but not filled.
9327 // Later when calling boundTransclusion functions with a slot name we only error if the
9328 // slot is `undefined`
9329 slots[slotName] = null;
9330
9331 // filledSlots contains `true` for all slots that are either optional or have been
9332 // filled. This is used to check that we have not missed any required slots
9333 filledSlots[slotName] = optional;
9334 });
9335
9336 // Add the matching elements into their slot
9337 forEach($compileNode.contents(), function(node) {
9338 var slotName = slotMap[directiveNormalize(nodeName_(node))];
9339 if (slotName) {
9340 filledSlots[slotName] = true;
9341 slots[slotName] = slots[slotName] || [];
9342 slots[slotName].push(node);
9343 } else {
9344 $template.push(node);
9345 }
9346 });
9347
9348 // Check for required slots that were not filled
9349 forEach(filledSlots, function(filled, slotName) {
9350 if (!filled) {
9351 throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
9352 }
9353 });
9354
9355 for (var slotName in slots) {
9356 if (slots[slotName]) {
9357 // Only define a transclusion function if the slot was filled
9358 slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
9359 }
9360 }
9361 }
9362
9363 $compileNode.empty(); // clear contents
9364 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
9365 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
9366 childTranscludeFn.$$slots = slots;
9367 }
9368 }
9369
9370 if (directive.template) {
9371 hasTemplate = true;
9372 assertNoDuplicate('template', templateDirective, directive, $compileNode);
9373 templateDirective = directive;
9374
9375 directiveValue = (isFunction(directive.template))
9376 ? directive.template($compileNode, templateAttrs)
9377 : directive.template;
9378
9379 directiveValue = denormalizeTemplate(directiveValue);
9380
9381 if (directive.replace) {
9382 replaceDirective = directive;
9383 if (jqLiteIsTextNode(directiveValue)) {
9384 $template = [];
9385 } else {
9386 $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
9387 }
9388 compileNode = $template[0];
9389
9390 if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
9391 throw $compileMinErr('tplrt',
9392 'Template for directive \'{0}\' must have exactly one root element. {1}',
9393 directiveName, '');
9394 }
9395
9396 replaceWith(jqCollection, $compileNode, compileNode);
9397
9398 var newTemplateAttrs = {$attr: {}};
9399
9400 // combine directives from the original node and from the template:
9401 // - take the array of directives for this element
9402 // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
9403 // - collect directives from the template and sort them by priority
9404 // - combine directives as: processed + template + unprocessed
9405 var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
9406 var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
9407
9408 if (newIsolateScopeDirective || newScopeDirective) {
9409 // The original directive caused the current element to be replaced but this element
9410 // also needs to have a new scope, so we need to tell the template directives
9411 // that they would need to get their scope from further up, if they require transclusion
9412 markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
9413 }
9414 directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
9415 mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
9416
9417 ii = directives.length;
9418 } else {
9419 $compileNode.html(directiveValue);
9420 }
9421 }
9422
9423 if (directive.templateUrl) {
9424 hasTemplate = true;
9425 assertNoDuplicate('template', templateDirective, directive, $compileNode);
9426 templateDirective = directive;
9427
9428 if (directive.replace) {
9429 replaceDirective = directive;
9430 }
9431
9432 // eslint-disable-next-line no-func-assign
9433 nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
9434 templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
9435 controllerDirectives: controllerDirectives,
9436 newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
9437 newIsolateScopeDirective: newIsolateScopeDirective,
9438 templateDirective: templateDirective,
9439 nonTlbTranscludeDirective: nonTlbTranscludeDirective
9440 });
9441 ii = directives.length;
9442 } else if (directive.compile) {
9443 try {
9444 linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
9445 var context = directive.$$originalDirective || directive;
9446 if (isFunction(linkFn)) {
9447 addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
9448 } else if (linkFn) {
9449 addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
9450 }
9451 } catch (e) {
9452 $exceptionHandler(e, startingTag($compileNode));
9453 }
9454 }
9455
9456 if (directive.terminal) {
9457 nodeLinkFn.terminal = true;
9458 terminalPriority = Math.max(terminalPriority, directive.priority);
9459 }
9460
9461 }
9462
9463 nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
9464 nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
9465 nodeLinkFn.templateOnThisElement = hasTemplate;
9466 nodeLinkFn.transclude = childTranscludeFn;
9467
9468 previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
9469
9470 // might be normal or delayed nodeLinkFn depending on if templateUrl is present
9471 return nodeLinkFn;
9472
9473 ////////////////////
9474
9475 function addLinkFns(pre, post, attrStart, attrEnd) {
9476 if (pre) {
9477 if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
9478 pre.require = directive.require;
9479 pre.directiveName = directiveName;
9480 if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
9481 pre = cloneAndAnnotateFn(pre, {isolateScope: true});
9482 }
9483 preLinkFns.push(pre);
9484 }
9485 if (post) {
9486 if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
9487 post.require = directive.require;
9488 post.directiveName = directiveName;
9489 if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
9490 post = cloneAndAnnotateFn(post, {isolateScope: true});
9491 }
9492 postLinkFns.push(post);
9493 }
9494 }
9495
9496 function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
9497 var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
9498 attrs, scopeBindingInfo;
9499
9500 if (compileNode === linkNode) {
9501 attrs = templateAttrs;
9502 $element = templateAttrs.$$element;
9503 } else {
9504 $element = jqLite(linkNode);
9505 attrs = new Attributes($element, templateAttrs);
9506 }
9507
9508 controllerScope = scope;
9509 if (newIsolateScopeDirective) {
9510 isolateScope = scope.$new(true);
9511 } else if (newScopeDirective) {
9512 controllerScope = scope.$parent;
9513 }
9514
9515 if (boundTranscludeFn) {
9516 // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
9517 // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
9518 transcludeFn = controllersBoundTransclude;
9519 transcludeFn.$$boundTransclude = boundTranscludeFn;
9520 // expose the slots on the `$transclude` function
9521 transcludeFn.isSlotFilled = function(slotName) {
9522 return !!boundTranscludeFn.$$slots[slotName];
9523 };
9524 }
9525
9526 if (controllerDirectives) {
9527 elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
9528 }
9529
9530 if (newIsolateScopeDirective) {
9531 // Initialize isolate scope bindings for new isolate scope directive.
9532 compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
9533 templateDirective === newIsolateScopeDirective.$$originalDirective)));
9534 compile.$$addScopeClass($element, true);
9535 isolateScope.$$isolateBindings =
9536 newIsolateScopeDirective.$$isolateBindings;
9537 scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
9538 isolateScope.$$isolateBindings,
9539 newIsolateScopeDirective);
9540 if (scopeBindingInfo.removeWatches) {
9541 isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
9542 }
9543 }
9544
9545 // Initialize bindToController bindings
9546 for (var name in elementControllers) {
9547 var controllerDirective = controllerDirectives[name];
9548 var controller = elementControllers[name];
9549 var bindings = controllerDirective.$$bindings.bindToController;
9550
9551 if (preAssignBindingsEnabled) {
9552 if (bindings) {
9553 controller.bindingInfo =
9554 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
9555 } else {
9556 controller.bindingInfo = {};
9557 }
9558
9559 var controllerResult = controller();
9560 if (controllerResult !== controller.instance) {
9561 // If the controller constructor has a return value, overwrite the instance
9562 // from setupControllers
9563 controller.instance = controllerResult;
9564 $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
9565 if (controller.bindingInfo.removeWatches) {
9566 controller.bindingInfo.removeWatches();
9567 }
9568 controller.bindingInfo =
9569 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
9570 }
9571 } else {
9572 controller.instance = controller();
9573 $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
9574 controller.bindingInfo =
9575 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
9576 }
9577 }
9578
9579 // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
9580 forEach(controllerDirectives, function(controllerDirective, name) {
9581 var require = controllerDirective.require;
9582 if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
9583 extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
9584 }
9585 });
9586
9587 // Handle the init and destroy lifecycle hooks on all controllers that have them
9588 forEach(elementControllers, function(controller) {
9589 var controllerInstance = controller.instance;
9590 if (isFunction(controllerInstance.$onChanges)) {
9591 try {
9592 controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
9593 } catch (e) {
9594 $exceptionHandler(e);
9595 }
9596 }
9597 if (isFunction(controllerInstance.$onInit)) {
9598 try {
9599 controllerInstance.$onInit();
9600 } catch (e) {
9601 $exceptionHandler(e);
9602 }
9603 }
9604 if (isFunction(controllerInstance.$doCheck)) {
9605 controllerScope.$watch(function() { controllerInstance.$doCheck(); });
9606 controllerInstance.$doCheck();
9607 }
9608 if (isFunction(controllerInstance.$onDestroy)) {
9609 controllerScope.$on('$destroy', function callOnDestroyHook() {
9610 controllerInstance.$onDestroy();
9611 });
9612 }
9613 });
9614
9615 // PRELINKING
9616 for (i = 0, ii = preLinkFns.length; i < ii; i++) {
9617 linkFn = preLinkFns[i];
9618 invokeLinkFn(linkFn,
9619 linkFn.isolateScope ? isolateScope : scope,
9620 $element,
9621 attrs,
9622 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
9623 transcludeFn
9624 );
9625 }
9626
9627 // RECURSION
9628 // We only pass the isolate scope, if the isolate directive has a template,
9629 // otherwise the child elements do not belong to the isolate directive.
9630 var scopeToChild = scope;
9631 if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
9632 scopeToChild = isolateScope;
9633 }
9634 if (childLinkFn) {
9635 childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
9636 }
9637
9638 // POSTLINKING
9639 for (i = postLinkFns.length - 1; i >= 0; i--) {
9640 linkFn = postLinkFns[i];
9641 invokeLinkFn(linkFn,
9642 linkFn.isolateScope ? isolateScope : scope,
9643 $element,
9644 attrs,
9645 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
9646 transcludeFn
9647 );
9648 }
9649
9650 // Trigger $postLink lifecycle hooks
9651 forEach(elementControllers, function(controller) {
9652 var controllerInstance = controller.instance;
9653 if (isFunction(controllerInstance.$postLink)) {
9654 controllerInstance.$postLink();
9655 }
9656 });
9657
9658 // This is the function that is injected as `$transclude`.
9659 // Note: all arguments are optional!
9660 function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
9661 var transcludeControllers;
9662 // No scope passed in:
9663 if (!isScope(scope)) {
9664 slotName = futureParentElement;
9665 futureParentElement = cloneAttachFn;
9666 cloneAttachFn = scope;
9667 scope = undefined;
9668 }
9669
9670 if (hasElementTranscludeDirective) {
9671 transcludeControllers = elementControllers;
9672 }
9673 if (!futureParentElement) {
9674 futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
9675 }
9676 if (slotName) {
9677 // slotTranscludeFn can be one of three things:
9678 // * a transclude function - a filled slot
9679 // * `null` - an optional slot that was not filled
9680 // * `undefined` - a slot that was not declared (i.e. invalid)
9681 var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
9682 if (slotTranscludeFn) {
9683 return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
9684 } else if (isUndefined(slotTranscludeFn)) {
9685 throw $compileMinErr('noslot',
9686 'No parent directive that requires a transclusion with slot name "{0}". ' +
9687 'Element: {1}',
9688 slotName, startingTag($element));
9689 }
9690 } else {
9691 return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
9692 }
9693 }
9694 }
9695 }
9696
9697 function getControllers(directiveName, require, $element, elementControllers) {
9698 var value;
9699
9700 if (isString(require)) {
9701 var match = require.match(REQUIRE_PREFIX_REGEXP);
9702 var name = require.substring(match[0].length);
9703 var inheritType = match[1] || match[3];
9704 var optional = match[2] === '?';
9705
9706 //If only parents then start at the parent element
9707 if (inheritType === '^^') {
9708 $element = $element.parent();
9709 //Otherwise attempt getting the controller from elementControllers in case
9710 //the element is transcluded (and has no data) and to avoid .data if possible
9711 } else {
9712 value = elementControllers && elementControllers[name];
9713 value = value && value.instance;
9714 }
9715
9716 if (!value) {
9717 var dataName = '$' + name + 'Controller';
9718 value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
9719 }
9720
9721 if (!value && !optional) {
9722 throw $compileMinErr('ctreq',
9723 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
9724 name, directiveName);
9725 }
9726 } else if (isArray(require)) {
9727 value = [];
9728 for (var i = 0, ii = require.length; i < ii; i++) {
9729 value[i] = getControllers(directiveName, require[i], $element, elementControllers);
9730 }
9731 } else if (isObject(require)) {
9732 value = {};
9733 forEach(require, function(controller, property) {
9734 value[property] = getControllers(directiveName, controller, $element, elementControllers);
9735 });
9736 }
9737
9738 return value || null;
9739 }
9740
9741 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
9742 var elementControllers = createMap();
9743 for (var controllerKey in controllerDirectives) {
9744 var directive = controllerDirectives[controllerKey];
9745 var locals = {
9746 $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
9747 $element: $element,
9748 $attrs: attrs,
9749 $transclude: transcludeFn
9750 };
9751
9752 var controller = directive.controller;
9753 if (controller === '@') {
9754 controller = attrs[directive.name];
9755 }
9756
9757 var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
9758
9759 // For directives with element transclusion the element is a comment.
9760 // In this case .data will not attach any data.
9761 // Instead, we save the controllers for the element in a local hash and attach to .data
9762 // later, once we have the actual element.
9763 elementControllers[directive.name] = controllerInstance;
9764 $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
9765 }
9766 return elementControllers;
9767 }
9768
9769 // Depending upon the context in which a directive finds itself it might need to have a new isolated
9770 // or child scope created. For instance:
9771 // * if the directive has been pulled into a template because another directive with a higher priority
9772 // asked for element transclusion
9773 // * if the directive itself asks for transclusion but it is at the root of a template and the original
9774 // element was replaced. See https://github.com/angular/angular.js/issues/12936
9775 function markDirectiveScope(directives, isolateScope, newScope) {
9776 for (var j = 0, jj = directives.length; j < jj; j++) {
9777 directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
9778 }
9779 }
9780
9781 /**
9782 * looks up the directive and decorates it with exception handling and proper parameters. We
9783 * call this the boundDirective.
9784 *
9785 * @param {string} name name of the directive to look up.
9786 * @param {string} location The directive must be found in specific format.
9787 * String containing any of theses characters:
9788 *
9789 * * `E`: element name
9790 * * `A': attribute
9791 * * `C`: class
9792 * * `M`: comment
9793 * @returns {boolean} true if directive was added.
9794 */
9795 function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
9796 endAttrName) {
9797 if (name === ignoreDirective) return null;
9798 var match = null;
9799 if (hasDirectives.hasOwnProperty(name)) {
9800 for (var directive, directives = $injector.get(name + Suffix),
9801 i = 0, ii = directives.length; i < ii; i++) {
9802 directive = directives[i];
9803 if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
9804 directive.restrict.indexOf(location) !== -1) {
9805 if (startAttrName) {
9806 directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
9807 }
9808 if (!directive.$$bindings) {
9809 var bindings = directive.$$bindings =
9810 parseDirectiveBindings(directive, directive.name);
9811 if (isObject(bindings.isolateScope)) {
9812 directive.$$isolateBindings = bindings.isolateScope;
9813 }
9814 }
9815 tDirectives.push(directive);
9816 match = directive;
9817 }
9818 }
9819 }
9820 return match;
9821 }
9822
9823
9824 /**
9825 * looks up the directive and returns true if it is a multi-element directive,
9826 * and therefore requires DOM nodes between -start and -end markers to be grouped
9827 * together.
9828 *
9829 * @param {string} name name of the directive to look up.
9830 * @returns true if directive was registered as multi-element.
9831 */
9832 function directiveIsMultiElement(name) {
9833 if (hasDirectives.hasOwnProperty(name)) {
9834 for (var directive, directives = $injector.get(name + Suffix),
9835 i = 0, ii = directives.length; i < ii; i++) {
9836 directive = directives[i];
9837 if (directive.multiElement) {
9838 return true;
9839 }
9840 }
9841 }
9842 return false;
9843 }
9844
9845 /**
9846 * When the element is replaced with HTML template then the new attributes
9847 * on the template need to be merged with the existing attributes in the DOM.
9848 * The desired effect is to have both of the attributes present.
9849 *
9850 * @param {object} dst destination attributes (original DOM)
9851 * @param {object} src source attributes (from the directive template)
9852 */
9853 function mergeTemplateAttributes(dst, src) {
9854 var srcAttr = src.$attr,
9855 dstAttr = dst.$attr;
9856
9857 // reapply the old attributes to the new element
9858 forEach(dst, function(value, key) {
9859 if (key.charAt(0) !== '$') {
9860 if (src[key] && src[key] !== value) {
9861 if (value.length) {
9862 value += (key === 'style' ? ';' : ' ') + src[key];
9863 } else {
9864 value = src[key];
9865 }
9866 }
9867 dst.$set(key, value, true, srcAttr[key]);
9868 }
9869 });
9870
9871 // copy the new attributes on the old attrs object
9872 forEach(src, function(value, key) {
9873 // Check if we already set this attribute in the loop above.
9874 // `dst` will never contain hasOwnProperty as DOM parser won't let it.
9875 // You will get an "InvalidCharacterError: DOM Exception 5" error if you
9876 // have an attribute like "has-own-property" or "data-has-own-property", etc.
9877 if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
9878 dst[key] = value;
9879
9880 if (key !== 'class' && key !== 'style') {
9881 dstAttr[key] = srcAttr[key];
9882 }
9883 }
9884 });
9885 }
9886
9887
9888 function compileTemplateUrl(directives, $compileNode, tAttrs,
9889 $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
9890 var linkQueue = [],
9891 afterTemplateNodeLinkFn,
9892 afterTemplateChildLinkFn,
9893 beforeTemplateCompileNode = $compileNode[0],
9894 origAsyncDirective = directives.shift(),
9895 derivedSyncDirective = inherit(origAsyncDirective, {
9896 templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
9897 }),
9898 templateUrl = (isFunction(origAsyncDirective.templateUrl))
9899 ? origAsyncDirective.templateUrl($compileNode, tAttrs)
9900 : origAsyncDirective.templateUrl,
9901 templateNamespace = origAsyncDirective.templateNamespace;
9902
9903 $compileNode.empty();
9904
9905 $templateRequest(templateUrl)
9906 .then(function(content) {
9907 var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
9908
9909 content = denormalizeTemplate(content);
9910
9911 if (origAsyncDirective.replace) {
9912 if (jqLiteIsTextNode(content)) {
9913 $template = [];
9914 } else {
9915 $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
9916 }
9917 compileNode = $template[0];
9918
9919 if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
9920 throw $compileMinErr('tplrt',
9921 'Template for directive \'{0}\' must have exactly one root element. {1}',
9922 origAsyncDirective.name, templateUrl);
9923 }
9924
9925 tempTemplateAttrs = {$attr: {}};
9926 replaceWith($rootElement, $compileNode, compileNode);
9927 var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
9928
9929 if (isObject(origAsyncDirective.scope)) {
9930 // the original directive that caused the template to be loaded async required
9931 // an isolate scope
9932 markDirectiveScope(templateDirectives, true);
9933 }
9934 directives = templateDirectives.concat(directives);
9935 mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
9936 } else {
9937 compileNode = beforeTemplateCompileNode;
9938 $compileNode.html(content);
9939 }
9940
9941 directives.unshift(derivedSyncDirective);
9942
9943 afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
9944 childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
9945 previousCompileContext);
9946 forEach($rootElement, function(node, i) {
9947 if (node === compileNode) {
9948 $rootElement[i] = $compileNode[0];
9949 }
9950 });
9951 afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
9952
9953 while (linkQueue.length) {
9954 var scope = linkQueue.shift(),
9955 beforeTemplateLinkNode = linkQueue.shift(),
9956 linkRootElement = linkQueue.shift(),
9957 boundTranscludeFn = linkQueue.shift(),
9958 linkNode = $compileNode[0];
9959
9960 if (scope.$$destroyed) continue;
9961
9962 if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
9963 var oldClasses = beforeTemplateLinkNode.className;
9964
9965 if (!(previousCompileContext.hasElementTranscludeDirective &&
9966 origAsyncDirective.replace)) {
9967 // it was cloned therefore we have to clone as well.
9968 linkNode = jqLiteClone(compileNode);
9969 }
9970 replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
9971
9972 // Copy in CSS classes from original node
9973 safeAddClass(jqLite(linkNode), oldClasses);
9974 }
9975 if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
9976 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
9977 } else {
9978 childBoundTranscludeFn = boundTranscludeFn;
9979 }
9980 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
9981 childBoundTranscludeFn);
9982 }
9983 linkQueue = null;
9984 }).catch(function(error) {
9985 if (error instanceof Error) {
9986 $exceptionHandler(error);
9987 }
9988 }).catch(noop);
9989
9990 return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
9991 var childBoundTranscludeFn = boundTranscludeFn;
9992 if (scope.$$destroyed) return;
9993 if (linkQueue) {
9994 linkQueue.push(scope,
9995 node,
9996 rootElement,
9997 childBoundTranscludeFn);
9998 } else {
9999 if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
10000 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
10001 }
10002 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
10003 }
10004 };
10005 }
10006
10007
10008 /**
10009 * Sorting function for bound directives.
10010 */
10011 function byPriority(a, b) {
10012 var diff = b.priority - a.priority;
10013 if (diff !== 0) return diff;
10014 if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
10015 return a.index - b.index;
10016 }
10017
10018 function assertNoDuplicate(what, previousDirective, directive, element) {
10019
10020 function wrapModuleNameIfDefined(moduleName) {
10021 return moduleName ?
10022 (' (module: ' + moduleName + ')') :
10023 '';
10024 }
10025
10026 if (previousDirective) {
10027 throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
10028 previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
10029 directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
10030 }
10031 }
10032
10033
10034 function addTextInterpolateDirective(directives, text) {
10035 var interpolateFn = $interpolate(text, true);
10036 if (interpolateFn) {
10037 directives.push({
10038 priority: 0,
10039 compile: function textInterpolateCompileFn(templateNode) {
10040 var templateNodeParent = templateNode.parent(),
10041 hasCompileParent = !!templateNodeParent.length;
10042
10043 // When transcluding a template that has bindings in the root
10044 // we don't have a parent and thus need to add the class during linking fn.
10045 if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
10046
10047 return function textInterpolateLinkFn(scope, node) {
10048 var parent = node.parent();
10049 if (!hasCompileParent) compile.$$addBindingClass(parent);
10050 compile.$$addBindingInfo(parent, interpolateFn.expressions);
10051 scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
10052 node[0].nodeValue = value;
10053 });
10054 };
10055 }
10056 });
10057 }
10058 }
10059
10060
10061 function wrapTemplate(type, template) {
10062 type = lowercase(type || 'html');
10063 switch (type) {
10064 case 'svg':
10065 case 'math':
10066 var wrapper = window.document.createElement('div');
10067 wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
10068 return wrapper.childNodes[0].childNodes;
10069 default:
10070 return template;
10071 }
10072 }
10073
10074
10075 function getTrustedContext(node, attrNormalizedName) {
10076 if (attrNormalizedName === 'srcdoc') {
10077 return $sce.HTML;
10078 }
10079 var tag = nodeName_(node);
10080 // All tags with src attributes require a RESOURCE_URL value, except for
10081 // img and various html5 media tags.
10082 if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
10083 if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
10084 return $sce.RESOURCE_URL;
10085 }
10086 // maction[xlink:href] can source SVG. It's not limited to <maction>.
10087 } else if (attrNormalizedName === 'xlinkHref' ||
10088 (tag === 'form' && attrNormalizedName === 'action') ||
10089 // links can be stylesheets or imports, which can run script in the current origin
10090 (tag === 'link' && attrNormalizedName === 'href')
10091 ) {
10092 return $sce.RESOURCE_URL;
10093 }
10094 }
10095
10096
10097 function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
10098 var trustedContext = getTrustedContext(node, name);
10099 var mustHaveExpression = !isNgAttr;
10100 var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
10101
10102 var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
10103
10104 // no interpolation found -> ignore
10105 if (!interpolateFn) return;
10106
10107 if (name === 'multiple' && nodeName_(node) === 'select') {
10108 throw $compileMinErr('selmulti',
10109 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
10110 startingTag(node));
10111 }
10112
10113 if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
10114 throw $compileMinErr('nodomevents',
10115 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
10116 'ng- versions (such as ng-click instead of onclick) instead.');
10117 }
10118
10119 directives.push({
10120 priority: 100,
10121 compile: function() {
10122 return {
10123 pre: function attrInterpolatePreLinkFn(scope, element, attr) {
10124 var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
10125
10126 // If the attribute has changed since last $interpolate()ed
10127 var newValue = attr[name];
10128 if (newValue !== value) {
10129 // we need to interpolate again since the attribute value has been updated
10130 // (e.g. by another directive's compile function)
10131 // ensure unset/empty values make interpolateFn falsy
10132 interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
10133 value = newValue;
10134 }
10135
10136 // if attribute was updated so that there is no interpolation going on we don't want to
10137 // register any observers
10138 if (!interpolateFn) return;
10139
10140 // initialize attr object so that it's ready in case we need the value for isolate
10141 // scope initialization, otherwise the value would not be available from isolate
10142 // directive's linking fn during linking phase
10143 attr[name] = interpolateFn(scope);
10144
10145 ($$observers[name] || ($$observers[name] = [])).$$inter = true;
10146 (attr.$$observers && attr.$$observers[name].$$scope || scope).
10147 $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
10148 //special case for class attribute addition + removal
10149 //so that class changes can tap into the animation
10150 //hooks provided by the $animate service. Be sure to
10151 //skip animations when the first digest occurs (when
10152 //both the new and the old values are the same) since
10153 //the CSS classes are the non-interpolated values
10154 if (name === 'class' && newValue !== oldValue) {
10155 attr.$updateClass(newValue, oldValue);
10156 } else {
10157 attr.$set(name, newValue);
10158 }
10159 });
10160 }
10161 };
10162 }
10163 });
10164 }
10165
10166
10167 /**
10168 * This is a special jqLite.replaceWith, which can replace items which
10169 * have no parents, provided that the containing jqLite collection is provided.
10170 *
10171 * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
10172 * in the root of the tree.
10173 * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
10174 * the shell, but replace its DOM node reference.
10175 * @param {Node} newNode The new DOM node.
10176 */
10177 function replaceWith($rootElement, elementsToRemove, newNode) {
10178 var firstElementToRemove = elementsToRemove[0],
10179 removeCount = elementsToRemove.length,
10180 parent = firstElementToRemove.parentNode,
10181 i, ii;
10182
10183 if ($rootElement) {
10184 for (i = 0, ii = $rootElement.length; i < ii; i++) {
10185 if ($rootElement[i] === firstElementToRemove) {
10186 $rootElement[i++] = newNode;
10187 for (var j = i, j2 = j + removeCount - 1,
10188 jj = $rootElement.length;
10189 j < jj; j++, j2++) {
10190 if (j2 < jj) {
10191 $rootElement[j] = $rootElement[j2];
10192 } else {
10193 delete $rootElement[j];
10194 }
10195 }
10196 $rootElement.length -= removeCount - 1;
10197
10198 // If the replaced element is also the jQuery .context then replace it
10199 // .context is a deprecated jQuery api, so we should set it only when jQuery set it
10200 // http://api.jquery.com/context/
10201 if ($rootElement.context === firstElementToRemove) {
10202 $rootElement.context = newNode;
10203 }
10204 break;
10205 }
10206 }
10207 }
10208
10209 if (parent) {
10210 parent.replaceChild(newNode, firstElementToRemove);
10211 }
10212
10213 // Append all the `elementsToRemove` to a fragment. This will...
10214 // - remove them from the DOM
10215 // - allow them to still be traversed with .nextSibling
10216 // - allow a single fragment.qSA to fetch all elements being removed
10217 var fragment = window.document.createDocumentFragment();
10218 for (i = 0; i < removeCount; i++) {
10219 fragment.appendChild(elementsToRemove[i]);
10220 }
10221
10222 if (jqLite.hasData(firstElementToRemove)) {
10223 // Copy over user data (that includes Angular's $scope etc.). Don't copy private
10224 // data here because there's no public interface in jQuery to do that and copying over
10225 // event listeners (which is the main use of private data) wouldn't work anyway.
10226 jqLite.data(newNode, jqLite.data(firstElementToRemove));
10227
10228 // Remove $destroy event listeners from `firstElementToRemove`
10229 jqLite(firstElementToRemove).off('$destroy');
10230 }
10231
10232 // Cleanup any data/listeners on the elements and children.
10233 // This includes invoking the $destroy event on any elements with listeners.
10234 jqLite.cleanData(fragment.querySelectorAll('*'));
10235
10236 // Update the jqLite collection to only contain the `newNode`
10237 for (i = 1; i < removeCount; i++) {
10238 delete elementsToRemove[i];
10239 }
10240 elementsToRemove[0] = newNode;
10241 elementsToRemove.length = 1;
10242 }
10243
10244
10245 function cloneAndAnnotateFn(fn, annotation) {
10246 return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
10247 }
10248
10249
10250 function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
10251 try {
10252 linkFn(scope, $element, attrs, controllers, transcludeFn);
10253 } catch (e) {
10254 $exceptionHandler(e, startingTag($element));
10255 }
10256 }
10257
10258
10259 // Set up $watches for isolate scope and controller bindings.
10260 function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
10261 var removeWatchCollection = [];
10262 var initialChanges = {};
10263 var changes;
10264 forEach(bindings, function initializeBinding(definition, scopeName) {
10265 var attrName = definition.attrName,
10266 optional = definition.optional,
10267 mode = definition.mode, // @, =, <, or &
10268 lastValue,
10269 parentGet, parentSet, compare, removeWatch;
10270
10271 switch (mode) {
10272
10273 case '@':
10274 if (!optional && !hasOwnProperty.call(attrs, attrName)) {
10275 destination[scopeName] = attrs[attrName] = undefined;
10276 }
10277 removeWatch = attrs.$observe(attrName, function(value) {
10278 if (isString(value) || isBoolean(value)) {
10279 var oldValue = destination[scopeName];
10280 recordChanges(scopeName, value, oldValue);
10281 destination[scopeName] = value;
10282 }
10283 });
10284 attrs.$$observers[attrName].$$scope = scope;
10285 lastValue = attrs[attrName];
10286 if (isString(lastValue)) {
10287 // If the attribute has been provided then we trigger an interpolation to ensure
10288 // the value is there for use in the link fn
10289 destination[scopeName] = $interpolate(lastValue)(scope);
10290 } else if (isBoolean(lastValue)) {
10291 // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
10292 // the value to boolean rather than a string, so we special case this situation
10293 destination[scopeName] = lastValue;
10294 }
10295 initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
10296 removeWatchCollection.push(removeWatch);
10297 break;
10298
10299 case '=':
10300 if (!hasOwnProperty.call(attrs, attrName)) {
10301 if (optional) break;
10302 attrs[attrName] = undefined;
10303 }
10304 if (optional && !attrs[attrName]) break;
10305
10306 parentGet = $parse(attrs[attrName]);
10307 if (parentGet.literal) {
10308 compare = equals;
10309 } else {
10310 // eslint-disable-next-line no-self-compare
10311 compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
10312 }
10313 parentSet = parentGet.assign || function() {
10314 // reset the change, or we will throw this exception on every $digest
10315 lastValue = destination[scopeName] = parentGet(scope);
10316 throw $compileMinErr('nonassign',
10317 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
10318 attrs[attrName], attrName, directive.name);
10319 };
10320 lastValue = destination[scopeName] = parentGet(scope);
10321 var parentValueWatch = function parentValueWatch(parentValue) {
10322 if (!compare(parentValue, destination[scopeName])) {
10323 // we are out of sync and need to copy
10324 if (!compare(parentValue, lastValue)) {
10325 // parent changed and it has precedence
10326 destination[scopeName] = parentValue;
10327 } else {
10328 // if the parent can be assigned then do so
10329 parentSet(scope, parentValue = destination[scopeName]);
10330 }
10331 }
10332 lastValue = parentValue;
10333 return lastValue;
10334 };
10335 parentValueWatch.$stateful = true;
10336 if (definition.collection) {
10337 removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
10338 } else {
10339 removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
10340 }
10341 removeWatchCollection.push(removeWatch);
10342 break;
10343
10344 case '<':
10345 if (!hasOwnProperty.call(attrs, attrName)) {
10346 if (optional) break;
10347 attrs[attrName] = undefined;
10348 }
10349 if (optional && !attrs[attrName]) break;
10350
10351 parentGet = $parse(attrs[attrName]);
10352 var deepWatch = parentGet.literal;
10353
10354 var initialValue = destination[scopeName] = parentGet(scope);
10355 initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
10356
10357 removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
10358 if (oldValue === newValue) {
10359 if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
10360 return;
10361 }
10362 oldValue = initialValue;
10363 }
10364 recordChanges(scopeName, newValue, oldValue);
10365 destination[scopeName] = newValue;
10366 }, deepWatch);
10367
10368 removeWatchCollection.push(removeWatch);
10369 break;
10370
10371 case '&':
10372 // Don't assign Object.prototype method to scope
10373 parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
10374
10375 // Don't assign noop to destination if expression is not valid
10376 if (parentGet === noop && optional) break;
10377
10378 destination[scopeName] = function(locals) {
10379 return parentGet(scope, locals);
10380 };
10381 break;
10382 }
10383 });
10384
10385 function recordChanges(key, currentValue, previousValue) {
10386 if (isFunction(destination.$onChanges) && currentValue !== previousValue &&
10387 // eslint-disable-next-line no-self-compare
10388 (currentValue === currentValue || previousValue === previousValue)) {
10389 // If we have not already scheduled the top level onChangesQueue handler then do so now
10390 if (!onChangesQueue) {
10391 scope.$$postDigest(flushOnChangesQueue);
10392 onChangesQueue = [];
10393 }
10394 // If we have not already queued a trigger of onChanges for this controller then do so now
10395 if (!changes) {
10396 changes = {};
10397 onChangesQueue.push(triggerOnChangesHook);
10398 }
10399 // If the has been a change on this property already then we need to reuse the previous value
10400 if (changes[key]) {
10401 previousValue = changes[key].previousValue;
10402 }
10403 // Store this change
10404 changes[key] = new SimpleChange(previousValue, currentValue);
10405 }
10406 }
10407
10408 function triggerOnChangesHook() {
10409 destination.$onChanges(changes);
10410 // Now clear the changes so that we schedule onChanges when more changes arrive
10411 changes = undefined;
10412 }
10413
10414 return {
10415 initialChanges: initialChanges,
10416 removeWatches: removeWatchCollection.length && function removeWatches() {
10417 for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
10418 removeWatchCollection[i]();
10419 }
10420 }
10421 };
10422 }
10423 }];
10424}
10425
10426function SimpleChange(previous, current) {
10427 this.previousValue = previous;
10428 this.currentValue = current;
10429}
10430SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
10431
10432
10433var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
10434var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
10435
10436/**
10437 * Converts all accepted directives format into proper directive name.
10438 * @param name Name to normalize
10439 */
10440function directiveNormalize(name) {
10441 return name
10442 .replace(PREFIX_REGEXP, '')
10443 .replace(SPECIAL_CHARS_REGEXP, fnCamelCaseReplace);
10444}
10445
10446/**
10447 * @ngdoc type
10448 * @name $compile.directive.Attributes
10449 *
10450 * @description
10451 * A shared object between directive compile / linking functions which contains normalized DOM
10452 * element attributes. The values reflect current binding state `{{ }}`. The normalization is
10453 * needed since all of these are treated as equivalent in Angular:
10454 *
10455 * ```
10456 * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
10457 * ```
10458 */
10459
10460/**
10461 * @ngdoc property
10462 * @name $compile.directive.Attributes#$attr
10463 *
10464 * @description
10465 * A map of DOM element attribute names to the normalized name. This is
10466 * needed to do reverse lookup from normalized name back to actual name.
10467 */
10468
10469
10470/**
10471 * @ngdoc method
10472 * @name $compile.directive.Attributes#$set
10473 * @kind function
10474 *
10475 * @description
10476 * Set DOM element attribute value.
10477 *
10478 *
10479 * @param {string} name Normalized element attribute name of the property to modify. The name is
10480 * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
10481 * property to the original name.
10482 * @param {string} value Value to set the attribute to. The value can be an interpolated string.
10483 */
10484
10485
10486
10487/**
10488 * Closure compiler type information
10489 */
10490
10491function nodesetLinkingFn(
10492 /* angular.Scope */ scope,
10493 /* NodeList */ nodeList,
10494 /* Element */ rootElement,
10495 /* function(Function) */ boundTranscludeFn
10496) {}
10497
10498function directiveLinkingFn(
10499 /* nodesetLinkingFn */ nodesetLinkingFn,
10500 /* angular.Scope */ scope,
10501 /* Node */ node,
10502 /* Element */ rootElement,
10503 /* function(Function) */ boundTranscludeFn
10504) {}
10505
10506function tokenDifference(str1, str2) {
10507 var values = '',
10508 tokens1 = str1.split(/\s+/),
10509 tokens2 = str2.split(/\s+/);
10510
10511 outer:
10512 for (var i = 0; i < tokens1.length; i++) {
10513 var token = tokens1[i];
10514 for (var j = 0; j < tokens2.length; j++) {
10515 if (token === tokens2[j]) continue outer;
10516 }
10517 values += (values.length > 0 ? ' ' : '') + token;
10518 }
10519 return values;
10520}
10521
10522function removeComments(jqNodes) {
10523 jqNodes = jqLite(jqNodes);
10524 var i = jqNodes.length;
10525
10526 if (i <= 1) {
10527 return jqNodes;
10528 }
10529
10530 while (i--) {
10531 var node = jqNodes[i];
10532 if (node.nodeType === NODE_TYPE_COMMENT ||
10533 (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
10534 splice.call(jqNodes, i, 1);
10535 }
10536 }
10537 return jqNodes;
10538}
10539
10540var $controllerMinErr = minErr('$controller');
10541
10542
10543var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
10544function identifierForController(controller, ident) {
10545 if (ident && isString(ident)) return ident;
10546 if (isString(controller)) {
10547 var match = CNTRL_REG.exec(controller);
10548 if (match) return match[3];
10549 }
10550}
10551
10552
10553/**
10554 * @ngdoc provider
10555 * @name $controllerProvider
10556 * @this
10557 *
10558 * @description
10559 * The {@link ng.$controller $controller service} is used by Angular to create new
10560 * controllers.
10561 *
10562 * This provider allows controller registration via the
10563 * {@link ng.$controllerProvider#register register} method.
10564 */
10565function $ControllerProvider() {
10566 var controllers = {},
10567 globals = false;
10568
10569 /**
10570 * @ngdoc method
10571 * @name $controllerProvider#has
10572 * @param {string} name Controller name to check.
10573 */
10574 this.has = function(name) {
10575 return controllers.hasOwnProperty(name);
10576 };
10577
10578 /**
10579 * @ngdoc method
10580 * @name $controllerProvider#register
10581 * @param {string|Object} name Controller name, or an object map of controllers where the keys are
10582 * the names and the values are the constructors.
10583 * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
10584 * annotations in the array notation).
10585 */
10586 this.register = function(name, constructor) {
10587 assertNotHasOwnProperty(name, 'controller');
10588 if (isObject(name)) {
10589 extend(controllers, name);
10590 } else {
10591 controllers[name] = constructor;
10592 }
10593 };
10594
10595 /**
10596 * @ngdoc method
10597 * @name $controllerProvider#allowGlobals
10598 * @description If called, allows `$controller` to find controller constructors on `window`
10599 *
10600 * @deprecated
10601 * sinceVersion="v1.3.0"
10602 * removeVersion="v1.7.0"
10603 * This method of finding controllers has been deprecated.
10604 */
10605 this.allowGlobals = function() {
10606 globals = true;
10607 };
10608
10609
10610 this.$get = ['$injector', '$window', function($injector, $window) {
10611
10612 /**
10613 * @ngdoc service
10614 * @name $controller
10615 * @requires $injector
10616 *
10617 * @param {Function|string} constructor If called with a function then it's considered to be the
10618 * controller constructor function. Otherwise it's considered to be a string which is used
10619 * to retrieve the controller constructor using the following steps:
10620 *
10621 * * check if a controller with given name is registered via `$controllerProvider`
10622 * * check if evaluating the string on the current scope returns a constructor
10623 * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
10624 * `window` object (deprecated, not recommended)
10625 *
10626 * The string can use the `controller as property` syntax, where the controller instance is published
10627 * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
10628 * to work correctly.
10629 *
10630 * @param {Object} locals Injection locals for Controller.
10631 * @return {Object} Instance of given controller.
10632 *
10633 * @description
10634 * `$controller` service is responsible for instantiating controllers.
10635 *
10636 * It's just a simple call to {@link auto.$injector $injector}, but extracted into
10637 * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
10638 */
10639 return function $controller(expression, locals, later, ident) {
10640 // PRIVATE API:
10641 // param `later` --- indicates that the controller's constructor is invoked at a later time.
10642 // If true, $controller will allocate the object with the correct
10643 // prototype chain, but will not invoke the controller until a returned
10644 // callback is invoked.
10645 // param `ident` --- An optional label which overrides the label parsed from the controller
10646 // expression, if any.
10647 var instance, match, constructor, identifier;
10648 later = later === true;
10649 if (ident && isString(ident)) {
10650 identifier = ident;
10651 }
10652
10653 if (isString(expression)) {
10654 match = expression.match(CNTRL_REG);
10655 if (!match) {
10656 throw $controllerMinErr('ctrlfmt',
10657 'Badly formed controller string \'{0}\'. ' +
10658 'Must match `__name__ as __id__` or `__name__`.', expression);
10659 }
10660 constructor = match[1];
10661 identifier = identifier || match[3];
10662 expression = controllers.hasOwnProperty(constructor)
10663 ? controllers[constructor]
10664 : getter(locals.$scope, constructor, true) ||
10665 (globals ? getter($window, constructor, true) : undefined);
10666
10667 if (!expression) {
10668 throw $controllerMinErr('ctrlreg',
10669 'The controller with the name \'{0}\' is not registered.', constructor);
10670 }
10671
10672 assertArgFn(expression, constructor, true);
10673 }
10674
10675 if (later) {
10676 // Instantiate controller later:
10677 // This machinery is used to create an instance of the object before calling the
10678 // controller's constructor itself.
10679 //
10680 // This allows properties to be added to the controller before the constructor is
10681 // invoked. Primarily, this is used for isolate scope bindings in $compile.
10682 //
10683 // This feature is not intended for use by applications, and is thus not documented
10684 // publicly.
10685 // Object creation: http://jsperf.com/create-constructor/2
10686 var controllerPrototype = (isArray(expression) ?
10687 expression[expression.length - 1] : expression).prototype;
10688 instance = Object.create(controllerPrototype || null);
10689
10690 if (identifier) {
10691 addIdentifier(locals, identifier, instance, constructor || expression.name);
10692 }
10693
10694 return extend(function $controllerInit() {
10695 var result = $injector.invoke(expression, instance, locals, constructor);
10696 if (result !== instance && (isObject(result) || isFunction(result))) {
10697 instance = result;
10698 if (identifier) {
10699 // If result changed, re-assign controllerAs value to scope.
10700 addIdentifier(locals, identifier, instance, constructor || expression.name);
10701 }
10702 }
10703 return instance;
10704 }, {
10705 instance: instance,
10706 identifier: identifier
10707 });
10708 }
10709
10710 instance = $injector.instantiate(expression, locals, constructor);
10711
10712 if (identifier) {
10713 addIdentifier(locals, identifier, instance, constructor || expression.name);
10714 }
10715
10716 return instance;
10717 };
10718
10719 function addIdentifier(locals, identifier, instance, name) {
10720 if (!(locals && isObject(locals.$scope))) {
10721 throw minErr('$controller')('noscp',
10722 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
10723 name, identifier);
10724 }
10725
10726 locals.$scope[identifier] = instance;
10727 }
10728 }];
10729}
10730
10731/**
10732 * @ngdoc service
10733 * @name $document
10734 * @requires $window
10735 * @this
10736 *
10737 * @description
10738 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
10739 *
10740 * @example
10741 <example module="documentExample" name="document">
10742 <file name="index.html">
10743 <div ng-controller="ExampleController">
10744 <p>$document title: <b ng-bind="title"></b></p>
10745 <p>window.document title: <b ng-bind="windowTitle"></b></p>
10746 </div>
10747 </file>
10748 <file name="script.js">
10749 angular.module('documentExample', [])
10750 .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
10751 $scope.title = $document[0].title;
10752 $scope.windowTitle = angular.element(window.document)[0].title;
10753 }]);
10754 </file>
10755 </example>
10756 */
10757function $DocumentProvider() {
10758 this.$get = ['$window', function(window) {
10759 return jqLite(window.document);
10760 }];
10761}
10762
10763
10764/**
10765 * @private
10766 * @this
10767 * Listens for document visibility change and makes the current status accessible.
10768 */
10769function $$IsDocumentHiddenProvider() {
10770 this.$get = ['$document', '$rootScope', function($document, $rootScope) {
10771 var doc = $document[0];
10772 var hidden = doc && doc.hidden;
10773
10774 $document.on('visibilitychange', changeListener);
10775
10776 $rootScope.$on('$destroy', function() {
10777 $document.off('visibilitychange', changeListener);
10778 });
10779
10780 function changeListener() {
10781 hidden = doc.hidden;
10782 }
10783
10784 return function() {
10785 return hidden;
10786 };
10787 }];
10788}
10789
10790/**
10791 * @ngdoc service
10792 * @name $exceptionHandler
10793 * @requires ng.$log
10794 * @this
10795 *
10796 * @description
10797 * Any uncaught exception in angular expressions is delegated to this service.
10798 * The default implementation simply delegates to `$log.error` which logs it into
10799 * the browser console.
10800 *
10801 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
10802 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
10803 *
10804 * ## Example:
10805 *
10806 * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
10807 * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
10808 * of `$log.error()`.
10809 *
10810 * ```js
10811 * angular.
10812 * module('exceptionOverwrite', []).
10813 * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
10814 * return function myExceptionHandler(exception, cause) {
10815 * logErrorsToBackend(exception, cause);
10816 * $log.warn(exception, cause);
10817 * };
10818 * }]);
10819 * ```
10820 *
10821 * <hr />
10822 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
10823 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
10824 * (unless executed during a digest).
10825 *
10826 * If you wish, you can manually delegate exceptions, e.g.
10827 * `try { ... } catch(e) { $exceptionHandler(e); }`
10828 *
10829 * @param {Error} exception Exception associated with the error.
10830 * @param {string=} cause Optional information about the context in which
10831 * the error was thrown.
10832 *
10833 */
10834function $ExceptionHandlerProvider() {
10835 this.$get = ['$log', function($log) {
10836 return function(exception, cause) {
10837 $log.error.apply($log, arguments);
10838 };
10839 }];
10840}
10841
10842var $$ForceReflowProvider = /** @this */ function() {
10843 this.$get = ['$document', function($document) {
10844 return function(domNode) {
10845 //the line below will force the browser to perform a repaint so
10846 //that all the animated elements within the animation frame will
10847 //be properly updated and drawn on screen. This is required to
10848 //ensure that the preparation animation is properly flushed so that
10849 //the active state picks up from there. DO NOT REMOVE THIS LINE.
10850 //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
10851 //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
10852 //WILL TAKE YEARS AWAY FROM YOUR LIFE.
10853 if (domNode) {
10854 if (!domNode.nodeType && domNode instanceof jqLite) {
10855 domNode = domNode[0];
10856 }
10857 } else {
10858 domNode = $document[0].body;
10859 }
10860 return domNode.offsetWidth + 1;
10861 };
10862 }];
10863};
10864
10865var APPLICATION_JSON = 'application/json';
10866var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
10867var JSON_START = /^\[|^\{(?!\{)/;
10868var JSON_ENDS = {
10869 '[': /]$/,
10870 '{': /}$/
10871};
10872var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
10873var $httpMinErr = minErr('$http');
10874
10875function serializeValue(v) {
10876 if (isObject(v)) {
10877 return isDate(v) ? v.toISOString() : toJson(v);
10878 }
10879 return v;
10880}
10881
10882
10883/** @this */
10884function $HttpParamSerializerProvider() {
10885 /**
10886 * @ngdoc service
10887 * @name $httpParamSerializer
10888 * @description
10889 *
10890 * Default {@link $http `$http`} params serializer that converts objects to strings
10891 * according to the following rules:
10892 *
10893 * * `{'foo': 'bar'}` results in `foo=bar`
10894 * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
10895 * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
10896 * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
10897 *
10898 * Note that serializer will sort the request parameters alphabetically.
10899 * */
10900
10901 this.$get = function() {
10902 return function ngParamSerializer(params) {
10903 if (!params) return '';
10904 var parts = [];
10905 forEachSorted(params, function(value, key) {
10906 if (value === null || isUndefined(value)) return;
10907 if (isArray(value)) {
10908 forEach(value, function(v) {
10909 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
10910 });
10911 } else {
10912 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
10913 }
10914 });
10915
10916 return parts.join('&');
10917 };
10918 };
10919}
10920
10921/** @this */
10922function $HttpParamSerializerJQLikeProvider() {
10923 /**
10924 * @ngdoc service
10925 * @name $httpParamSerializerJQLike
10926 *
10927 * @description
10928 *
10929 * Alternative {@link $http `$http`} params serializer that follows
10930 * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
10931 * The serializer will also sort the params alphabetically.
10932 *
10933 * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
10934 *
10935 * ```js
10936 * $http({
10937 * url: myUrl,
10938 * method: 'GET',
10939 * params: myParams,
10940 * paramSerializer: '$httpParamSerializerJQLike'
10941 * });
10942 * ```
10943 *
10944 * It is also possible to set it as the default `paramSerializer` in the
10945 * {@link $httpProvider#defaults `$httpProvider`}.
10946 *
10947 * Additionally, you can inject the serializer and use it explicitly, for example to serialize
10948 * form data for submission:
10949 *
10950 * ```js
10951 * .controller(function($http, $httpParamSerializerJQLike) {
10952 * //...
10953 *
10954 * $http({
10955 * url: myUrl,
10956 * method: 'POST',
10957 * data: $httpParamSerializerJQLike(myData),
10958 * headers: {
10959 * 'Content-Type': 'application/x-www-form-urlencoded'
10960 * }
10961 * });
10962 *
10963 * });
10964 * ```
10965 *
10966 * */
10967 this.$get = function() {
10968 return function jQueryLikeParamSerializer(params) {
10969 if (!params) return '';
10970 var parts = [];
10971 serialize(params, '', true);
10972 return parts.join('&');
10973
10974 function serialize(toSerialize, prefix, topLevel) {
10975 if (toSerialize === null || isUndefined(toSerialize)) return;
10976 if (isArray(toSerialize)) {
10977 forEach(toSerialize, function(value, index) {
10978 serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
10979 });
10980 } else if (isObject(toSerialize) && !isDate(toSerialize)) {
10981 forEachSorted(toSerialize, function(value, key) {
10982 serialize(value, prefix +
10983 (topLevel ? '' : '[') +
10984 key +
10985 (topLevel ? '' : ']'));
10986 });
10987 } else {
10988 parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
10989 }
10990 }
10991 };
10992 };
10993}
10994
10995function defaultHttpResponseTransform(data, headers) {
10996 if (isString(data)) {
10997 // Strip json vulnerability protection prefix and trim whitespace
10998 var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
10999
11000 if (tempData) {
11001 var contentType = headers('Content-Type');
11002 if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
11003 data = fromJson(tempData);
11004 }
11005 }
11006 }
11007
11008 return data;
11009}
11010
11011function isJsonLike(str) {
11012 var jsonStart = str.match(JSON_START);
11013 return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
11014}
11015
11016/**
11017 * Parse headers into key value object
11018 *
11019 * @param {string} headers Raw headers as a string
11020 * @returns {Object} Parsed headers as key value object
11021 */
11022function parseHeaders(headers) {
11023 var parsed = createMap(), i;
11024
11025 function fillInParsed(key, val) {
11026 if (key) {
11027 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
11028 }
11029 }
11030
11031 if (isString(headers)) {
11032 forEach(headers.split('\n'), function(line) {
11033 i = line.indexOf(':');
11034 fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
11035 });
11036 } else if (isObject(headers)) {
11037 forEach(headers, function(headerVal, headerKey) {
11038 fillInParsed(lowercase(headerKey), trim(headerVal));
11039 });
11040 }
11041
11042 return parsed;
11043}
11044
11045
11046/**
11047 * Returns a function that provides access to parsed headers.
11048 *
11049 * Headers are lazy parsed when first requested.
11050 * @see parseHeaders
11051 *
11052 * @param {(string|Object)} headers Headers to provide access to.
11053 * @returns {function(string=)} Returns a getter function which if called with:
11054 *
11055 * - if called with an argument returns a single header value or null
11056 * - if called with no arguments returns an object containing all headers.
11057 */
11058function headersGetter(headers) {
11059 var headersObj;
11060
11061 return function(name) {
11062 if (!headersObj) headersObj = parseHeaders(headers);
11063
11064 if (name) {
11065 var value = headersObj[lowercase(name)];
11066 if (value === undefined) {
11067 value = null;
11068 }
11069 return value;
11070 }
11071
11072 return headersObj;
11073 };
11074}
11075
11076
11077/**
11078 * Chain all given functions
11079 *
11080 * This function is used for both request and response transforming
11081 *
11082 * @param {*} data Data to transform.
11083 * @param {function(string=)} headers HTTP headers getter fn.
11084 * @param {number} status HTTP status code of the response.
11085 * @param {(Function|Array.<Function>)} fns Function or an array of functions.
11086 * @returns {*} Transformed data.
11087 */
11088function transformData(data, headers, status, fns) {
11089 if (isFunction(fns)) {
11090 return fns(data, headers, status);
11091 }
11092
11093 forEach(fns, function(fn) {
11094 data = fn(data, headers, status);
11095 });
11096
11097 return data;
11098}
11099
11100
11101function isSuccess(status) {
11102 return 200 <= status && status < 300;
11103}
11104
11105
11106/**
11107 * @ngdoc provider
11108 * @name $httpProvider
11109 * @this
11110 *
11111 * @description
11112 * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
11113 * */
11114function $HttpProvider() {
11115 /**
11116 * @ngdoc property
11117 * @name $httpProvider#defaults
11118 * @description
11119 *
11120 * Object containing default values for all {@link ng.$http $http} requests.
11121 *
11122 * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
11123 * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
11124 * by default. See {@link $http#caching $http Caching} for more information.
11125 *
11126 * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
11127 * Defaults value is `'XSRF-TOKEN'`.
11128 *
11129 * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
11130 * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
11131 *
11132 * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
11133 * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
11134 * setting default headers.
11135 * - **`defaults.headers.common`**
11136 * - **`defaults.headers.post`**
11137 * - **`defaults.headers.put`**
11138 * - **`defaults.headers.patch`**
11139 *
11140 *
11141 * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
11142 * used to the prepare string representation of request parameters (specified as an object).
11143 * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
11144 * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
11145 *
11146 * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
11147 * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
11148 * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
11149 *
11150 **/
11151 var defaults = this.defaults = {
11152 // transform incoming response data
11153 transformResponse: [defaultHttpResponseTransform],
11154
11155 // transform outgoing request data
11156 transformRequest: [function(d) {
11157 return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
11158 }],
11159
11160 // default headers
11161 headers: {
11162 common: {
11163 'Accept': 'application/json, text/plain, */*'
11164 },
11165 post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
11166 put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
11167 patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
11168 },
11169
11170 xsrfCookieName: 'XSRF-TOKEN',
11171 xsrfHeaderName: 'X-XSRF-TOKEN',
11172
11173 paramSerializer: '$httpParamSerializer',
11174
11175 jsonpCallbackParam: 'callback'
11176 };
11177
11178 var useApplyAsync = false;
11179 /**
11180 * @ngdoc method
11181 * @name $httpProvider#useApplyAsync
11182 * @description
11183 *
11184 * Configure $http service to combine processing of multiple http responses received at around
11185 * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
11186 * significant performance improvement for bigger applications that make many HTTP requests
11187 * concurrently (common during application bootstrap).
11188 *
11189 * Defaults to false. If no value is specified, returns the current configured value.
11190 *
11191 * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
11192 * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
11193 * to load and share the same digest cycle.
11194 *
11195 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
11196 * otherwise, returns the current configured value.
11197 **/
11198 this.useApplyAsync = function(value) {
11199 if (isDefined(value)) {
11200 useApplyAsync = !!value;
11201 return this;
11202 }
11203 return useApplyAsync;
11204 };
11205
11206 /**
11207 * @ngdoc property
11208 * @name $httpProvider#interceptors
11209 * @description
11210 *
11211 * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
11212 * pre-processing of request or postprocessing of responses.
11213 *
11214 * These service factories are ordered by request, i.e. they are applied in the same order as the
11215 * array, on request, but reverse order, on response.
11216 *
11217 * {@link ng.$http#interceptors Interceptors detailed info}
11218 **/
11219 var interceptorFactories = this.interceptors = [];
11220
11221 this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
11222 function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
11223
11224 var defaultCache = $cacheFactory('$http');
11225
11226 /**
11227 * Make sure that default param serializer is exposed as a function
11228 */
11229 defaults.paramSerializer = isString(defaults.paramSerializer) ?
11230 $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
11231
11232 /**
11233 * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
11234 * The reversal is needed so that we can build up the interception chain around the
11235 * server request.
11236 */
11237 var reversedInterceptors = [];
11238
11239 forEach(interceptorFactories, function(interceptorFactory) {
11240 reversedInterceptors.unshift(isString(interceptorFactory)
11241 ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
11242 });
11243
11244 /**
11245 * @ngdoc service
11246 * @kind function
11247 * @name $http
11248 * @requires ng.$httpBackend
11249 * @requires $cacheFactory
11250 * @requires $rootScope
11251 * @requires $q
11252 * @requires $injector
11253 *
11254 * @description
11255 * The `$http` service is a core Angular service that facilitates communication with the remote
11256 * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
11257 * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
11258 *
11259 * For unit testing applications that use `$http` service, see
11260 * {@link ngMock.$httpBackend $httpBackend mock}.
11261 *
11262 * For a higher level of abstraction, please check out the {@link ngResource.$resource
11263 * $resource} service.
11264 *
11265 * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
11266 * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
11267 * it is important to familiarize yourself with these APIs and the guarantees they provide.
11268 *
11269 *
11270 * ## General usage
11271 * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
11272 * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
11273 *
11274 * ```js
11275 * // Simple GET request example:
11276 * $http({
11277 * method: 'GET',
11278 * url: '/someUrl'
11279 * }).then(function successCallback(response) {
11280 * // this callback will be called asynchronously
11281 * // when the response is available
11282 * }, function errorCallback(response) {
11283 * // called asynchronously if an error occurs
11284 * // or server returns response with an error status.
11285 * });
11286 * ```
11287 *
11288 * The response object has these properties:
11289 *
11290 * - **data** – `{string|Object}` – The response body transformed with the transform
11291 * functions.
11292 * - **status** – `{number}` – HTTP status code of the response.
11293 * - **headers** – `{function([headerName])}` – Header getter function.
11294 * - **config** – `{Object}` – The configuration object that was used to generate the request.
11295 * - **statusText** – `{string}` – HTTP status text of the response.
11296 *
11297 * A response status code between 200 and 299 is considered a success status and will result in
11298 * the success callback being called. Any response status code outside of that range is
11299 * considered an error status and will result in the error callback being called.
11300 * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
11301 * aborted, e.g. using a `config.timeout`.
11302 * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
11303 * that the outcome (success or error) will be determined by the final response status code.
11304 *
11305 *
11306 * ## Shortcut methods
11307 *
11308 * Shortcut methods are also available. All shortcut methods require passing in the URL, and
11309 * request data must be passed in for POST/PUT requests. An optional config can be passed as the
11310 * last argument.
11311 *
11312 * ```js
11313 * $http.get('/someUrl', config).then(successCallback, errorCallback);
11314 * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
11315 * ```
11316 *
11317 * Complete list of shortcut methods:
11318 *
11319 * - {@link ng.$http#get $http.get}
11320 * - {@link ng.$http#head $http.head}
11321 * - {@link ng.$http#post $http.post}
11322 * - {@link ng.$http#put $http.put}
11323 * - {@link ng.$http#delete $http.delete}
11324 * - {@link ng.$http#jsonp $http.jsonp}
11325 * - {@link ng.$http#patch $http.patch}
11326 *
11327 *
11328 * ## Writing Unit Tests that use $http
11329 * When unit testing (using {@link ngMock ngMock}), it is necessary to call
11330 * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
11331 * request using trained responses.
11332 *
11333 * ```
11334 * $httpBackend.expectGET(...);
11335 * $http.get(...);
11336 * $httpBackend.flush();
11337 * ```
11338 *
11339 * ## Setting HTTP Headers
11340 *
11341 * The $http service will automatically add certain HTTP headers to all requests. These defaults
11342 * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
11343 * object, which currently contains this default configuration:
11344 *
11345 * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
11346 * - <code>Accept: application/json, text/plain, \*/\*</code>
11347 * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
11348 * - `Content-Type: application/json`
11349 * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
11350 * - `Content-Type: application/json`
11351 *
11352 * To add or overwrite these defaults, simply add or remove a property from these configuration
11353 * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
11354 * with the lowercased HTTP method name as the key, e.g.
11355 * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
11356 *
11357 * The defaults can also be set at runtime via the `$http.defaults` object in the same
11358 * fashion. For example:
11359 *
11360 * ```
11361 * module.run(function($http) {
11362 * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
11363 * });
11364 * ```
11365 *
11366 * In addition, you can supply a `headers` property in the config object passed when
11367 * calling `$http(config)`, which overrides the defaults without changing them globally.
11368 *
11369 * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
11370 * Use the `headers` property, setting the desired header to `undefined`. For example:
11371 *
11372 * ```js
11373 * var req = {
11374 * method: 'POST',
11375 * url: 'http://example.com',
11376 * headers: {
11377 * 'Content-Type': undefined
11378 * },
11379 * data: { test: 'test' }
11380 * }
11381 *
11382 * $http(req).then(function(){...}, function(){...});
11383 * ```
11384 *
11385 * ## Transforming Requests and Responses
11386 *
11387 * Both requests and responses can be transformed using transformation functions: `transformRequest`
11388 * and `transformResponse`. These properties can be a single function that returns
11389 * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
11390 * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
11391 *
11392 * <div class="alert alert-warning">
11393 * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
11394 * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
11395 * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
11396 * function will be reflected on the scope and in any templates where the object is data-bound.
11397 * To prevent this, transform functions should have no side-effects.
11398 * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
11399 * </div>
11400 *
11401 * ### Default Transformations
11402 *
11403 * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
11404 * `defaults.transformResponse` properties. If a request does not provide its own transformations
11405 * then these will be applied.
11406 *
11407 * You can augment or replace the default transformations by modifying these properties by adding to or
11408 * replacing the array.
11409 *
11410 * Angular provides the following default transformations:
11411 *
11412 * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
11413 *
11414 * - If the `data` property of the request configuration object contains an object, serialize it
11415 * into JSON format.
11416 *
11417 * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
11418 *
11419 * - If XSRF prefix is detected, strip it (see Security Considerations section below).
11420 * - If JSON response is detected, deserialize it using a JSON parser.
11421 *
11422 *
11423 * ### Overriding the Default Transformations Per Request
11424 *
11425 * If you wish to override the request/response transformations only for a single request then provide
11426 * `transformRequest` and/or `transformResponse` properties on the configuration object passed
11427 * into `$http`.
11428 *
11429 * Note that if you provide these properties on the config object the default transformations will be
11430 * overwritten. If you wish to augment the default transformations then you must include them in your
11431 * local transformation array.
11432 *
11433 * The following code demonstrates adding a new response transformation to be run after the default response
11434 * transformations have been run.
11435 *
11436 * ```js
11437 * function appendTransform(defaults, transform) {
11438 *
11439 * // We can't guarantee that the default transformation is an array
11440 * defaults = angular.isArray(defaults) ? defaults : [defaults];
11441 *
11442 * // Append the new transformation to the defaults
11443 * return defaults.concat(transform);
11444 * }
11445 *
11446 * $http({
11447 * url: '...',
11448 * method: 'GET',
11449 * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
11450 * return doTransform(value);
11451 * })
11452 * });
11453 * ```
11454 *
11455 *
11456 * ## Caching
11457 *
11458 * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
11459 * set the config.cache value or the default cache value to TRUE or to a cache object (created
11460 * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
11461 * precedence over the default cache value.
11462 *
11463 * In order to:
11464 * * cache all responses - set the default cache value to TRUE or to a cache object
11465 * * cache a specific response - set config.cache value to TRUE or to a cache object
11466 *
11467 * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
11468 * then the default `$cacheFactory("$http")` object is used.
11469 *
11470 * The default cache value can be set by updating the
11471 * {@link ng.$http#defaults `$http.defaults.cache`} property or the
11472 * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
11473 *
11474 * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
11475 * the relevant cache object. The next time the same request is made, the response is returned
11476 * from the cache without sending a request to the server.
11477 *
11478 * Take note that:
11479 *
11480 * * Only GET and JSONP requests are cached.
11481 * * The cache key is the request URL including search parameters; headers are not considered.
11482 * * Cached responses are returned asynchronously, in the same way as responses from the server.
11483 * * If multiple identical requests are made using the same cache, which is not yet populated,
11484 * one request will be made to the server and remaining requests will return the same response.
11485 * * A cache-control header on the response does not affect if or how responses are cached.
11486 *
11487 *
11488 * ## Interceptors
11489 *
11490 * Before you start creating interceptors, be sure to understand the
11491 * {@link ng.$q $q and deferred/promise APIs}.
11492 *
11493 * For purposes of global error handling, authentication, or any kind of synchronous or
11494 * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
11495 * able to intercept requests before they are handed to the server and
11496 * responses before they are handed over to the application code that
11497 * initiated these requests. The interceptors leverage the {@link ng.$q
11498 * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
11499 *
11500 * The interceptors are service factories that are registered with the `$httpProvider` by
11501 * adding them to the `$httpProvider.interceptors` array. The factory is called and
11502 * injected with dependencies (if specified) and returns the interceptor.
11503 *
11504 * There are two kinds of interceptors (and two kinds of rejection interceptors):
11505 *
11506 * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
11507 * modify the `config` object or create a new one. The function needs to return the `config`
11508 * object directly, or a promise containing the `config` or a new `config` object.
11509 * * `requestError`: interceptor gets called when a previous interceptor threw an error or
11510 * resolved with a rejection.
11511 * * `response`: interceptors get called with http `response` object. The function is free to
11512 * modify the `response` object or create a new one. The function needs to return the `response`
11513 * object directly, or as a promise containing the `response` or a new `response` object.
11514 * * `responseError`: interceptor gets called when a previous interceptor threw an error or
11515 * resolved with a rejection.
11516 *
11517 *
11518 * ```js
11519 * // register the interceptor as a service
11520 * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
11521 * return {
11522 * // optional method
11523 * 'request': function(config) {
11524 * // do something on success
11525 * return config;
11526 * },
11527 *
11528 * // optional method
11529 * 'requestError': function(rejection) {
11530 * // do something on error
11531 * if (canRecover(rejection)) {
11532 * return responseOrNewPromise
11533 * }
11534 * return $q.reject(rejection);
11535 * },
11536 *
11537 *
11538 *
11539 * // optional method
11540 * 'response': function(response) {
11541 * // do something on success
11542 * return response;
11543 * },
11544 *
11545 * // optional method
11546 * 'responseError': function(rejection) {
11547 * // do something on error
11548 * if (canRecover(rejection)) {
11549 * return responseOrNewPromise
11550 * }
11551 * return $q.reject(rejection);
11552 * }
11553 * };
11554 * });
11555 *
11556 * $httpProvider.interceptors.push('myHttpInterceptor');
11557 *
11558 *
11559 * // alternatively, register the interceptor via an anonymous factory
11560 * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
11561 * return {
11562 * 'request': function(config) {
11563 * // same as above
11564 * },
11565 *
11566 * 'response': function(response) {
11567 * // same as above
11568 * }
11569 * };
11570 * });
11571 * ```
11572 *
11573 * ## Security Considerations
11574 *
11575 * When designing web applications, consider security threats from:
11576 *
11577 * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
11578 * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
11579 *
11580 * Both server and the client must cooperate in order to eliminate these threats. Angular comes
11581 * pre-configured with strategies that address these issues, but for this to work backend server
11582 * cooperation is required.
11583 *
11584 * ### JSON Vulnerability Protection
11585 *
11586 * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
11587 * allows third party website to turn your JSON resource URL into
11588 * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
11589 * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
11590 * Angular will automatically strip the prefix before processing it as JSON.
11591 *
11592 * For example if your server needs to return:
11593 * ```js
11594 * ['one','two']
11595 * ```
11596 *
11597 * which is vulnerable to attack, your server can return:
11598 * ```js
11599 * )]}',
11600 * ['one','two']
11601 * ```
11602 *
11603 * Angular will strip the prefix, before processing the JSON.
11604 *
11605 *
11606 * ### Cross Site Request Forgery (XSRF) Protection
11607 *
11608 * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
11609 * which the attacker can trick an authenticated user into unknowingly executing actions on your
11610 * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
11611 * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
11612 * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
11613 * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
11614 * The header will not be set for cross-domain requests.
11615 *
11616 * To take advantage of this, your server needs to set a token in a JavaScript readable session
11617 * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
11618 * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
11619 * that only JavaScript running on your domain could have sent the request. The token must be
11620 * unique for each user and must be verifiable by the server (to prevent the JavaScript from
11621 * making up its own tokens). We recommend that the token is a digest of your site's
11622 * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
11623 * for added security.
11624 *
11625 * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
11626 * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
11627 * or the per-request config object.
11628 *
11629 * In order to prevent collisions in environments where multiple Angular apps share the
11630 * same domain or subdomain, we recommend that each application uses unique cookie name.
11631 *
11632 * @param {object} config Object describing the request to be made and how it should be
11633 * processed. The object has following properties:
11634 *
11635 * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
11636 * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
11637 * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
11638 * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
11639 * with the `paramSerializer` and appended as GET parameters.
11640 * - **data** – `{string|Object}` – Data to be sent as the request message data.
11641 * - **headers** – `{Object}` – Map of strings or functions which return strings representing
11642 * HTTP headers to send to the server. If the return value of a function is null, the
11643 * header will not be sent. Functions accept a config object as an argument.
11644 * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
11645 * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
11646 * The handler will be called in the context of a `$apply` block.
11647 * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
11648 * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
11649 * The handler will be called in the context of a `$apply` block.
11650 * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
11651 * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
11652 * - **transformRequest** –
11653 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
11654 * transform function or an array of such functions. The transform function takes the http
11655 * request body and headers and returns its transformed (typically serialized) version.
11656 * See {@link ng.$http#overriding-the-default-transformations-per-request
11657 * Overriding the Default Transformations}
11658 * - **transformResponse** –
11659 * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
11660 * transform function or an array of such functions. The transform function takes the http
11661 * response body, headers and status and returns its transformed (typically deserialized) version.
11662 * See {@link ng.$http#overriding-the-default-transformations-per-request
11663 * Overriding the Default Transformations}
11664 * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
11665 * prepare the string representation of request parameters (specified as an object).
11666 * If specified as string, it is interpreted as function registered with the
11667 * {@link $injector $injector}, which means you can create your own serializer
11668 * by registering it as a {@link auto.$provide#service service}.
11669 * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
11670 * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
11671 * - **cache** – `{boolean|Object}` – A boolean value or object created with
11672 * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
11673 * See {@link $http#caching $http Caching} for more information.
11674 * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
11675 * that should abort the request when resolved.
11676 * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
11677 * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
11678 * for more information.
11679 * - **responseType** - `{string}` - see
11680 * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
11681 *
11682 * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
11683 * when the request succeeds or fails.
11684 *
11685 *
11686 * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
11687 * requests. This is primarily meant to be used for debugging purposes.
11688 *
11689 *
11690 * @example
11691<example module="httpExample" name="http-service">
11692<file name="index.html">
11693 <div ng-controller="FetchController">
11694 <select ng-model="method" aria-label="Request method">
11695 <option>GET</option>
11696 <option>JSONP</option>
11697 </select>
11698 <input type="text" ng-model="url" size="80" aria-label="URL" />
11699 <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
11700 <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
11701 <button id="samplejsonpbtn"
11702 ng-click="updateModel('JSONP',
11703 'https://angularjs.org/greet.php?name=Super%20Hero')">
11704 Sample JSONP
11705 </button>
11706 <button id="invalidjsonpbtn"
11707 ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
11708 Invalid JSONP
11709 </button>
11710 <pre>http status code: {{status}}</pre>
11711 <pre>http response data: {{data}}</pre>
11712 </div>
11713</file>
11714<file name="script.js">
11715 angular.module('httpExample', [])
11716 .config(['$sceDelegateProvider', function($sceDelegateProvider) {
11717 // We must whitelist the JSONP endpoint that we are using to show that we trust it
11718 $sceDelegateProvider.resourceUrlWhitelist([
11719 'self',
11720 'https://angularjs.org/**'
11721 ]);
11722 }])
11723 .controller('FetchController', ['$scope', '$http', '$templateCache',
11724 function($scope, $http, $templateCache) {
11725 $scope.method = 'GET';
11726 $scope.url = 'http-hello.html';
11727
11728 $scope.fetch = function() {
11729 $scope.code = null;
11730 $scope.response = null;
11731
11732 $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
11733 then(function(response) {
11734 $scope.status = response.status;
11735 $scope.data = response.data;
11736 }, function(response) {
11737 $scope.data = response.data || 'Request failed';
11738 $scope.status = response.status;
11739 });
11740 };
11741
11742 $scope.updateModel = function(method, url) {
11743 $scope.method = method;
11744 $scope.url = url;
11745 };
11746 }]);
11747</file>
11748<file name="http-hello.html">
11749 Hello, $http!
11750</file>
11751<file name="protractor.js" type="protractor">
11752 var status = element(by.binding('status'));
11753 var data = element(by.binding('data'));
11754 var fetchBtn = element(by.id('fetchbtn'));
11755 var sampleGetBtn = element(by.id('samplegetbtn'));
11756 var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
11757
11758 it('should make an xhr GET request', function() {
11759 sampleGetBtn.click();
11760 fetchBtn.click();
11761 expect(status.getText()).toMatch('200');
11762 expect(data.getText()).toMatch(/Hello, \$http!/);
11763 });
11764
11765// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
11766// it('should make a JSONP request to angularjs.org', function() {
11767// var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
11768// sampleJsonpBtn.click();
11769// fetchBtn.click();
11770// expect(status.getText()).toMatch('200');
11771// expect(data.getText()).toMatch(/Super Hero!/);
11772// });
11773
11774 it('should make JSONP request to invalid URL and invoke the error handler',
11775 function() {
11776 invalidJsonpBtn.click();
11777 fetchBtn.click();
11778 expect(status.getText()).toMatch('0');
11779 expect(data.getText()).toMatch('Request failed');
11780 });
11781</file>
11782</example>
11783 */
11784 function $http(requestConfig) {
11785
11786 if (!isObject(requestConfig)) {
11787 throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
11788 }
11789
11790 if (!isString($sce.valueOf(requestConfig.url))) {
11791 throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
11792 }
11793
11794 var config = extend({
11795 method: 'get',
11796 transformRequest: defaults.transformRequest,
11797 transformResponse: defaults.transformResponse,
11798 paramSerializer: defaults.paramSerializer,
11799 jsonpCallbackParam: defaults.jsonpCallbackParam
11800 }, requestConfig);
11801
11802 config.headers = mergeHeaders(requestConfig);
11803 config.method = uppercase(config.method);
11804 config.paramSerializer = isString(config.paramSerializer) ?
11805 $injector.get(config.paramSerializer) : config.paramSerializer;
11806
11807 $browser.$$incOutstandingRequestCount();
11808
11809 var requestInterceptors = [];
11810 var responseInterceptors = [];
11811 var promise = $q.resolve(config);
11812
11813 // apply interceptors
11814 forEach(reversedInterceptors, function(interceptor) {
11815 if (interceptor.request || interceptor.requestError) {
11816 requestInterceptors.unshift(interceptor.request, interceptor.requestError);
11817 }
11818 if (interceptor.response || interceptor.responseError) {
11819 responseInterceptors.push(interceptor.response, interceptor.responseError);
11820 }
11821 });
11822
11823 promise = chainInterceptors(promise, requestInterceptors);
11824 promise = promise.then(serverRequest);
11825 promise = chainInterceptors(promise, responseInterceptors);
11826 promise = promise.finally(completeOutstandingRequest);
11827
11828 return promise;
11829
11830
11831 function chainInterceptors(promise, interceptors) {
11832 for (var i = 0, ii = interceptors.length; i < ii;) {
11833 var thenFn = interceptors[i++];
11834 var rejectFn = interceptors[i++];
11835
11836 promise = promise.then(thenFn, rejectFn);
11837 }
11838
11839 interceptors.length = 0;
11840
11841 return promise;
11842 }
11843
11844 function completeOutstandingRequest() {
11845 $browser.$$completeOutstandingRequest(noop);
11846 }
11847
11848 function executeHeaderFns(headers, config) {
11849 var headerContent, processedHeaders = {};
11850
11851 forEach(headers, function(headerFn, header) {
11852 if (isFunction(headerFn)) {
11853 headerContent = headerFn(config);
11854 if (headerContent != null) {
11855 processedHeaders[header] = headerContent;
11856 }
11857 } else {
11858 processedHeaders[header] = headerFn;
11859 }
11860 });
11861
11862 return processedHeaders;
11863 }
11864
11865 function mergeHeaders(config) {
11866 var defHeaders = defaults.headers,
11867 reqHeaders = extend({}, config.headers),
11868 defHeaderName, lowercaseDefHeaderName, reqHeaderName;
11869
11870 defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
11871
11872 // using for-in instead of forEach to avoid unnecessary iteration after header has been found
11873 defaultHeadersIteration:
11874 for (defHeaderName in defHeaders) {
11875 lowercaseDefHeaderName = lowercase(defHeaderName);
11876
11877 for (reqHeaderName in reqHeaders) {
11878 if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
11879 continue defaultHeadersIteration;
11880 }
11881 }
11882
11883 reqHeaders[defHeaderName] = defHeaders[defHeaderName];
11884 }
11885
11886 // execute if header value is a function for merged headers
11887 return executeHeaderFns(reqHeaders, shallowCopy(config));
11888 }
11889
11890 function serverRequest(config) {
11891 var headers = config.headers;
11892 var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
11893
11894 // strip content-type if data is undefined
11895 if (isUndefined(reqData)) {
11896 forEach(headers, function(value, header) {
11897 if (lowercase(header) === 'content-type') {
11898 delete headers[header];
11899 }
11900 });
11901 }
11902
11903 if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
11904 config.withCredentials = defaults.withCredentials;
11905 }
11906
11907 // send request
11908 return sendReq(config, reqData).then(transformResponse, transformResponse);
11909 }
11910
11911 function transformResponse(response) {
11912 // make a copy since the response must be cacheable
11913 var resp = extend({}, response);
11914 resp.data = transformData(response.data, response.headers, response.status,
11915 config.transformResponse);
11916 return (isSuccess(response.status))
11917 ? resp
11918 : $q.reject(resp);
11919 }
11920 }
11921
11922 $http.pendingRequests = [];
11923
11924 /**
11925 * @ngdoc method
11926 * @name $http#get
11927 *
11928 * @description
11929 * Shortcut method to perform `GET` request.
11930 *
11931 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
11932 * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
11933 * @param {Object=} config Optional configuration object
11934 * @returns {HttpPromise} Future object
11935 */
11936
11937 /**
11938 * @ngdoc method
11939 * @name $http#delete
11940 *
11941 * @description
11942 * Shortcut method to perform `DELETE` request.
11943 *
11944 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
11945 * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
11946 * @param {Object=} config Optional configuration object
11947 * @returns {HttpPromise} Future object
11948 */
11949
11950 /**
11951 * @ngdoc method
11952 * @name $http#head
11953 *
11954 * @description
11955 * Shortcut method to perform `HEAD` request.
11956 *
11957 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
11958 * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
11959 * @param {Object=} config Optional configuration object
11960 * @returns {HttpPromise} Future object
11961 */
11962
11963 /**
11964 * @ngdoc method
11965 * @name $http#jsonp
11966 *
11967 * @description
11968 * Shortcut method to perform `JSONP` request.
11969 *
11970 * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
11971 * the url must be declared, via {@link $sce} as a trusted resource URL.
11972 * You can trust a URL by adding it to the whitelist via
11973 * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
11974 * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
11975 *
11976 * JSONP requests must specify a callback to be used in the response from the server. This callback
11977 * is passed as a query parameter in the request. You must specify the name of this parameter by
11978 * setting the `jsonpCallbackParam` property on the request config object.
11979 *
11980 * ```
11981 * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
11982 * ```
11983 *
11984 * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
11985 * Initially this is set to `'callback'`.
11986 *
11987 * <div class="alert alert-danger">
11988 * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
11989 * parameter value should go.
11990 * </div>
11991 *
11992 * If you would like to customise where and how the callbacks are stored then try overriding
11993 * or decorating the {@link $jsonpCallbacks} service.
11994 *
11995 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
11996 * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
11997 * @param {Object=} config Optional configuration object
11998 * @returns {HttpPromise} Future object
11999 */
12000 createShortMethods('get', 'delete', 'head', 'jsonp');
12001
12002 /**
12003 * @ngdoc method
12004 * @name $http#post
12005 *
12006 * @description
12007 * Shortcut method to perform `POST` request.
12008 *
12009 * @param {string} url Relative or absolute URL specifying the destination of the request
12010 * @param {*} data Request content
12011 * @param {Object=} config Optional configuration object
12012 * @returns {HttpPromise} Future object
12013 */
12014
12015 /**
12016 * @ngdoc method
12017 * @name $http#put
12018 *
12019 * @description
12020 * Shortcut method to perform `PUT` request.
12021 *
12022 * @param {string} url Relative or absolute URL specifying the destination of the request
12023 * @param {*} data Request content
12024 * @param {Object=} config Optional configuration object
12025 * @returns {HttpPromise} Future object
12026 */
12027
12028 /**
12029 * @ngdoc method
12030 * @name $http#patch
12031 *
12032 * @description
12033 * Shortcut method to perform `PATCH` request.
12034 *
12035 * @param {string} url Relative or absolute URL specifying the destination of the request
12036 * @param {*} data Request content
12037 * @param {Object=} config Optional configuration object
12038 * @returns {HttpPromise} Future object
12039 */
12040 createShortMethodsWithData('post', 'put', 'patch');
12041
12042 /**
12043 * @ngdoc property
12044 * @name $http#defaults
12045 *
12046 * @description
12047 * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
12048 * default headers, withCredentials as well as request and response transformations.
12049 *
12050 * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
12051 */
12052 $http.defaults = defaults;
12053
12054
12055 return $http;
12056
12057
12058 function createShortMethods(names) {
12059 forEach(arguments, function(name) {
12060 $http[name] = function(url, config) {
12061 return $http(extend({}, config || {}, {
12062 method: name,
12063 url: url
12064 }));
12065 };
12066 });
12067 }
12068
12069
12070 function createShortMethodsWithData(name) {
12071 forEach(arguments, function(name) {
12072 $http[name] = function(url, data, config) {
12073 return $http(extend({}, config || {}, {
12074 method: name,
12075 url: url,
12076 data: data
12077 }));
12078 };
12079 });
12080 }
12081
12082
12083 /**
12084 * Makes the request.
12085 *
12086 * !!! ACCESSES CLOSURE VARS:
12087 * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
12088 */
12089 function sendReq(config, reqData) {
12090 var deferred = $q.defer(),
12091 promise = deferred.promise,
12092 cache,
12093 cachedResp,
12094 reqHeaders = config.headers,
12095 isJsonp = lowercase(config.method) === 'jsonp',
12096 url = config.url;
12097
12098 if (isJsonp) {
12099 // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
12100 // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
12101 url = $sce.getTrustedResourceUrl(url);
12102 } else if (!isString(url)) {
12103 // If it is not a string then the URL must be a $sce trusted object
12104 url = $sce.valueOf(url);
12105 }
12106
12107 url = buildUrl(url, config.paramSerializer(config.params));
12108
12109 if (isJsonp) {
12110 // Check the url and add the JSONP callback placeholder
12111 url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
12112 }
12113
12114 $http.pendingRequests.push(config);
12115 promise.then(removePendingReq, removePendingReq);
12116
12117 if ((config.cache || defaults.cache) && config.cache !== false &&
12118 (config.method === 'GET' || config.method === 'JSONP')) {
12119 cache = isObject(config.cache) ? config.cache
12120 : isObject(defaults.cache) ? defaults.cache
12121 : defaultCache;
12122 }
12123
12124 if (cache) {
12125 cachedResp = cache.get(url);
12126 if (isDefined(cachedResp)) {
12127 if (isPromiseLike(cachedResp)) {
12128 // cached request has already been sent, but there is no response yet
12129 cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
12130 } else {
12131 // serving from cache
12132 if (isArray(cachedResp)) {
12133 resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
12134 } else {
12135 resolvePromise(cachedResp, 200, {}, 'OK');
12136 }
12137 }
12138 } else {
12139 // put the promise for the non-transformed response into cache as a placeholder
12140 cache.put(url, promise);
12141 }
12142 }
12143
12144
12145 // if we won't have the response in cache, set the xsrf headers and
12146 // send the request to the backend
12147 if (isUndefined(cachedResp)) {
12148 var xsrfValue = urlIsSameOrigin(config.url)
12149 ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
12150 : undefined;
12151 if (xsrfValue) {
12152 reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
12153 }
12154
12155 $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
12156 config.withCredentials, config.responseType,
12157 createApplyHandlers(config.eventHandlers),
12158 createApplyHandlers(config.uploadEventHandlers));
12159 }
12160
12161 return promise;
12162
12163 function createApplyHandlers(eventHandlers) {
12164 if (eventHandlers) {
12165 var applyHandlers = {};
12166 forEach(eventHandlers, function(eventHandler, key) {
12167 applyHandlers[key] = function(event) {
12168 if (useApplyAsync) {
12169 $rootScope.$applyAsync(callEventHandler);
12170 } else if ($rootScope.$$phase) {
12171 callEventHandler();
12172 } else {
12173 $rootScope.$apply(callEventHandler);
12174 }
12175
12176 function callEventHandler() {
12177 eventHandler(event);
12178 }
12179 };
12180 });
12181 return applyHandlers;
12182 }
12183 }
12184
12185
12186 /**
12187 * Callback registered to $httpBackend():
12188 * - caches the response if desired
12189 * - resolves the raw $http promise
12190 * - calls $apply
12191 */
12192 function done(status, response, headersString, statusText) {
12193 if (cache) {
12194 if (isSuccess(status)) {
12195 cache.put(url, [status, response, parseHeaders(headersString), statusText]);
12196 } else {
12197 // remove promise from the cache
12198 cache.remove(url);
12199 }
12200 }
12201
12202 function resolveHttpPromise() {
12203 resolvePromise(response, status, headersString, statusText);
12204 }
12205
12206 if (useApplyAsync) {
12207 $rootScope.$applyAsync(resolveHttpPromise);
12208 } else {
12209 resolveHttpPromise();
12210 if (!$rootScope.$$phase) $rootScope.$apply();
12211 }
12212 }
12213
12214
12215 /**
12216 * Resolves the raw $http promise.
12217 */
12218 function resolvePromise(response, status, headers, statusText) {
12219 //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
12220 status = status >= -1 ? status : 0;
12221
12222 (isSuccess(status) ? deferred.resolve : deferred.reject)({
12223 data: response,
12224 status: status,
12225 headers: headersGetter(headers),
12226 config: config,
12227 statusText: statusText
12228 });
12229 }
12230
12231 function resolvePromiseWithResult(result) {
12232 resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
12233 }
12234
12235 function removePendingReq() {
12236 var idx = $http.pendingRequests.indexOf(config);
12237 if (idx !== -1) $http.pendingRequests.splice(idx, 1);
12238 }
12239 }
12240
12241
12242 function buildUrl(url, serializedParams) {
12243 if (serializedParams.length > 0) {
12244 url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
12245 }
12246 return url;
12247 }
12248
12249 function sanitizeJsonpCallbackParam(url, key) {
12250 if (/[&?][^=]+=JSON_CALLBACK/.test(url)) {
12251 // Throw if the url already contains a reference to JSON_CALLBACK
12252 throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
12253 }
12254
12255 var callbackParamRegex = new RegExp('[&?]' + key + '=');
12256 if (callbackParamRegex.test(url)) {
12257 // Throw if the callback param was already provided
12258 throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', key, url);
12259 }
12260
12261 // Add in the JSON_CALLBACK callback param value
12262 url += ((url.indexOf('?') === -1) ? '?' : '&') + key + '=JSON_CALLBACK';
12263
12264 return url;
12265 }
12266 }];
12267}
12268
12269/**
12270 * @ngdoc service
12271 * @name $xhrFactory
12272 * @this
12273 *
12274 * @description
12275 * Factory function used to create XMLHttpRequest objects.
12276 *
12277 * Replace or decorate this service to create your own custom XMLHttpRequest objects.
12278 *
12279 * ```
12280 * angular.module('myApp', [])
12281 * .factory('$xhrFactory', function() {
12282 * return function createXhr(method, url) {
12283 * return new window.XMLHttpRequest({mozSystem: true});
12284 * };
12285 * });
12286 * ```
12287 *
12288 * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
12289 * @param {string} url URL of the request.
12290 */
12291function $xhrFactoryProvider() {
12292 this.$get = function() {
12293 return function createXhr() {
12294 return new window.XMLHttpRequest();
12295 };
12296 };
12297}
12298
12299/**
12300 * @ngdoc service
12301 * @name $httpBackend
12302 * @requires $jsonpCallbacks
12303 * @requires $document
12304 * @requires $xhrFactory
12305 * @this
12306 *
12307 * @description
12308 * HTTP backend used by the {@link ng.$http service} that delegates to
12309 * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
12310 *
12311 * You should never need to use this service directly, instead use the higher-level abstractions:
12312 * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
12313 *
12314 * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
12315 * $httpBackend} which can be trained with responses.
12316 */
12317function $HttpBackendProvider() {
12318 this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
12319 return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
12320 }];
12321}
12322
12323function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
12324 // TODO(vojta): fix the signature
12325 return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
12326 url = url || $browser.url();
12327
12328 if (lowercase(method) === 'jsonp') {
12329 var callbackPath = callbacks.createCallback(url);
12330 var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
12331 // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
12332 var response = (status === 200) && callbacks.getResponse(callbackPath);
12333 completeRequest(callback, status, response, '', text);
12334 callbacks.removeCallback(callbackPath);
12335 });
12336 } else {
12337
12338 var xhr = createXhr(method, url);
12339
12340 xhr.open(method, url, true);
12341 forEach(headers, function(value, key) {
12342 if (isDefined(value)) {
12343 xhr.setRequestHeader(key, value);
12344 }
12345 });
12346
12347 xhr.onload = function requestLoaded() {
12348 var statusText = xhr.statusText || '';
12349
12350 // responseText is the old-school way of retrieving response (supported by IE9)
12351 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
12352 var response = ('response' in xhr) ? xhr.response : xhr.responseText;
12353
12354 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
12355 var status = xhr.status === 1223 ? 204 : xhr.status;
12356
12357 // fix status code when it is 0 (0 status is undocumented).
12358 // Occurs when accessing file resources or on Android 4.1 stock browser
12359 // while retrieving files from application cache.
12360 if (status === 0) {
12361 status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
12362 }
12363
12364 completeRequest(callback,
12365 status,
12366 response,
12367 xhr.getAllResponseHeaders(),
12368 statusText);
12369 };
12370
12371 var requestError = function() {
12372 // The response is always empty
12373 // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
12374 completeRequest(callback, -1, null, null, '');
12375 };
12376
12377 xhr.onerror = requestError;
12378 xhr.onabort = requestError;
12379 xhr.ontimeout = requestError;
12380
12381 forEach(eventHandlers, function(value, key) {
12382 xhr.addEventListener(key, value);
12383 });
12384
12385 forEach(uploadEventHandlers, function(value, key) {
12386 xhr.upload.addEventListener(key, value);
12387 });
12388
12389 if (withCredentials) {
12390 xhr.withCredentials = true;
12391 }
12392
12393 if (responseType) {
12394 try {
12395 xhr.responseType = responseType;
12396 } catch (e) {
12397 // WebKit added support for the json responseType value on 09/03/2013
12398 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
12399 // known to throw when setting the value "json" as the response type. Other older
12400 // browsers implementing the responseType
12401 //
12402 // The json response type can be ignored if not supported, because JSON payloads are
12403 // parsed on the client-side regardless.
12404 if (responseType !== 'json') {
12405 throw e;
12406 }
12407 }
12408 }
12409
12410 xhr.send(isUndefined(post) ? null : post);
12411 }
12412
12413 if (timeout > 0) {
12414 var timeoutId = $browserDefer(timeoutRequest, timeout);
12415 } else if (isPromiseLike(timeout)) {
12416 timeout.then(timeoutRequest);
12417 }
12418
12419
12420 function timeoutRequest() {
12421 if (jsonpDone) {
12422 jsonpDone();
12423 }
12424 if (xhr) {
12425 xhr.abort();
12426 }
12427 }
12428
12429 function completeRequest(callback, status, response, headersString, statusText) {
12430 // cancel timeout and subsequent timeout promise resolution
12431 if (isDefined(timeoutId)) {
12432 $browserDefer.cancel(timeoutId);
12433 }
12434 jsonpDone = xhr = null;
12435
12436 callback(status, response, headersString, statusText);
12437 }
12438 };
12439
12440 function jsonpReq(url, callbackPath, done) {
12441 url = url.replace('JSON_CALLBACK', callbackPath);
12442 // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
12443 // - fetches local scripts via XHR and evals them
12444 // - adds and immediately removes script elements from the document
12445 var script = rawDocument.createElement('script'), callback = null;
12446 script.type = 'text/javascript';
12447 script.src = url;
12448 script.async = true;
12449
12450 callback = function(event) {
12451 script.removeEventListener('load', callback);
12452 script.removeEventListener('error', callback);
12453 rawDocument.body.removeChild(script);
12454 script = null;
12455 var status = -1;
12456 var text = 'unknown';
12457
12458 if (event) {
12459 if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
12460 event = { type: 'error' };
12461 }
12462 text = event.type;
12463 status = event.type === 'error' ? 404 : 200;
12464 }
12465
12466 if (done) {
12467 done(status, text);
12468 }
12469 };
12470
12471 script.addEventListener('load', callback);
12472 script.addEventListener('error', callback);
12473 rawDocument.body.appendChild(script);
12474 return callback;
12475 }
12476}
12477
12478var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
12479$interpolateMinErr.throwNoconcat = function(text) {
12480 throw $interpolateMinErr('noconcat',
12481 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
12482 'interpolations that concatenate multiple expressions when a trusted value is ' +
12483 'required. See http://docs.angularjs.org/api/ng.$sce', text);
12484};
12485
12486$interpolateMinErr.interr = function(text, err) {
12487 return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
12488};
12489
12490/**
12491 * @ngdoc provider
12492 * @name $interpolateProvider
12493 * @this
12494 *
12495 * @description
12496 *
12497 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
12498 *
12499 * <div class="alert alert-danger">
12500 * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
12501 * template within a Python Jinja template (or any other template language). Mixing templating
12502 * languages is **very dangerous**. The embedding template language will not safely escape Angular
12503 * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
12504 * security bugs!
12505 * </div>
12506 *
12507 * @example
12508<example name="custom-interpolation-markup" module="customInterpolationApp">
12509<file name="index.html">
12510<script>
12511 var customInterpolationApp = angular.module('customInterpolationApp', []);
12512
12513 customInterpolationApp.config(function($interpolateProvider) {
12514 $interpolateProvider.startSymbol('//');
12515 $interpolateProvider.endSymbol('//');
12516 });
12517
12518
12519 customInterpolationApp.controller('DemoController', function() {
12520 this.label = "This binding is brought you by // interpolation symbols.";
12521 });
12522</script>
12523<div ng-controller="DemoController as demo">
12524 //demo.label//
12525</div>
12526</file>
12527<file name="protractor.js" type="protractor">
12528 it('should interpolate binding with custom symbols', function() {
12529 expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
12530 });
12531</file>
12532</example>
12533 */
12534function $InterpolateProvider() {
12535 var startSymbol = '{{';
12536 var endSymbol = '}}';
12537
12538 /**
12539 * @ngdoc method
12540 * @name $interpolateProvider#startSymbol
12541 * @description
12542 * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
12543 *
12544 * @param {string=} value new value to set the starting symbol to.
12545 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
12546 */
12547 this.startSymbol = function(value) {
12548 if (value) {
12549 startSymbol = value;
12550 return this;
12551 } else {
12552 return startSymbol;
12553 }
12554 };
12555
12556 /**
12557 * @ngdoc method
12558 * @name $interpolateProvider#endSymbol
12559 * @description
12560 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
12561 *
12562 * @param {string=} value new value to set the ending symbol to.
12563 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
12564 */
12565 this.endSymbol = function(value) {
12566 if (value) {
12567 endSymbol = value;
12568 return this;
12569 } else {
12570 return endSymbol;
12571 }
12572 };
12573
12574
12575 this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
12576 var startSymbolLength = startSymbol.length,
12577 endSymbolLength = endSymbol.length,
12578 escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
12579 escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
12580
12581 function escape(ch) {
12582 return '\\\\\\' + ch;
12583 }
12584
12585 function unescapeText(text) {
12586 return text.replace(escapedStartRegexp, startSymbol).
12587 replace(escapedEndRegexp, endSymbol);
12588 }
12589
12590 // TODO: this is the same as the constantWatchDelegate in parse.js
12591 function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
12592 var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
12593 unwatch();
12594 return constantInterp(scope);
12595 }, listener, objectEquality);
12596 return unwatch;
12597 }
12598
12599 /**
12600 * @ngdoc service
12601 * @name $interpolate
12602 * @kind function
12603 *
12604 * @requires $parse
12605 * @requires $sce
12606 *
12607 * @description
12608 *
12609 * Compiles a string with markup into an interpolation function. This service is used by the
12610 * HTML {@link ng.$compile $compile} service for data binding. See
12611 * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
12612 * interpolation markup.
12613 *
12614 *
12615 * ```js
12616 * var $interpolate = ...; // injected
12617 * var exp = $interpolate('Hello {{name | uppercase}}!');
12618 * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
12619 * ```
12620 *
12621 * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
12622 * `true`, the interpolation function will return `undefined` unless all embedded expressions
12623 * evaluate to a value other than `undefined`.
12624 *
12625 * ```js
12626 * var $interpolate = ...; // injected
12627 * var context = {greeting: 'Hello', name: undefined };
12628 *
12629 * // default "forgiving" mode
12630 * var exp = $interpolate('{{greeting}} {{name}}!');
12631 * expect(exp(context)).toEqual('Hello !');
12632 *
12633 * // "allOrNothing" mode
12634 * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
12635 * expect(exp(context)).toBeUndefined();
12636 * context.name = 'Angular';
12637 * expect(exp(context)).toEqual('Hello Angular!');
12638 * ```
12639 *
12640 * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
12641 *
12642 * #### Escaped Interpolation
12643 * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
12644 * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
12645 * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
12646 * or binding.
12647 *
12648 * This enables web-servers to prevent script injection attacks and defacing attacks, to some
12649 * degree, while also enabling code examples to work without relying on the
12650 * {@link ng.directive:ngNonBindable ngNonBindable} directive.
12651 *
12652 * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
12653 * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all
12654 * interpolation start/end markers with their escaped counterparts.**
12655 *
12656 * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
12657 * output when the $interpolate service processes the text. So, for HTML elements interpolated
12658 * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
12659 * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
12660 * this is typically useful only when user-data is used in rendering a template from the server, or
12661 * when otherwise untrusted data is used by a directive.
12662 *
12663 * <example name="interpolation">
12664 * <file name="index.html">
12665 * <div ng-init="username='A user'">
12666 * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
12667 * </p>
12668 * <p><strong>{{username}}</strong> attempts to inject code which will deface the
12669 * application, but fails to accomplish their task, because the server has correctly
12670 * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
12671 * characters.</p>
12672 * <p>Instead, the result of the attempted script injection is visible, and can be removed
12673 * from the database by an administrator.</p>
12674 * </div>
12675 * </file>
12676 * </example>
12677 *
12678 * @knownIssue
12679 * It is currently not possible for an interpolated expression to contain the interpolation end
12680 * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
12681 * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
12682 *
12683 * @knownIssue
12684 * All directives and components must use the standard `{{` `}}` interpolation symbols
12685 * in their templates. If you change the application interpolation symbols the {@link $compile}
12686 * service will attempt to denormalize the standard symbols to the custom symbols.
12687 * The denormalization process is not clever enough to know not to replace instances of the standard
12688 * symbols where they would not normally be treated as interpolation symbols. For example in the following
12689 * code snippet the closing braces of the literal object will get incorrectly denormalized:
12690 *
12691 * ```
12692 * <div data-context='{"context":{"id":3,"type":"page"}}">
12693 * ```
12694 *
12695 * The workaround is to ensure that such instances are separated by whitespace:
12696 * ```
12697 * <div data-context='{"context":{"id":3,"type":"page"} }">
12698 * ```
12699 *
12700 * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
12701 *
12702 * @param {string} text The text with markup to interpolate.
12703 * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
12704 * embedded expression in order to return an interpolation function. Strings with no
12705 * embedded expression will return null for the interpolation function.
12706 * @param {string=} trustedContext when provided, the returned function passes the interpolated
12707 * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
12708 * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
12709 * provides Strict Contextual Escaping for details.
12710 * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
12711 * unless all embedded expressions evaluate to a value other than `undefined`.
12712 * @returns {function(context)} an interpolation function which is used to compute the
12713 * interpolated string. The function has these parameters:
12714 *
12715 * - `context`: evaluation context for all expressions embedded in the interpolated text
12716 */
12717 function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
12718 // Provide a quick exit and simplified result function for text with no interpolation
12719 if (!text.length || text.indexOf(startSymbol) === -1) {
12720 var constantInterp;
12721 if (!mustHaveExpression) {
12722 var unescapedText = unescapeText(text);
12723 constantInterp = valueFn(unescapedText);
12724 constantInterp.exp = text;
12725 constantInterp.expressions = [];
12726 constantInterp.$$watchDelegate = constantWatchDelegate;
12727 }
12728 return constantInterp;
12729 }
12730
12731 allOrNothing = !!allOrNothing;
12732 var startIndex,
12733 endIndex,
12734 index = 0,
12735 expressions = [],
12736 parseFns = [],
12737 textLength = text.length,
12738 exp,
12739 concat = [],
12740 expressionPositions = [];
12741
12742 while (index < textLength) {
12743 if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
12744 ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
12745 if (index !== startIndex) {
12746 concat.push(unescapeText(text.substring(index, startIndex)));
12747 }
12748 exp = text.substring(startIndex + startSymbolLength, endIndex);
12749 expressions.push(exp);
12750 parseFns.push($parse(exp, parseStringifyInterceptor));
12751 index = endIndex + endSymbolLength;
12752 expressionPositions.push(concat.length);
12753 concat.push('');
12754 } else {
12755 // we did not find an interpolation, so we have to add the remainder to the separators array
12756 if (index !== textLength) {
12757 concat.push(unescapeText(text.substring(index)));
12758 }
12759 break;
12760 }
12761 }
12762
12763 // Concatenating expressions makes it hard to reason about whether some combination of
12764 // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
12765 // single expression be used for iframe[src], object[src], etc., we ensure that the value
12766 // that's used is assigned or constructed by some JS code somewhere that is more testable or
12767 // make it obvious that you bound the value to some user controlled value. This helps reduce
12768 // the load when auditing for XSS issues.
12769 if (trustedContext && concat.length > 1) {
12770 $interpolateMinErr.throwNoconcat(text);
12771 }
12772
12773 if (!mustHaveExpression || expressions.length) {
12774 var compute = function(values) {
12775 for (var i = 0, ii = expressions.length; i < ii; i++) {
12776 if (allOrNothing && isUndefined(values[i])) return;
12777 concat[expressionPositions[i]] = values[i];
12778 }
12779 return concat.join('');
12780 };
12781
12782 var getValue = function(value) {
12783 return trustedContext ?
12784 $sce.getTrusted(trustedContext, value) :
12785 $sce.valueOf(value);
12786 };
12787
12788 return extend(function interpolationFn(context) {
12789 var i = 0;
12790 var ii = expressions.length;
12791 var values = new Array(ii);
12792
12793 try {
12794 for (; i < ii; i++) {
12795 values[i] = parseFns[i](context);
12796 }
12797
12798 return compute(values);
12799 } catch (err) {
12800 $exceptionHandler($interpolateMinErr.interr(text, err));
12801 }
12802
12803 }, {
12804 // all of these properties are undocumented for now
12805 exp: text, //just for compatibility with regular watchers created via $watch
12806 expressions: expressions,
12807 $$watchDelegate: function(scope, listener) {
12808 var lastValue;
12809 return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
12810 var currValue = compute(values);
12811 if (isFunction(listener)) {
12812 listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
12813 }
12814 lastValue = currValue;
12815 });
12816 }
12817 });
12818 }
12819
12820 function parseStringifyInterceptor(value) {
12821 try {
12822 value = getValue(value);
12823 return allOrNothing && !isDefined(value) ? value : stringify(value);
12824 } catch (err) {
12825 $exceptionHandler($interpolateMinErr.interr(text, err));
12826 }
12827 }
12828 }
12829
12830
12831 /**
12832 * @ngdoc method
12833 * @name $interpolate#startSymbol
12834 * @description
12835 * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
12836 *
12837 * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
12838 * the symbol.
12839 *
12840 * @returns {string} start symbol.
12841 */
12842 $interpolate.startSymbol = function() {
12843 return startSymbol;
12844 };
12845
12846
12847 /**
12848 * @ngdoc method
12849 * @name $interpolate#endSymbol
12850 * @description
12851 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
12852 *
12853 * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
12854 * the symbol.
12855 *
12856 * @returns {string} end symbol.
12857 */
12858 $interpolate.endSymbol = function() {
12859 return endSymbol;
12860 };
12861
12862 return $interpolate;
12863 }];
12864}
12865
12866/** @this */
12867function $IntervalProvider() {
12868 this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
12869 function($rootScope, $window, $q, $$q, $browser) {
12870 var intervals = {};
12871
12872
12873 /**
12874 * @ngdoc service
12875 * @name $interval
12876 *
12877 * @description
12878 * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
12879 * milliseconds.
12880 *
12881 * The return value of registering an interval function is a promise. This promise will be
12882 * notified upon each tick of the interval, and will be resolved after `count` iterations, or
12883 * run indefinitely if `count` is not defined. The value of the notification will be the
12884 * number of iterations that have run.
12885 * To cancel an interval, call `$interval.cancel(promise)`.
12886 *
12887 * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
12888 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
12889 * time.
12890 *
12891 * <div class="alert alert-warning">
12892 * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
12893 * with them. In particular they are not automatically destroyed when a controller's scope or a
12894 * directive's element are destroyed.
12895 * You should take this into consideration and make sure to always cancel the interval at the
12896 * appropriate moment. See the example below for more details on how and when to do this.
12897 * </div>
12898 *
12899 * @param {function()} fn A function that should be called repeatedly. If no additional arguments
12900 * are passed (see below), the function is called with the current iteration count.
12901 * @param {number} delay Number of milliseconds between each function call.
12902 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
12903 * indefinitely.
12904 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
12905 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
12906 * @param {...*=} Pass additional parameters to the executed function.
12907 * @returns {promise} A promise which will be notified on each iteration.
12908 *
12909 * @example
12910 * <example module="intervalExample" name="interval-service">
12911 * <file name="index.html">
12912 * <script>
12913 * angular.module('intervalExample', [])
12914 * .controller('ExampleController', ['$scope', '$interval',
12915 * function($scope, $interval) {
12916 * $scope.format = 'M/d/yy h:mm:ss a';
12917 * $scope.blood_1 = 100;
12918 * $scope.blood_2 = 120;
12919 *
12920 * var stop;
12921 * $scope.fight = function() {
12922 * // Don't start a new fight if we are already fighting
12923 * if ( angular.isDefined(stop) ) return;
12924 *
12925 * stop = $interval(function() {
12926 * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
12927 * $scope.blood_1 = $scope.blood_1 - 3;
12928 * $scope.blood_2 = $scope.blood_2 - 4;
12929 * } else {
12930 * $scope.stopFight();
12931 * }
12932 * }, 100);
12933 * };
12934 *
12935 * $scope.stopFight = function() {
12936 * if (angular.isDefined(stop)) {
12937 * $interval.cancel(stop);
12938 * stop = undefined;
12939 * }
12940 * };
12941 *
12942 * $scope.resetFight = function() {
12943 * $scope.blood_1 = 100;
12944 * $scope.blood_2 = 120;
12945 * };
12946 *
12947 * $scope.$on('$destroy', function() {
12948 * // Make sure that the interval is destroyed too
12949 * $scope.stopFight();
12950 * });
12951 * }])
12952 * // Register the 'myCurrentTime' directive factory method.
12953 * // We inject $interval and dateFilter service since the factory method is DI.
12954 * .directive('myCurrentTime', ['$interval', 'dateFilter',
12955 * function($interval, dateFilter) {
12956 * // return the directive link function. (compile function not needed)
12957 * return function(scope, element, attrs) {
12958 * var format, // date format
12959 * stopTime; // so that we can cancel the time updates
12960 *
12961 * // used to update the UI
12962 * function updateTime() {
12963 * element.text(dateFilter(new Date(), format));
12964 * }
12965 *
12966 * // watch the expression, and update the UI on change.
12967 * scope.$watch(attrs.myCurrentTime, function(value) {
12968 * format = value;
12969 * updateTime();
12970 * });
12971 *
12972 * stopTime = $interval(updateTime, 1000);
12973 *
12974 * // listen on DOM destroy (removal) event, and cancel the next UI update
12975 * // to prevent updating time after the DOM element was removed.
12976 * element.on('$destroy', function() {
12977 * $interval.cancel(stopTime);
12978 * });
12979 * }
12980 * }]);
12981 * </script>
12982 *
12983 * <div>
12984 * <div ng-controller="ExampleController">
12985 * <label>Date format: <input ng-model="format"></label> <hr/>
12986 * Current time is: <span my-current-time="format"></span>
12987 * <hr/>
12988 * Blood 1 : <font color='red'>{{blood_1}}</font>
12989 * Blood 2 : <font color='red'>{{blood_2}}</font>
12990 * <button type="button" data-ng-click="fight()">Fight</button>
12991 * <button type="button" data-ng-click="stopFight()">StopFight</button>
12992 * <button type="button" data-ng-click="resetFight()">resetFight</button>
12993 * </div>
12994 * </div>
12995 *
12996 * </file>
12997 * </example>
12998 */
12999 function interval(fn, delay, count, invokeApply) {
13000 var hasParams = arguments.length > 4,
13001 args = hasParams ? sliceArgs(arguments, 4) : [],
13002 setInterval = $window.setInterval,
13003 clearInterval = $window.clearInterval,
13004 iteration = 0,
13005 skipApply = (isDefined(invokeApply) && !invokeApply),
13006 deferred = (skipApply ? $$q : $q).defer(),
13007 promise = deferred.promise;
13008
13009 count = isDefined(count) ? count : 0;
13010
13011 promise.$$intervalId = setInterval(function tick() {
13012 if (skipApply) {
13013 $browser.defer(callback);
13014 } else {
13015 $rootScope.$evalAsync(callback);
13016 }
13017 deferred.notify(iteration++);
13018
13019 if (count > 0 && iteration >= count) {
13020 deferred.resolve(iteration);
13021 clearInterval(promise.$$intervalId);
13022 delete intervals[promise.$$intervalId];
13023 }
13024
13025 if (!skipApply) $rootScope.$apply();
13026
13027 }, delay);
13028
13029 intervals[promise.$$intervalId] = deferred;
13030
13031 return promise;
13032
13033 function callback() {
13034 if (!hasParams) {
13035 fn(iteration);
13036 } else {
13037 fn.apply(null, args);
13038 }
13039 }
13040 }
13041
13042
13043 /**
13044 * @ngdoc method
13045 * @name $interval#cancel
13046 *
13047 * @description
13048 * Cancels a task associated with the `promise`.
13049 *
13050 * @param {Promise=} promise returned by the `$interval` function.
13051 * @returns {boolean} Returns `true` if the task was successfully canceled.
13052 */
13053 interval.cancel = function(promise) {
13054 if (promise && promise.$$intervalId in intervals) {
13055 // Interval cancels should not report as unhandled promise.
13056 intervals[promise.$$intervalId].promise.catch(noop);
13057 intervals[promise.$$intervalId].reject('canceled');
13058 $window.clearInterval(promise.$$intervalId);
13059 delete intervals[promise.$$intervalId];
13060 return true;
13061 }
13062 return false;
13063 };
13064
13065 return interval;
13066 }];
13067}
13068
13069/**
13070 * @ngdoc service
13071 * @name $jsonpCallbacks
13072 * @requires $window
13073 * @description
13074 * This service handles the lifecycle of callbacks to handle JSONP requests.
13075 * Override this service if you wish to customise where the callbacks are stored and
13076 * how they vary compared to the requested url.
13077 */
13078var $jsonpCallbacksProvider = /** @this */ function() {
13079 this.$get = ['$window', function($window) {
13080 var callbacks = $window.angular.callbacks;
13081 var callbackMap = {};
13082
13083 function createCallback(callbackId) {
13084 var callback = function(data) {
13085 callback.data = data;
13086 callback.called = true;
13087 };
13088 callback.id = callbackId;
13089 return callback;
13090 }
13091
13092 return {
13093 /**
13094 * @ngdoc method
13095 * @name $jsonpCallbacks#createCallback
13096 * @param {string} url the url of the JSONP request
13097 * @returns {string} the callback path to send to the server as part of the JSONP request
13098 * @description
13099 * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
13100 * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
13101 */
13102 createCallback: function(url) {
13103 var callbackId = '_' + (callbacks.$$counter++).toString(36);
13104 var callbackPath = 'angular.callbacks.' + callbackId;
13105 var callback = createCallback(callbackId);
13106 callbackMap[callbackPath] = callbacks[callbackId] = callback;
13107 return callbackPath;
13108 },
13109 /**
13110 * @ngdoc method
13111 * @name $jsonpCallbacks#wasCalled
13112 * @param {string} callbackPath the path to the callback that was sent in the JSONP request
13113 * @returns {boolean} whether the callback has been called, as a result of the JSONP response
13114 * @description
13115 * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
13116 * callback that was passed in the request.
13117 */
13118 wasCalled: function(callbackPath) {
13119 return callbackMap[callbackPath].called;
13120 },
13121 /**
13122 * @ngdoc method
13123 * @name $jsonpCallbacks#getResponse
13124 * @param {string} callbackPath the path to the callback that was sent in the JSONP request
13125 * @returns {*} the data received from the response via the registered callback
13126 * @description
13127 * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
13128 * in the JSONP response.
13129 */
13130 getResponse: function(callbackPath) {
13131 return callbackMap[callbackPath].data;
13132 },
13133 /**
13134 * @ngdoc method
13135 * @name $jsonpCallbacks#removeCallback
13136 * @param {string} callbackPath the path to the callback that was sent in the JSONP request
13137 * @description
13138 * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
13139 * completed or timed-out.
13140 */
13141 removeCallback: function(callbackPath) {
13142 var callback = callbackMap[callbackPath];
13143 delete callbacks[callback.id];
13144 delete callbackMap[callbackPath];
13145 }
13146 };
13147 }];
13148};
13149
13150/**
13151 * @ngdoc service
13152 * @name $locale
13153 *
13154 * @description
13155 * $locale service provides localization rules for various Angular components. As of right now the
13156 * only public api is:
13157 *
13158 * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
13159 */
13160
13161var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
13162 DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
13163var $locationMinErr = minErr('$location');
13164
13165
13166/**
13167 * Encode path using encodeUriSegment, ignoring forward slashes
13168 *
13169 * @param {string} path Path to encode
13170 * @returns {string}
13171 */
13172function encodePath(path) {
13173 var segments = path.split('/'),
13174 i = segments.length;
13175
13176 while (i--) {
13177 segments[i] = encodeUriSegment(segments[i]);
13178 }
13179
13180 return segments.join('/');
13181}
13182
13183function parseAbsoluteUrl(absoluteUrl, locationObj) {
13184 var parsedUrl = urlResolve(absoluteUrl);
13185
13186 locationObj.$$protocol = parsedUrl.protocol;
13187 locationObj.$$host = parsedUrl.hostname;
13188 locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
13189}
13190
13191var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
13192function parseAppUrl(url, locationObj) {
13193
13194 if (DOUBLE_SLASH_REGEX.test(url)) {
13195 throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
13196 }
13197
13198 var prefixed = (url.charAt(0) !== '/');
13199 if (prefixed) {
13200 url = '/' + url;
13201 }
13202 var match = urlResolve(url);
13203 locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
13204 match.pathname.substring(1) : match.pathname);
13205 locationObj.$$search = parseKeyValue(match.search);
13206 locationObj.$$hash = decodeURIComponent(match.hash);
13207
13208 // make sure path starts with '/';
13209 if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
13210 locationObj.$$path = '/' + locationObj.$$path;
13211 }
13212}
13213
13214function startsWith(str, search) {
13215 return str.slice(0, search.length) === search;
13216}
13217
13218/**
13219 *
13220 * @param {string} base
13221 * @param {string} url
13222 * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
13223 * the expected string.
13224 */
13225function stripBaseUrl(base, url) {
13226 if (startsWith(url, base)) {
13227 return url.substr(base.length);
13228 }
13229}
13230
13231
13232function stripHash(url) {
13233 var index = url.indexOf('#');
13234 return index === -1 ? url : url.substr(0, index);
13235}
13236
13237function trimEmptyHash(url) {
13238 return url.replace(/(#.+)|#$/, '$1');
13239}
13240
13241
13242function stripFile(url) {
13243 return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
13244}
13245
13246/* return the server only (scheme://host:port) */
13247function serverBase(url) {
13248 return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
13249}
13250
13251
13252/**
13253 * LocationHtml5Url represents a URL
13254 * This object is exposed as $location service when HTML5 mode is enabled and supported
13255 *
13256 * @constructor
13257 * @param {string} appBase application base URL
13258 * @param {string} appBaseNoFile application base URL stripped of any filename
13259 * @param {string} basePrefix URL path prefix
13260 */
13261function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
13262 this.$$html5 = true;
13263 basePrefix = basePrefix || '';
13264 parseAbsoluteUrl(appBase, this);
13265
13266
13267 /**
13268 * Parse given HTML5 (regular) URL string into properties
13269 * @param {string} url HTML5 URL
13270 * @private
13271 */
13272 this.$$parse = function(url) {
13273 var pathUrl = stripBaseUrl(appBaseNoFile, url);
13274 if (!isString(pathUrl)) {
13275 throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
13276 appBaseNoFile);
13277 }
13278
13279 parseAppUrl(pathUrl, this);
13280
13281 if (!this.$$path) {
13282 this.$$path = '/';
13283 }
13284
13285 this.$$compose();
13286 };
13287
13288 /**
13289 * Compose url and update `absUrl` property
13290 * @private
13291 */
13292 this.$$compose = function() {
13293 var search = toKeyValue(this.$$search),
13294 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
13295
13296 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
13297 this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
13298 };
13299
13300 this.$$parseLinkUrl = function(url, relHref) {
13301 if (relHref && relHref[0] === '#') {
13302 // special case for links to hash fragments:
13303 // keep the old url and only replace the hash fragment
13304 this.hash(relHref.slice(1));
13305 return true;
13306 }
13307 var appUrl, prevAppUrl;
13308 var rewrittenUrl;
13309
13310
13311 if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
13312 prevAppUrl = appUrl;
13313 if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
13314 rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
13315 } else {
13316 rewrittenUrl = appBase + prevAppUrl;
13317 }
13318 } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
13319 rewrittenUrl = appBaseNoFile + appUrl;
13320 } else if (appBaseNoFile === url + '/') {
13321 rewrittenUrl = appBaseNoFile;
13322 }
13323 if (rewrittenUrl) {
13324 this.$$parse(rewrittenUrl);
13325 }
13326 return !!rewrittenUrl;
13327 };
13328}
13329
13330
13331/**
13332 * LocationHashbangUrl represents URL
13333 * This object is exposed as $location service when developer doesn't opt into html5 mode.
13334 * It also serves as the base class for html5 mode fallback on legacy browsers.
13335 *
13336 * @constructor
13337 * @param {string} appBase application base URL
13338 * @param {string} appBaseNoFile application base URL stripped of any filename
13339 * @param {string} hashPrefix hashbang prefix
13340 */
13341function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
13342
13343 parseAbsoluteUrl(appBase, this);
13344
13345
13346 /**
13347 * Parse given hashbang URL into properties
13348 * @param {string} url Hashbang URL
13349 * @private
13350 */
13351 this.$$parse = function(url) {
13352 var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
13353 var withoutHashUrl;
13354
13355 if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
13356
13357 // The rest of the URL starts with a hash so we have
13358 // got either a hashbang path or a plain hash fragment
13359 withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
13360 if (isUndefined(withoutHashUrl)) {
13361 // There was no hashbang prefix so we just have a hash fragment
13362 withoutHashUrl = withoutBaseUrl;
13363 }
13364
13365 } else {
13366 // There was no hashbang path nor hash fragment:
13367 // If we are in HTML5 mode we use what is left as the path;
13368 // Otherwise we ignore what is left
13369 if (this.$$html5) {
13370 withoutHashUrl = withoutBaseUrl;
13371 } else {
13372 withoutHashUrl = '';
13373 if (isUndefined(withoutBaseUrl)) {
13374 appBase = url;
13375 this.replace();
13376 }
13377 }
13378 }
13379
13380 parseAppUrl(withoutHashUrl, this);
13381
13382 this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
13383
13384 this.$$compose();
13385
13386 /*
13387 * In Windows, on an anchor node on documents loaded from
13388 * the filesystem, the browser will return a pathname
13389 * prefixed with the drive name ('/C:/path') when a
13390 * pathname without a drive is set:
13391 * * a.setAttribute('href', '/foo')
13392 * * a.pathname === '/C:/foo' //true
13393 *
13394 * Inside of Angular, we're always using pathnames that
13395 * do not include drive names for routing.
13396 */
13397 function removeWindowsDriveName(path, url, base) {
13398 /*
13399 Matches paths for file protocol on windows,
13400 such as /C:/foo/bar, and captures only /foo/bar.
13401 */
13402 var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
13403
13404 var firstPathSegmentMatch;
13405
13406 //Get the relative path from the input URL.
13407 if (startsWith(url, base)) {
13408 url = url.replace(base, '');
13409 }
13410
13411 // The input URL intentionally contains a first path segment that ends with a colon.
13412 if (windowsFilePathExp.exec(url)) {
13413 return path;
13414 }
13415
13416 firstPathSegmentMatch = windowsFilePathExp.exec(path);
13417 return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
13418 }
13419 };
13420
13421 /**
13422 * Compose hashbang URL and update `absUrl` property
13423 * @private
13424 */
13425 this.$$compose = function() {
13426 var search = toKeyValue(this.$$search),
13427 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
13428
13429 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
13430 this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
13431 };
13432
13433 this.$$parseLinkUrl = function(url, relHref) {
13434 if (stripHash(appBase) === stripHash(url)) {
13435 this.$$parse(url);
13436 return true;
13437 }
13438 return false;
13439 };
13440}
13441
13442
13443/**
13444 * LocationHashbangUrl represents URL
13445 * This object is exposed as $location service when html5 history api is enabled but the browser
13446 * does not support it.
13447 *
13448 * @constructor
13449 * @param {string} appBase application base URL
13450 * @param {string} appBaseNoFile application base URL stripped of any filename
13451 * @param {string} hashPrefix hashbang prefix
13452 */
13453function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
13454 this.$$html5 = true;
13455 LocationHashbangUrl.apply(this, arguments);
13456
13457 this.$$parseLinkUrl = function(url, relHref) {
13458 if (relHref && relHref[0] === '#') {
13459 // special case for links to hash fragments:
13460 // keep the old url and only replace the hash fragment
13461 this.hash(relHref.slice(1));
13462 return true;
13463 }
13464
13465 var rewrittenUrl;
13466 var appUrl;
13467
13468 if (appBase === stripHash(url)) {
13469 rewrittenUrl = url;
13470 } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
13471 rewrittenUrl = appBase + hashPrefix + appUrl;
13472 } else if (appBaseNoFile === url + '/') {
13473 rewrittenUrl = appBaseNoFile;
13474 }
13475 if (rewrittenUrl) {
13476 this.$$parse(rewrittenUrl);
13477 }
13478 return !!rewrittenUrl;
13479 };
13480
13481 this.$$compose = function() {
13482 var search = toKeyValue(this.$$search),
13483 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
13484
13485 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
13486 // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
13487 this.$$absUrl = appBase + hashPrefix + this.$$url;
13488 };
13489
13490}
13491
13492
13493var locationPrototype = {
13494
13495 /**
13496 * Ensure absolute URL is initialized.
13497 * @private
13498 */
13499 $$absUrl:'',
13500
13501 /**
13502 * Are we in html5 mode?
13503 * @private
13504 */
13505 $$html5: false,
13506
13507 /**
13508 * Has any change been replacing?
13509 * @private
13510 */
13511 $$replace: false,
13512
13513 /**
13514 * @ngdoc method
13515 * @name $location#absUrl
13516 *
13517 * @description
13518 * This method is getter only.
13519 *
13520 * Return full URL representation with all segments encoded according to rules specified in
13521 * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
13522 *
13523 *
13524 * ```js
13525 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
13526 * var absUrl = $location.absUrl();
13527 * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
13528 * ```
13529 *
13530 * @return {string} full URL
13531 */
13532 absUrl: locationGetter('$$absUrl'),
13533
13534 /**
13535 * @ngdoc method
13536 * @name $location#url
13537 *
13538 * @description
13539 * This method is getter / setter.
13540 *
13541 * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
13542 *
13543 * Change path, search and hash, when called with parameter and return `$location`.
13544 *
13545 *
13546 * ```js
13547 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
13548 * var url = $location.url();
13549 * // => "/some/path?foo=bar&baz=xoxo"
13550 * ```
13551 *
13552 * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
13553 * @return {string} url
13554 */
13555 url: function(url) {
13556 if (isUndefined(url)) {
13557 return this.$$url;
13558 }
13559
13560 var match = PATH_MATCH.exec(url);
13561 if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
13562 if (match[2] || match[1] || url === '') this.search(match[3] || '');
13563 this.hash(match[5] || '');
13564
13565 return this;
13566 },
13567
13568 /**
13569 * @ngdoc method
13570 * @name $location#protocol
13571 *
13572 * @description
13573 * This method is getter only.
13574 *
13575 * Return protocol of current URL.
13576 *
13577 *
13578 * ```js
13579 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
13580 * var protocol = $location.protocol();
13581 * // => "http"
13582 * ```
13583 *
13584 * @return {string} protocol of current URL
13585 */
13586 protocol: locationGetter('$$protocol'),
13587
13588 /**
13589 * @ngdoc method
13590 * @name $location#host
13591 *
13592 * @description
13593 * This method is getter only.
13594 *
13595 * Return host of current URL.
13596 *
13597 * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
13598 *
13599 *
13600 * ```js
13601 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
13602 * var host = $location.host();
13603 * // => "example.com"
13604 *
13605 * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
13606 * host = $location.host();
13607 * // => "example.com"
13608 * host = location.host;
13609 * // => "example.com:8080"
13610 * ```
13611 *
13612 * @return {string} host of current URL.
13613 */
13614 host: locationGetter('$$host'),
13615
13616 /**
13617 * @ngdoc method
13618 * @name $location#port
13619 *
13620 * @description
13621 * This method is getter only.
13622 *
13623 * Return port of current URL.
13624 *
13625 *
13626 * ```js
13627 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
13628 * var port = $location.port();
13629 * // => 80
13630 * ```
13631 *
13632 * @return {Number} port
13633 */
13634 port: locationGetter('$$port'),
13635
13636 /**
13637 * @ngdoc method
13638 * @name $location#path
13639 *
13640 * @description
13641 * This method is getter / setter.
13642 *
13643 * Return path of current URL when called without any parameter.
13644 *
13645 * Change path when called with parameter and return `$location`.
13646 *
13647 * Note: Path should always begin with forward slash (/), this method will add the forward slash
13648 * if it is missing.
13649 *
13650 *
13651 * ```js
13652 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
13653 * var path = $location.path();
13654 * // => "/some/path"
13655 * ```
13656 *
13657 * @param {(string|number)=} path New path
13658 * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
13659 */
13660 path: locationGetterSetter('$$path', function(path) {
13661 path = path !== null ? path.toString() : '';
13662 return path.charAt(0) === '/' ? path : '/' + path;
13663 }),
13664
13665 /**
13666 * @ngdoc method
13667 * @name $location#search
13668 *
13669 * @description
13670 * This method is getter / setter.
13671 *
13672 * Return search part (as object) of current URL when called without any parameter.
13673 *
13674 * Change search part when called with parameter and return `$location`.
13675 *
13676 *
13677 * ```js
13678 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
13679 * var searchObject = $location.search();
13680 * // => {foo: 'bar', baz: 'xoxo'}
13681 *
13682 * // set foo to 'yipee'
13683 * $location.search('foo', 'yipee');
13684 * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
13685 * ```
13686 *
13687 * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
13688 * hash object.
13689 *
13690 * When called with a single argument the method acts as a setter, setting the `search` component
13691 * of `$location` to the specified value.
13692 *
13693 * If the argument is a hash object containing an array of values, these values will be encoded
13694 * as duplicate search parameters in the URL.
13695 *
13696 * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
13697 * will override only a single search property.
13698 *
13699 * If `paramValue` is an array, it will override the property of the `search` component of
13700 * `$location` specified via the first argument.
13701 *
13702 * If `paramValue` is `null`, the property specified via the first argument will be deleted.
13703 *
13704 * If `paramValue` is `true`, the property specified via the first argument will be added with no
13705 * value nor trailing equal sign.
13706 *
13707 * @return {Object} If called with no arguments returns the parsed `search` object. If called with
13708 * one or more arguments returns `$location` object itself.
13709 */
13710 search: function(search, paramValue) {
13711 switch (arguments.length) {
13712 case 0:
13713 return this.$$search;
13714 case 1:
13715 if (isString(search) || isNumber(search)) {
13716 search = search.toString();
13717 this.$$search = parseKeyValue(search);
13718 } else if (isObject(search)) {
13719 search = copy(search, {});
13720 // remove object undefined or null properties
13721 forEach(search, function(value, key) {
13722 if (value == null) delete search[key];
13723 });
13724
13725 this.$$search = search;
13726 } else {
13727 throw $locationMinErr('isrcharg',
13728 'The first argument of the `$location#search()` call must be a string or an object.');
13729 }
13730 break;
13731 default:
13732 if (isUndefined(paramValue) || paramValue === null) {
13733 delete this.$$search[search];
13734 } else {
13735 this.$$search[search] = paramValue;
13736 }
13737 }
13738
13739 this.$$compose();
13740 return this;
13741 },
13742
13743 /**
13744 * @ngdoc method
13745 * @name $location#hash
13746 *
13747 * @description
13748 * This method is getter / setter.
13749 *
13750 * Returns the hash fragment when called without any parameters.
13751 *
13752 * Changes the hash fragment when called with a parameter and returns `$location`.
13753 *
13754 *
13755 * ```js
13756 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
13757 * var hash = $location.hash();
13758 * // => "hashValue"
13759 * ```
13760 *
13761 * @param {(string|number)=} hash New hash fragment
13762 * @return {string} hash
13763 */
13764 hash: locationGetterSetter('$$hash', function(hash) {
13765 return hash !== null ? hash.toString() : '';
13766 }),
13767
13768 /**
13769 * @ngdoc method
13770 * @name $location#replace
13771 *
13772 * @description
13773 * If called, all changes to $location during the current `$digest` will replace the current history
13774 * record, instead of adding a new one.
13775 */
13776 replace: function() {
13777 this.$$replace = true;
13778 return this;
13779 }
13780};
13781
13782forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
13783 Location.prototype = Object.create(locationPrototype);
13784
13785 /**
13786 * @ngdoc method
13787 * @name $location#state
13788 *
13789 * @description
13790 * This method is getter / setter.
13791 *
13792 * Return the history state object when called without any parameter.
13793 *
13794 * Change the history state object when called with one parameter and return `$location`.
13795 * The state object is later passed to `pushState` or `replaceState`.
13796 *
13797 * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
13798 * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
13799 * older browsers (like IE9 or Android < 4.0), don't use this method.
13800 *
13801 * @param {object=} state State object for pushState or replaceState
13802 * @return {object} state
13803 */
13804 Location.prototype.state = function(state) {
13805 if (!arguments.length) {
13806 return this.$$state;
13807 }
13808
13809 if (Location !== LocationHtml5Url || !this.$$html5) {
13810 throw $locationMinErr('nostate', 'History API state support is available only ' +
13811 'in HTML5 mode and only in browsers supporting HTML5 History API');
13812 }
13813 // The user might modify `stateObject` after invoking `$location.state(stateObject)`
13814 // but we're changing the $$state reference to $browser.state() during the $digest
13815 // so the modification window is narrow.
13816 this.$$state = isUndefined(state) ? null : state;
13817
13818 return this;
13819 };
13820});
13821
13822
13823function locationGetter(property) {
13824 return /** @this */ function() {
13825 return this[property];
13826 };
13827}
13828
13829
13830function locationGetterSetter(property, preprocess) {
13831 return /** @this */ function(value) {
13832 if (isUndefined(value)) {
13833 return this[property];
13834 }
13835
13836 this[property] = preprocess(value);
13837 this.$$compose();
13838
13839 return this;
13840 };
13841}
13842
13843
13844/**
13845 * @ngdoc service
13846 * @name $location
13847 *
13848 * @requires $rootElement
13849 *
13850 * @description
13851 * The $location service parses the URL in the browser address bar (based on the
13852 * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
13853 * available to your application. Changes to the URL in the address bar are reflected into
13854 * $location service and changes to $location are reflected into the browser address bar.
13855 *
13856 * **The $location service:**
13857 *
13858 * - Exposes the current URL in the browser address bar, so you can
13859 * - Watch and observe the URL.
13860 * - Change the URL.
13861 * - Synchronizes the URL with the browser when the user
13862 * - Changes the address bar.
13863 * - Clicks the back or forward button (or clicks a History link).
13864 * - Clicks on a link.
13865 * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
13866 *
13867 * For more information see {@link guide/$location Developer Guide: Using $location}
13868 */
13869
13870/**
13871 * @ngdoc provider
13872 * @name $locationProvider
13873 * @this
13874 *
13875 * @description
13876 * Use the `$locationProvider` to configure how the application deep linking paths are stored.
13877 */
13878function $LocationProvider() {
13879 var hashPrefix = '!',
13880 html5Mode = {
13881 enabled: false,
13882 requireBase: true,
13883 rewriteLinks: true
13884 };
13885
13886 /**
13887 * @ngdoc method
13888 * @name $locationProvider#hashPrefix
13889 * @description
13890 * The default value for the prefix is `'!'`.
13891 * @param {string=} prefix Prefix for hash part (containing path and search)
13892 * @returns {*} current value if used as getter or itself (chaining) if used as setter
13893 */
13894 this.hashPrefix = function(prefix) {
13895 if (isDefined(prefix)) {
13896 hashPrefix = prefix;
13897 return this;
13898 } else {
13899 return hashPrefix;
13900 }
13901 };
13902
13903 /**
13904 * @ngdoc method
13905 * @name $locationProvider#html5Mode
13906 * @description
13907 * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
13908 * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
13909 * properties:
13910 * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
13911 * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
13912 * support `pushState`.
13913 * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
13914 * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
13915 * true, and a base tag is not present, an error will be thrown when `$location` is injected.
13916 * See the {@link guide/$location $location guide for more information}
13917 * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
13918 * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
13919 * only happen on links with an attribute that matches the given string. For example, if set
13920 * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
13921 * Note that [attribute name normalization](guide/directive#normalization) does not apply
13922 * here, so `'internalLink'` will **not** match `'internal-link'`.
13923 *
13924 * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
13925 */
13926 this.html5Mode = function(mode) {
13927 if (isBoolean(mode)) {
13928 html5Mode.enabled = mode;
13929 return this;
13930 } else if (isObject(mode)) {
13931
13932 if (isBoolean(mode.enabled)) {
13933 html5Mode.enabled = mode.enabled;
13934 }
13935
13936 if (isBoolean(mode.requireBase)) {
13937 html5Mode.requireBase = mode.requireBase;
13938 }
13939
13940 if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
13941 html5Mode.rewriteLinks = mode.rewriteLinks;
13942 }
13943
13944 return this;
13945 } else {
13946 return html5Mode;
13947 }
13948 };
13949
13950 /**
13951 * @ngdoc event
13952 * @name $location#$locationChangeStart
13953 * @eventType broadcast on root scope
13954 * @description
13955 * Broadcasted before a URL will change.
13956 *
13957 * This change can be prevented by calling
13958 * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
13959 * details about event object. Upon successful change
13960 * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
13961 *
13962 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
13963 * the browser supports the HTML5 History API.
13964 *
13965 * @param {Object} angularEvent Synthetic event object.
13966 * @param {string} newUrl New URL
13967 * @param {string=} oldUrl URL that was before it was changed.
13968 * @param {string=} newState New history state object
13969 * @param {string=} oldState History state object that was before it was changed.
13970 */
13971
13972 /**
13973 * @ngdoc event
13974 * @name $location#$locationChangeSuccess
13975 * @eventType broadcast on root scope
13976 * @description
13977 * Broadcasted after a URL was changed.
13978 *
13979 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
13980 * the browser supports the HTML5 History API.
13981 *
13982 * @param {Object} angularEvent Synthetic event object.
13983 * @param {string} newUrl New URL
13984 * @param {string=} oldUrl URL that was before it was changed.
13985 * @param {string=} newState New history state object
13986 * @param {string=} oldState History state object that was before it was changed.
13987 */
13988
13989 this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
13990 function($rootScope, $browser, $sniffer, $rootElement, $window) {
13991 var $location,
13992 LocationMode,
13993 baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
13994 initialUrl = $browser.url(),
13995 appBase;
13996
13997 if (html5Mode.enabled) {
13998 if (!baseHref && html5Mode.requireBase) {
13999 throw $locationMinErr('nobase',
14000 '$location in HTML5 mode requires a <base> tag to be present!');
14001 }
14002 appBase = serverBase(initialUrl) + (baseHref || '/');
14003 LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
14004 } else {
14005 appBase = stripHash(initialUrl);
14006 LocationMode = LocationHashbangUrl;
14007 }
14008 var appBaseNoFile = stripFile(appBase);
14009
14010 $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
14011 $location.$$parseLinkUrl(initialUrl, initialUrl);
14012
14013 $location.$$state = $browser.state();
14014
14015 var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
14016
14017 function setBrowserUrlWithFallback(url, replace, state) {
14018 var oldUrl = $location.url();
14019 var oldState = $location.$$state;
14020 try {
14021 $browser.url(url, replace, state);
14022
14023 // Make sure $location.state() returns referentially identical (not just deeply equal)
14024 // state object; this makes possible quick checking if the state changed in the digest
14025 // loop. Checking deep equality would be too expensive.
14026 $location.$$state = $browser.state();
14027 } catch (e) {
14028 // Restore old values if pushState fails
14029 $location.url(oldUrl);
14030 $location.$$state = oldState;
14031
14032 throw e;
14033 }
14034 }
14035
14036 $rootElement.on('click', function(event) {
14037 var rewriteLinks = html5Mode.rewriteLinks;
14038 // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
14039 // currently we open nice url link and redirect then
14040
14041 if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
14042
14043 var elm = jqLite(event.target);
14044
14045 // traverse the DOM up to find first A tag
14046 while (nodeName_(elm[0]) !== 'a') {
14047 // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
14048 if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
14049 }
14050
14051 if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
14052
14053 var absHref = elm.prop('href');
14054 // get the actual href attribute - see
14055 // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
14056 var relHref = elm.attr('href') || elm.attr('xlink:href');
14057
14058 if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
14059 // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
14060 // an animation.
14061 absHref = urlResolve(absHref.animVal).href;
14062 }
14063
14064 // Ignore when url is started with javascript: or mailto:
14065 if (IGNORE_URI_REGEXP.test(absHref)) return;
14066
14067 if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
14068 if ($location.$$parseLinkUrl(absHref, relHref)) {
14069 // We do a preventDefault for all urls that are part of the angular application,
14070 // in html5mode and also without, so that we are able to abort navigation without
14071 // getting double entries in the location history.
14072 event.preventDefault();
14073 // update location manually
14074 if ($location.absUrl() !== $browser.url()) {
14075 $rootScope.$apply();
14076 // hack to work around FF6 bug 684208 when scenario runner clicks on links
14077 $window.angular['ff-684208-preventDefault'] = true;
14078 }
14079 }
14080 }
14081 });
14082
14083
14084 // rewrite hashbang url <> html5 url
14085 if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
14086 $browser.url($location.absUrl(), true);
14087 }
14088
14089 var initializing = true;
14090
14091 // update $location when $browser url changes
14092 $browser.onUrlChange(function(newUrl, newState) {
14093
14094 if (!startsWith(newUrl, appBaseNoFile)) {
14095 // If we are navigating outside of the app then force a reload
14096 $window.location.href = newUrl;
14097 return;
14098 }
14099
14100 $rootScope.$evalAsync(function() {
14101 var oldUrl = $location.absUrl();
14102 var oldState = $location.$$state;
14103 var defaultPrevented;
14104 newUrl = trimEmptyHash(newUrl);
14105 $location.$$parse(newUrl);
14106 $location.$$state = newState;
14107
14108 defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
14109 newState, oldState).defaultPrevented;
14110
14111 // if the location was changed by a `$locationChangeStart` handler then stop
14112 // processing this location change
14113 if ($location.absUrl() !== newUrl) return;
14114
14115 if (defaultPrevented) {
14116 $location.$$parse(oldUrl);
14117 $location.$$state = oldState;
14118 setBrowserUrlWithFallback(oldUrl, false, oldState);
14119 } else {
14120 initializing = false;
14121 afterLocationChange(oldUrl, oldState);
14122 }
14123 });
14124 if (!$rootScope.$$phase) $rootScope.$digest();
14125 });
14126
14127 // update browser
14128 $rootScope.$watch(function $locationWatch() {
14129 var oldUrl = trimEmptyHash($browser.url());
14130 var newUrl = trimEmptyHash($location.absUrl());
14131 var oldState = $browser.state();
14132 var currentReplace = $location.$$replace;
14133 var urlOrStateChanged = oldUrl !== newUrl ||
14134 ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
14135
14136 if (initializing || urlOrStateChanged) {
14137 initializing = false;
14138
14139 $rootScope.$evalAsync(function() {
14140 var newUrl = $location.absUrl();
14141 var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
14142 $location.$$state, oldState).defaultPrevented;
14143
14144 // if the location was changed by a `$locationChangeStart` handler then stop
14145 // processing this location change
14146 if ($location.absUrl() !== newUrl) return;
14147
14148 if (defaultPrevented) {
14149 $location.$$parse(oldUrl);
14150 $location.$$state = oldState;
14151 } else {
14152 if (urlOrStateChanged) {
14153 setBrowserUrlWithFallback(newUrl, currentReplace,
14154 oldState === $location.$$state ? null : $location.$$state);
14155 }
14156 afterLocationChange(oldUrl, oldState);
14157 }
14158 });
14159 }
14160
14161 $location.$$replace = false;
14162
14163 // we don't need to return anything because $evalAsync will make the digest loop dirty when
14164 // there is a change
14165 });
14166
14167 return $location;
14168
14169 function afterLocationChange(oldUrl, oldState) {
14170 $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
14171 $location.$$state, oldState);
14172 }
14173}];
14174}
14175
14176/**
14177 * @ngdoc service
14178 * @name $log
14179 * @requires $window
14180 *
14181 * @description
14182 * Simple service for logging. Default implementation safely writes the message
14183 * into the browser's console (if present).
14184 *
14185 * The main purpose of this service is to simplify debugging and troubleshooting.
14186 *
14187 * The default is to log `debug` messages. You can use
14188 * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
14189 *
14190 * @example
14191 <example module="logExample" name="log-service">
14192 <file name="script.js">
14193 angular.module('logExample', [])
14194 .controller('LogController', ['$scope', '$log', function($scope, $log) {
14195 $scope.$log = $log;
14196 $scope.message = 'Hello World!';
14197 }]);
14198 </file>
14199 <file name="index.html">
14200 <div ng-controller="LogController">
14201 <p>Reload this page with open console, enter text and hit the log button...</p>
14202 <label>Message:
14203 <input type="text" ng-model="message" /></label>
14204 <button ng-click="$log.log(message)">log</button>
14205 <button ng-click="$log.warn(message)">warn</button>
14206 <button ng-click="$log.info(message)">info</button>
14207 <button ng-click="$log.error(message)">error</button>
14208 <button ng-click="$log.debug(message)">debug</button>
14209 </div>
14210 </file>
14211 </example>
14212 */
14213
14214/**
14215 * @ngdoc provider
14216 * @name $logProvider
14217 * @this
14218 *
14219 * @description
14220 * Use the `$logProvider` to configure how the application logs messages
14221 */
14222function $LogProvider() {
14223 var debug = true,
14224 self = this;
14225
14226 /**
14227 * @ngdoc method
14228 * @name $logProvider#debugEnabled
14229 * @description
14230 * @param {boolean=} flag enable or disable debug level messages
14231 * @returns {*} current value if used as getter or itself (chaining) if used as setter
14232 */
14233 this.debugEnabled = function(flag) {
14234 if (isDefined(flag)) {
14235 debug = flag;
14236 return this;
14237 } else {
14238 return debug;
14239 }
14240 };
14241
14242 this.$get = ['$window', function($window) {
14243 return {
14244 /**
14245 * @ngdoc method
14246 * @name $log#log
14247 *
14248 * @description
14249 * Write a log message
14250 */
14251 log: consoleLog('log'),
14252
14253 /**
14254 * @ngdoc method
14255 * @name $log#info
14256 *
14257 * @description
14258 * Write an information message
14259 */
14260 info: consoleLog('info'),
14261
14262 /**
14263 * @ngdoc method
14264 * @name $log#warn
14265 *
14266 * @description
14267 * Write a warning message
14268 */
14269 warn: consoleLog('warn'),
14270
14271 /**
14272 * @ngdoc method
14273 * @name $log#error
14274 *
14275 * @description
14276 * Write an error message
14277 */
14278 error: consoleLog('error'),
14279
14280 /**
14281 * @ngdoc method
14282 * @name $log#debug
14283 *
14284 * @description
14285 * Write a debug message
14286 */
14287 debug: (function() {
14288 var fn = consoleLog('debug');
14289
14290 return function() {
14291 if (debug) {
14292 fn.apply(self, arguments);
14293 }
14294 };
14295 })()
14296 };
14297
14298 function formatError(arg) {
14299 if (arg instanceof Error) {
14300 if (arg.stack) {
14301 arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
14302 ? 'Error: ' + arg.message + '\n' + arg.stack
14303 : arg.stack;
14304 } else if (arg.sourceURL) {
14305 arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
14306 }
14307 }
14308 return arg;
14309 }
14310
14311 function consoleLog(type) {
14312 var console = $window.console || {},
14313 logFn = console[type] || console.log || noop,
14314 hasApply = false;
14315
14316 // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
14317 // The reason behind this is that console.log has type "object" in IE8...
14318 try {
14319 hasApply = !!logFn.apply;
14320 } catch (e) { /* empty */ }
14321
14322 if (hasApply) {
14323 return function() {
14324 var args = [];
14325 forEach(arguments, function(arg) {
14326 args.push(formatError(arg));
14327 });
14328 return logFn.apply(console, args);
14329 };
14330 }
14331
14332 // we are IE which either doesn't have window.console => this is noop and we do nothing,
14333 // or we are IE where console.log doesn't have apply so we log at least first 2 args
14334 return function(arg1, arg2) {
14335 logFn(arg1, arg2 == null ? '' : arg2);
14336 };
14337 }
14338 }];
14339}
14340
14341/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
14342 * Any commits to this file should be reviewed with security in mind. *
14343 * Changes to this file can potentially create security vulnerabilities. *
14344 * An approval from 2 Core members with history of modifying *
14345 * this file is required. *
14346 * *
14347 * Does the change somehow allow for arbitrary javascript to be executed? *
14348 * Or allows for someone to change the prototype of built-in objects? *
14349 * Or gives undesired access to variables likes document or window? *
14350 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
14351
14352var $parseMinErr = minErr('$parse');
14353
14354var objectValueOf = {}.constructor.prototype.valueOf;
14355
14356// Sandboxing Angular Expressions
14357// ------------------------------
14358// Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
14359// various means such as obtaining a reference to native JS functions like the Function constructor.
14360//
14361// As an example, consider the following Angular expression:
14362//
14363// {}.toString.constructor('alert("evil JS code")')
14364//
14365// It is important to realize that if you create an expression from a string that contains user provided
14366// content then it is possible that your application contains a security vulnerability to an XSS style attack.
14367//
14368// See https://docs.angularjs.org/guide/security
14369
14370
14371function getStringValue(name) {
14372 // Property names must be strings. This means that non-string objects cannot be used
14373 // as keys in an object. Any non-string object, including a number, is typecasted
14374 // into a string via the toString method.
14375 // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
14376 //
14377 // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
14378 // to a string. It's not always possible. If `name` is an object and its `toString` method is
14379 // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
14380 //
14381 // TypeError: Cannot convert object to primitive value
14382 //
14383 // For performance reasons, we don't catch this error here and allow it to propagate up the call
14384 // stack. Note that you'll get the same error in JavaScript if you try to access a property using
14385 // such a 'broken' object as a key.
14386 return name + '';
14387}
14388
14389
14390var OPERATORS = createMap();
14391forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
14392var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
14393
14394
14395/////////////////////////////////////////
14396
14397
14398/**
14399 * @constructor
14400 */
14401var Lexer = function Lexer(options) {
14402 this.options = options;
14403};
14404
14405Lexer.prototype = {
14406 constructor: Lexer,
14407
14408 lex: function(text) {
14409 this.text = text;
14410 this.index = 0;
14411 this.tokens = [];
14412
14413 while (this.index < this.text.length) {
14414 var ch = this.text.charAt(this.index);
14415 if (ch === '"' || ch === '\'') {
14416 this.readString(ch);
14417 } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
14418 this.readNumber();
14419 } else if (this.isIdentifierStart(this.peekMultichar())) {
14420 this.readIdent();
14421 } else if (this.is(ch, '(){}[].,;:?')) {
14422 this.tokens.push({index: this.index, text: ch});
14423 this.index++;
14424 } else if (this.isWhitespace(ch)) {
14425 this.index++;
14426 } else {
14427 var ch2 = ch + this.peek();
14428 var ch3 = ch2 + this.peek(2);
14429 var op1 = OPERATORS[ch];
14430 var op2 = OPERATORS[ch2];
14431 var op3 = OPERATORS[ch3];
14432 if (op1 || op2 || op3) {
14433 var token = op3 ? ch3 : (op2 ? ch2 : ch);
14434 this.tokens.push({index: this.index, text: token, operator: true});
14435 this.index += token.length;
14436 } else {
14437 this.throwError('Unexpected next character ', this.index, this.index + 1);
14438 }
14439 }
14440 }
14441 return this.tokens;
14442 },
14443
14444 is: function(ch, chars) {
14445 return chars.indexOf(ch) !== -1;
14446 },
14447
14448 peek: function(i) {
14449 var num = i || 1;
14450 return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
14451 },
14452
14453 isNumber: function(ch) {
14454 return ('0' <= ch && ch <= '9') && typeof ch === 'string';
14455 },
14456
14457 isWhitespace: function(ch) {
14458 // IE treats non-breaking space as \u00A0
14459 return (ch === ' ' || ch === '\r' || ch === '\t' ||
14460 ch === '\n' || ch === '\v' || ch === '\u00A0');
14461 },
14462
14463 isIdentifierStart: function(ch) {
14464 return this.options.isIdentifierStart ?
14465 this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
14466 this.isValidIdentifierStart(ch);
14467 },
14468
14469 isValidIdentifierStart: function(ch) {
14470 return ('a' <= ch && ch <= 'z' ||
14471 'A' <= ch && ch <= 'Z' ||
14472 '_' === ch || ch === '$');
14473 },
14474
14475 isIdentifierContinue: function(ch) {
14476 return this.options.isIdentifierContinue ?
14477 this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
14478 this.isValidIdentifierContinue(ch);
14479 },
14480
14481 isValidIdentifierContinue: function(ch, cp) {
14482 return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
14483 },
14484
14485 codePointAt: function(ch) {
14486 if (ch.length === 1) return ch.charCodeAt(0);
14487 // eslint-disable-next-line no-bitwise
14488 return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
14489 },
14490
14491 peekMultichar: function() {
14492 var ch = this.text.charAt(this.index);
14493 var peek = this.peek();
14494 if (!peek) {
14495 return ch;
14496 }
14497 var cp1 = ch.charCodeAt(0);
14498 var cp2 = peek.charCodeAt(0);
14499 if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
14500 return ch + peek;
14501 }
14502 return ch;
14503 },
14504
14505 isExpOperator: function(ch) {
14506 return (ch === '-' || ch === '+' || this.isNumber(ch));
14507 },
14508
14509 throwError: function(error, start, end) {
14510 end = end || this.index;
14511 var colStr = (isDefined(start)
14512 ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
14513 : ' ' + end);
14514 throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
14515 error, colStr, this.text);
14516 },
14517
14518 readNumber: function() {
14519 var number = '';
14520 var start = this.index;
14521 while (this.index < this.text.length) {
14522 var ch = lowercase(this.text.charAt(this.index));
14523 if (ch === '.' || this.isNumber(ch)) {
14524 number += ch;
14525 } else {
14526 var peekCh = this.peek();
14527 if (ch === 'e' && this.isExpOperator(peekCh)) {
14528 number += ch;
14529 } else if (this.isExpOperator(ch) &&
14530 peekCh && this.isNumber(peekCh) &&
14531 number.charAt(number.length - 1) === 'e') {
14532 number += ch;
14533 } else if (this.isExpOperator(ch) &&
14534 (!peekCh || !this.isNumber(peekCh)) &&
14535 number.charAt(number.length - 1) === 'e') {
14536 this.throwError('Invalid exponent');
14537 } else {
14538 break;
14539 }
14540 }
14541 this.index++;
14542 }
14543 this.tokens.push({
14544 index: start,
14545 text: number,
14546 constant: true,
14547 value: Number(number)
14548 });
14549 },
14550
14551 readIdent: function() {
14552 var start = this.index;
14553 this.index += this.peekMultichar().length;
14554 while (this.index < this.text.length) {
14555 var ch = this.peekMultichar();
14556 if (!this.isIdentifierContinue(ch)) {
14557 break;
14558 }
14559 this.index += ch.length;
14560 }
14561 this.tokens.push({
14562 index: start,
14563 text: this.text.slice(start, this.index),
14564 identifier: true
14565 });
14566 },
14567
14568 readString: function(quote) {
14569 var start = this.index;
14570 this.index++;
14571 var string = '';
14572 var rawString = quote;
14573 var escape = false;
14574 while (this.index < this.text.length) {
14575 var ch = this.text.charAt(this.index);
14576 rawString += ch;
14577 if (escape) {
14578 if (ch === 'u') {
14579 var hex = this.text.substring(this.index + 1, this.index + 5);
14580 if (!hex.match(/[\da-f]{4}/i)) {
14581 this.throwError('Invalid unicode escape [\\u' + hex + ']');
14582 }
14583 this.index += 4;
14584 string += String.fromCharCode(parseInt(hex, 16));
14585 } else {
14586 var rep = ESCAPE[ch];
14587 string = string + (rep || ch);
14588 }
14589 escape = false;
14590 } else if (ch === '\\') {
14591 escape = true;
14592 } else if (ch === quote) {
14593 this.index++;
14594 this.tokens.push({
14595 index: start,
14596 text: rawString,
14597 constant: true,
14598 value: string
14599 });
14600 return;
14601 } else {
14602 string += ch;
14603 }
14604 this.index++;
14605 }
14606 this.throwError('Unterminated quote', start);
14607 }
14608};
14609
14610var AST = function AST(lexer, options) {
14611 this.lexer = lexer;
14612 this.options = options;
14613};
14614
14615AST.Program = 'Program';
14616AST.ExpressionStatement = 'ExpressionStatement';
14617AST.AssignmentExpression = 'AssignmentExpression';
14618AST.ConditionalExpression = 'ConditionalExpression';
14619AST.LogicalExpression = 'LogicalExpression';
14620AST.BinaryExpression = 'BinaryExpression';
14621AST.UnaryExpression = 'UnaryExpression';
14622AST.CallExpression = 'CallExpression';
14623AST.MemberExpression = 'MemberExpression';
14624AST.Identifier = 'Identifier';
14625AST.Literal = 'Literal';
14626AST.ArrayExpression = 'ArrayExpression';
14627AST.Property = 'Property';
14628AST.ObjectExpression = 'ObjectExpression';
14629AST.ThisExpression = 'ThisExpression';
14630AST.LocalsExpression = 'LocalsExpression';
14631
14632// Internal use only
14633AST.NGValueParameter = 'NGValueParameter';
14634
14635AST.prototype = {
14636 ast: function(text) {
14637 this.text = text;
14638 this.tokens = this.lexer.lex(text);
14639
14640 var value = this.program();
14641
14642 if (this.tokens.length !== 0) {
14643 this.throwError('is an unexpected token', this.tokens[0]);
14644 }
14645
14646 return value;
14647 },
14648
14649 program: function() {
14650 var body = [];
14651 while (true) {
14652 if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
14653 body.push(this.expressionStatement());
14654 if (!this.expect(';')) {
14655 return { type: AST.Program, body: body};
14656 }
14657 }
14658 },
14659
14660 expressionStatement: function() {
14661 return { type: AST.ExpressionStatement, expression: this.filterChain() };
14662 },
14663
14664 filterChain: function() {
14665 var left = this.expression();
14666 while (this.expect('|')) {
14667 left = this.filter(left);
14668 }
14669 return left;
14670 },
14671
14672 expression: function() {
14673 return this.assignment();
14674 },
14675
14676 assignment: function() {
14677 var result = this.ternary();
14678 if (this.expect('=')) {
14679 if (!isAssignable(result)) {
14680 throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
14681 }
14682
14683 result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
14684 }
14685 return result;
14686 },
14687
14688 ternary: function() {
14689 var test = this.logicalOR();
14690 var alternate;
14691 var consequent;
14692 if (this.expect('?')) {
14693 alternate = this.expression();
14694 if (this.consume(':')) {
14695 consequent = this.expression();
14696 return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
14697 }
14698 }
14699 return test;
14700 },
14701
14702 logicalOR: function() {
14703 var left = this.logicalAND();
14704 while (this.expect('||')) {
14705 left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
14706 }
14707 return left;
14708 },
14709
14710 logicalAND: function() {
14711 var left = this.equality();
14712 while (this.expect('&&')) {
14713 left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
14714 }
14715 return left;
14716 },
14717
14718 equality: function() {
14719 var left = this.relational();
14720 var token;
14721 while ((token = this.expect('==','!=','===','!=='))) {
14722 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
14723 }
14724 return left;
14725 },
14726
14727 relational: function() {
14728 var left = this.additive();
14729 var token;
14730 while ((token = this.expect('<', '>', '<=', '>='))) {
14731 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
14732 }
14733 return left;
14734 },
14735
14736 additive: function() {
14737 var left = this.multiplicative();
14738 var token;
14739 while ((token = this.expect('+','-'))) {
14740 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
14741 }
14742 return left;
14743 },
14744
14745 multiplicative: function() {
14746 var left = this.unary();
14747 var token;
14748 while ((token = this.expect('*','/','%'))) {
14749 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
14750 }
14751 return left;
14752 },
14753
14754 unary: function() {
14755 var token;
14756 if ((token = this.expect('+', '-', '!'))) {
14757 return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
14758 } else {
14759 return this.primary();
14760 }
14761 },
14762
14763 primary: function() {
14764 var primary;
14765 if (this.expect('(')) {
14766 primary = this.filterChain();
14767 this.consume(')');
14768 } else if (this.expect('[')) {
14769 primary = this.arrayDeclaration();
14770 } else if (this.expect('{')) {
14771 primary = this.object();
14772 } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
14773 primary = copy(this.selfReferential[this.consume().text]);
14774 } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
14775 primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
14776 } else if (this.peek().identifier) {
14777 primary = this.identifier();
14778 } else if (this.peek().constant) {
14779 primary = this.constant();
14780 } else {
14781 this.throwError('not a primary expression', this.peek());
14782 }
14783
14784 var next;
14785 while ((next = this.expect('(', '[', '.'))) {
14786 if (next.text === '(') {
14787 primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
14788 this.consume(')');
14789 } else if (next.text === '[') {
14790 primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
14791 this.consume(']');
14792 } else if (next.text === '.') {
14793 primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
14794 } else {
14795 this.throwError('IMPOSSIBLE');
14796 }
14797 }
14798 return primary;
14799 },
14800
14801 filter: function(baseExpression) {
14802 var args = [baseExpression];
14803 var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
14804
14805 while (this.expect(':')) {
14806 args.push(this.expression());
14807 }
14808
14809 return result;
14810 },
14811
14812 parseArguments: function() {
14813 var args = [];
14814 if (this.peekToken().text !== ')') {
14815 do {
14816 args.push(this.filterChain());
14817 } while (this.expect(','));
14818 }
14819 return args;
14820 },
14821
14822 identifier: function() {
14823 var token = this.consume();
14824 if (!token.identifier) {
14825 this.throwError('is not a valid identifier', token);
14826 }
14827 return { type: AST.Identifier, name: token.text };
14828 },
14829
14830 constant: function() {
14831 // TODO check that it is a constant
14832 return { type: AST.Literal, value: this.consume().value };
14833 },
14834
14835 arrayDeclaration: function() {
14836 var elements = [];
14837 if (this.peekToken().text !== ']') {
14838 do {
14839 if (this.peek(']')) {
14840 // Support trailing commas per ES5.1.
14841 break;
14842 }
14843 elements.push(this.expression());
14844 } while (this.expect(','));
14845 }
14846 this.consume(']');
14847
14848 return { type: AST.ArrayExpression, elements: elements };
14849 },
14850
14851 object: function() {
14852 var properties = [], property;
14853 if (this.peekToken().text !== '}') {
14854 do {
14855 if (this.peek('}')) {
14856 // Support trailing commas per ES5.1.
14857 break;
14858 }
14859 property = {type: AST.Property, kind: 'init'};
14860 if (this.peek().constant) {
14861 property.key = this.constant();
14862 property.computed = false;
14863 this.consume(':');
14864 property.value = this.expression();
14865 } else if (this.peek().identifier) {
14866 property.key = this.identifier();
14867 property.computed = false;
14868 if (this.peek(':')) {
14869 this.consume(':');
14870 property.value = this.expression();
14871 } else {
14872 property.value = property.key;
14873 }
14874 } else if (this.peek('[')) {
14875 this.consume('[');
14876 property.key = this.expression();
14877 this.consume(']');
14878 property.computed = true;
14879 this.consume(':');
14880 property.value = this.expression();
14881 } else {
14882 this.throwError('invalid key', this.peek());
14883 }
14884 properties.push(property);
14885 } while (this.expect(','));
14886 }
14887 this.consume('}');
14888
14889 return {type: AST.ObjectExpression, properties: properties };
14890 },
14891
14892 throwError: function(msg, token) {
14893 throw $parseMinErr('syntax',
14894 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
14895 token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
14896 },
14897
14898 consume: function(e1) {
14899 if (this.tokens.length === 0) {
14900 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
14901 }
14902
14903 var token = this.expect(e1);
14904 if (!token) {
14905 this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
14906 }
14907 return token;
14908 },
14909
14910 peekToken: function() {
14911 if (this.tokens.length === 0) {
14912 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
14913 }
14914 return this.tokens[0];
14915 },
14916
14917 peek: function(e1, e2, e3, e4) {
14918 return this.peekAhead(0, e1, e2, e3, e4);
14919 },
14920
14921 peekAhead: function(i, e1, e2, e3, e4) {
14922 if (this.tokens.length > i) {
14923 var token = this.tokens[i];
14924 var t = token.text;
14925 if (t === e1 || t === e2 || t === e3 || t === e4 ||
14926 (!e1 && !e2 && !e3 && !e4)) {
14927 return token;
14928 }
14929 }
14930 return false;
14931 },
14932
14933 expect: function(e1, e2, e3, e4) {
14934 var token = this.peek(e1, e2, e3, e4);
14935 if (token) {
14936 this.tokens.shift();
14937 return token;
14938 }
14939 return false;
14940 },
14941
14942 selfReferential: {
14943 'this': {type: AST.ThisExpression },
14944 '$locals': {type: AST.LocalsExpression }
14945 }
14946};
14947
14948function ifDefined(v, d) {
14949 return typeof v !== 'undefined' ? v : d;
14950}
14951
14952function plusFn(l, r) {
14953 if (typeof l === 'undefined') return r;
14954 if (typeof r === 'undefined') return l;
14955 return l + r;
14956}
14957
14958function isStateless($filter, filterName) {
14959 var fn = $filter(filterName);
14960 return !fn.$stateful;
14961}
14962
14963function findConstantAndWatchExpressions(ast, $filter) {
14964 var allConstants;
14965 var argsToWatch;
14966 var isStatelessFilter;
14967 switch (ast.type) {
14968 case AST.Program:
14969 allConstants = true;
14970 forEach(ast.body, function(expr) {
14971 findConstantAndWatchExpressions(expr.expression, $filter);
14972 allConstants = allConstants && expr.expression.constant;
14973 });
14974 ast.constant = allConstants;
14975 break;
14976 case AST.Literal:
14977 ast.constant = true;
14978 ast.toWatch = [];
14979 break;
14980 case AST.UnaryExpression:
14981 findConstantAndWatchExpressions(ast.argument, $filter);
14982 ast.constant = ast.argument.constant;
14983 ast.toWatch = ast.argument.toWatch;
14984 break;
14985 case AST.BinaryExpression:
14986 findConstantAndWatchExpressions(ast.left, $filter);
14987 findConstantAndWatchExpressions(ast.right, $filter);
14988 ast.constant = ast.left.constant && ast.right.constant;
14989 ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
14990 break;
14991 case AST.LogicalExpression:
14992 findConstantAndWatchExpressions(ast.left, $filter);
14993 findConstantAndWatchExpressions(ast.right, $filter);
14994 ast.constant = ast.left.constant && ast.right.constant;
14995 ast.toWatch = ast.constant ? [] : [ast];
14996 break;
14997 case AST.ConditionalExpression:
14998 findConstantAndWatchExpressions(ast.test, $filter);
14999 findConstantAndWatchExpressions(ast.alternate, $filter);
15000 findConstantAndWatchExpressions(ast.consequent, $filter);
15001 ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
15002 ast.toWatch = ast.constant ? [] : [ast];
15003 break;
15004 case AST.Identifier:
15005 ast.constant = false;
15006 ast.toWatch = [ast];
15007 break;
15008 case AST.MemberExpression:
15009 findConstantAndWatchExpressions(ast.object, $filter);
15010 if (ast.computed) {
15011 findConstantAndWatchExpressions(ast.property, $filter);
15012 }
15013 ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
15014 ast.toWatch = [ast];
15015 break;
15016 case AST.CallExpression:
15017 isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
15018 allConstants = isStatelessFilter;
15019 argsToWatch = [];
15020 forEach(ast.arguments, function(expr) {
15021 findConstantAndWatchExpressions(expr, $filter);
15022 allConstants = allConstants && expr.constant;
15023 if (!expr.constant) {
15024 argsToWatch.push.apply(argsToWatch, expr.toWatch);
15025 }
15026 });
15027 ast.constant = allConstants;
15028 ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
15029 break;
15030 case AST.AssignmentExpression:
15031 findConstantAndWatchExpressions(ast.left, $filter);
15032 findConstantAndWatchExpressions(ast.right, $filter);
15033 ast.constant = ast.left.constant && ast.right.constant;
15034 ast.toWatch = [ast];
15035 break;
15036 case AST.ArrayExpression:
15037 allConstants = true;
15038 argsToWatch = [];
15039 forEach(ast.elements, function(expr) {
15040 findConstantAndWatchExpressions(expr, $filter);
15041 allConstants = allConstants && expr.constant;
15042 if (!expr.constant) {
15043 argsToWatch.push.apply(argsToWatch, expr.toWatch);
15044 }
15045 });
15046 ast.constant = allConstants;
15047 ast.toWatch = argsToWatch;
15048 break;
15049 case AST.ObjectExpression:
15050 allConstants = true;
15051 argsToWatch = [];
15052 forEach(ast.properties, function(property) {
15053 findConstantAndWatchExpressions(property.value, $filter);
15054 allConstants = allConstants && property.value.constant && !property.computed;
15055 if (!property.value.constant) {
15056 argsToWatch.push.apply(argsToWatch, property.value.toWatch);
15057 }
15058 });
15059 ast.constant = allConstants;
15060 ast.toWatch = argsToWatch;
15061 break;
15062 case AST.ThisExpression:
15063 ast.constant = false;
15064 ast.toWatch = [];
15065 break;
15066 case AST.LocalsExpression:
15067 ast.constant = false;
15068 ast.toWatch = [];
15069 break;
15070 }
15071}
15072
15073function getInputs(body) {
15074 if (body.length !== 1) return;
15075 var lastExpression = body[0].expression;
15076 var candidate = lastExpression.toWatch;
15077 if (candidate.length !== 1) return candidate;
15078 return candidate[0] !== lastExpression ? candidate : undefined;
15079}
15080
15081function isAssignable(ast) {
15082 return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
15083}
15084
15085function assignableAST(ast) {
15086 if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
15087 return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
15088 }
15089}
15090
15091function isLiteral(ast) {
15092 return ast.body.length === 0 ||
15093 ast.body.length === 1 && (
15094 ast.body[0].expression.type === AST.Literal ||
15095 ast.body[0].expression.type === AST.ArrayExpression ||
15096 ast.body[0].expression.type === AST.ObjectExpression);
15097}
15098
15099function isConstant(ast) {
15100 return ast.constant;
15101}
15102
15103function ASTCompiler(astBuilder, $filter) {
15104 this.astBuilder = astBuilder;
15105 this.$filter = $filter;
15106}
15107
15108ASTCompiler.prototype = {
15109 compile: function(expression) {
15110 var self = this;
15111 var ast = this.astBuilder.ast(expression);
15112 this.state = {
15113 nextId: 0,
15114 filters: {},
15115 fn: {vars: [], body: [], own: {}},
15116 assign: {vars: [], body: [], own: {}},
15117 inputs: []
15118 };
15119 findConstantAndWatchExpressions(ast, self.$filter);
15120 var extra = '';
15121 var assignable;
15122 this.stage = 'assign';
15123 if ((assignable = assignableAST(ast))) {
15124 this.state.computing = 'assign';
15125 var result = this.nextId();
15126 this.recurse(assignable, result);
15127 this.return_(result);
15128 extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
15129 }
15130 var toWatch = getInputs(ast.body);
15131 self.stage = 'inputs';
15132 forEach(toWatch, function(watch, key) {
15133 var fnKey = 'fn' + key;
15134 self.state[fnKey] = {vars: [], body: [], own: {}};
15135 self.state.computing = fnKey;
15136 var intoId = self.nextId();
15137 self.recurse(watch, intoId);
15138 self.return_(intoId);
15139 self.state.inputs.push(fnKey);
15140 watch.watchId = key;
15141 });
15142 this.state.computing = 'fn';
15143 this.stage = 'main';
15144 this.recurse(ast);
15145 var fnString =
15146 // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
15147 // This is a workaround for this until we do a better job at only removing the prefix only when we should.
15148 '"' + this.USE + ' ' + this.STRICT + '";\n' +
15149 this.filterPrefix() +
15150 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
15151 extra +
15152 this.watchFns() +
15153 'return fn;';
15154
15155 // eslint-disable-next-line no-new-func
15156 var fn = (new Function('$filter',
15157 'getStringValue',
15158 'ifDefined',
15159 'plus',
15160 fnString))(
15161 this.$filter,
15162 getStringValue,
15163 ifDefined,
15164 plusFn);
15165 this.state = this.stage = undefined;
15166 fn.literal = isLiteral(ast);
15167 fn.constant = isConstant(ast);
15168 return fn;
15169 },
15170
15171 USE: 'use',
15172
15173 STRICT: 'strict',
15174
15175 watchFns: function() {
15176 var result = [];
15177 var fns = this.state.inputs;
15178 var self = this;
15179 forEach(fns, function(name) {
15180 result.push('var ' + name + '=' + self.generateFunction(name, 's'));
15181 });
15182 if (fns.length) {
15183 result.push('fn.inputs=[' + fns.join(',') + '];');
15184 }
15185 return result.join('');
15186 },
15187
15188 generateFunction: function(name, params) {
15189 return 'function(' + params + '){' +
15190 this.varsPrefix(name) +
15191 this.body(name) +
15192 '};';
15193 },
15194
15195 filterPrefix: function() {
15196 var parts = [];
15197 var self = this;
15198 forEach(this.state.filters, function(id, filter) {
15199 parts.push(id + '=$filter(' + self.escape(filter) + ')');
15200 });
15201 if (parts.length) return 'var ' + parts.join(',') + ';';
15202 return '';
15203 },
15204
15205 varsPrefix: function(section) {
15206 return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
15207 },
15208
15209 body: function(section) {
15210 return this.state[section].body.join('');
15211 },
15212
15213 recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
15214 var left, right, self = this, args, expression, computed;
15215 recursionFn = recursionFn || noop;
15216 if (!skipWatchIdCheck && isDefined(ast.watchId)) {
15217 intoId = intoId || this.nextId();
15218 this.if_('i',
15219 this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
15220 this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
15221 );
15222 return;
15223 }
15224 switch (ast.type) {
15225 case AST.Program:
15226 forEach(ast.body, function(expression, pos) {
15227 self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
15228 if (pos !== ast.body.length - 1) {
15229 self.current().body.push(right, ';');
15230 } else {
15231 self.return_(right);
15232 }
15233 });
15234 break;
15235 case AST.Literal:
15236 expression = this.escape(ast.value);
15237 this.assign(intoId, expression);
15238 recursionFn(intoId || expression);
15239 break;
15240 case AST.UnaryExpression:
15241 this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
15242 expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
15243 this.assign(intoId, expression);
15244 recursionFn(expression);
15245 break;
15246 case AST.BinaryExpression:
15247 this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
15248 this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
15249 if (ast.operator === '+') {
15250 expression = this.plus(left, right);
15251 } else if (ast.operator === '-') {
15252 expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
15253 } else {
15254 expression = '(' + left + ')' + ast.operator + '(' + right + ')';
15255 }
15256 this.assign(intoId, expression);
15257 recursionFn(expression);
15258 break;
15259 case AST.LogicalExpression:
15260 intoId = intoId || this.nextId();
15261 self.recurse(ast.left, intoId);
15262 self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
15263 recursionFn(intoId);
15264 break;
15265 case AST.ConditionalExpression:
15266 intoId = intoId || this.nextId();
15267 self.recurse(ast.test, intoId);
15268 self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
15269 recursionFn(intoId);
15270 break;
15271 case AST.Identifier:
15272 intoId = intoId || this.nextId();
15273 if (nameId) {
15274 nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
15275 nameId.computed = false;
15276 nameId.name = ast.name;
15277 }
15278 self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
15279 function() {
15280 self.if_(self.stage === 'inputs' || 's', function() {
15281 if (create && create !== 1) {
15282 self.if_(
15283 self.isNull(self.nonComputedMember('s', ast.name)),
15284 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
15285 }
15286 self.assign(intoId, self.nonComputedMember('s', ast.name));
15287 });
15288 }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
15289 );
15290 recursionFn(intoId);
15291 break;
15292 case AST.MemberExpression:
15293 left = nameId && (nameId.context = this.nextId()) || this.nextId();
15294 intoId = intoId || this.nextId();
15295 self.recurse(ast.object, left, undefined, function() {
15296 self.if_(self.notNull(left), function() {
15297 if (ast.computed) {
15298 right = self.nextId();
15299 self.recurse(ast.property, right);
15300 self.getStringValue(right);
15301 if (create && create !== 1) {
15302 self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
15303 }
15304 expression = self.computedMember(left, right);
15305 self.assign(intoId, expression);
15306 if (nameId) {
15307 nameId.computed = true;
15308 nameId.name = right;
15309 }
15310 } else {
15311 if (create && create !== 1) {
15312 self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
15313 }
15314 expression = self.nonComputedMember(left, ast.property.name);
15315 self.assign(intoId, expression);
15316 if (nameId) {
15317 nameId.computed = false;
15318 nameId.name = ast.property.name;
15319 }
15320 }
15321 }, function() {
15322 self.assign(intoId, 'undefined');
15323 });
15324 recursionFn(intoId);
15325 }, !!create);
15326 break;
15327 case AST.CallExpression:
15328 intoId = intoId || this.nextId();
15329 if (ast.filter) {
15330 right = self.filter(ast.callee.name);
15331 args = [];
15332 forEach(ast.arguments, function(expr) {
15333 var argument = self.nextId();
15334 self.recurse(expr, argument);
15335 args.push(argument);
15336 });
15337 expression = right + '(' + args.join(',') + ')';
15338 self.assign(intoId, expression);
15339 recursionFn(intoId);
15340 } else {
15341 right = self.nextId();
15342 left = {};
15343 args = [];
15344 self.recurse(ast.callee, right, left, function() {
15345 self.if_(self.notNull(right), function() {
15346 forEach(ast.arguments, function(expr) {
15347 self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
15348 args.push(argument);
15349 });
15350 });
15351 if (left.name) {
15352 expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
15353 } else {
15354 expression = right + '(' + args.join(',') + ')';
15355 }
15356 self.assign(intoId, expression);
15357 }, function() {
15358 self.assign(intoId, 'undefined');
15359 });
15360 recursionFn(intoId);
15361 });
15362 }
15363 break;
15364 case AST.AssignmentExpression:
15365 right = this.nextId();
15366 left = {};
15367 this.recurse(ast.left, undefined, left, function() {
15368 self.if_(self.notNull(left.context), function() {
15369 self.recurse(ast.right, right);
15370 expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
15371 self.assign(intoId, expression);
15372 recursionFn(intoId || expression);
15373 });
15374 }, 1);
15375 break;
15376 case AST.ArrayExpression:
15377 args = [];
15378 forEach(ast.elements, function(expr) {
15379 self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
15380 args.push(argument);
15381 });
15382 });
15383 expression = '[' + args.join(',') + ']';
15384 this.assign(intoId, expression);
15385 recursionFn(intoId || expression);
15386 break;
15387 case AST.ObjectExpression:
15388 args = [];
15389 computed = false;
15390 forEach(ast.properties, function(property) {
15391 if (property.computed) {
15392 computed = true;
15393 }
15394 });
15395 if (computed) {
15396 intoId = intoId || this.nextId();
15397 this.assign(intoId, '{}');
15398 forEach(ast.properties, function(property) {
15399 if (property.computed) {
15400 left = self.nextId();
15401 self.recurse(property.key, left);
15402 } else {
15403 left = property.key.type === AST.Identifier ?
15404 property.key.name :
15405 ('' + property.key.value);
15406 }
15407 right = self.nextId();
15408 self.recurse(property.value, right);
15409 self.assign(self.member(intoId, left, property.computed), right);
15410 });
15411 } else {
15412 forEach(ast.properties, function(property) {
15413 self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
15414 args.push(self.escape(
15415 property.key.type === AST.Identifier ? property.key.name :
15416 ('' + property.key.value)) +
15417 ':' + expr);
15418 });
15419 });
15420 expression = '{' + args.join(',') + '}';
15421 this.assign(intoId, expression);
15422 }
15423 recursionFn(intoId || expression);
15424 break;
15425 case AST.ThisExpression:
15426 this.assign(intoId, 's');
15427 recursionFn(intoId || 's');
15428 break;
15429 case AST.LocalsExpression:
15430 this.assign(intoId, 'l');
15431 recursionFn(intoId || 'l');
15432 break;
15433 case AST.NGValueParameter:
15434 this.assign(intoId, 'v');
15435 recursionFn(intoId || 'v');
15436 break;
15437 }
15438 },
15439
15440 getHasOwnProperty: function(element, property) {
15441 var key = element + '.' + property;
15442 var own = this.current().own;
15443 if (!own.hasOwnProperty(key)) {
15444 own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
15445 }
15446 return own[key];
15447 },
15448
15449 assign: function(id, value) {
15450 if (!id) return;
15451 this.current().body.push(id, '=', value, ';');
15452 return id;
15453 },
15454
15455 filter: function(filterName) {
15456 if (!this.state.filters.hasOwnProperty(filterName)) {
15457 this.state.filters[filterName] = this.nextId(true);
15458 }
15459 return this.state.filters[filterName];
15460 },
15461
15462 ifDefined: function(id, defaultValue) {
15463 return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
15464 },
15465
15466 plus: function(left, right) {
15467 return 'plus(' + left + ',' + right + ')';
15468 },
15469
15470 return_: function(id) {
15471 this.current().body.push('return ', id, ';');
15472 },
15473
15474 if_: function(test, alternate, consequent) {
15475 if (test === true) {
15476 alternate();
15477 } else {
15478 var body = this.current().body;
15479 body.push('if(', test, '){');
15480 alternate();
15481 body.push('}');
15482 if (consequent) {
15483 body.push('else{');
15484 consequent();
15485 body.push('}');
15486 }
15487 }
15488 },
15489
15490 not: function(expression) {
15491 return '!(' + expression + ')';
15492 },
15493
15494 isNull: function(expression) {
15495 return expression + '==null';
15496 },
15497
15498 notNull: function(expression) {
15499 return expression + '!=null';
15500 },
15501
15502 nonComputedMember: function(left, right) {
15503 var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
15504 var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
15505 if (SAFE_IDENTIFIER.test(right)) {
15506 return left + '.' + right;
15507 } else {
15508 return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
15509 }
15510 },
15511
15512 computedMember: function(left, right) {
15513 return left + '[' + right + ']';
15514 },
15515
15516 member: function(left, right, computed) {
15517 if (computed) return this.computedMember(left, right);
15518 return this.nonComputedMember(left, right);
15519 },
15520
15521 getStringValue: function(item) {
15522 this.assign(item, 'getStringValue(' + item + ')');
15523 },
15524
15525 lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
15526 var self = this;
15527 return function() {
15528 self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
15529 };
15530 },
15531
15532 lazyAssign: function(id, value) {
15533 var self = this;
15534 return function() {
15535 self.assign(id, value);
15536 };
15537 },
15538
15539 stringEscapeRegex: /[^ a-zA-Z0-9]/g,
15540
15541 stringEscapeFn: function(c) {
15542 return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
15543 },
15544
15545 escape: function(value) {
15546 if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
15547 if (isNumber(value)) return value.toString();
15548 if (value === true) return 'true';
15549 if (value === false) return 'false';
15550 if (value === null) return 'null';
15551 if (typeof value === 'undefined') return 'undefined';
15552
15553 throw $parseMinErr('esc', 'IMPOSSIBLE');
15554 },
15555
15556 nextId: function(skip, init) {
15557 var id = 'v' + (this.state.nextId++);
15558 if (!skip) {
15559 this.current().vars.push(id + (init ? '=' + init : ''));
15560 }
15561 return id;
15562 },
15563
15564 current: function() {
15565 return this.state[this.state.computing];
15566 }
15567};
15568
15569
15570function ASTInterpreter(astBuilder, $filter) {
15571 this.astBuilder = astBuilder;
15572 this.$filter = $filter;
15573}
15574
15575ASTInterpreter.prototype = {
15576 compile: function(expression) {
15577 var self = this;
15578 var ast = this.astBuilder.ast(expression);
15579 findConstantAndWatchExpressions(ast, self.$filter);
15580 var assignable;
15581 var assign;
15582 if ((assignable = assignableAST(ast))) {
15583 assign = this.recurse(assignable);
15584 }
15585 var toWatch = getInputs(ast.body);
15586 var inputs;
15587 if (toWatch) {
15588 inputs = [];
15589 forEach(toWatch, function(watch, key) {
15590 var input = self.recurse(watch);
15591 watch.input = input;
15592 inputs.push(input);
15593 watch.watchId = key;
15594 });
15595 }
15596 var expressions = [];
15597 forEach(ast.body, function(expression) {
15598 expressions.push(self.recurse(expression.expression));
15599 });
15600 var fn = ast.body.length === 0 ? noop :
15601 ast.body.length === 1 ? expressions[0] :
15602 function(scope, locals) {
15603 var lastValue;
15604 forEach(expressions, function(exp) {
15605 lastValue = exp(scope, locals);
15606 });
15607 return lastValue;
15608 };
15609 if (assign) {
15610 fn.assign = function(scope, value, locals) {
15611 return assign(scope, locals, value);
15612 };
15613 }
15614 if (inputs) {
15615 fn.inputs = inputs;
15616 }
15617 fn.literal = isLiteral(ast);
15618 fn.constant = isConstant(ast);
15619 return fn;
15620 },
15621
15622 recurse: function(ast, context, create) {
15623 var left, right, self = this, args;
15624 if (ast.input) {
15625 return this.inputs(ast.input, ast.watchId);
15626 }
15627 switch (ast.type) {
15628 case AST.Literal:
15629 return this.value(ast.value, context);
15630 case AST.UnaryExpression:
15631 right = this.recurse(ast.argument);
15632 return this['unary' + ast.operator](right, context);
15633 case AST.BinaryExpression:
15634 left = this.recurse(ast.left);
15635 right = this.recurse(ast.right);
15636 return this['binary' + ast.operator](left, right, context);
15637 case AST.LogicalExpression:
15638 left = this.recurse(ast.left);
15639 right = this.recurse(ast.right);
15640 return this['binary' + ast.operator](left, right, context);
15641 case AST.ConditionalExpression:
15642 return this['ternary?:'](
15643 this.recurse(ast.test),
15644 this.recurse(ast.alternate),
15645 this.recurse(ast.consequent),
15646 context
15647 );
15648 case AST.Identifier:
15649 return self.identifier(ast.name, context, create);
15650 case AST.MemberExpression:
15651 left = this.recurse(ast.object, false, !!create);
15652 if (!ast.computed) {
15653 right = ast.property.name;
15654 }
15655 if (ast.computed) right = this.recurse(ast.property);
15656 return ast.computed ?
15657 this.computedMember(left, right, context, create) :
15658 this.nonComputedMember(left, right, context, create);
15659 case AST.CallExpression:
15660 args = [];
15661 forEach(ast.arguments, function(expr) {
15662 args.push(self.recurse(expr));
15663 });
15664 if (ast.filter) right = this.$filter(ast.callee.name);
15665 if (!ast.filter) right = this.recurse(ast.callee, true);
15666 return ast.filter ?
15667 function(scope, locals, assign, inputs) {
15668 var values = [];
15669 for (var i = 0; i < args.length; ++i) {
15670 values.push(args[i](scope, locals, assign, inputs));
15671 }
15672 var value = right.apply(undefined, values, inputs);
15673 return context ? {context: undefined, name: undefined, value: value} : value;
15674 } :
15675 function(scope, locals, assign, inputs) {
15676 var rhs = right(scope, locals, assign, inputs);
15677 var value;
15678 if (rhs.value != null) {
15679 var values = [];
15680 for (var i = 0; i < args.length; ++i) {
15681 values.push(args[i](scope, locals, assign, inputs));
15682 }
15683 value = rhs.value.apply(rhs.context, values);
15684 }
15685 return context ? {value: value} : value;
15686 };
15687 case AST.AssignmentExpression:
15688 left = this.recurse(ast.left, true, 1);
15689 right = this.recurse(ast.right);
15690 return function(scope, locals, assign, inputs) {
15691 var lhs = left(scope, locals, assign, inputs);
15692 var rhs = right(scope, locals, assign, inputs);
15693 lhs.context[lhs.name] = rhs;
15694 return context ? {value: rhs} : rhs;
15695 };
15696 case AST.ArrayExpression:
15697 args = [];
15698 forEach(ast.elements, function(expr) {
15699 args.push(self.recurse(expr));
15700 });
15701 return function(scope, locals, assign, inputs) {
15702 var value = [];
15703 for (var i = 0; i < args.length; ++i) {
15704 value.push(args[i](scope, locals, assign, inputs));
15705 }
15706 return context ? {value: value} : value;
15707 };
15708 case AST.ObjectExpression:
15709 args = [];
15710 forEach(ast.properties, function(property) {
15711 if (property.computed) {
15712 args.push({key: self.recurse(property.key),
15713 computed: true,
15714 value: self.recurse(property.value)
15715 });
15716 } else {
15717 args.push({key: property.key.type === AST.Identifier ?
15718 property.key.name :
15719 ('' + property.key.value),
15720 computed: false,
15721 value: self.recurse(property.value)
15722 });
15723 }
15724 });
15725 return function(scope, locals, assign, inputs) {
15726 var value = {};
15727 for (var i = 0; i < args.length; ++i) {
15728 if (args[i].computed) {
15729 value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
15730 } else {
15731 value[args[i].key] = args[i].value(scope, locals, assign, inputs);
15732 }
15733 }
15734 return context ? {value: value} : value;
15735 };
15736 case AST.ThisExpression:
15737 return function(scope) {
15738 return context ? {value: scope} : scope;
15739 };
15740 case AST.LocalsExpression:
15741 return function(scope, locals) {
15742 return context ? {value: locals} : locals;
15743 };
15744 case AST.NGValueParameter:
15745 return function(scope, locals, assign) {
15746 return context ? {value: assign} : assign;
15747 };
15748 }
15749 },
15750
15751 'unary+': function(argument, context) {
15752 return function(scope, locals, assign, inputs) {
15753 var arg = argument(scope, locals, assign, inputs);
15754 if (isDefined(arg)) {
15755 arg = +arg;
15756 } else {
15757 arg = 0;
15758 }
15759 return context ? {value: arg} : arg;
15760 };
15761 },
15762 'unary-': function(argument, context) {
15763 return function(scope, locals, assign, inputs) {
15764 var arg = argument(scope, locals, assign, inputs);
15765 if (isDefined(arg)) {
15766 arg = -arg;
15767 } else {
15768 arg = -0;
15769 }
15770 return context ? {value: arg} : arg;
15771 };
15772 },
15773 'unary!': function(argument, context) {
15774 return function(scope, locals, assign, inputs) {
15775 var arg = !argument(scope, locals, assign, inputs);
15776 return context ? {value: arg} : arg;
15777 };
15778 },
15779 'binary+': function(left, right, context) {
15780 return function(scope, locals, assign, inputs) {
15781 var lhs = left(scope, locals, assign, inputs);
15782 var rhs = right(scope, locals, assign, inputs);
15783 var arg = plusFn(lhs, rhs);
15784 return context ? {value: arg} : arg;
15785 };
15786 },
15787 'binary-': function(left, right, context) {
15788 return function(scope, locals, assign, inputs) {
15789 var lhs = left(scope, locals, assign, inputs);
15790 var rhs = right(scope, locals, assign, inputs);
15791 var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
15792 return context ? {value: arg} : arg;
15793 };
15794 },
15795 'binary*': function(left, right, context) {
15796 return function(scope, locals, assign, inputs) {
15797 var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
15798 return context ? {value: arg} : arg;
15799 };
15800 },
15801 'binary/': function(left, right, context) {
15802 return function(scope, locals, assign, inputs) {
15803 var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
15804 return context ? {value: arg} : arg;
15805 };
15806 },
15807 'binary%': function(left, right, context) {
15808 return function(scope, locals, assign, inputs) {
15809 var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
15810 return context ? {value: arg} : arg;
15811 };
15812 },
15813 'binary===': function(left, right, context) {
15814 return function(scope, locals, assign, inputs) {
15815 var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
15816 return context ? {value: arg} : arg;
15817 };
15818 },
15819 'binary!==': function(left, right, context) {
15820 return function(scope, locals, assign, inputs) {
15821 var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
15822 return context ? {value: arg} : arg;
15823 };
15824 },
15825 'binary==': function(left, right, context) {
15826 return function(scope, locals, assign, inputs) {
15827 // eslint-disable-next-line eqeqeq
15828 var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
15829 return context ? {value: arg} : arg;
15830 };
15831 },
15832 'binary!=': function(left, right, context) {
15833 return function(scope, locals, assign, inputs) {
15834 // eslint-disable-next-line eqeqeq
15835 var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
15836 return context ? {value: arg} : arg;
15837 };
15838 },
15839 'binary<': function(left, right, context) {
15840 return function(scope, locals, assign, inputs) {
15841 var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
15842 return context ? {value: arg} : arg;
15843 };
15844 },
15845 'binary>': function(left, right, context) {
15846 return function(scope, locals, assign, inputs) {
15847 var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
15848 return context ? {value: arg} : arg;
15849 };
15850 },
15851 'binary<=': function(left, right, context) {
15852 return function(scope, locals, assign, inputs) {
15853 var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
15854 return context ? {value: arg} : arg;
15855 };
15856 },
15857 'binary>=': function(left, right, context) {
15858 return function(scope, locals, assign, inputs) {
15859 var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
15860 return context ? {value: arg} : arg;
15861 };
15862 },
15863 'binary&&': function(left, right, context) {
15864 return function(scope, locals, assign, inputs) {
15865 var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
15866 return context ? {value: arg} : arg;
15867 };
15868 },
15869 'binary||': function(left, right, context) {
15870 return function(scope, locals, assign, inputs) {
15871 var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
15872 return context ? {value: arg} : arg;
15873 };
15874 },
15875 'ternary?:': function(test, alternate, consequent, context) {
15876 return function(scope, locals, assign, inputs) {
15877 var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
15878 return context ? {value: arg} : arg;
15879 };
15880 },
15881 value: function(value, context) {
15882 return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
15883 },
15884 identifier: function(name, context, create) {
15885 return function(scope, locals, assign, inputs) {
15886 var base = locals && (name in locals) ? locals : scope;
15887 if (create && create !== 1 && base && base[name] == null) {
15888 base[name] = {};
15889 }
15890 var value = base ? base[name] : undefined;
15891 if (context) {
15892 return {context: base, name: name, value: value};
15893 } else {
15894 return value;
15895 }
15896 };
15897 },
15898 computedMember: function(left, right, context, create) {
15899 return function(scope, locals, assign, inputs) {
15900 var lhs = left(scope, locals, assign, inputs);
15901 var rhs;
15902 var value;
15903 if (lhs != null) {
15904 rhs = right(scope, locals, assign, inputs);
15905 rhs = getStringValue(rhs);
15906 if (create && create !== 1) {
15907 if (lhs && !(lhs[rhs])) {
15908 lhs[rhs] = {};
15909 }
15910 }
15911 value = lhs[rhs];
15912 }
15913 if (context) {
15914 return {context: lhs, name: rhs, value: value};
15915 } else {
15916 return value;
15917 }
15918 };
15919 },
15920 nonComputedMember: function(left, right, context, create) {
15921 return function(scope, locals, assign, inputs) {
15922 var lhs = left(scope, locals, assign, inputs);
15923 if (create && create !== 1) {
15924 if (lhs && lhs[right] == null) {
15925 lhs[right] = {};
15926 }
15927 }
15928 var value = lhs != null ? lhs[right] : undefined;
15929 if (context) {
15930 return {context: lhs, name: right, value: value};
15931 } else {
15932 return value;
15933 }
15934 };
15935 },
15936 inputs: function(input, watchId) {
15937 return function(scope, value, locals, inputs) {
15938 if (inputs) return inputs[watchId];
15939 return input(scope, value, locals);
15940 };
15941 }
15942};
15943
15944/**
15945 * @constructor
15946 */
15947var Parser = function Parser(lexer, $filter, options) {
15948 this.lexer = lexer;
15949 this.$filter = $filter;
15950 this.options = options;
15951 this.ast = new AST(lexer, options);
15952 this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
15953 new ASTCompiler(this.ast, $filter);
15954};
15955
15956Parser.prototype = {
15957 constructor: Parser,
15958
15959 parse: function(text) {
15960 return this.astCompiler.compile(text);
15961 }
15962};
15963
15964function getValueOf(value) {
15965 return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
15966}
15967
15968///////////////////////////////////
15969
15970/**
15971 * @ngdoc service
15972 * @name $parse
15973 * @kind function
15974 *
15975 * @description
15976 *
15977 * Converts Angular {@link guide/expression expression} into a function.
15978 *
15979 * ```js
15980 * var getter = $parse('user.name');
15981 * var setter = getter.assign;
15982 * var context = {user:{name:'angular'}};
15983 * var locals = {user:{name:'local'}};
15984 *
15985 * expect(getter(context)).toEqual('angular');
15986 * setter(context, 'newValue');
15987 * expect(context.user.name).toEqual('newValue');
15988 * expect(getter(context, locals)).toEqual('local');
15989 * ```
15990 *
15991 *
15992 * @param {string} expression String expression to compile.
15993 * @returns {function(context, locals)} a function which represents the compiled expression:
15994 *
15995 * * `context` – `{object}` – an object against which any expressions embedded in the strings
15996 * are evaluated against (typically a scope object).
15997 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
15998 * `context`.
15999 *
16000 * The returned function also has the following properties:
16001 * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
16002 * literal.
16003 * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
16004 * constant literals.
16005 * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
16006 * set to a function to change its value on the given context.
16007 *
16008 */
16009
16010
16011/**
16012 * @ngdoc provider
16013 * @name $parseProvider
16014 * @this
16015 *
16016 * @description
16017 * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
16018 * service.
16019 */
16020function $ParseProvider() {
16021 var cache = createMap();
16022 var literals = {
16023 'true': true,
16024 'false': false,
16025 'null': null,
16026 'undefined': undefined
16027 };
16028 var identStart, identContinue;
16029
16030 /**
16031 * @ngdoc method
16032 * @name $parseProvider#addLiteral
16033 * @description
16034 *
16035 * Configure $parse service to add literal values that will be present as literal at expressions.
16036 *
16037 * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
16038 * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
16039 *
16040 **/
16041 this.addLiteral = function(literalName, literalValue) {
16042 literals[literalName] = literalValue;
16043 };
16044
16045 /**
16046 * @ngdoc method
16047 * @name $parseProvider#setIdentifierFns
16048 *
16049 * @description
16050 *
16051 * Allows defining the set of characters that are allowed in Angular expressions. The function
16052 * `identifierStart` will get called to know if a given character is a valid character to be the
16053 * first character for an identifier. The function `identifierContinue` will get called to know if
16054 * a given character is a valid character to be a follow-up identifier character. The functions
16055 * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
16056 * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
16057 * mind that the `string` parameter can be two characters long depending on the character
16058 * representation. It is expected for the function to return `true` or `false`, whether that
16059 * character is allowed or not.
16060 *
16061 * Since this function will be called extensively, keep the implementation of these functions fast,
16062 * as the performance of these functions have a direct impact on the expressions parsing speed.
16063 *
16064 * @param {function=} identifierStart The function that will decide whether the given character is
16065 * a valid identifier start character.
16066 * @param {function=} identifierContinue The function that will decide whether the given character is
16067 * a valid identifier continue character.
16068 */
16069 this.setIdentifierFns = function(identifierStart, identifierContinue) {
16070 identStart = identifierStart;
16071 identContinue = identifierContinue;
16072 return this;
16073 };
16074
16075 this.$get = ['$filter', function($filter) {
16076 var noUnsafeEval = csp().noUnsafeEval;
16077 var $parseOptions = {
16078 csp: noUnsafeEval,
16079 literals: copy(literals),
16080 isIdentifierStart: isFunction(identStart) && identStart,
16081 isIdentifierContinue: isFunction(identContinue) && identContinue
16082 };
16083 return $parse;
16084
16085 function $parse(exp, interceptorFn) {
16086 var parsedExpression, oneTime, cacheKey;
16087
16088 switch (typeof exp) {
16089 case 'string':
16090 exp = exp.trim();
16091 cacheKey = exp;
16092
16093 parsedExpression = cache[cacheKey];
16094
16095 if (!parsedExpression) {
16096 if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
16097 oneTime = true;
16098 exp = exp.substring(2);
16099 }
16100 var lexer = new Lexer($parseOptions);
16101 var parser = new Parser(lexer, $filter, $parseOptions);
16102 parsedExpression = parser.parse(exp);
16103 if (parsedExpression.constant) {
16104 parsedExpression.$$watchDelegate = constantWatchDelegate;
16105 } else if (oneTime) {
16106 parsedExpression.$$watchDelegate = parsedExpression.literal ?
16107 oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
16108 } else if (parsedExpression.inputs) {
16109 parsedExpression.$$watchDelegate = inputsWatchDelegate;
16110 }
16111 cache[cacheKey] = parsedExpression;
16112 }
16113 return addInterceptor(parsedExpression, interceptorFn);
16114
16115 case 'function':
16116 return addInterceptor(exp, interceptorFn);
16117
16118 default:
16119 return addInterceptor(noop, interceptorFn);
16120 }
16121 }
16122
16123 function expressionInputDirtyCheck(newValue, oldValueOfValue) {
16124
16125 if (newValue == null || oldValueOfValue == null) { // null/undefined
16126 return newValue === oldValueOfValue;
16127 }
16128
16129 if (typeof newValue === 'object') {
16130
16131 // attempt to convert the value to a primitive type
16132 // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
16133 // be cheaply dirty-checked
16134 newValue = getValueOf(newValue);
16135
16136 if (typeof newValue === 'object') {
16137 // objects/arrays are not supported - deep-watching them would be too expensive
16138 return false;
16139 }
16140
16141 // fall-through to the primitive equality check
16142 }
16143
16144 //Primitive or NaN
16145 // eslint-disable-next-line no-self-compare
16146 return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
16147 }
16148
16149 function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
16150 var inputExpressions = parsedExpression.inputs;
16151 var lastResult;
16152
16153 if (inputExpressions.length === 1) {
16154 var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
16155 inputExpressions = inputExpressions[0];
16156 return scope.$watch(function expressionInputWatch(scope) {
16157 var newInputValue = inputExpressions(scope);
16158 if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
16159 lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
16160 oldInputValueOf = newInputValue && getValueOf(newInputValue);
16161 }
16162 return lastResult;
16163 }, listener, objectEquality, prettyPrintExpression);
16164 }
16165
16166 var oldInputValueOfValues = [];
16167 var oldInputValues = [];
16168 for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
16169 oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
16170 oldInputValues[i] = null;
16171 }
16172
16173 return scope.$watch(function expressionInputsWatch(scope) {
16174 var changed = false;
16175
16176 for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
16177 var newInputValue = inputExpressions[i](scope);
16178 if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
16179 oldInputValues[i] = newInputValue;
16180 oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
16181 }
16182 }
16183
16184 if (changed) {
16185 lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
16186 }
16187
16188 return lastResult;
16189 }, listener, objectEquality, prettyPrintExpression);
16190 }
16191
16192 function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
16193 var unwatch, lastValue;
16194 if (parsedExpression.inputs) {
16195 unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
16196 } else {
16197 unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
16198 }
16199 return unwatch;
16200
16201 function oneTimeWatch(scope) {
16202 return parsedExpression(scope);
16203 }
16204 function oneTimeListener(value, old, scope) {
16205 lastValue = value;
16206 if (isFunction(listener)) {
16207 listener(value, old, scope);
16208 }
16209 if (isDefined(value)) {
16210 scope.$$postDigest(function() {
16211 if (isDefined(lastValue)) {
16212 unwatch();
16213 }
16214 });
16215 }
16216 }
16217 }
16218
16219 function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
16220 var unwatch, lastValue;
16221 unwatch = scope.$watch(function oneTimeWatch(scope) {
16222 return parsedExpression(scope);
16223 }, function oneTimeListener(value, old, scope) {
16224 lastValue = value;
16225 if (isFunction(listener)) {
16226 listener(value, old, scope);
16227 }
16228 if (isAllDefined(value)) {
16229 scope.$$postDigest(function() {
16230 if (isAllDefined(lastValue)) unwatch();
16231 });
16232 }
16233 }, objectEquality);
16234
16235 return unwatch;
16236
16237 function isAllDefined(value) {
16238 var allDefined = true;
16239 forEach(value, function(val) {
16240 if (!isDefined(val)) allDefined = false;
16241 });
16242 return allDefined;
16243 }
16244 }
16245
16246 function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
16247 var unwatch = scope.$watch(function constantWatch(scope) {
16248 unwatch();
16249 return parsedExpression(scope);
16250 }, listener, objectEquality);
16251 return unwatch;
16252 }
16253
16254 function addInterceptor(parsedExpression, interceptorFn) {
16255 if (!interceptorFn) return parsedExpression;
16256 var watchDelegate = parsedExpression.$$watchDelegate;
16257 var useInputs = false;
16258
16259 var regularWatch =
16260 watchDelegate !== oneTimeLiteralWatchDelegate &&
16261 watchDelegate !== oneTimeWatchDelegate;
16262
16263 var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
16264 var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
16265 return interceptorFn(value, scope, locals);
16266 } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
16267 var value = parsedExpression(scope, locals, assign, inputs);
16268 var result = interceptorFn(value, scope, locals);
16269 // we only return the interceptor's result if the
16270 // initial value is defined (for bind-once)
16271 return isDefined(value) ? result : value;
16272 };
16273
16274 // Propagate $$watchDelegates other then inputsWatchDelegate
16275 useInputs = !parsedExpression.inputs;
16276 if (parsedExpression.$$watchDelegate &&
16277 parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
16278 fn.$$watchDelegate = parsedExpression.$$watchDelegate;
16279 fn.inputs = parsedExpression.inputs;
16280 } else if (!interceptorFn.$stateful) {
16281 // If there is an interceptor, but no watchDelegate then treat the interceptor like
16282 // we treat filters - it is assumed to be a pure function unless flagged with $stateful
16283 fn.$$watchDelegate = inputsWatchDelegate;
16284 fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
16285 }
16286
16287 return fn;
16288 }
16289 }];
16290}
16291
16292/**
16293 * @ngdoc service
16294 * @name $q
16295 * @requires $rootScope
16296 *
16297 * @description
16298 * A service that helps you run functions asynchronously, and use their return values (or exceptions)
16299 * when they are done processing.
16300 *
16301 * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
16302 * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
16303 *
16304 * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
16305 * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
16306 *
16307 * # $q constructor
16308 *
16309 * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
16310 * function as the first argument. This is similar to the native Promise implementation from ES6,
16311 * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
16312 *
16313 * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
16314 * available yet.
16315 *
16316 * It can be used like so:
16317 *
16318 * ```js
16319 * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
16320 * // are available in the current lexical scope (they could have been injected or passed in).
16321 *
16322 * function asyncGreet(name) {
16323 * // perform some asynchronous operation, resolve or reject the promise when appropriate.
16324 * return $q(function(resolve, reject) {
16325 * setTimeout(function() {
16326 * if (okToGreet(name)) {
16327 * resolve('Hello, ' + name + '!');
16328 * } else {
16329 * reject('Greeting ' + name + ' is not allowed.');
16330 * }
16331 * }, 1000);
16332 * });
16333 * }
16334 *
16335 * var promise = asyncGreet('Robin Hood');
16336 * promise.then(function(greeting) {
16337 * alert('Success: ' + greeting);
16338 * }, function(reason) {
16339 * alert('Failed: ' + reason);
16340 * });
16341 * ```
16342 *
16343 * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
16344 *
16345 * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
16346 *
16347 * However, the more traditional CommonJS-style usage is still available, and documented below.
16348 *
16349 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
16350 * interface for interacting with an object that represents the result of an action that is
16351 * performed asynchronously, and may or may not be finished at any given point in time.
16352 *
16353 * From the perspective of dealing with error handling, deferred and promise APIs are to
16354 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
16355 *
16356 * ```js
16357 * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
16358 * // are available in the current lexical scope (they could have been injected or passed in).
16359 *
16360 * function asyncGreet(name) {
16361 * var deferred = $q.defer();
16362 *
16363 * setTimeout(function() {
16364 * deferred.notify('About to greet ' + name + '.');
16365 *
16366 * if (okToGreet(name)) {
16367 * deferred.resolve('Hello, ' + name + '!');
16368 * } else {
16369 * deferred.reject('Greeting ' + name + ' is not allowed.');
16370 * }
16371 * }, 1000);
16372 *
16373 * return deferred.promise;
16374 * }
16375 *
16376 * var promise = asyncGreet('Robin Hood');
16377 * promise.then(function(greeting) {
16378 * alert('Success: ' + greeting);
16379 * }, function(reason) {
16380 * alert('Failed: ' + reason);
16381 * }, function(update) {
16382 * alert('Got notification: ' + update);
16383 * });
16384 * ```
16385 *
16386 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
16387 * comes in the way of guarantees that promise and deferred APIs make, see
16388 * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
16389 *
16390 * Additionally the promise api allows for composition that is very hard to do with the
16391 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
16392 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
16393 * section on serial or parallel joining of promises.
16394 *
16395 * # The Deferred API
16396 *
16397 * A new instance of deferred is constructed by calling `$q.defer()`.
16398 *
16399 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
16400 * that can be used for signaling the successful or unsuccessful completion, as well as the status
16401 * of the task.
16402 *
16403 * **Methods**
16404 *
16405 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
16406 * constructed via `$q.reject`, the promise will be rejected instead.
16407 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
16408 * resolving it with a rejection constructed via `$q.reject`.
16409 * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
16410 * multiple times before the promise is either resolved or rejected.
16411 *
16412 * **Properties**
16413 *
16414 * - promise – `{Promise}` – promise object associated with this deferred.
16415 *
16416 *
16417 * # The Promise API
16418 *
16419 * A new promise instance is created when a deferred instance is created and can be retrieved by
16420 * calling `deferred.promise`.
16421 *
16422 * The purpose of the promise object is to allow for interested parties to get access to the result
16423 * of the deferred task when it completes.
16424 *
16425 * **Methods**
16426 *
16427 * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
16428 * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
16429 * as soon as the result is available. The callbacks are called with a single argument: the result
16430 * or rejection reason. Additionally, the notify callback may be called zero or more times to
16431 * provide a progress indication, before the promise is resolved or rejected.
16432 *
16433 * This method *returns a new promise* which is resolved or rejected via the return value of the
16434 * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
16435 * with the value which is resolved in that promise using
16436 * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
16437 * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
16438 * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
16439 * arguments are optional.
16440 *
16441 * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
16442 *
16443 * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
16444 * but to do so without modifying the final value. This is useful to release resources or do some
16445 * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
16446 * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
16447 * more information.
16448 *
16449 * # Chaining promises
16450 *
16451 * Because calling the `then` method of a promise returns a new derived promise, it is easily
16452 * possible to create a chain of promises:
16453 *
16454 * ```js
16455 * promiseB = promiseA.then(function(result) {
16456 * return result + 1;
16457 * });
16458 *
16459 * // promiseB will be resolved immediately after promiseA is resolved and its value
16460 * // will be the result of promiseA incremented by 1
16461 * ```
16462 *
16463 * It is possible to create chains of any length and since a promise can be resolved with another
16464 * promise (which will defer its resolution further), it is possible to pause/defer resolution of
16465 * the promises at any point in the chain. This makes it possible to implement powerful APIs like
16466 * $http's response interceptors.
16467 *
16468 *
16469 * # Differences between Kris Kowal's Q and $q
16470 *
16471 * There are two main differences:
16472 *
16473 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
16474 * mechanism in angular, which means faster propagation of resolution or rejection into your
16475 * models and avoiding unnecessary browser repaints, which would result in flickering UI.
16476 * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
16477 * all the important functionality needed for common async tasks.
16478 *
16479 * # Testing
16480 *
16481 * ```js
16482 * it('should simulate promise', inject(function($q, $rootScope) {
16483 * var deferred = $q.defer();
16484 * var promise = deferred.promise;
16485 * var resolvedValue;
16486 *
16487 * promise.then(function(value) { resolvedValue = value; });
16488 * expect(resolvedValue).toBeUndefined();
16489 *
16490 * // Simulate resolving of promise
16491 * deferred.resolve(123);
16492 * // Note that the 'then' function does not get called synchronously.
16493 * // This is because we want the promise API to always be async, whether or not
16494 * // it got called synchronously or asynchronously.
16495 * expect(resolvedValue).toBeUndefined();
16496 *
16497 * // Propagate promise resolution to 'then' functions using $apply().
16498 * $rootScope.$apply();
16499 * expect(resolvedValue).toEqual(123);
16500 * }));
16501 * ```
16502 *
16503 * @param {function(function, function)} resolver Function which is responsible for resolving or
16504 * rejecting the newly created promise. The first parameter is a function which resolves the
16505 * promise, the second parameter is a function which rejects the promise.
16506 *
16507 * @returns {Promise} The newly created promise.
16508 */
16509/**
16510 * @ngdoc provider
16511 * @name $qProvider
16512 * @this
16513 *
16514 * @description
16515 */
16516function $QProvider() {
16517 var errorOnUnhandledRejections = true;
16518 this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
16519 return qFactory(function(callback) {
16520 $rootScope.$evalAsync(callback);
16521 }, $exceptionHandler, errorOnUnhandledRejections);
16522 }];
16523
16524 /**
16525 * @ngdoc method
16526 * @name $qProvider#errorOnUnhandledRejections
16527 * @kind function
16528 *
16529 * @description
16530 * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
16531 * This feature is enabled by default.
16532 *
16533 * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
16534 * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
16535 * chaining otherwise.
16536 */
16537 this.errorOnUnhandledRejections = function(value) {
16538 if (isDefined(value)) {
16539 errorOnUnhandledRejections = value;
16540 return this;
16541 } else {
16542 return errorOnUnhandledRejections;
16543 }
16544 };
16545}
16546
16547/** @this */
16548function $$QProvider() {
16549 var errorOnUnhandledRejections = true;
16550 this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
16551 return qFactory(function(callback) {
16552 $browser.defer(callback);
16553 }, $exceptionHandler, errorOnUnhandledRejections);
16554 }];
16555
16556 this.errorOnUnhandledRejections = function(value) {
16557 if (isDefined(value)) {
16558 errorOnUnhandledRejections = value;
16559 return this;
16560 } else {
16561 return errorOnUnhandledRejections;
16562 }
16563 };
16564}
16565
16566/**
16567 * Constructs a promise manager.
16568 *
16569 * @param {function(function)} nextTick Function for executing functions in the next turn.
16570 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
16571 * debugging purposes.
16572 @ param {=boolean} errorOnUnhandledRejections Whether an error should be generated on unhandled
16573 * promises rejections.
16574 * @returns {object} Promise manager.
16575 */
16576function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
16577 var $qMinErr = minErr('$q', TypeError);
16578 var queueSize = 0;
16579 var checkQueue = [];
16580
16581 /**
16582 * @ngdoc method
16583 * @name ng.$q#defer
16584 * @kind function
16585 *
16586 * @description
16587 * Creates a `Deferred` object which represents a task which will finish in the future.
16588 *
16589 * @returns {Deferred} Returns a new instance of deferred.
16590 */
16591 function defer() {
16592 return new Deferred();
16593 }
16594
16595 function Deferred() {
16596 var promise = this.promise = new Promise();
16597 //Non prototype methods necessary to support unbound execution :/
16598 this.resolve = function(val) { resolvePromise(promise, val); };
16599 this.reject = function(reason) { rejectPromise(promise, reason); };
16600 this.notify = function(progress) { notifyPromise(promise, progress); };
16601 }
16602
16603
16604 function Promise() {
16605 this.$$state = { status: 0 };
16606 }
16607
16608 extend(Promise.prototype, {
16609 then: function(onFulfilled, onRejected, progressBack) {
16610 if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
16611 return this;
16612 }
16613 var result = new Promise();
16614
16615 this.$$state.pending = this.$$state.pending || [];
16616 this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
16617 if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
16618
16619 return result;
16620 },
16621
16622 'catch': function(callback) {
16623 return this.then(null, callback);
16624 },
16625
16626 'finally': function(callback, progressBack) {
16627 return this.then(function(value) {
16628 return handleCallback(value, resolve, callback);
16629 }, function(error) {
16630 return handleCallback(error, reject, callback);
16631 }, progressBack);
16632 }
16633 });
16634
16635 function processQueue(state) {
16636 var fn, promise, pending;
16637
16638 pending = state.pending;
16639 state.processScheduled = false;
16640 state.pending = undefined;
16641 try {
16642 for (var i = 0, ii = pending.length; i < ii; ++i) {
16643 state.pur = true;
16644 promise = pending[i][0];
16645 fn = pending[i][state.status];
16646 try {
16647 if (isFunction(fn)) {
16648 resolvePromise(promise, fn(state.value));
16649 } else if (state.status === 1) {
16650 resolvePromise(promise, state.value);
16651 } else {
16652 rejectPromise(promise, state.value);
16653 }
16654 } catch (e) {
16655 rejectPromise(promise, e);
16656 }
16657 }
16658 } finally {
16659 --queueSize;
16660 if (errorOnUnhandledRejections && queueSize === 0) {
16661 nextTick(processChecks);
16662 }
16663 }
16664 }
16665
16666 function processChecks() {
16667 // eslint-disable-next-line no-unmodified-loop-condition
16668 while (!queueSize && checkQueue.length) {
16669 var toCheck = checkQueue.shift();
16670 if (!toCheck.pur) {
16671 toCheck.pur = true;
16672 var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
16673 if (toCheck.value instanceof Error) {
16674 exceptionHandler(toCheck.value, errorMessage);
16675 } else {
16676 exceptionHandler(errorMessage);
16677 }
16678 }
16679 }
16680 }
16681
16682 function scheduleProcessQueue(state) {
16683 if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !state.pur) {
16684 if (queueSize === 0 && checkQueue.length === 0) {
16685 nextTick(processChecks);
16686 }
16687 checkQueue.push(state);
16688 }
16689 if (state.processScheduled || !state.pending) return;
16690 state.processScheduled = true;
16691 ++queueSize;
16692 nextTick(function() { processQueue(state); });
16693 }
16694
16695 function resolvePromise(promise, val) {
16696 if (promise.$$state.status) return;
16697 if (val === promise) {
16698 $$reject(promise, $qMinErr(
16699 'qcycle',
16700 'Expected promise to be resolved with value other than itself \'{0}\'',
16701 val));
16702 } else {
16703 $$resolve(promise, val);
16704 }
16705
16706 }
16707
16708 function $$resolve(promise, val) {
16709 var then;
16710 var done = false;
16711 try {
16712 if (isObject(val) || isFunction(val)) then = val.then;
16713 if (isFunction(then)) {
16714 promise.$$state.status = -1;
16715 then.call(val, doResolve, doReject, doNotify);
16716 } else {
16717 promise.$$state.value = val;
16718 promise.$$state.status = 1;
16719 scheduleProcessQueue(promise.$$state);
16720 }
16721 } catch (e) {
16722 doReject(e);
16723 }
16724
16725 function doResolve(val) {
16726 if (done) return;
16727 done = true;
16728 $$resolve(promise, val);
16729 }
16730 function doReject(val) {
16731 if (done) return;
16732 done = true;
16733 $$reject(promise, val);
16734 }
16735 function doNotify(progress) {
16736 notifyPromise(promise, progress);
16737 }
16738 }
16739
16740 function rejectPromise(promise, reason) {
16741 if (promise.$$state.status) return;
16742 $$reject(promise, reason);
16743 }
16744
16745 function $$reject(promise, reason) {
16746 promise.$$state.value = reason;
16747 promise.$$state.status = 2;
16748 scheduleProcessQueue(promise.$$state);
16749 }
16750
16751 function notifyPromise(promise, progress) {
16752 var callbacks = promise.$$state.pending;
16753
16754 if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
16755 nextTick(function() {
16756 var callback, result;
16757 for (var i = 0, ii = callbacks.length; i < ii; i++) {
16758 result = callbacks[i][0];
16759 callback = callbacks[i][3];
16760 try {
16761 notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
16762 } catch (e) {
16763 exceptionHandler(e);
16764 }
16765 }
16766 });
16767 }
16768 }
16769
16770 /**
16771 * @ngdoc method
16772 * @name $q#reject
16773 * @kind function
16774 *
16775 * @description
16776 * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
16777 * used to forward rejection in a chain of promises. If you are dealing with the last promise in
16778 * a promise chain, you don't need to worry about it.
16779 *
16780 * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
16781 * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
16782 * a promise error callback and you want to forward the error to the promise derived from the
16783 * current promise, you have to "rethrow" the error by returning a rejection constructed via
16784 * `reject`.
16785 *
16786 * ```js
16787 * promiseB = promiseA.then(function(result) {
16788 * // success: do something and resolve promiseB
16789 * // with the old or a new result
16790 * return result;
16791 * }, function(reason) {
16792 * // error: handle the error if possible and
16793 * // resolve promiseB with newPromiseOrValue,
16794 * // otherwise forward the rejection to promiseB
16795 * if (canHandle(reason)) {
16796 * // handle the error and recover
16797 * return newPromiseOrValue;
16798 * }
16799 * return $q.reject(reason);
16800 * });
16801 * ```
16802 *
16803 * @param {*} reason Constant, message, exception or an object representing the rejection reason.
16804 * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
16805 */
16806 function reject(reason) {
16807 var result = new Promise();
16808 rejectPromise(result, reason);
16809 return result;
16810 }
16811
16812 function handleCallback(value, resolver, callback) {
16813 var callbackOutput = null;
16814 try {
16815 if (isFunction(callback)) callbackOutput = callback();
16816 } catch (e) {
16817 return reject(e);
16818 }
16819 if (isPromiseLike(callbackOutput)) {
16820 return callbackOutput.then(function() {
16821 return resolver(value);
16822 }, reject);
16823 } else {
16824 return resolver(value);
16825 }
16826 }
16827
16828 /**
16829 * @ngdoc method
16830 * @name $q#when
16831 * @kind function
16832 *
16833 * @description
16834 * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
16835 * This is useful when you are dealing with an object that might or might not be a promise, or if
16836 * the promise comes from a source that can't be trusted.
16837 *
16838 * @param {*} value Value or a promise
16839 * @param {Function=} successCallback
16840 * @param {Function=} errorCallback
16841 * @param {Function=} progressCallback
16842 * @returns {Promise} Returns a promise of the passed value or promise
16843 */
16844
16845
16846 function when(value, callback, errback, progressBack) {
16847 var result = new Promise();
16848 resolvePromise(result, value);
16849 return result.then(callback, errback, progressBack);
16850 }
16851
16852 /**
16853 * @ngdoc method
16854 * @name $q#resolve
16855 * @kind function
16856 *
16857 * @description
16858 * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
16859 *
16860 * @param {*} value Value or a promise
16861 * @param {Function=} successCallback
16862 * @param {Function=} errorCallback
16863 * @param {Function=} progressCallback
16864 * @returns {Promise} Returns a promise of the passed value or promise
16865 */
16866 var resolve = when;
16867
16868 /**
16869 * @ngdoc method
16870 * @name $q#all
16871 * @kind function
16872 *
16873 * @description
16874 * Combines multiple promises into a single promise that is resolved when all of the input
16875 * promises are resolved.
16876 *
16877 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
16878 * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
16879 * each value corresponding to the promise at the same index/key in the `promises` array/hash.
16880 * If any of the promises is resolved with a rejection, this resulting promise will be rejected
16881 * with the same rejection value.
16882 */
16883
16884 function all(promises) {
16885 var result = new Promise(),
16886 counter = 0,
16887 results = isArray(promises) ? [] : {};
16888
16889 forEach(promises, function(promise, key) {
16890 counter++;
16891 when(promise).then(function(value) {
16892 results[key] = value;
16893 if (!(--counter)) resolvePromise(result, results);
16894 }, function(reason) {
16895 rejectPromise(result, reason);
16896 });
16897 });
16898
16899 if (counter === 0) {
16900 resolvePromise(result, results);
16901 }
16902
16903 return result;
16904 }
16905
16906 /**
16907 * @ngdoc method
16908 * @name $q#race
16909 * @kind function
16910 *
16911 * @description
16912 * Returns a promise that resolves or rejects as soon as one of those promises
16913 * resolves or rejects, with the value or reason from that promise.
16914 *
16915 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
16916 * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
16917 * resolves or rejects, with the value or reason from that promise.
16918 */
16919
16920 function race(promises) {
16921 var deferred = defer();
16922
16923 forEach(promises, function(promise) {
16924 when(promise).then(deferred.resolve, deferred.reject);
16925 });
16926
16927 return deferred.promise;
16928 }
16929
16930 function $Q(resolver) {
16931 if (!isFunction(resolver)) {
16932 throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
16933 }
16934
16935 var promise = new Promise();
16936
16937 function resolveFn(value) {
16938 resolvePromise(promise, value);
16939 }
16940
16941 function rejectFn(reason) {
16942 rejectPromise(promise, reason);
16943 }
16944
16945 resolver(resolveFn, rejectFn);
16946
16947 return promise;
16948 }
16949
16950 // Let's make the instanceof operator work for promises, so that
16951 // `new $q(fn) instanceof $q` would evaluate to true.
16952 $Q.prototype = Promise.prototype;
16953
16954 $Q.defer = defer;
16955 $Q.reject = reject;
16956 $Q.when = when;
16957 $Q.resolve = resolve;
16958 $Q.all = all;
16959 $Q.race = race;
16960
16961 return $Q;
16962}
16963
16964/** @this */
16965function $$RAFProvider() { //rAF
16966 this.$get = ['$window', '$timeout', function($window, $timeout) {
16967 var requestAnimationFrame = $window.requestAnimationFrame ||
16968 $window.webkitRequestAnimationFrame;
16969
16970 var cancelAnimationFrame = $window.cancelAnimationFrame ||
16971 $window.webkitCancelAnimationFrame ||
16972 $window.webkitCancelRequestAnimationFrame;
16973
16974 var rafSupported = !!requestAnimationFrame;
16975 var raf = rafSupported
16976 ? function(fn) {
16977 var id = requestAnimationFrame(fn);
16978 return function() {
16979 cancelAnimationFrame(id);
16980 };
16981 }
16982 : function(fn) {
16983 var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
16984 return function() {
16985 $timeout.cancel(timer);
16986 };
16987 };
16988
16989 raf.supported = rafSupported;
16990
16991 return raf;
16992 }];
16993}
16994
16995/**
16996 * DESIGN NOTES
16997 *
16998 * The design decisions behind the scope are heavily favored for speed and memory consumption.
16999 *
17000 * The typical use of scope is to watch the expressions, which most of the time return the same
17001 * value as last time so we optimize the operation.
17002 *
17003 * Closures construction is expensive in terms of speed as well as memory:
17004 * - No closures, instead use prototypical inheritance for API
17005 * - Internal state needs to be stored on scope directly, which means that private state is
17006 * exposed as $$____ properties
17007 *
17008 * Loop operations are optimized by using while(count--) { ... }
17009 * - This means that in order to keep the same order of execution as addition we have to add
17010 * items to the array at the beginning (unshift) instead of at the end (push)
17011 *
17012 * Child scopes are created and removed often
17013 * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
17014 *
17015 * There are fewer watches than observers. This is why you don't want the observer to be implemented
17016 * in the same way as watch. Watch requires return of the initialization function which is expensive
17017 * to construct.
17018 */
17019
17020
17021/**
17022 * @ngdoc provider
17023 * @name $rootScopeProvider
17024 * @description
17025 *
17026 * Provider for the $rootScope service.
17027 */
17028
17029/**
17030 * @ngdoc method
17031 * @name $rootScopeProvider#digestTtl
17032 * @description
17033 *
17034 * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
17035 * assuming that the model is unstable.
17036 *
17037 * The current default is 10 iterations.
17038 *
17039 * In complex applications it's possible that the dependencies between `$watch`s will result in
17040 * several digest iterations. However if an application needs more than the default 10 digest
17041 * iterations for its model to stabilize then you should investigate what is causing the model to
17042 * continuously change during the digest.
17043 *
17044 * Increasing the TTL could have performance implications, so you should not change it without
17045 * proper justification.
17046 *
17047 * @param {number} limit The number of digest iterations.
17048 */
17049
17050
17051/**
17052 * @ngdoc service
17053 * @name $rootScope
17054 * @this
17055 *
17056 * @description
17057 *
17058 * Every application has a single root {@link ng.$rootScope.Scope scope}.
17059 * All other scopes are descendant scopes of the root scope. Scopes provide separation
17060 * between the model and the view, via a mechanism for watching the model for changes.
17061 * They also provide event emission/broadcast and subscription facility. See the
17062 * {@link guide/scope developer guide on scopes}.
17063 */
17064function $RootScopeProvider() {
17065 var TTL = 10;
17066 var $rootScopeMinErr = minErr('$rootScope');
17067 var lastDirtyWatch = null;
17068 var applyAsyncId = null;
17069
17070 this.digestTtl = function(value) {
17071 if (arguments.length) {
17072 TTL = value;
17073 }
17074 return TTL;
17075 };
17076
17077 function createChildScopeClass(parent) {
17078 function ChildScope() {
17079 this.$$watchers = this.$$nextSibling =
17080 this.$$childHead = this.$$childTail = null;
17081 this.$$listeners = {};
17082 this.$$listenerCount = {};
17083 this.$$watchersCount = 0;
17084 this.$id = nextUid();
17085 this.$$ChildScope = null;
17086 }
17087 ChildScope.prototype = parent;
17088 return ChildScope;
17089 }
17090
17091 this.$get = ['$exceptionHandler', '$parse', '$browser',
17092 function($exceptionHandler, $parse, $browser) {
17093
17094 function destroyChildScope($event) {
17095 $event.currentScope.$$destroyed = true;
17096 }
17097
17098 function cleanUpScope($scope) {
17099
17100 // Support: IE 9 only
17101 if (msie === 9) {
17102 // There is a memory leak in IE9 if all child scopes are not disconnected
17103 // completely when a scope is destroyed. So this code will recurse up through
17104 // all this scopes children
17105 //
17106 // See issue https://github.com/angular/angular.js/issues/10706
17107 if ($scope.$$childHead) {
17108 cleanUpScope($scope.$$childHead);
17109 }
17110 if ($scope.$$nextSibling) {
17111 cleanUpScope($scope.$$nextSibling);
17112 }
17113 }
17114
17115 // The code below works around IE9 and V8's memory leaks
17116 //
17117 // See:
17118 // - https://code.google.com/p/v8/issues/detail?id=2073#c26
17119 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
17120 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
17121
17122 $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
17123 $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
17124 }
17125
17126 /**
17127 * @ngdoc type
17128 * @name $rootScope.Scope
17129 *
17130 * @description
17131 * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
17132 * {@link auto.$injector $injector}. Child scopes are created using the
17133 * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
17134 * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
17135 * an in-depth introduction and usage examples.
17136 *
17137 *
17138 * # Inheritance
17139 * A scope can inherit from a parent scope, as in this example:
17140 * ```js
17141 var parent = $rootScope;
17142 var child = parent.$new();
17143
17144 parent.salutation = "Hello";
17145 expect(child.salutation).toEqual('Hello');
17146
17147 child.salutation = "Welcome";
17148 expect(child.salutation).toEqual('Welcome');
17149 expect(parent.salutation).toEqual('Hello');
17150 * ```
17151 *
17152 * When interacting with `Scope` in tests, additional helper methods are available on the
17153 * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
17154 * details.
17155 *
17156 *
17157 * @param {Object.<string, function()>=} providers Map of service factory which need to be
17158 * provided for the current scope. Defaults to {@link ng}.
17159 * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
17160 * append/override services provided by `providers`. This is handy
17161 * when unit-testing and having the need to override a default
17162 * service.
17163 * @returns {Object} Newly created scope.
17164 *
17165 */
17166 function Scope() {
17167 this.$id = nextUid();
17168 this.$$phase = this.$parent = this.$$watchers =
17169 this.$$nextSibling = this.$$prevSibling =
17170 this.$$childHead = this.$$childTail = null;
17171 this.$root = this;
17172 this.$$destroyed = false;
17173 this.$$listeners = {};
17174 this.$$listenerCount = {};
17175 this.$$watchersCount = 0;
17176 this.$$isolateBindings = null;
17177 }
17178
17179 /**
17180 * @ngdoc property
17181 * @name $rootScope.Scope#$id
17182 *
17183 * @description
17184 * Unique scope ID (monotonically increasing) useful for debugging.
17185 */
17186
17187 /**
17188 * @ngdoc property
17189 * @name $rootScope.Scope#$parent
17190 *
17191 * @description
17192 * Reference to the parent scope.
17193 */
17194
17195 /**
17196 * @ngdoc property
17197 * @name $rootScope.Scope#$root
17198 *
17199 * @description
17200 * Reference to the root scope.
17201 */
17202
17203 Scope.prototype = {
17204 constructor: Scope,
17205 /**
17206 * @ngdoc method
17207 * @name $rootScope.Scope#$new
17208 * @kind function
17209 *
17210 * @description
17211 * Creates a new child {@link ng.$rootScope.Scope scope}.
17212 *
17213 * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
17214 * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
17215 *
17216 * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
17217 * desired for the scope and its child scopes to be permanently detached from the parent and
17218 * thus stop participating in model change detection and listener notification by invoking.
17219 *
17220 * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
17221 * parent scope. The scope is isolated, as it can not see parent scope properties.
17222 * When creating widgets, it is useful for the widget to not accidentally read parent
17223 * state.
17224 *
17225 * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
17226 * of the newly created scope. Defaults to `this` scope if not provided.
17227 * This is used when creating a transclude scope to correctly place it
17228 * in the scope hierarchy while maintaining the correct prototypical
17229 * inheritance.
17230 *
17231 * @returns {Object} The newly created child scope.
17232 *
17233 */
17234 $new: function(isolate, parent) {
17235 var child;
17236
17237 parent = parent || this;
17238
17239 if (isolate) {
17240 child = new Scope();
17241 child.$root = this.$root;
17242 } else {
17243 // Only create a child scope class if somebody asks for one,
17244 // but cache it to allow the VM to optimize lookups.
17245 if (!this.$$ChildScope) {
17246 this.$$ChildScope = createChildScopeClass(this);
17247 }
17248 child = new this.$$ChildScope();
17249 }
17250 child.$parent = parent;
17251 child.$$prevSibling = parent.$$childTail;
17252 if (parent.$$childHead) {
17253 parent.$$childTail.$$nextSibling = child;
17254 parent.$$childTail = child;
17255 } else {
17256 parent.$$childHead = parent.$$childTail = child;
17257 }
17258
17259 // When the new scope is not isolated or we inherit from `this`, and
17260 // the parent scope is destroyed, the property `$$destroyed` is inherited
17261 // prototypically. In all other cases, this property needs to be set
17262 // when the parent scope is destroyed.
17263 // The listener needs to be added after the parent is set
17264 if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
17265
17266 return child;
17267 },
17268
17269 /**
17270 * @ngdoc method
17271 * @name $rootScope.Scope#$watch
17272 * @kind function
17273 *
17274 * @description
17275 * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
17276 *
17277 * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
17278 * $digest()} and should return the value that will be watched. (`watchExpression` should not change
17279 * its value when executed multiple times with the same input because it may be executed multiple
17280 * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
17281 * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
17282 * - The `listener` is called only when the value from the current `watchExpression` and the
17283 * previous call to `watchExpression` are not equal (with the exception of the initial run,
17284 * see below). Inequality is determined according to reference inequality,
17285 * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
17286 * via the `!==` Javascript operator, unless `objectEquality == true`
17287 * (see next point)
17288 * - When `objectEquality == true`, inequality of the `watchExpression` is determined
17289 * according to the {@link angular.equals} function. To save the value of the object for
17290 * later comparison, the {@link angular.copy} function is used. This therefore means that
17291 * watching complex objects will have adverse memory and performance implications.
17292 * - This should not be used to watch for changes in objects that are
17293 * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
17294 * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
17295 * This is achieved by rerunning the watchers until no changes are detected. The rerun
17296 * iteration limit is 10 to prevent an infinite loop deadlock.
17297 *
17298 *
17299 * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
17300 * you can register a `watchExpression` function with no `listener`. (Be prepared for
17301 * multiple calls to your `watchExpression` because it will execute multiple times in a
17302 * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
17303 *
17304 * After a watcher is registered with the scope, the `listener` fn is called asynchronously
17305 * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
17306 * watcher. In rare cases, this is undesirable because the listener is called when the result
17307 * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
17308 * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
17309 * listener was called due to initialization.
17310 *
17311 *
17312 *
17313 * # Example
17314 * ```js
17315 // let's assume that scope was dependency injected as the $rootScope
17316 var scope = $rootScope;
17317 scope.name = 'misko';
17318 scope.counter = 0;
17319
17320 expect(scope.counter).toEqual(0);
17321 scope.$watch('name', function(newValue, oldValue) {
17322 scope.counter = scope.counter + 1;
17323 });
17324 expect(scope.counter).toEqual(0);
17325
17326 scope.$digest();
17327 // the listener is always called during the first $digest loop after it was registered
17328 expect(scope.counter).toEqual(1);
17329
17330 scope.$digest();
17331 // but now it will not be called unless the value changes
17332 expect(scope.counter).toEqual(1);
17333
17334 scope.name = 'adam';
17335 scope.$digest();
17336 expect(scope.counter).toEqual(2);
17337
17338
17339
17340 // Using a function as a watchExpression
17341 var food;
17342 scope.foodCounter = 0;
17343 expect(scope.foodCounter).toEqual(0);
17344 scope.$watch(
17345 // This function returns the value being watched. It is called for each turn of the $digest loop
17346 function() { return food; },
17347 // This is the change listener, called when the value returned from the above function changes
17348 function(newValue, oldValue) {
17349 if ( newValue !== oldValue ) {
17350 // Only increment the counter if the value changed
17351 scope.foodCounter = scope.foodCounter + 1;
17352 }
17353 }
17354 );
17355 // No digest has been run so the counter will be zero
17356 expect(scope.foodCounter).toEqual(0);
17357
17358 // Run the digest but since food has not changed count will still be zero
17359 scope.$digest();
17360 expect(scope.foodCounter).toEqual(0);
17361
17362 // Update food and run digest. Now the counter will increment
17363 food = 'cheeseburger';
17364 scope.$digest();
17365 expect(scope.foodCounter).toEqual(1);
17366
17367 * ```
17368 *
17369 *
17370 *
17371 * @param {(function()|string)} watchExpression Expression that is evaluated on each
17372 * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
17373 * a call to the `listener`.
17374 *
17375 * - `string`: Evaluated as {@link guide/expression expression}
17376 * - `function(scope)`: called with current `scope` as a parameter.
17377 * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
17378 * of `watchExpression` changes.
17379 *
17380 * - `newVal` contains the current value of the `watchExpression`
17381 * - `oldVal` contains the previous value of the `watchExpression`
17382 * - `scope` refers to the current scope
17383 * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
17384 * comparing for reference equality.
17385 * @returns {function()} Returns a deregistration function for this listener.
17386 */
17387 $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
17388 var get = $parse(watchExp);
17389
17390 if (get.$$watchDelegate) {
17391 return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
17392 }
17393 var scope = this,
17394 array = scope.$$watchers,
17395 watcher = {
17396 fn: listener,
17397 last: initWatchVal,
17398 get: get,
17399 exp: prettyPrintExpression || watchExp,
17400 eq: !!objectEquality
17401 };
17402
17403 lastDirtyWatch = null;
17404
17405 if (!isFunction(listener)) {
17406 watcher.fn = noop;
17407 }
17408
17409 if (!array) {
17410 array = scope.$$watchers = [];
17411 array.$$digestWatchIndex = -1;
17412 }
17413 // we use unshift since we use a while loop in $digest for speed.
17414 // the while loop reads in reverse order.
17415 array.unshift(watcher);
17416 array.$$digestWatchIndex++;
17417 incrementWatchersCount(this, 1);
17418
17419 return function deregisterWatch() {
17420 var index = arrayRemove(array, watcher);
17421 if (index >= 0) {
17422 incrementWatchersCount(scope, -1);
17423 if (index < array.$$digestWatchIndex) {
17424 array.$$digestWatchIndex--;
17425 }
17426 }
17427 lastDirtyWatch = null;
17428 };
17429 },
17430
17431 /**
17432 * @ngdoc method
17433 * @name $rootScope.Scope#$watchGroup
17434 * @kind function
17435 *
17436 * @description
17437 * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
17438 * If any one expression in the collection changes the `listener` is executed.
17439 *
17440 * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
17441 * values are examined for changes on every call to `$digest`.
17442 * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
17443 *
17444 * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
17445 * watched using {@link ng.$rootScope.Scope#$watch $watch()}
17446 *
17447 * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
17448 * expression in `watchExpressions` changes
17449 * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
17450 * those of `watchExpression`
17451 * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
17452 * those of `watchExpression`
17453 * The `scope` refers to the current scope.
17454 * @returns {function()} Returns a de-registration function for all listeners.
17455 */
17456 $watchGroup: function(watchExpressions, listener) {
17457 var oldValues = new Array(watchExpressions.length);
17458 var newValues = new Array(watchExpressions.length);
17459 var deregisterFns = [];
17460 var self = this;
17461 var changeReactionScheduled = false;
17462 var firstRun = true;
17463
17464 if (!watchExpressions.length) {
17465 // No expressions means we call the listener ASAP
17466 var shouldCall = true;
17467 self.$evalAsync(function() {
17468 if (shouldCall) listener(newValues, newValues, self);
17469 });
17470 return function deregisterWatchGroup() {
17471 shouldCall = false;
17472 };
17473 }
17474
17475 if (watchExpressions.length === 1) {
17476 // Special case size of one
17477 return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
17478 newValues[0] = value;
17479 oldValues[0] = oldValue;
17480 listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
17481 });
17482 }
17483
17484 forEach(watchExpressions, function(expr, i) {
17485 var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
17486 newValues[i] = value;
17487 oldValues[i] = oldValue;
17488 if (!changeReactionScheduled) {
17489 changeReactionScheduled = true;
17490 self.$evalAsync(watchGroupAction);
17491 }
17492 });
17493 deregisterFns.push(unwatchFn);
17494 });
17495
17496 function watchGroupAction() {
17497 changeReactionScheduled = false;
17498
17499 if (firstRun) {
17500 firstRun = false;
17501 listener(newValues, newValues, self);
17502 } else {
17503 listener(newValues, oldValues, self);
17504 }
17505 }
17506
17507 return function deregisterWatchGroup() {
17508 while (deregisterFns.length) {
17509 deregisterFns.shift()();
17510 }
17511 };
17512 },
17513
17514
17515 /**
17516 * @ngdoc method
17517 * @name $rootScope.Scope#$watchCollection
17518 * @kind function
17519 *
17520 * @description
17521 * Shallow watches the properties of an object and fires whenever any of the properties change
17522 * (for arrays, this implies watching the array items; for object maps, this implies watching
17523 * the properties). If a change is detected, the `listener` callback is fired.
17524 *
17525 * - The `obj` collection is observed via standard $watch operation and is examined on every
17526 * call to $digest() to see if any items have been added, removed, or moved.
17527 * - The `listener` is called whenever anything within the `obj` has changed. Examples include
17528 * adding, removing, and moving items belonging to an object or array.
17529 *
17530 *
17531 * # Example
17532 * ```js
17533 $scope.names = ['igor', 'matias', 'misko', 'james'];
17534 $scope.dataCount = 4;
17535
17536 $scope.$watchCollection('names', function(newNames, oldNames) {
17537 $scope.dataCount = newNames.length;
17538 });
17539
17540 expect($scope.dataCount).toEqual(4);
17541 $scope.$digest();
17542
17543 //still at 4 ... no changes
17544 expect($scope.dataCount).toEqual(4);
17545
17546 $scope.names.pop();
17547 $scope.$digest();
17548
17549 //now there's been a change
17550 expect($scope.dataCount).toEqual(3);
17551 * ```
17552 *
17553 *
17554 * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
17555 * expression value should evaluate to an object or an array which is observed on each
17556 * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
17557 * collection will trigger a call to the `listener`.
17558 *
17559 * @param {function(newCollection, oldCollection, scope)} listener a callback function called
17560 * when a change is detected.
17561 * - The `newCollection` object is the newly modified data obtained from the `obj` expression
17562 * - The `oldCollection` object is a copy of the former collection data.
17563 * Due to performance considerations, the`oldCollection` value is computed only if the
17564 * `listener` function declares two or more arguments.
17565 * - The `scope` argument refers to the current scope.
17566 *
17567 * @returns {function()} Returns a de-registration function for this listener. When the
17568 * de-registration function is executed, the internal watch operation is terminated.
17569 */
17570 $watchCollection: function(obj, listener) {
17571 $watchCollectionInterceptor.$stateful = true;
17572
17573 var self = this;
17574 // the current value, updated on each dirty-check run
17575 var newValue;
17576 // a shallow copy of the newValue from the last dirty-check run,
17577 // updated to match newValue during dirty-check run
17578 var oldValue;
17579 // a shallow copy of the newValue from when the last change happened
17580 var veryOldValue;
17581 // only track veryOldValue if the listener is asking for it
17582 var trackVeryOldValue = (listener.length > 1);
17583 var changeDetected = 0;
17584 var changeDetector = $parse(obj, $watchCollectionInterceptor);
17585 var internalArray = [];
17586 var internalObject = {};
17587 var initRun = true;
17588 var oldLength = 0;
17589
17590 function $watchCollectionInterceptor(_value) {
17591 newValue = _value;
17592 var newLength, key, bothNaN, newItem, oldItem;
17593
17594 // If the new value is undefined, then return undefined as the watch may be a one-time watch
17595 if (isUndefined(newValue)) return;
17596
17597 if (!isObject(newValue)) { // if primitive
17598 if (oldValue !== newValue) {
17599 oldValue = newValue;
17600 changeDetected++;
17601 }
17602 } else if (isArrayLike(newValue)) {
17603 if (oldValue !== internalArray) {
17604 // we are transitioning from something which was not an array into array.
17605 oldValue = internalArray;
17606 oldLength = oldValue.length = 0;
17607 changeDetected++;
17608 }
17609
17610 newLength = newValue.length;
17611
17612 if (oldLength !== newLength) {
17613 // if lengths do not match we need to trigger change notification
17614 changeDetected++;
17615 oldValue.length = oldLength = newLength;
17616 }
17617 // copy the items to oldValue and look for changes.
17618 for (var i = 0; i < newLength; i++) {
17619 oldItem = oldValue[i];
17620 newItem = newValue[i];
17621
17622 // eslint-disable-next-line no-self-compare
17623 bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
17624 if (!bothNaN && (oldItem !== newItem)) {
17625 changeDetected++;
17626 oldValue[i] = newItem;
17627 }
17628 }
17629 } else {
17630 if (oldValue !== internalObject) {
17631 // we are transitioning from something which was not an object into object.
17632 oldValue = internalObject = {};
17633 oldLength = 0;
17634 changeDetected++;
17635 }
17636 // copy the items to oldValue and look for changes.
17637 newLength = 0;
17638 for (key in newValue) {
17639 if (hasOwnProperty.call(newValue, key)) {
17640 newLength++;
17641 newItem = newValue[key];
17642 oldItem = oldValue[key];
17643
17644 if (key in oldValue) {
17645 // eslint-disable-next-line no-self-compare
17646 bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
17647 if (!bothNaN && (oldItem !== newItem)) {
17648 changeDetected++;
17649 oldValue[key] = newItem;
17650 }
17651 } else {
17652 oldLength++;
17653 oldValue[key] = newItem;
17654 changeDetected++;
17655 }
17656 }
17657 }
17658 if (oldLength > newLength) {
17659 // we used to have more keys, need to find them and destroy them.
17660 changeDetected++;
17661 for (key in oldValue) {
17662 if (!hasOwnProperty.call(newValue, key)) {
17663 oldLength--;
17664 delete oldValue[key];
17665 }
17666 }
17667 }
17668 }
17669 return changeDetected;
17670 }
17671
17672 function $watchCollectionAction() {
17673 if (initRun) {
17674 initRun = false;
17675 listener(newValue, newValue, self);
17676 } else {
17677 listener(newValue, veryOldValue, self);
17678 }
17679
17680 // make a copy for the next time a collection is changed
17681 if (trackVeryOldValue) {
17682 if (!isObject(newValue)) {
17683 //primitive
17684 veryOldValue = newValue;
17685 } else if (isArrayLike(newValue)) {
17686 veryOldValue = new Array(newValue.length);
17687 for (var i = 0; i < newValue.length; i++) {
17688 veryOldValue[i] = newValue[i];
17689 }
17690 } else { // if object
17691 veryOldValue = {};
17692 for (var key in newValue) {
17693 if (hasOwnProperty.call(newValue, key)) {
17694 veryOldValue[key] = newValue[key];
17695 }
17696 }
17697 }
17698 }
17699 }
17700
17701 return this.$watch(changeDetector, $watchCollectionAction);
17702 },
17703
17704 /**
17705 * @ngdoc method
17706 * @name $rootScope.Scope#$digest
17707 * @kind function
17708 *
17709 * @description
17710 * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
17711 * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
17712 * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
17713 * until no more listeners are firing. This means that it is possible to get into an infinite
17714 * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
17715 * iterations exceeds 10.
17716 *
17717 * Usually, you don't call `$digest()` directly in
17718 * {@link ng.directive:ngController controllers} or in
17719 * {@link ng.$compileProvider#directive directives}.
17720 * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
17721 * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
17722 *
17723 * If you want to be notified whenever `$digest()` is called,
17724 * you can register a `watchExpression` function with
17725 * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
17726 *
17727 * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
17728 *
17729 * # Example
17730 * ```js
17731 var scope = ...;
17732 scope.name = 'misko';
17733 scope.counter = 0;
17734
17735 expect(scope.counter).toEqual(0);
17736 scope.$watch('name', function(newValue, oldValue) {
17737 scope.counter = scope.counter + 1;
17738 });
17739 expect(scope.counter).toEqual(0);
17740
17741 scope.$digest();
17742 // the listener is always called during the first $digest loop after it was registered
17743 expect(scope.counter).toEqual(1);
17744
17745 scope.$digest();
17746 // but now it will not be called unless the value changes
17747 expect(scope.counter).toEqual(1);
17748
17749 scope.name = 'adam';
17750 scope.$digest();
17751 expect(scope.counter).toEqual(2);
17752 * ```
17753 *
17754 */
17755 $digest: function() {
17756 var watch, value, last, fn, get,
17757 watchers,
17758 dirty, ttl = TTL,
17759 next, current, target = this,
17760 watchLog = [],
17761 logIdx, asyncTask;
17762
17763 beginPhase('$digest');
17764 // Check for changes to browser url that happened in sync before the call to $digest
17765 $browser.$$checkUrlChange();
17766
17767 if (this === $rootScope && applyAsyncId !== null) {
17768 // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
17769 // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
17770 $browser.defer.cancel(applyAsyncId);
17771 flushApplyAsync();
17772 }
17773
17774 lastDirtyWatch = null;
17775
17776 do { // "while dirty" loop
17777 dirty = false;
17778 current = target;
17779
17780 // It's safe for asyncQueuePosition to be a local variable here because this loop can't
17781 // be reentered recursively. Calling $digest from a function passed to $applyAsync would
17782 // lead to a '$digest already in progress' error.
17783 for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
17784 try {
17785 asyncTask = asyncQueue[asyncQueuePosition];
17786 asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
17787 } catch (e) {
17788 $exceptionHandler(e);
17789 }
17790 lastDirtyWatch = null;
17791 }
17792 asyncQueue.length = 0;
17793
17794 traverseScopesLoop:
17795 do { // "traverse the scopes" loop
17796 if ((watchers = current.$$watchers)) {
17797 // process our watches
17798 watchers.$$digestWatchIndex = watchers.length;
17799 while (watchers.$$digestWatchIndex--) {
17800 try {
17801 watch = watchers[watchers.$$digestWatchIndex];
17802 // Most common watches are on primitives, in which case we can short
17803 // circuit it with === operator, only when === fails do we use .equals
17804 if (watch) {
17805 get = watch.get;
17806 if ((value = get(current)) !== (last = watch.last) &&
17807 !(watch.eq
17808 ? equals(value, last)
17809 : (isNumberNaN(value) && isNumberNaN(last)))) {
17810 dirty = true;
17811 lastDirtyWatch = watch;
17812 watch.last = watch.eq ? copy(value, null) : value;
17813 fn = watch.fn;
17814 fn(value, ((last === initWatchVal) ? value : last), current);
17815 if (ttl < 5) {
17816 logIdx = 4 - ttl;
17817 if (!watchLog[logIdx]) watchLog[logIdx] = [];
17818 watchLog[logIdx].push({
17819 msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
17820 newVal: value,
17821 oldVal: last
17822 });
17823 }
17824 } else if (watch === lastDirtyWatch) {
17825 // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
17826 // have already been tested.
17827 dirty = false;
17828 break traverseScopesLoop;
17829 }
17830 }
17831 } catch (e) {
17832 $exceptionHandler(e);
17833 }
17834 }
17835 }
17836
17837 // Insanity Warning: scope depth-first traversal
17838 // yes, this code is a bit crazy, but it works and we have tests to prove it!
17839 // this piece should be kept in sync with the traversal in $broadcast
17840 if (!(next = ((current.$$watchersCount && current.$$childHead) ||
17841 (current !== target && current.$$nextSibling)))) {
17842 while (current !== target && !(next = current.$$nextSibling)) {
17843 current = current.$parent;
17844 }
17845 }
17846 } while ((current = next));
17847
17848 // `break traverseScopesLoop;` takes us to here
17849
17850 if ((dirty || asyncQueue.length) && !(ttl--)) {
17851 clearPhase();
17852 throw $rootScopeMinErr('infdig',
17853 '{0} $digest() iterations reached. Aborting!\n' +
17854 'Watchers fired in the last 5 iterations: {1}',
17855 TTL, watchLog);
17856 }
17857
17858 } while (dirty || asyncQueue.length);
17859
17860 clearPhase();
17861
17862 // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
17863 while (postDigestQueuePosition < postDigestQueue.length) {
17864 try {
17865 postDigestQueue[postDigestQueuePosition++]();
17866 } catch (e) {
17867 $exceptionHandler(e);
17868 }
17869 }
17870 postDigestQueue.length = postDigestQueuePosition = 0;
17871 },
17872
17873
17874 /**
17875 * @ngdoc event
17876 * @name $rootScope.Scope#$destroy
17877 * @eventType broadcast on scope being destroyed
17878 *
17879 * @description
17880 * Broadcasted when a scope and its children are being destroyed.
17881 *
17882 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
17883 * clean up DOM bindings before an element is removed from the DOM.
17884 */
17885
17886 /**
17887 * @ngdoc method
17888 * @name $rootScope.Scope#$destroy
17889 * @kind function
17890 *
17891 * @description
17892 * Removes the current scope (and all of its children) from the parent scope. Removal implies
17893 * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
17894 * propagate to the current scope and its children. Removal also implies that the current
17895 * scope is eligible for garbage collection.
17896 *
17897 * The `$destroy()` is usually used by directives such as
17898 * {@link ng.directive:ngRepeat ngRepeat} for managing the
17899 * unrolling of the loop.
17900 *
17901 * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
17902 * Application code can register a `$destroy` event handler that will give it a chance to
17903 * perform any necessary cleanup.
17904 *
17905 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
17906 * clean up DOM bindings before an element is removed from the DOM.
17907 */
17908 $destroy: function() {
17909 // We can't destroy a scope that has been already destroyed.
17910 if (this.$$destroyed) return;
17911 var parent = this.$parent;
17912
17913 this.$broadcast('$destroy');
17914 this.$$destroyed = true;
17915
17916 if (this === $rootScope) {
17917 //Remove handlers attached to window when $rootScope is removed
17918 $browser.$$applicationDestroyed();
17919 }
17920
17921 incrementWatchersCount(this, -this.$$watchersCount);
17922 for (var eventName in this.$$listenerCount) {
17923 decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
17924 }
17925
17926 // sever all the references to parent scopes (after this cleanup, the current scope should
17927 // not be retained by any of our references and should be eligible for garbage collection)
17928 if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
17929 if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
17930 if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
17931 if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
17932
17933 // Disable listeners, watchers and apply/digest methods
17934 this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
17935 this.$on = this.$watch = this.$watchGroup = function() { return noop; };
17936 this.$$listeners = {};
17937
17938 // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
17939 this.$$nextSibling = null;
17940 cleanUpScope(this);
17941 },
17942
17943 /**
17944 * @ngdoc method
17945 * @name $rootScope.Scope#$eval
17946 * @kind function
17947 *
17948 * @description
17949 * Executes the `expression` on the current scope and returns the result. Any exceptions in
17950 * the expression are propagated (uncaught). This is useful when evaluating Angular
17951 * expressions.
17952 *
17953 * # Example
17954 * ```js
17955 var scope = ng.$rootScope.Scope();
17956 scope.a = 1;
17957 scope.b = 2;
17958
17959 expect(scope.$eval('a+b')).toEqual(3);
17960 expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
17961 * ```
17962 *
17963 * @param {(string|function())=} expression An angular expression to be executed.
17964 *
17965 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
17966 * - `function(scope)`: execute the function with the current `scope` parameter.
17967 *
17968 * @param {(object)=} locals Local variables object, useful for overriding values in scope.
17969 * @returns {*} The result of evaluating the expression.
17970 */
17971 $eval: function(expr, locals) {
17972 return $parse(expr)(this, locals);
17973 },
17974
17975 /**
17976 * @ngdoc method
17977 * @name $rootScope.Scope#$evalAsync
17978 * @kind function
17979 *
17980 * @description
17981 * Executes the expression on the current scope at a later point in time.
17982 *
17983 * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
17984 * that:
17985 *
17986 * - it will execute after the function that scheduled the evaluation (preferably before DOM
17987 * rendering).
17988 * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
17989 * `expression` execution.
17990 *
17991 * Any exceptions from the execution of the expression are forwarded to the
17992 * {@link ng.$exceptionHandler $exceptionHandler} service.
17993 *
17994 * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
17995 * will be scheduled. However, it is encouraged to always call code that changes the model
17996 * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
17997 *
17998 * @param {(string|function())=} expression An angular expression to be executed.
17999 *
18000 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
18001 * - `function(scope)`: execute the function with the current `scope` parameter.
18002 *
18003 * @param {(object)=} locals Local variables object, useful for overriding values in scope.
18004 */
18005 $evalAsync: function(expr, locals) {
18006 // if we are outside of an $digest loop and this is the first time we are scheduling async
18007 // task also schedule async auto-flush
18008 if (!$rootScope.$$phase && !asyncQueue.length) {
18009 $browser.defer(function() {
18010 if (asyncQueue.length) {
18011 $rootScope.$digest();
18012 }
18013 });
18014 }
18015
18016 asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
18017 },
18018
18019 $$postDigest: function(fn) {
18020 postDigestQueue.push(fn);
18021 },
18022
18023 /**
18024 * @ngdoc method
18025 * @name $rootScope.Scope#$apply
18026 * @kind function
18027 *
18028 * @description
18029 * `$apply()` is used to execute an expression in angular from outside of the angular
18030 * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
18031 * Because we are calling into the angular framework we need to perform proper scope life
18032 * cycle of {@link ng.$exceptionHandler exception handling},
18033 * {@link ng.$rootScope.Scope#$digest executing watches}.
18034 *
18035 * ## Life cycle
18036 *
18037 * # Pseudo-Code of `$apply()`
18038 * ```js
18039 function $apply(expr) {
18040 try {
18041 return $eval(expr);
18042 } catch (e) {
18043 $exceptionHandler(e);
18044 } finally {
18045 $root.$digest();
18046 }
18047 }
18048 * ```
18049 *
18050 *
18051 * Scope's `$apply()` method transitions through the following stages:
18052 *
18053 * 1. The {@link guide/expression expression} is executed using the
18054 * {@link ng.$rootScope.Scope#$eval $eval()} method.
18055 * 2. Any exceptions from the execution of the expression are forwarded to the
18056 * {@link ng.$exceptionHandler $exceptionHandler} service.
18057 * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
18058 * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
18059 *
18060 *
18061 * @param {(string|function())=} exp An angular expression to be executed.
18062 *
18063 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
18064 * - `function(scope)`: execute the function with current `scope` parameter.
18065 *
18066 * @returns {*} The result of evaluating the expression.
18067 */
18068 $apply: function(expr) {
18069 try {
18070 beginPhase('$apply');
18071 try {
18072 return this.$eval(expr);
18073 } finally {
18074 clearPhase();
18075 }
18076 } catch (e) {
18077 $exceptionHandler(e);
18078 } finally {
18079 try {
18080 $rootScope.$digest();
18081 } catch (e) {
18082 $exceptionHandler(e);
18083 // eslint-disable-next-line no-unsafe-finally
18084 throw e;
18085 }
18086 }
18087 },
18088
18089 /**
18090 * @ngdoc method
18091 * @name $rootScope.Scope#$applyAsync
18092 * @kind function
18093 *
18094 * @description
18095 * Schedule the invocation of $apply to occur at a later time. The actual time difference
18096 * varies across browsers, but is typically around ~10 milliseconds.
18097 *
18098 * This can be used to queue up multiple expressions which need to be evaluated in the same
18099 * digest.
18100 *
18101 * @param {(string|function())=} exp An angular expression to be executed.
18102 *
18103 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
18104 * - `function(scope)`: execute the function with current `scope` parameter.
18105 */
18106 $applyAsync: function(expr) {
18107 var scope = this;
18108 if (expr) {
18109 applyAsyncQueue.push($applyAsyncExpression);
18110 }
18111 expr = $parse(expr);
18112 scheduleApplyAsync();
18113
18114 function $applyAsyncExpression() {
18115 scope.$eval(expr);
18116 }
18117 },
18118
18119 /**
18120 * @ngdoc method
18121 * @name $rootScope.Scope#$on
18122 * @kind function
18123 *
18124 * @description
18125 * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
18126 * discussion of event life cycle.
18127 *
18128 * The event listener function format is: `function(event, args...)`. The `event` object
18129 * passed into the listener has the following attributes:
18130 *
18131 * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
18132 * `$broadcast`-ed.
18133 * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
18134 * event propagates through the scope hierarchy, this property is set to null.
18135 * - `name` - `{string}`: name of the event.
18136 * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
18137 * further event propagation (available only for events that were `$emit`-ed).
18138 * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
18139 * to true.
18140 * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
18141 *
18142 * @param {string} name Event name to listen on.
18143 * @param {function(event, ...args)} listener Function to call when the event is emitted.
18144 * @returns {function()} Returns a deregistration function for this listener.
18145 */
18146 $on: function(name, listener) {
18147 var namedListeners = this.$$listeners[name];
18148 if (!namedListeners) {
18149 this.$$listeners[name] = namedListeners = [];
18150 }
18151 namedListeners.push(listener);
18152
18153 var current = this;
18154 do {
18155 if (!current.$$listenerCount[name]) {
18156 current.$$listenerCount[name] = 0;
18157 }
18158 current.$$listenerCount[name]++;
18159 } while ((current = current.$parent));
18160
18161 var self = this;
18162 return function() {
18163 var indexOfListener = namedListeners.indexOf(listener);
18164 if (indexOfListener !== -1) {
18165 namedListeners[indexOfListener] = null;
18166 decrementListenerCount(self, 1, name);
18167 }
18168 };
18169 },
18170
18171
18172 /**
18173 * @ngdoc method
18174 * @name $rootScope.Scope#$emit
18175 * @kind function
18176 *
18177 * @description
18178 * Dispatches an event `name` upwards through the scope hierarchy notifying the
18179 * registered {@link ng.$rootScope.Scope#$on} listeners.
18180 *
18181 * The event life cycle starts at the scope on which `$emit` was called. All
18182 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
18183 * notified. Afterwards, the event traverses upwards toward the root scope and calls all
18184 * registered listeners along the way. The event will stop propagating if one of the listeners
18185 * cancels it.
18186 *
18187 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
18188 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
18189 *
18190 * @param {string} name Event name to emit.
18191 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
18192 * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
18193 */
18194 $emit: function(name, args) {
18195 var empty = [],
18196 namedListeners,
18197 scope = this,
18198 stopPropagation = false,
18199 event = {
18200 name: name,
18201 targetScope: scope,
18202 stopPropagation: function() {stopPropagation = true;},
18203 preventDefault: function() {
18204 event.defaultPrevented = true;
18205 },
18206 defaultPrevented: false
18207 },
18208 listenerArgs = concat([event], arguments, 1),
18209 i, length;
18210
18211 do {
18212 namedListeners = scope.$$listeners[name] || empty;
18213 event.currentScope = scope;
18214 for (i = 0, length = namedListeners.length; i < length; i++) {
18215
18216 // if listeners were deregistered, defragment the array
18217 if (!namedListeners[i]) {
18218 namedListeners.splice(i, 1);
18219 i--;
18220 length--;
18221 continue;
18222 }
18223 try {
18224 //allow all listeners attached to the current scope to run
18225 namedListeners[i].apply(null, listenerArgs);
18226 } catch (e) {
18227 $exceptionHandler(e);
18228 }
18229 }
18230 //if any listener on the current scope stops propagation, prevent bubbling
18231 if (stopPropagation) {
18232 event.currentScope = null;
18233 return event;
18234 }
18235 //traverse upwards
18236 scope = scope.$parent;
18237 } while (scope);
18238
18239 event.currentScope = null;
18240
18241 return event;
18242 },
18243
18244
18245 /**
18246 * @ngdoc method
18247 * @name $rootScope.Scope#$broadcast
18248 * @kind function
18249 *
18250 * @description
18251 * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
18252 * registered {@link ng.$rootScope.Scope#$on} listeners.
18253 *
18254 * The event life cycle starts at the scope on which `$broadcast` was called. All
18255 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
18256 * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
18257 * scope and calls all registered listeners along the way. The event cannot be canceled.
18258 *
18259 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
18260 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
18261 *
18262 * @param {string} name Event name to broadcast.
18263 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
18264 * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
18265 */
18266 $broadcast: function(name, args) {
18267 var target = this,
18268 current = target,
18269 next = target,
18270 event = {
18271 name: name,
18272 targetScope: target,
18273 preventDefault: function() {
18274 event.defaultPrevented = true;
18275 },
18276 defaultPrevented: false
18277 };
18278
18279 if (!target.$$listenerCount[name]) return event;
18280
18281 var listenerArgs = concat([event], arguments, 1),
18282 listeners, i, length;
18283
18284 //down while you can, then up and next sibling or up and next sibling until back at root
18285 while ((current = next)) {
18286 event.currentScope = current;
18287 listeners = current.$$listeners[name] || [];
18288 for (i = 0, length = listeners.length; i < length; i++) {
18289 // if listeners were deregistered, defragment the array
18290 if (!listeners[i]) {
18291 listeners.splice(i, 1);
18292 i--;
18293 length--;
18294 continue;
18295 }
18296
18297 try {
18298 listeners[i].apply(null, listenerArgs);
18299 } catch (e) {
18300 $exceptionHandler(e);
18301 }
18302 }
18303
18304 // Insanity Warning: scope depth-first traversal
18305 // yes, this code is a bit crazy, but it works and we have tests to prove it!
18306 // this piece should be kept in sync with the traversal in $digest
18307 // (though it differs due to having the extra check for $$listenerCount)
18308 if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
18309 (current !== target && current.$$nextSibling)))) {
18310 while (current !== target && !(next = current.$$nextSibling)) {
18311 current = current.$parent;
18312 }
18313 }
18314 }
18315
18316 event.currentScope = null;
18317 return event;
18318 }
18319 };
18320
18321 var $rootScope = new Scope();
18322
18323 //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
18324 var asyncQueue = $rootScope.$$asyncQueue = [];
18325 var postDigestQueue = $rootScope.$$postDigestQueue = [];
18326 var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
18327
18328 var postDigestQueuePosition = 0;
18329
18330 return $rootScope;
18331
18332
18333 function beginPhase(phase) {
18334 if ($rootScope.$$phase) {
18335 throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
18336 }
18337
18338 $rootScope.$$phase = phase;
18339 }
18340
18341 function clearPhase() {
18342 $rootScope.$$phase = null;
18343 }
18344
18345 function incrementWatchersCount(current, count) {
18346 do {
18347 current.$$watchersCount += count;
18348 } while ((current = current.$parent));
18349 }
18350
18351 function decrementListenerCount(current, count, name) {
18352 do {
18353 current.$$listenerCount[name] -= count;
18354
18355 if (current.$$listenerCount[name] === 0) {
18356 delete current.$$listenerCount[name];
18357 }
18358 } while ((current = current.$parent));
18359 }
18360
18361 /**
18362 * function used as an initial value for watchers.
18363 * because it's unique we can easily tell it apart from other values
18364 */
18365 function initWatchVal() {}
18366
18367 function flushApplyAsync() {
18368 while (applyAsyncQueue.length) {
18369 try {
18370 applyAsyncQueue.shift()();
18371 } catch (e) {
18372 $exceptionHandler(e);
18373 }
18374 }
18375 applyAsyncId = null;
18376 }
18377
18378 function scheduleApplyAsync() {
18379 if (applyAsyncId === null) {
18380 applyAsyncId = $browser.defer(function() {
18381 $rootScope.$apply(flushApplyAsync);
18382 });
18383 }
18384 }
18385 }];
18386}
18387
18388/**
18389 * @ngdoc service
18390 * @name $rootElement
18391 *
18392 * @description
18393 * The root element of Angular application. This is either the element where {@link
18394 * ng.directive:ngApp ngApp} was declared or the element passed into
18395 * {@link angular.bootstrap}. The element represents the root element of application. It is also the
18396 * location where the application's {@link auto.$injector $injector} service gets
18397 * published, and can be retrieved using `$rootElement.injector()`.
18398 */
18399
18400
18401// the implementation is in angular.bootstrap
18402
18403/**
18404 * @this
18405 * @description
18406 * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
18407 */
18408function $$SanitizeUriProvider() {
18409 var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
18410 imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
18411
18412 /**
18413 * @description
18414 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
18415 * urls during a[href] sanitization.
18416 *
18417 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
18418 *
18419 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
18420 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
18421 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
18422 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
18423 *
18424 * @param {RegExp=} regexp New regexp to whitelist urls with.
18425 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
18426 * chaining otherwise.
18427 */
18428 this.aHrefSanitizationWhitelist = function(regexp) {
18429 if (isDefined(regexp)) {
18430 aHrefSanitizationWhitelist = regexp;
18431 return this;
18432 }
18433 return aHrefSanitizationWhitelist;
18434 };
18435
18436
18437 /**
18438 * @description
18439 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
18440 * urls during img[src] sanitization.
18441 *
18442 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
18443 *
18444 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
18445 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
18446 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
18447 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
18448 *
18449 * @param {RegExp=} regexp New regexp to whitelist urls with.
18450 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
18451 * chaining otherwise.
18452 */
18453 this.imgSrcSanitizationWhitelist = function(regexp) {
18454 if (isDefined(regexp)) {
18455 imgSrcSanitizationWhitelist = regexp;
18456 return this;
18457 }
18458 return imgSrcSanitizationWhitelist;
18459 };
18460
18461 this.$get = function() {
18462 return function sanitizeUri(uri, isImage) {
18463 var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
18464 var normalizedVal;
18465 normalizedVal = urlResolve(uri).href;
18466 if (normalizedVal !== '' && !normalizedVal.match(regex)) {
18467 return 'unsafe:' + normalizedVal;
18468 }
18469 return uri;
18470 };
18471 };
18472}
18473
18474/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
18475 * Any commits to this file should be reviewed with security in mind. *
18476 * Changes to this file can potentially create security vulnerabilities. *
18477 * An approval from 2 Core members with history of modifying *
18478 * this file is required. *
18479 * *
18480 * Does the change somehow allow for arbitrary javascript to be executed? *
18481 * Or allows for someone to change the prototype of built-in objects? *
18482 * Or gives undesired access to variables likes document or window? *
18483 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
18484
18485/* exported $SceProvider, $SceDelegateProvider */
18486
18487var $sceMinErr = minErr('$sce');
18488
18489var SCE_CONTEXTS = {
18490 HTML: 'html',
18491 CSS: 'css',
18492 URL: 'url',
18493 // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
18494 // url. (e.g. ng-include, script src, templateUrl)
18495 RESOURCE_URL: 'resourceUrl',
18496 JS: 'js'
18497};
18498
18499// Helper functions follow.
18500
18501var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
18502
18503function snakeToCamel(name) {
18504 return name
18505 .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
18506}
18507
18508function adjustMatcher(matcher) {
18509 if (matcher === 'self') {
18510 return matcher;
18511 } else if (isString(matcher)) {
18512 // Strings match exactly except for 2 wildcards - '*' and '**'.
18513 // '*' matches any character except those from the set ':/.?&'.
18514 // '**' matches any character (like .* in a RegExp).
18515 // More than 2 *'s raises an error as it's ill defined.
18516 if (matcher.indexOf('***') > -1) {
18517 throw $sceMinErr('iwcard',
18518 'Illegal sequence *** in string matcher. String: {0}', matcher);
18519 }
18520 matcher = escapeForRegexp(matcher).
18521 replace(/\\\*\\\*/g, '.*').
18522 replace(/\\\*/g, '[^:/.?&;]*');
18523 return new RegExp('^' + matcher + '$');
18524 } else if (isRegExp(matcher)) {
18525 // The only other type of matcher allowed is a Regexp.
18526 // Match entire URL / disallow partial matches.
18527 // Flags are reset (i.e. no global, ignoreCase or multiline)
18528 return new RegExp('^' + matcher.source + '$');
18529 } else {
18530 throw $sceMinErr('imatcher',
18531 'Matchers may only be "self", string patterns or RegExp objects');
18532 }
18533}
18534
18535
18536function adjustMatchers(matchers) {
18537 var adjustedMatchers = [];
18538 if (isDefined(matchers)) {
18539 forEach(matchers, function(matcher) {
18540 adjustedMatchers.push(adjustMatcher(matcher));
18541 });
18542 }
18543 return adjustedMatchers;
18544}
18545
18546
18547/**
18548 * @ngdoc service
18549 * @name $sceDelegate
18550 * @kind function
18551 *
18552 * @description
18553 *
18554 * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
18555 * Contextual Escaping (SCE)} services to AngularJS.
18556 *
18557 * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
18558 * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
18559 * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
18560 * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
18561 * work because `$sce` delegates to `$sceDelegate` for these operations.
18562 *
18563 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
18564 *
18565 * The default instance of `$sceDelegate` should work out of the box with little pain. While you
18566 * can override it completely to change the behavior of `$sce`, the common case would
18567 * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
18568 * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
18569 * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
18570 * $sceDelegateProvider.resourceUrlWhitelist} and {@link
18571 * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
18572 */
18573
18574/**
18575 * @ngdoc provider
18576 * @name $sceDelegateProvider
18577 * @this
18578 *
18579 * @description
18580 *
18581 * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
18582 * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
18583 * that the URLs used for sourcing Angular templates are safe. Refer {@link
18584 * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
18585 * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
18586 *
18587 * For the general details about this service in Angular, read the main page for {@link ng.$sce
18588 * Strict Contextual Escaping (SCE)}.
18589 *
18590 * **Example**: Consider the following case. <a name="example"></a>
18591 *
18592 * - your app is hosted at url `http://myapp.example.com/`
18593 * - but some of your templates are hosted on other domains you control such as
18594 * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
18595 * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
18596 *
18597 * Here is what a secure configuration for this scenario might look like:
18598 *
18599 * ```
18600 * angular.module('myApp', []).config(function($sceDelegateProvider) {
18601 * $sceDelegateProvider.resourceUrlWhitelist([
18602 * // Allow same origin resource loads.
18603 * 'self',
18604 * // Allow loading from our assets domain. Notice the difference between * and **.
18605 * 'http://srv*.assets.example.com/**'
18606 * ]);
18607 *
18608 * // The blacklist overrides the whitelist so the open redirect here is blocked.
18609 * $sceDelegateProvider.resourceUrlBlacklist([
18610 * 'http://myapp.example.com/clickThru**'
18611 * ]);
18612 * });
18613 * ```
18614 */
18615
18616function $SceDelegateProvider() {
18617 this.SCE_CONTEXTS = SCE_CONTEXTS;
18618
18619 // Resource URLs can also be trusted by policy.
18620 var resourceUrlWhitelist = ['self'],
18621 resourceUrlBlacklist = [];
18622
18623 /**
18624 * @ngdoc method
18625 * @name $sceDelegateProvider#resourceUrlWhitelist
18626 * @kind function
18627 *
18628 * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
18629 * provided. This must be an array or null. A snapshot of this array is used so further
18630 * changes to the array are ignored.
18631 *
18632 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
18633 * allowed in this array.
18634 *
18635 * <div class="alert alert-warning">
18636 * **Note:** an empty whitelist array will block all URLs!
18637 * </div>
18638 *
18639 * @return {Array} the currently set whitelist array.
18640 *
18641 * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
18642 * same origin resource requests.
18643 *
18644 * @description
18645 * Sets/Gets the whitelist of trusted resource URLs.
18646 */
18647 this.resourceUrlWhitelist = function(value) {
18648 if (arguments.length) {
18649 resourceUrlWhitelist = adjustMatchers(value);
18650 }
18651 return resourceUrlWhitelist;
18652 };
18653
18654 /**
18655 * @ngdoc method
18656 * @name $sceDelegateProvider#resourceUrlBlacklist
18657 * @kind function
18658 *
18659 * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
18660 * provided. This must be an array or null. A snapshot of this array is used so further
18661 * changes to the array are ignored.
18662 *
18663 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
18664 * allowed in this array.
18665 *
18666 * The typical usage for the blacklist is to **block
18667 * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
18668 * these would otherwise be trusted but actually return content from the redirected domain.
18669 *
18670 * Finally, **the blacklist overrides the whitelist** and has the final say.
18671 *
18672 * @return {Array} the currently set blacklist array.
18673 *
18674 * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
18675 * is no blacklist.)
18676 *
18677 * @description
18678 * Sets/Gets the blacklist of trusted resource URLs.
18679 */
18680
18681 this.resourceUrlBlacklist = function(value) {
18682 if (arguments.length) {
18683 resourceUrlBlacklist = adjustMatchers(value);
18684 }
18685 return resourceUrlBlacklist;
18686 };
18687
18688 this.$get = ['$injector', function($injector) {
18689
18690 var htmlSanitizer = function htmlSanitizer(html) {
18691 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
18692 };
18693
18694 if ($injector.has('$sanitize')) {
18695 htmlSanitizer = $injector.get('$sanitize');
18696 }
18697
18698
18699 function matchUrl(matcher, parsedUrl) {
18700 if (matcher === 'self') {
18701 return urlIsSameOrigin(parsedUrl);
18702 } else {
18703 // definitely a regex. See adjustMatchers()
18704 return !!matcher.exec(parsedUrl.href);
18705 }
18706 }
18707
18708 function isResourceUrlAllowedByPolicy(url) {
18709 var parsedUrl = urlResolve(url.toString());
18710 var i, n, allowed = false;
18711 // Ensure that at least one item from the whitelist allows this url.
18712 for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
18713 if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
18714 allowed = true;
18715 break;
18716 }
18717 }
18718 if (allowed) {
18719 // Ensure that no item from the blacklist blocked this url.
18720 for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
18721 if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
18722 allowed = false;
18723 break;
18724 }
18725 }
18726 }
18727 return allowed;
18728 }
18729
18730 function generateHolderType(Base) {
18731 var holderType = function TrustedValueHolderType(trustedValue) {
18732 this.$$unwrapTrustedValue = function() {
18733 return trustedValue;
18734 };
18735 };
18736 if (Base) {
18737 holderType.prototype = new Base();
18738 }
18739 holderType.prototype.valueOf = function sceValueOf() {
18740 return this.$$unwrapTrustedValue();
18741 };
18742 holderType.prototype.toString = function sceToString() {
18743 return this.$$unwrapTrustedValue().toString();
18744 };
18745 return holderType;
18746 }
18747
18748 var trustedValueHolderBase = generateHolderType(),
18749 byType = {};
18750
18751 byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
18752 byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
18753 byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
18754 byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
18755 byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
18756
18757 /**
18758 * @ngdoc method
18759 * @name $sceDelegate#trustAs
18760 *
18761 * @description
18762 * Returns an object that is trusted by angular for use in specified strict
18763 * contextual escaping contexts (such as ng-bind-html, ng-include, any src
18764 * attribute interpolation, any dom event binding attribute interpolation
18765 * such as for onclick, etc.) that uses the provided value.
18766 * See {@link ng.$sce $sce} for enabling strict contextual escaping.
18767 *
18768 * @param {string} type The kind of context in which this value is safe for use. e.g. url,
18769 * resourceUrl, html, js and css.
18770 * @param {*} value The value that that should be considered trusted/safe.
18771 * @returns {*} A value that can be used to stand in for the provided `value` in places
18772 * where Angular expects a $sce.trustAs() return value.
18773 */
18774 function trustAs(type, trustedValue) {
18775 var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
18776 if (!Constructor) {
18777 throw $sceMinErr('icontext',
18778 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
18779 type, trustedValue);
18780 }
18781 if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
18782 return trustedValue;
18783 }
18784 // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
18785 // mutable objects, we ensure here that the value passed in is actually a string.
18786 if (typeof trustedValue !== 'string') {
18787 throw $sceMinErr('itype',
18788 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
18789 type);
18790 }
18791 return new Constructor(trustedValue);
18792 }
18793
18794 /**
18795 * @ngdoc method
18796 * @name $sceDelegate#valueOf
18797 *
18798 * @description
18799 * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
18800 * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
18801 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
18802 *
18803 * If the passed parameter is not a value that had been returned by {@link
18804 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
18805 *
18806 * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
18807 * call or anything else.
18808 * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
18809 * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
18810 * `value` unchanged.
18811 */
18812 function valueOf(maybeTrusted) {
18813 if (maybeTrusted instanceof trustedValueHolderBase) {
18814 return maybeTrusted.$$unwrapTrustedValue();
18815 } else {
18816 return maybeTrusted;
18817 }
18818 }
18819
18820 /**
18821 * @ngdoc method
18822 * @name $sceDelegate#getTrusted
18823 *
18824 * @description
18825 * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
18826 * returns the originally supplied value if the queried context type is a supertype of the
18827 * created type. If this condition isn't satisfied, throws an exception.
18828 *
18829 * <div class="alert alert-danger">
18830 * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
18831 * (XSS) vulnerability in your application.
18832 * </div>
18833 *
18834 * @param {string} type The kind of context in which this value is to be used.
18835 * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
18836 * `$sceDelegate.trustAs`} call.
18837 * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
18838 * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
18839 */
18840 function getTrusted(type, maybeTrusted) {
18841 if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
18842 return maybeTrusted;
18843 }
18844 var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
18845 if (constructor && maybeTrusted instanceof constructor) {
18846 return maybeTrusted.$$unwrapTrustedValue();
18847 }
18848 // If we get here, then we may only take one of two actions.
18849 // 1. sanitize the value for the requested type, or
18850 // 2. throw an exception.
18851 if (type === SCE_CONTEXTS.RESOURCE_URL) {
18852 if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
18853 return maybeTrusted;
18854 } else {
18855 throw $sceMinErr('insecurl',
18856 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
18857 maybeTrusted.toString());
18858 }
18859 } else if (type === SCE_CONTEXTS.HTML) {
18860 return htmlSanitizer(maybeTrusted);
18861 }
18862 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
18863 }
18864
18865 return { trustAs: trustAs,
18866 getTrusted: getTrusted,
18867 valueOf: valueOf };
18868 }];
18869}
18870
18871
18872/**
18873 * @ngdoc provider
18874 * @name $sceProvider
18875 * @this
18876 *
18877 * @description
18878 *
18879 * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
18880 * - enable/disable Strict Contextual Escaping (SCE) in a module
18881 * - override the default implementation with a custom delegate
18882 *
18883 * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
18884 */
18885
18886/**
18887 * @ngdoc service
18888 * @name $sce
18889 * @kind function
18890 *
18891 * @description
18892 *
18893 * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
18894 *
18895 * # Strict Contextual Escaping
18896 *
18897 * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
18898 * contexts to result in a value that is marked as safe to use for that context. One example of
18899 * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
18900 * to these contexts as privileged or SCE contexts.
18901 *
18902 * As of version 1.2, Angular ships with SCE enabled by default.
18903 *
18904 * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
18905 * one to execute arbitrary javascript by the use of the expression() syntax. Refer
18906 * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
18907 * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
18908 * to the top of your HTML document.
18909 *
18910 * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for
18911 * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
18912 *
18913 * Here's an example of a binding in a privileged context:
18914 *
18915 * ```
18916 * <input ng-model="userHtml" aria-label="User input">
18917 * <div ng-bind-html="userHtml"></div>
18918 * ```
18919 *
18920 * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
18921 * disabled, this application allows the user to render arbitrary HTML into the DIV.
18922 * In a more realistic example, one may be rendering user comments, blog articles, etc. via
18923 * bindings. (HTML is just one example of a context where rendering user controlled input creates
18924 * security vulnerabilities.)
18925 *
18926 * For the case of HTML, you might use a library, either on the client side, or on the server side,
18927 * to sanitize unsafe HTML before binding to the value and rendering it in the document.
18928 *
18929 * How would you ensure that every place that used these types of bindings was bound to a value that
18930 * was sanitized by your library (or returned as safe for rendering by your server?) How can you
18931 * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
18932 * properties/fields and forgot to update the binding to the sanitized value?
18933 *
18934 * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
18935 * determine that something explicitly says it's safe to use a value for binding in that
18936 * context. You can then audit your code (a simple grep would do) to ensure that this is only done
18937 * for those values that you can easily tell are safe - because they were received from your server,
18938 * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
18939 * allowing only the files in a specific directory to do this. Ensuring that the internal API
18940 * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
18941 *
18942 * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
18943 * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
18944 * obtain values that will be accepted by SCE / privileged contexts.
18945 *
18946 *
18947 * ## How does it work?
18948 *
18949 * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
18950 * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
18951 * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
18952 * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
18953 *
18954 * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
18955 * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
18956 * simplified):
18957 *
18958 * ```
18959 * var ngBindHtmlDirective = ['$sce', function($sce) {
18960 * return function(scope, element, attr) {
18961 * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
18962 * element.html(value || '');
18963 * });
18964 * };
18965 * }];
18966 * ```
18967 *
18968 * ## Impact on loading templates
18969 *
18970 * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
18971 * `templateUrl`'s specified by {@link guide/directive directives}.
18972 *
18973 * By default, Angular only loads templates from the same domain and protocol as the application
18974 * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
18975 * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
18976 * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
18977 * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
18978 *
18979 * *Please note*:
18980 * The browser's
18981 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
18982 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
18983 * policy apply in addition to this and may further restrict whether the template is successfully
18984 * loaded. This means that without the right CORS policy, loading templates from a different domain
18985 * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
18986 * browsers.
18987 *
18988 * ## This feels like too much overhead
18989 *
18990 * It's important to remember that SCE only applies to interpolation expressions.
18991 *
18992 * If your expressions are constant literals, they're automatically trusted and you don't need to
18993 * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
18994 * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
18995 *
18996 * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
18997 * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
18998 *
18999 * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
19000 * templates in `ng-include` from your application's domain without having to even know about SCE.
19001 * It blocks loading templates from other domains or loading templates over http from an https
19002 * served document. You can change these by setting your own custom {@link
19003 * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
19004 * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
19005 *
19006 * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
19007 * application that's secure and can be audited to verify that with much more ease than bolting
19008 * security onto an application later.
19009 *
19010 * <a name="contexts"></a>
19011 * ## What trusted context types are supported?
19012 *
19013 * | Context | Notes |
19014 * |---------------------|----------------|
19015 * | `$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. |
19016 * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
19017 * | `$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. |
19018 * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
19019 * | `$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. |
19020 *
19021 * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
19022 *
19023 * Each element in these arrays must be one of the following:
19024 *
19025 * - **'self'**
19026 * - The special **string**, `'self'`, can be used to match against all URLs of the **same
19027 * domain** as the application document using the **same protocol**.
19028 * - **String** (except the special value `'self'`)
19029 * - The string is matched against the full *normalized / absolute URL* of the resource
19030 * being tested (substring matches are not good enough.)
19031 * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
19032 * match themselves.
19033 * - `*`: matches zero or more occurrences of any character other than one of the following 6
19034 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
19035 * in a whitelist.
19036 * - `**`: matches zero or more occurrences of *any* character. As such, it's not
19037 * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
19038 * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
19039 * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
19040 * http://foo.example.com/templates/**).
19041 * - **RegExp** (*see caveat below*)
19042 * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
19043 * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
19044 * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
19045 * have good test coverage). For instance, the use of `.` in the regex is correct only in a
19046 * small number of cases. A `.` character in the regex used when matching the scheme or a
19047 * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
19048 * is highly recommended to use the string patterns and only fall back to regular expressions
19049 * as a last resort.
19050 * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
19051 * matched against the **entire** *normalized / absolute URL* of the resource being tested
19052 * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
19053 * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
19054 * - If you are generating your JavaScript from some other templating engine (not
19055 * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
19056 * remember to escape your regular expression (and be aware that you might need more than
19057 * one level of escaping depending on your templating engine and the way you interpolated
19058 * the value.) Do make use of your platform's escaping mechanism as it might be good
19059 * enough before coding your own. E.g. Ruby has
19060 * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
19061 * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
19062 * Javascript lacks a similar built in function for escaping. Take a look at Google
19063 * Closure library's [goog.string.regExpEscape(s)](
19064 * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
19065 *
19066 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
19067 *
19068 * ## Show me an example using SCE.
19069 *
19070 * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
19071 * <file name="index.html">
19072 * <div ng-controller="AppController as myCtrl">
19073 * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
19074 * <b>User comments</b><br>
19075 * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
19076 * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
19077 * exploit.
19078 * <div class="well">
19079 * <div ng-repeat="userComment in myCtrl.userComments">
19080 * <b>{{userComment.name}}</b>:
19081 * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
19082 * <br>
19083 * </div>
19084 * </div>
19085 * </div>
19086 * </file>
19087 *
19088 * <file name="script.js">
19089 * angular.module('mySceApp', ['ngSanitize'])
19090 * .controller('AppController', ['$http', '$templateCache', '$sce',
19091 * function AppController($http, $templateCache, $sce) {
19092 * var self = this;
19093 * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
19094 * self.userComments = response.data;
19095 * });
19096 * self.explicitlyTrustedHtml = $sce.trustAsHtml(
19097 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
19098 * 'sanitization."">Hover over this text.</span>');
19099 * }]);
19100 * </file>
19101 *
19102 * <file name="test_data.json">
19103 * [
19104 * { "name": "Alice",
19105 * "htmlComment":
19106 * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
19107 * },
19108 * { "name": "Bob",
19109 * "htmlComment": "<i>Yes!</i> Am I the only other one?"
19110 * }
19111 * ]
19112 * </file>
19113 *
19114 * <file name="protractor.js" type="protractor">
19115 * describe('SCE doc demo', function() {
19116 * it('should sanitize untrusted values', function() {
19117 * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
19118 * .toBe('<span>Is <i>anyone</i> reading this?</span>');
19119 * });
19120 *
19121 * it('should NOT sanitize explicitly trusted values', function() {
19122 * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
19123 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
19124 * 'sanitization."">Hover over this text.</span>');
19125 * });
19126 * });
19127 * </file>
19128 * </example>
19129 *
19130 *
19131 *
19132 * ## Can I disable SCE completely?
19133 *
19134 * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
19135 * for little coding overhead. It will be much harder to take an SCE disabled application and
19136 * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
19137 * for cases where you have a lot of existing code that was written before SCE was introduced and
19138 * you're migrating them a module at a time.
19139 *
19140 * That said, here's how you can completely disable SCE:
19141 *
19142 * ```
19143 * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
19144 * // Completely disable SCE. For demonstration purposes only!
19145 * // Do not use in new projects.
19146 * $sceProvider.enabled(false);
19147 * });
19148 * ```
19149 *
19150 */
19151
19152function $SceProvider() {
19153 var enabled = true;
19154
19155 /**
19156 * @ngdoc method
19157 * @name $sceProvider#enabled
19158 * @kind function
19159 *
19160 * @param {boolean=} value If provided, then enables/disables SCE.
19161 * @return {boolean} true if SCE is enabled, false otherwise.
19162 *
19163 * @description
19164 * Enables/disables SCE and returns the current value.
19165 */
19166 this.enabled = function(value) {
19167 if (arguments.length) {
19168 enabled = !!value;
19169 }
19170 return enabled;
19171 };
19172
19173
19174 /* Design notes on the default implementation for SCE.
19175 *
19176 * The API contract for the SCE delegate
19177 * -------------------------------------
19178 * The SCE delegate object must provide the following 3 methods:
19179 *
19180 * - trustAs(contextEnum, value)
19181 * This method is used to tell the SCE service that the provided value is OK to use in the
19182 * contexts specified by contextEnum. It must return an object that will be accepted by
19183 * getTrusted() for a compatible contextEnum and return this value.
19184 *
19185 * - valueOf(value)
19186 * For values that were not produced by trustAs(), return them as is. For values that were
19187 * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
19188 * trustAs is wrapping the given values into some type, this operation unwraps it when given
19189 * such a value.
19190 *
19191 * - getTrusted(contextEnum, value)
19192 * This function should return the a value that is safe to use in the context specified by
19193 * contextEnum or throw and exception otherwise.
19194 *
19195 * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
19196 * opaque or wrapped in some holder object. That happens to be an implementation detail. For
19197 * instance, an implementation could maintain a registry of all trusted objects by context. In
19198 * such a case, trustAs() would return the same object that was passed in. getTrusted() would
19199 * return the same object passed in if it was found in the registry under a compatible context or
19200 * throw an exception otherwise. An implementation might only wrap values some of the time based
19201 * on some criteria. getTrusted() might return a value and not throw an exception for special
19202 * constants or objects even if not wrapped. All such implementations fulfill this contract.
19203 *
19204 *
19205 * A note on the inheritance model for SCE contexts
19206 * ------------------------------------------------
19207 * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
19208 * is purely an implementation details.
19209 *
19210 * The contract is simply this:
19211 *
19212 * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
19213 * will also succeed.
19214 *
19215 * Inheritance happens to capture this in a natural way. In some future, we
19216 * may not use inheritance anymore. That is OK because no code outside of
19217 * sce.js and sceSpecs.js would need to be aware of this detail.
19218 */
19219
19220 this.$get = ['$parse', '$sceDelegate', function(
19221 $parse, $sceDelegate) {
19222 // Support: IE 9-11 only
19223 // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
19224 // the "expression(javascript expression)" syntax which is insecure.
19225 if (enabled && msie < 8) {
19226 throw $sceMinErr('iequirks',
19227 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
19228 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
19229 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
19230 }
19231
19232 var sce = shallowCopy(SCE_CONTEXTS);
19233
19234 /**
19235 * @ngdoc method
19236 * @name $sce#isEnabled
19237 * @kind function
19238 *
19239 * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
19240 * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
19241 *
19242 * @description
19243 * Returns a boolean indicating if SCE is enabled.
19244 */
19245 sce.isEnabled = function() {
19246 return enabled;
19247 };
19248 sce.trustAs = $sceDelegate.trustAs;
19249 sce.getTrusted = $sceDelegate.getTrusted;
19250 sce.valueOf = $sceDelegate.valueOf;
19251
19252 if (!enabled) {
19253 sce.trustAs = sce.getTrusted = function(type, value) { return value; };
19254 sce.valueOf = identity;
19255 }
19256
19257 /**
19258 * @ngdoc method
19259 * @name $sce#parseAs
19260 *
19261 * @description
19262 * Converts Angular {@link guide/expression expression} into a function. This is like {@link
19263 * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
19264 * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
19265 * *result*)}
19266 *
19267 * @param {string} type The kind of SCE context in which this result will be used.
19268 * @param {string} expression String expression to compile.
19269 * @returns {function(context, locals)} a function which represents the compiled expression:
19270 *
19271 * * `context` – `{object}` – an object against which any expressions embedded in the strings
19272 * are evaluated against (typically a scope object).
19273 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
19274 * `context`.
19275 */
19276 sce.parseAs = function sceParseAs(type, expr) {
19277 var parsed = $parse(expr);
19278 if (parsed.literal && parsed.constant) {
19279 return parsed;
19280 } else {
19281 return $parse(expr, function(value) {
19282 return sce.getTrusted(type, value);
19283 });
19284 }
19285 };
19286
19287 /**
19288 * @ngdoc method
19289 * @name $sce#trustAs
19290 *
19291 * @description
19292 * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
19293 * returns an object that is trusted by angular for use in specified strict contextual
19294 * escaping contexts (such as ng-bind-html, ng-include, any src attribute
19295 * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
19296 * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
19297 * escaping.
19298 *
19299 * @param {string} type The kind of context in which this value is safe for use. e.g. url,
19300 * resourceUrl, html, js and css.
19301 * @param {*} value The value that that should be considered trusted/safe.
19302 * @returns {*} A value that can be used to stand in for the provided `value` in places
19303 * where Angular expects a $sce.trustAs() return value.
19304 */
19305
19306 /**
19307 * @ngdoc method
19308 * @name $sce#trustAsHtml
19309 *
19310 * @description
19311 * Shorthand method. `$sce.trustAsHtml(value)` →
19312 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
19313 *
19314 * @param {*} value The value to trustAs.
19315 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
19316 * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
19317 * only accept expressions that are either literal constants or are the
19318 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
19319 */
19320
19321 /**
19322 * @ngdoc method
19323 * @name $sce#trustAsUrl
19324 *
19325 * @description
19326 * Shorthand method. `$sce.trustAsUrl(value)` →
19327 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
19328 *
19329 * @param {*} value The value to trustAs.
19330 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
19331 * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
19332 * only accept expressions that are either literal constants or are the
19333 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
19334 */
19335
19336 /**
19337 * @ngdoc method
19338 * @name $sce#trustAsResourceUrl
19339 *
19340 * @description
19341 * Shorthand method. `$sce.trustAsResourceUrl(value)` →
19342 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
19343 *
19344 * @param {*} value The value to trustAs.
19345 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
19346 * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
19347 * only accept expressions that are either literal constants or are the return
19348 * value of {@link ng.$sce#trustAs $sce.trustAs}.)
19349 */
19350
19351 /**
19352 * @ngdoc method
19353 * @name $sce#trustAsJs
19354 *
19355 * @description
19356 * Shorthand method. `$sce.trustAsJs(value)` →
19357 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
19358 *
19359 * @param {*} value The value to trustAs.
19360 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
19361 * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
19362 * only accept expressions that are either literal constants or are the
19363 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
19364 */
19365
19366 /**
19367 * @ngdoc method
19368 * @name $sce#getTrusted
19369 *
19370 * @description
19371 * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
19372 * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
19373 * originally supplied value if the queried context type is a supertype of the created type.
19374 * If this condition isn't satisfied, throws an exception.
19375 *
19376 * @param {string} type The kind of context in which this value is to be used.
19377 * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
19378 * call.
19379 * @returns {*} The value the was originally provided to
19380 * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
19381 * Otherwise, throws an exception.
19382 */
19383
19384 /**
19385 * @ngdoc method
19386 * @name $sce#getTrustedHtml
19387 *
19388 * @description
19389 * Shorthand method. `$sce.getTrustedHtml(value)` →
19390 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
19391 *
19392 * @param {*} value The value to pass to `$sce.getTrusted`.
19393 * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
19394 */
19395
19396 /**
19397 * @ngdoc method
19398 * @name $sce#getTrustedCss
19399 *
19400 * @description
19401 * Shorthand method. `$sce.getTrustedCss(value)` →
19402 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
19403 *
19404 * @param {*} value The value to pass to `$sce.getTrusted`.
19405 * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
19406 */
19407
19408 /**
19409 * @ngdoc method
19410 * @name $sce#getTrustedUrl
19411 *
19412 * @description
19413 * Shorthand method. `$sce.getTrustedUrl(value)` →
19414 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
19415 *
19416 * @param {*} value The value to pass to `$sce.getTrusted`.
19417 * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
19418 */
19419
19420 /**
19421 * @ngdoc method
19422 * @name $sce#getTrustedResourceUrl
19423 *
19424 * @description
19425 * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
19426 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
19427 *
19428 * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
19429 * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
19430 */
19431
19432 /**
19433 * @ngdoc method
19434 * @name $sce#getTrustedJs
19435 *
19436 * @description
19437 * Shorthand method. `$sce.getTrustedJs(value)` →
19438 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
19439 *
19440 * @param {*} value The value to pass to `$sce.getTrusted`.
19441 * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
19442 */
19443
19444 /**
19445 * @ngdoc method
19446 * @name $sce#parseAsHtml
19447 *
19448 * @description
19449 * Shorthand method. `$sce.parseAsHtml(expression string)` →
19450 * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
19451 *
19452 * @param {string} expression String expression to compile.
19453 * @returns {function(context, locals)} a function which represents the compiled expression:
19454 *
19455 * * `context` – `{object}` – an object against which any expressions embedded in the strings
19456 * are evaluated against (typically a scope object).
19457 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
19458 * `context`.
19459 */
19460
19461 /**
19462 * @ngdoc method
19463 * @name $sce#parseAsCss
19464 *
19465 * @description
19466 * Shorthand method. `$sce.parseAsCss(value)` →
19467 * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
19468 *
19469 * @param {string} expression String expression to compile.
19470 * @returns {function(context, locals)} a function which represents the compiled expression:
19471 *
19472 * * `context` – `{object}` – an object against which any expressions embedded in the strings
19473 * are evaluated against (typically a scope object).
19474 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
19475 * `context`.
19476 */
19477
19478 /**
19479 * @ngdoc method
19480 * @name $sce#parseAsUrl
19481 *
19482 * @description
19483 * Shorthand method. `$sce.parseAsUrl(value)` →
19484 * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
19485 *
19486 * @param {string} expression String expression to compile.
19487 * @returns {function(context, locals)} a function which represents the compiled expression:
19488 *
19489 * * `context` – `{object}` – an object against which any expressions embedded in the strings
19490 * are evaluated against (typically a scope object).
19491 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
19492 * `context`.
19493 */
19494
19495 /**
19496 * @ngdoc method
19497 * @name $sce#parseAsResourceUrl
19498 *
19499 * @description
19500 * Shorthand method. `$sce.parseAsResourceUrl(value)` →
19501 * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
19502 *
19503 * @param {string} expression String expression to compile.
19504 * @returns {function(context, locals)} a function which represents the compiled expression:
19505 *
19506 * * `context` – `{object}` – an object against which any expressions embedded in the strings
19507 * are evaluated against (typically a scope object).
19508 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
19509 * `context`.
19510 */
19511
19512 /**
19513 * @ngdoc method
19514 * @name $sce#parseAsJs
19515 *
19516 * @description
19517 * Shorthand method. `$sce.parseAsJs(value)` →
19518 * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
19519 *
19520 * @param {string} expression String expression to compile.
19521 * @returns {function(context, locals)} a function which represents the compiled expression:
19522 *
19523 * * `context` – `{object}` – an object against which any expressions embedded in the strings
19524 * are evaluated against (typically a scope object).
19525 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
19526 * `context`.
19527 */
19528
19529 // Shorthand delegations.
19530 var parse = sce.parseAs,
19531 getTrusted = sce.getTrusted,
19532 trustAs = sce.trustAs;
19533
19534 forEach(SCE_CONTEXTS, function(enumValue, name) {
19535 var lName = lowercase(name);
19536 sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
19537 return parse(enumValue, expr);
19538 };
19539 sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
19540 return getTrusted(enumValue, value);
19541 };
19542 sce[snakeToCamel('trust_as_' + lName)] = function(value) {
19543 return trustAs(enumValue, value);
19544 };
19545 });
19546
19547 return sce;
19548 }];
19549}
19550
19551/* exported $SnifferProvider */
19552
19553/**
19554 * !!! This is an undocumented "private" service !!!
19555 *
19556 * @name $sniffer
19557 * @requires $window
19558 * @requires $document
19559 * @this
19560 *
19561 * @property {boolean} history Does the browser support html5 history api ?
19562 * @property {boolean} transitions Does the browser support CSS transition events ?
19563 * @property {boolean} animations Does the browser support CSS animation events ?
19564 *
19565 * @description
19566 * This is very simple implementation of testing browser's features.
19567 */
19568function $SnifferProvider() {
19569 this.$get = ['$window', '$document', function($window, $document) {
19570 var eventSupport = {},
19571 // Chrome Packaged Apps are not allowed to access `history.pushState`.
19572 // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
19573 // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
19574 // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
19575 // (see https://developer.chrome.com/apps/manifest/sandbox).
19576 isChromePackagedApp =
19577 $window.chrome &&
19578 ($window.chrome.app && $window.chrome.app.runtime ||
19579 !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
19580 hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
19581 android =
19582 toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
19583 boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
19584 document = $document[0] || {},
19585 bodyStyle = document.body && document.body.style,
19586 transitions = false,
19587 animations = false;
19588
19589 if (bodyStyle) {
19590 // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
19591 // Mentioned browsers need a -webkit- prefix for transitions & animations.
19592 transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
19593 animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
19594 }
19595
19596
19597 return {
19598 // Android has history.pushState, but it does not update location correctly
19599 // so let's not use the history API at all.
19600 // http://code.google.com/p/android/issues/detail?id=17471
19601 // https://github.com/angular/angular.js/issues/904
19602
19603 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
19604 // so let's not use the history API also
19605 // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
19606 history: !!(hasHistoryPushState && !(android < 4) && !boxee),
19607 hasEvent: function(event) {
19608 // Support: IE 9-11 only
19609 // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
19610 // it. In particular the event is not fired when backspace or delete key are pressed or
19611 // when cut operation is performed.
19612 // IE10+ implements 'input' event but it erroneously fires under various situations,
19613 // e.g. when placeholder changes, or a form is focused.
19614 if (event === 'input' && msie) return false;
19615
19616 if (isUndefined(eventSupport[event])) {
19617 var divElm = document.createElement('div');
19618 eventSupport[event] = 'on' + event in divElm;
19619 }
19620
19621 return eventSupport[event];
19622 },
19623 csp: csp(),
19624 transitions: transitions,
19625 animations: animations,
19626 android: android
19627 };
19628 }];
19629}
19630
19631var $templateRequestMinErr = minErr('$compile');
19632
19633/**
19634 * @ngdoc provider
19635 * @name $templateRequestProvider
19636 * @this
19637 *
19638 * @description
19639 * Used to configure the options passed to the {@link $http} service when making a template request.
19640 *
19641 * For example, it can be used for specifying the "Accept" header that is sent to the server, when
19642 * requesting a template.
19643 */
19644function $TemplateRequestProvider() {
19645
19646 var httpOptions;
19647
19648 /**
19649 * @ngdoc method
19650 * @name $templateRequestProvider#httpOptions
19651 * @description
19652 * The options to be passed to the {@link $http} service when making the request.
19653 * You can use this to override options such as the "Accept" header for template requests.
19654 *
19655 * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
19656 * options if not overridden here.
19657 *
19658 * @param {string=} value new value for the {@link $http} options.
19659 * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
19660 */
19661 this.httpOptions = function(val) {
19662 if (val) {
19663 httpOptions = val;
19664 return this;
19665 }
19666 return httpOptions;
19667 };
19668
19669 /**
19670 * @ngdoc service
19671 * @name $templateRequest
19672 *
19673 * @description
19674 * The `$templateRequest` service runs security checks then downloads the provided template using
19675 * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
19676 * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
19677 * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
19678 * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
19679 * when `tpl` is of type string and `$templateCache` has the matching entry.
19680 *
19681 * If you want to pass custom options to the `$http` service, such as setting the Accept header you
19682 * can configure this via {@link $templateRequestProvider#httpOptions}.
19683 *
19684 * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
19685 * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
19686 *
19687 * @return {Promise} a promise for the HTTP response data of the given URL.
19688 *
19689 * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
19690 */
19691 this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
19692 function($exceptionHandler, $templateCache, $http, $q, $sce) {
19693
19694 function handleRequestFn(tpl, ignoreRequestError) {
19695 handleRequestFn.totalPendingRequests++;
19696
19697 // We consider the template cache holds only trusted templates, so
19698 // there's no need to go through whitelisting again for keys that already
19699 // are included in there. This also makes Angular accept any script
19700 // directive, no matter its name. However, we still need to unwrap trusted
19701 // types.
19702 if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
19703 tpl = $sce.getTrustedResourceUrl(tpl);
19704 }
19705
19706 var transformResponse = $http.defaults && $http.defaults.transformResponse;
19707
19708 if (isArray(transformResponse)) {
19709 transformResponse = transformResponse.filter(function(transformer) {
19710 return transformer !== defaultHttpResponseTransform;
19711 });
19712 } else if (transformResponse === defaultHttpResponseTransform) {
19713 transformResponse = null;
19714 }
19715
19716 return $http.get(tpl, extend({
19717 cache: $templateCache,
19718 transformResponse: transformResponse
19719 }, httpOptions))
19720 .finally(function() {
19721 handleRequestFn.totalPendingRequests--;
19722 })
19723 .then(function(response) {
19724 $templateCache.put(tpl, response.data);
19725 return response.data;
19726 }, handleError);
19727
19728 function handleError(resp) {
19729 if (!ignoreRequestError) {
19730 resp = $templateRequestMinErr('tpload',
19731 'Failed to load template: {0} (HTTP status: {1} {2})',
19732 tpl, resp.status, resp.statusText);
19733
19734 $exceptionHandler(resp);
19735 }
19736
19737 return $q.reject(resp);
19738 }
19739 }
19740
19741 handleRequestFn.totalPendingRequests = 0;
19742
19743 return handleRequestFn;
19744 }
19745 ];
19746}
19747
19748/** @this */
19749function $$TestabilityProvider() {
19750 this.$get = ['$rootScope', '$browser', '$location',
19751 function($rootScope, $browser, $location) {
19752
19753 /**
19754 * @name $testability
19755 *
19756 * @description
19757 * The private $$testability service provides a collection of methods for use when debugging
19758 * or by automated test and debugging tools.
19759 */
19760 var testability = {};
19761
19762 /**
19763 * @name $$testability#findBindings
19764 *
19765 * @description
19766 * Returns an array of elements that are bound (via ng-bind or {{}})
19767 * to expressions matching the input.
19768 *
19769 * @param {Element} element The element root to search from.
19770 * @param {string} expression The binding expression to match.
19771 * @param {boolean} opt_exactMatch If true, only returns exact matches
19772 * for the expression. Filters and whitespace are ignored.
19773 */
19774 testability.findBindings = function(element, expression, opt_exactMatch) {
19775 var bindings = element.getElementsByClassName('ng-binding');
19776 var matches = [];
19777 forEach(bindings, function(binding) {
19778 var dataBinding = angular.element(binding).data('$binding');
19779 if (dataBinding) {
19780 forEach(dataBinding, function(bindingName) {
19781 if (opt_exactMatch) {
19782 var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
19783 if (matcher.test(bindingName)) {
19784 matches.push(binding);
19785 }
19786 } else {
19787 if (bindingName.indexOf(expression) !== -1) {
19788 matches.push(binding);
19789 }
19790 }
19791 });
19792 }
19793 });
19794 return matches;
19795 };
19796
19797 /**
19798 * @name $$testability#findModels
19799 *
19800 * @description
19801 * Returns an array of elements that are two-way found via ng-model to
19802 * expressions matching the input.
19803 *
19804 * @param {Element} element The element root to search from.
19805 * @param {string} expression The model expression to match.
19806 * @param {boolean} opt_exactMatch If true, only returns exact matches
19807 * for the expression.
19808 */
19809 testability.findModels = function(element, expression, opt_exactMatch) {
19810 var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
19811 for (var p = 0; p < prefixes.length; ++p) {
19812 var attributeEquals = opt_exactMatch ? '=' : '*=';
19813 var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
19814 var elements = element.querySelectorAll(selector);
19815 if (elements.length) {
19816 return elements;
19817 }
19818 }
19819 };
19820
19821 /**
19822 * @name $$testability#getLocation
19823 *
19824 * @description
19825 * Shortcut for getting the location in a browser agnostic way. Returns
19826 * the path, search, and hash. (e.g. /path?a=b#hash)
19827 */
19828 testability.getLocation = function() {
19829 return $location.url();
19830 };
19831
19832 /**
19833 * @name $$testability#setLocation
19834 *
19835 * @description
19836 * Shortcut for navigating to a location without doing a full page reload.
19837 *
19838 * @param {string} url The location url (path, search and hash,
19839 * e.g. /path?a=b#hash) to go to.
19840 */
19841 testability.setLocation = function(url) {
19842 if (url !== $location.url()) {
19843 $location.url(url);
19844 $rootScope.$digest();
19845 }
19846 };
19847
19848 /**
19849 * @name $$testability#whenStable
19850 *
19851 * @description
19852 * Calls the callback when $timeout and $http requests are completed.
19853 *
19854 * @param {function} callback
19855 */
19856 testability.whenStable = function(callback) {
19857 $browser.notifyWhenNoOutstandingRequests(callback);
19858 };
19859
19860 return testability;
19861 }];
19862}
19863
19864/** @this */
19865function $TimeoutProvider() {
19866 this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
19867 function($rootScope, $browser, $q, $$q, $exceptionHandler) {
19868
19869 var deferreds = {};
19870
19871
19872 /**
19873 * @ngdoc service
19874 * @name $timeout
19875 *
19876 * @description
19877 * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
19878 * block and delegates any exceptions to
19879 * {@link ng.$exceptionHandler $exceptionHandler} service.
19880 *
19881 * The return value of calling `$timeout` is a promise, which will be resolved when
19882 * the delay has passed and the timeout function, if provided, is executed.
19883 *
19884 * To cancel a timeout request, call `$timeout.cancel(promise)`.
19885 *
19886 * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
19887 * synchronously flush the queue of deferred functions.
19888 *
19889 * If you only want a promise that will be resolved after some specified delay
19890 * then you can call `$timeout` without the `fn` function.
19891 *
19892 * @param {function()=} fn A function, whose execution should be delayed.
19893 * @param {number=} [delay=0] Delay in milliseconds.
19894 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
19895 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
19896 * @param {...*=} Pass additional parameters to the executed function.
19897 * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
19898 * will be resolved with the return value of the `fn` function.
19899 *
19900 */
19901 function timeout(fn, delay, invokeApply) {
19902 if (!isFunction(fn)) {
19903 invokeApply = delay;
19904 delay = fn;
19905 fn = noop;
19906 }
19907
19908 var args = sliceArgs(arguments, 3),
19909 skipApply = (isDefined(invokeApply) && !invokeApply),
19910 deferred = (skipApply ? $$q : $q).defer(),
19911 promise = deferred.promise,
19912 timeoutId;
19913
19914 timeoutId = $browser.defer(function() {
19915 try {
19916 deferred.resolve(fn.apply(null, args));
19917 } catch (e) {
19918 deferred.reject(e);
19919 $exceptionHandler(e);
19920 } finally {
19921 delete deferreds[promise.$$timeoutId];
19922 }
19923
19924 if (!skipApply) $rootScope.$apply();
19925 }, delay);
19926
19927 promise.$$timeoutId = timeoutId;
19928 deferreds[timeoutId] = deferred;
19929
19930 return promise;
19931 }
19932
19933
19934 /**
19935 * @ngdoc method
19936 * @name $timeout#cancel
19937 *
19938 * @description
19939 * Cancels a task associated with the `promise`. As a result of this, the promise will be
19940 * resolved with a rejection.
19941 *
19942 * @param {Promise=} promise Promise returned by the `$timeout` function.
19943 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
19944 * canceled.
19945 */
19946 timeout.cancel = function(promise) {
19947 if (promise && promise.$$timeoutId in deferreds) {
19948 // Timeout cancels should not report an unhandled promise.
19949 deferreds[promise.$$timeoutId].promise.catch(noop);
19950 deferreds[promise.$$timeoutId].reject('canceled');
19951 delete deferreds[promise.$$timeoutId];
19952 return $browser.defer.cancel(promise.$$timeoutId);
19953 }
19954 return false;
19955 };
19956
19957 return timeout;
19958 }];
19959}
19960
19961// NOTE: The usage of window and document instead of $window and $document here is
19962// deliberate. This service depends on the specific behavior of anchor nodes created by the
19963// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
19964// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
19965// doesn't know about mocked locations and resolves URLs to the real document - which is
19966// exactly the behavior needed here. There is little value is mocking these out for this
19967// service.
19968var urlParsingNode = window.document.createElement('a');
19969var originUrl = urlResolve(window.location.href);
19970
19971
19972/**
19973 *
19974 * Implementation Notes for non-IE browsers
19975 * ----------------------------------------
19976 * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
19977 * results both in the normalizing and parsing of the URL. Normalizing means that a relative
19978 * URL will be resolved into an absolute URL in the context of the application document.
19979 * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
19980 * properties are all populated to reflect the normalized URL. This approach has wide
19981 * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
19982 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
19983 *
19984 * Implementation Notes for IE
19985 * ---------------------------
19986 * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
19987 * browsers. However, the parsed components will not be set if the URL assigned did not specify
19988 * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
19989 * work around that by performing the parsing in a 2nd step by taking a previously normalized
19990 * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
19991 * properties such as protocol, hostname, port, etc.
19992 *
19993 * References:
19994 * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
19995 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
19996 * http://url.spec.whatwg.org/#urlutils
19997 * https://github.com/angular/angular.js/pull/2902
19998 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
19999 *
20000 * @kind function
20001 * @param {string} url The URL to be parsed.
20002 * @description Normalizes and parses a URL.
20003 * @returns {object} Returns the normalized URL as a dictionary.
20004 *
20005 * | member name | Description |
20006 * |---------------|----------------|
20007 * | href | A normalized version of the provided URL if it was not an absolute URL |
20008 * | protocol | The protocol including the trailing colon |
20009 * | host | The host and port (if the port is non-default) of the normalizedUrl |
20010 * | search | The search params, minus the question mark |
20011 * | hash | The hash string, minus the hash symbol
20012 * | hostname | The hostname
20013 * | port | The port, without ":"
20014 * | pathname | The pathname, beginning with "/"
20015 *
20016 */
20017function urlResolve(url) {
20018 var href = url;
20019
20020 // Support: IE 9-11 only
20021 if (msie) {
20022 // Normalize before parse. Refer Implementation Notes on why this is
20023 // done in two steps on IE.
20024 urlParsingNode.setAttribute('href', href);
20025 href = urlParsingNode.href;
20026 }
20027
20028 urlParsingNode.setAttribute('href', href);
20029
20030 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
20031 return {
20032 href: urlParsingNode.href,
20033 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
20034 host: urlParsingNode.host,
20035 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
20036 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
20037 hostname: urlParsingNode.hostname,
20038 port: urlParsingNode.port,
20039 pathname: (urlParsingNode.pathname.charAt(0) === '/')
20040 ? urlParsingNode.pathname
20041 : '/' + urlParsingNode.pathname
20042 };
20043}
20044
20045/**
20046 * Parse a request URL and determine whether this is a same-origin request as the application document.
20047 *
20048 * @param {string|object} requestUrl The url of the request as a string that will be resolved
20049 * or a parsed URL object.
20050 * @returns {boolean} Whether the request is for the same origin as the application document.
20051 */
20052function urlIsSameOrigin(requestUrl) {
20053 var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
20054 return (parsed.protocol === originUrl.protocol &&
20055 parsed.host === originUrl.host);
20056}
20057
20058/**
20059 * @ngdoc service
20060 * @name $window
20061 * @this
20062 *
20063 * @description
20064 * A reference to the browser's `window` object. While `window`
20065 * is globally available in JavaScript, it causes testability problems, because
20066 * it is a global variable. In angular we always refer to it through the
20067 * `$window` service, so it may be overridden, removed or mocked for testing.
20068 *
20069 * Expressions, like the one defined for the `ngClick` directive in the example
20070 * below, are evaluated with respect to the current scope. Therefore, there is
20071 * no risk of inadvertently coding in a dependency on a global value in such an
20072 * expression.
20073 *
20074 * @example
20075 <example module="windowExample" name="window-service">
20076 <file name="index.html">
20077 <script>
20078 angular.module('windowExample', [])
20079 .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
20080 $scope.greeting = 'Hello, World!';
20081 $scope.doGreeting = function(greeting) {
20082 $window.alert(greeting);
20083 };
20084 }]);
20085 </script>
20086 <div ng-controller="ExampleController">
20087 <input type="text" ng-model="greeting" aria-label="greeting" />
20088 <button ng-click="doGreeting(greeting)">ALERT</button>
20089 </div>
20090 </file>
20091 <file name="protractor.js" type="protractor">
20092 it('should display the greeting in the input box', function() {
20093 element(by.model('greeting')).sendKeys('Hello, E2E Tests');
20094 // If we click the button it will block the test runner
20095 // element(':button').click();
20096 });
20097 </file>
20098 </example>
20099 */
20100function $WindowProvider() {
20101 this.$get = valueFn(window);
20102}
20103
20104/**
20105 * @name $$cookieReader
20106 * @requires $document
20107 *
20108 * @description
20109 * This is a private service for reading cookies used by $http and ngCookies
20110 *
20111 * @return {Object} a key/value map of the current cookies
20112 */
20113function $$CookieReader($document) {
20114 var rawDocument = $document[0] || {};
20115 var lastCookies = {};
20116 var lastCookieString = '';
20117
20118 function safeGetCookie(rawDocument) {
20119 try {
20120 return rawDocument.cookie || '';
20121 } catch (e) {
20122 return '';
20123 }
20124 }
20125
20126 function safeDecodeURIComponent(str) {
20127 try {
20128 return decodeURIComponent(str);
20129 } catch (e) {
20130 return str;
20131 }
20132 }
20133
20134 return function() {
20135 var cookieArray, cookie, i, index, name;
20136 var currentCookieString = safeGetCookie(rawDocument);
20137
20138 if (currentCookieString !== lastCookieString) {
20139 lastCookieString = currentCookieString;
20140 cookieArray = lastCookieString.split('; ');
20141 lastCookies = {};
20142
20143 for (i = 0; i < cookieArray.length; i++) {
20144 cookie = cookieArray[i];
20145 index = cookie.indexOf('=');
20146 if (index > 0) { //ignore nameless cookies
20147 name = safeDecodeURIComponent(cookie.substring(0, index));
20148 // the first value that is seen for a cookie is the most
20149 // specific one. values for the same cookie name that
20150 // follow are for less specific paths.
20151 if (isUndefined(lastCookies[name])) {
20152 lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
20153 }
20154 }
20155 }
20156 }
20157 return lastCookies;
20158 };
20159}
20160
20161$$CookieReader.$inject = ['$document'];
20162
20163/** @this */
20164function $$CookieReaderProvider() {
20165 this.$get = $$CookieReader;
20166}
20167
20168/* global currencyFilter: true,
20169 dateFilter: true,
20170 filterFilter: true,
20171 jsonFilter: true,
20172 limitToFilter: true,
20173 lowercaseFilter: true,
20174 numberFilter: true,
20175 orderByFilter: true,
20176 uppercaseFilter: true,
20177 */
20178
20179/**
20180 * @ngdoc provider
20181 * @name $filterProvider
20182 * @description
20183 *
20184 * Filters are just functions which transform input to an output. However filters need to be
20185 * Dependency Injected. To achieve this a filter definition consists of a factory function which is
20186 * annotated with dependencies and is responsible for creating a filter function.
20187 *
20188 * <div class="alert alert-warning">
20189 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
20190 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
20191 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
20192 * (`myapp_subsection_filterx`).
20193 * </div>
20194 *
20195 * ```js
20196 * // Filter registration
20197 * function MyModule($provide, $filterProvider) {
20198 * // create a service to demonstrate injection (not always needed)
20199 * $provide.value('greet', function(name){
20200 * return 'Hello ' + name + '!';
20201 * });
20202 *
20203 * // register a filter factory which uses the
20204 * // greet service to demonstrate DI.
20205 * $filterProvider.register('greet', function(greet){
20206 * // return the filter function which uses the greet service
20207 * // to generate salutation
20208 * return function(text) {
20209 * // filters need to be forgiving so check input validity
20210 * return text && greet(text) || text;
20211 * };
20212 * });
20213 * }
20214 * ```
20215 *
20216 * The filter function is registered with the `$injector` under the filter name suffix with
20217 * `Filter`.
20218 *
20219 * ```js
20220 * it('should be the same instance', inject(
20221 * function($filterProvider) {
20222 * $filterProvider.register('reverse', function(){
20223 * return ...;
20224 * });
20225 * },
20226 * function($filter, reverseFilter) {
20227 * expect($filter('reverse')).toBe(reverseFilter);
20228 * });
20229 * ```
20230 *
20231 *
20232 * For more information about how angular filters work, and how to create your own filters, see
20233 * {@link guide/filter Filters} in the Angular Developer Guide.
20234 */
20235
20236/**
20237 * @ngdoc service
20238 * @name $filter
20239 * @kind function
20240 * @description
20241 * Filters are used for formatting data displayed to the user.
20242 *
20243 * They can be used in view templates, controllers or services.Angular comes
20244 * with a collection of [built-in filters](api/ng/filter), but it is easy to
20245 * define your own as well.
20246 *
20247 * The general syntax in templates is as follows:
20248 *
20249 * ```html
20250 * {{ expression [| filter_name[:parameter_value] ... ] }}
20251 * ```
20252 *
20253 * @param {String} name Name of the filter function to retrieve
20254 * @return {Function} the filter function
20255 * @example
20256 <example name="$filter" module="filterExample">
20257 <file name="index.html">
20258 <div ng-controller="MainCtrl">
20259 <h3>{{ originalText }}</h3>
20260 <h3>{{ filteredText }}</h3>
20261 </div>
20262 </file>
20263
20264 <file name="script.js">
20265 angular.module('filterExample', [])
20266 .controller('MainCtrl', function($scope, $filter) {
20267 $scope.originalText = 'hello';
20268 $scope.filteredText = $filter('uppercase')($scope.originalText);
20269 });
20270 </file>
20271 </example>
20272 */
20273$FilterProvider.$inject = ['$provide'];
20274/** @this */
20275function $FilterProvider($provide) {
20276 var suffix = 'Filter';
20277
20278 /**
20279 * @ngdoc method
20280 * @name $filterProvider#register
20281 * @param {string|Object} name Name of the filter function, or an object map of filters where
20282 * the keys are the filter names and the values are the filter factories.
20283 *
20284 * <div class="alert alert-warning">
20285 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
20286 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
20287 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
20288 * (`myapp_subsection_filterx`).
20289 * </div>
20290 * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
20291 * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
20292 * of the registered filter instances.
20293 */
20294 function register(name, factory) {
20295 if (isObject(name)) {
20296 var filters = {};
20297 forEach(name, function(filter, key) {
20298 filters[key] = register(key, filter);
20299 });
20300 return filters;
20301 } else {
20302 return $provide.factory(name + suffix, factory);
20303 }
20304 }
20305 this.register = register;
20306
20307 this.$get = ['$injector', function($injector) {
20308 return function(name) {
20309 return $injector.get(name + suffix);
20310 };
20311 }];
20312
20313 ////////////////////////////////////////
20314
20315 /* global
20316 currencyFilter: false,
20317 dateFilter: false,
20318 filterFilter: false,
20319 jsonFilter: false,
20320 limitToFilter: false,
20321 lowercaseFilter: false,
20322 numberFilter: false,
20323 orderByFilter: false,
20324 uppercaseFilter: false
20325 */
20326
20327 register('currency', currencyFilter);
20328 register('date', dateFilter);
20329 register('filter', filterFilter);
20330 register('json', jsonFilter);
20331 register('limitTo', limitToFilter);
20332 register('lowercase', lowercaseFilter);
20333 register('number', numberFilter);
20334 register('orderBy', orderByFilter);
20335 register('uppercase', uppercaseFilter);
20336}
20337
20338/**
20339 * @ngdoc filter
20340 * @name filter
20341 * @kind function
20342 *
20343 * @description
20344 * Selects a subset of items from `array` and returns it as a new array.
20345 *
20346 * @param {Array} array The source array.
20347 * @param {string|Object|function()} expression The predicate to be used for selecting items from
20348 * `array`.
20349 *
20350 * Can be one of:
20351 *
20352 * - `string`: The string is used for matching against the contents of the `array`. All strings or
20353 * objects with string properties in `array` that match this string will be returned. This also
20354 * applies to nested object properties.
20355 * The predicate can be negated by prefixing the string with `!`.
20356 *
20357 * - `Object`: A pattern object can be used to filter specific properties on objects contained
20358 * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
20359 * which have property `name` containing "M" and property `phone` containing "1". A special
20360 * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
20361 * against any property of the object or its nested object properties. That's equivalent to the
20362 * simple substring match with a `string` as described above. The special property name can be
20363 * overwritten, using the `anyPropertyKey` parameter.
20364 * The predicate can be negated by prefixing the string with `!`.
20365 * For example `{name: "!M"}` predicate will return an array of items which have property `name`
20366 * not containing "M".
20367 *
20368 * Note that a named property will match properties on the same level only, while the special
20369 * `$` property will match properties on the same level or deeper. E.g. an array item like
20370 * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
20371 * **will** be matched by `{$: 'John'}`.
20372 *
20373 * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
20374 * The function is called for each element of the array, with the element, its index, and
20375 * the entire array itself as arguments.
20376 *
20377 * The final result is an array of those elements that the predicate returned true for.
20378 *
20379 * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
20380 * determining if the expected value (from the filter expression) and actual value (from
20381 * the object in the array) should be considered a match.
20382 *
20383 * Can be one of:
20384 *
20385 * - `function(actual, expected)`:
20386 * The function will be given the object value and the predicate value to compare and
20387 * should return true if both values should be considered equal.
20388 *
20389 * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
20390 * This is essentially strict comparison of expected and actual.
20391 *
20392 * - `false`: A short hand for a function which will look for a substring match in a case
20393 * insensitive way. Primitive values are converted to strings. Objects are not compared against
20394 * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
20395 *
20396 *
20397 * Defaults to `false`.
20398 *
20399 * @param {string} [anyPropertyKey] The special property name that matches against any property.
20400 * By default `$`.
20401 *
20402 * @example
20403 <example name="filter-filter">
20404 <file name="index.html">
20405 <div ng-init="friends = [{name:'John', phone:'555-1276'},
20406 {name:'Mary', phone:'800-BIG-MARY'},
20407 {name:'Mike', phone:'555-4321'},
20408 {name:'Adam', phone:'555-5678'},
20409 {name:'Julie', phone:'555-8765'},
20410 {name:'Juliette', phone:'555-5678'}]"></div>
20411
20412 <label>Search: <input ng-model="searchText"></label>
20413 <table id="searchTextResults">
20414 <tr><th>Name</th><th>Phone</th></tr>
20415 <tr ng-repeat="friend in friends | filter:searchText">
20416 <td>{{friend.name}}</td>
20417 <td>{{friend.phone}}</td>
20418 </tr>
20419 </table>
20420 <hr>
20421 <label>Any: <input ng-model="search.$"></label> <br>
20422 <label>Name only <input ng-model="search.name"></label><br>
20423 <label>Phone only <input ng-model="search.phone"></label><br>
20424 <label>Equality <input type="checkbox" ng-model="strict"></label><br>
20425 <table id="searchObjResults">
20426 <tr><th>Name</th><th>Phone</th></tr>
20427 <tr ng-repeat="friendObj in friends | filter:search:strict">
20428 <td>{{friendObj.name}}</td>
20429 <td>{{friendObj.phone}}</td>
20430 </tr>
20431 </table>
20432 </file>
20433 <file name="protractor.js" type="protractor">
20434 var expectFriendNames = function(expectedNames, key) {
20435 element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
20436 arr.forEach(function(wd, i) {
20437 expect(wd.getText()).toMatch(expectedNames[i]);
20438 });
20439 });
20440 };
20441
20442 it('should search across all fields when filtering with a string', function() {
20443 var searchText = element(by.model('searchText'));
20444 searchText.clear();
20445 searchText.sendKeys('m');
20446 expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
20447
20448 searchText.clear();
20449 searchText.sendKeys('76');
20450 expectFriendNames(['John', 'Julie'], 'friend');
20451 });
20452
20453 it('should search in specific fields when filtering with a predicate object', function() {
20454 var searchAny = element(by.model('search.$'));
20455 searchAny.clear();
20456 searchAny.sendKeys('i');
20457 expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
20458 });
20459 it('should use a equal comparison when comparator is true', function() {
20460 var searchName = element(by.model('search.name'));
20461 var strict = element(by.model('strict'));
20462 searchName.clear();
20463 searchName.sendKeys('Julie');
20464 strict.click();
20465 expectFriendNames(['Julie'], 'friendObj');
20466 });
20467 </file>
20468 </example>
20469 */
20470
20471function filterFilter() {
20472 return function(array, expression, comparator, anyPropertyKey) {
20473 if (!isArrayLike(array)) {
20474 if (array == null) {
20475 return array;
20476 } else {
20477 throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
20478 }
20479 }
20480
20481 anyPropertyKey = anyPropertyKey || '$';
20482 var expressionType = getTypeForFilter(expression);
20483 var predicateFn;
20484 var matchAgainstAnyProp;
20485
20486 switch (expressionType) {
20487 case 'function':
20488 predicateFn = expression;
20489 break;
20490 case 'boolean':
20491 case 'null':
20492 case 'number':
20493 case 'string':
20494 matchAgainstAnyProp = true;
20495 // falls through
20496 case 'object':
20497 predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
20498 break;
20499 default:
20500 return array;
20501 }
20502
20503 return Array.prototype.filter.call(array, predicateFn);
20504 };
20505}
20506
20507// Helper functions for `filterFilter`
20508function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
20509 var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
20510 var predicateFn;
20511
20512 if (comparator === true) {
20513 comparator = equals;
20514 } else if (!isFunction(comparator)) {
20515 comparator = function(actual, expected) {
20516 if (isUndefined(actual)) {
20517 // No substring matching against `undefined`
20518 return false;
20519 }
20520 if ((actual === null) || (expected === null)) {
20521 // No substring matching against `null`; only match against `null`
20522 return actual === expected;
20523 }
20524 if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
20525 // Should not compare primitives against objects, unless they have custom `toString` method
20526 return false;
20527 }
20528
20529 actual = lowercase('' + actual);
20530 expected = lowercase('' + expected);
20531 return actual.indexOf(expected) !== -1;
20532 };
20533 }
20534
20535 predicateFn = function(item) {
20536 if (shouldMatchPrimitives && !isObject(item)) {
20537 return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
20538 }
20539 return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
20540 };
20541
20542 return predicateFn;
20543}
20544
20545function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
20546 var actualType = getTypeForFilter(actual);
20547 var expectedType = getTypeForFilter(expected);
20548
20549 if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
20550 return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
20551 } else if (isArray(actual)) {
20552 // In case `actual` is an array, consider it a match
20553 // if ANY of it's items matches `expected`
20554 return actual.some(function(item) {
20555 return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
20556 });
20557 }
20558
20559 switch (actualType) {
20560 case 'object':
20561 var key;
20562 if (matchAgainstAnyProp) {
20563 for (key in actual) {
20564 if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
20565 return true;
20566 }
20567 }
20568 return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
20569 } else if (expectedType === 'object') {
20570 for (key in expected) {
20571 var expectedVal = expected[key];
20572 if (isFunction(expectedVal) || isUndefined(expectedVal)) {
20573 continue;
20574 }
20575
20576 var matchAnyProperty = key === anyPropertyKey;
20577 var actualVal = matchAnyProperty ? actual : actual[key];
20578 if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
20579 return false;
20580 }
20581 }
20582 return true;
20583 } else {
20584 return comparator(actual, expected);
20585 }
20586 case 'function':
20587 return false;
20588 default:
20589 return comparator(actual, expected);
20590 }
20591}
20592
20593// Used for easily differentiating between `null` and actual `object`
20594function getTypeForFilter(val) {
20595 return (val === null) ? 'null' : typeof val;
20596}
20597
20598var MAX_DIGITS = 22;
20599var DECIMAL_SEP = '.';
20600var ZERO_CHAR = '0';
20601
20602/**
20603 * @ngdoc filter
20604 * @name currency
20605 * @kind function
20606 *
20607 * @description
20608 * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
20609 * symbol for current locale is used.
20610 *
20611 * @param {number} amount Input to filter.
20612 * @param {string=} symbol Currency symbol or identifier to be displayed.
20613 * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
20614 * @returns {string} Formatted number.
20615 *
20616 *
20617 * @example
20618 <example module="currencyExample" name="currency-filter">
20619 <file name="index.html">
20620 <script>
20621 angular.module('currencyExample', [])
20622 .controller('ExampleController', ['$scope', function($scope) {
20623 $scope.amount = 1234.56;
20624 }]);
20625 </script>
20626 <div ng-controller="ExampleController">
20627 <input type="number" ng-model="amount" aria-label="amount"> <br>
20628 default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
20629 custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
20630 no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
20631 </div>
20632 </file>
20633 <file name="protractor.js" type="protractor">
20634 it('should init with 1234.56', function() {
20635 expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
20636 expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
20637 expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
20638 });
20639 it('should update', function() {
20640 if (browser.params.browser === 'safari') {
20641 // Safari does not understand the minus key. See
20642 // https://github.com/angular/protractor/issues/481
20643 return;
20644 }
20645 element(by.model('amount')).clear();
20646 element(by.model('amount')).sendKeys('-1234');
20647 expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
20648 expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
20649 expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
20650 });
20651 </file>
20652 </example>
20653 */
20654currencyFilter.$inject = ['$locale'];
20655function currencyFilter($locale) {
20656 var formats = $locale.NUMBER_FORMATS;
20657 return function(amount, currencySymbol, fractionSize) {
20658 if (isUndefined(currencySymbol)) {
20659 currencySymbol = formats.CURRENCY_SYM;
20660 }
20661
20662 if (isUndefined(fractionSize)) {
20663 fractionSize = formats.PATTERNS[1].maxFrac;
20664 }
20665
20666 // if null or undefined pass it through
20667 return (amount == null)
20668 ? amount
20669 : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
20670 replace(/\u00A4/g, currencySymbol);
20671 };
20672}
20673
20674/**
20675 * @ngdoc filter
20676 * @name number
20677 * @kind function
20678 *
20679 * @description
20680 * Formats a number as text.
20681 *
20682 * If the input is null or undefined, it will just be returned.
20683 * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
20684 * If the input is not a number an empty string is returned.
20685 *
20686 *
20687 * @param {number|string} number Number to format.
20688 * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
20689 * If this is not provided then the fraction size is computed from the current locale's number
20690 * formatting pattern. In the case of the default locale, it will be 3.
20691 * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
20692 * locale (e.g., in the en_US locale it will have "." as the decimal separator and
20693 * include "," group separators after each third digit).
20694 *
20695 * @example
20696 <example module="numberFilterExample" name="number-filter">
20697 <file name="index.html">
20698 <script>
20699 angular.module('numberFilterExample', [])
20700 .controller('ExampleController', ['$scope', function($scope) {
20701 $scope.val = 1234.56789;
20702 }]);
20703 </script>
20704 <div ng-controller="ExampleController">
20705 <label>Enter number: <input ng-model='val'></label><br>
20706 Default formatting: <span id='number-default'>{{val | number}}</span><br>
20707 No fractions: <span>{{val | number:0}}</span><br>
20708 Negative number: <span>{{-val | number:4}}</span>
20709 </div>
20710 </file>
20711 <file name="protractor.js" type="protractor">
20712 it('should format numbers', function() {
20713 expect(element(by.id('number-default')).getText()).toBe('1,234.568');
20714 expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
20715 expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
20716 });
20717
20718 it('should update', function() {
20719 element(by.model('val')).clear();
20720 element(by.model('val')).sendKeys('3374.333');
20721 expect(element(by.id('number-default')).getText()).toBe('3,374.333');
20722 expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
20723 expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
20724 });
20725 </file>
20726 </example>
20727 */
20728numberFilter.$inject = ['$locale'];
20729function numberFilter($locale) {
20730 var formats = $locale.NUMBER_FORMATS;
20731 return function(number, fractionSize) {
20732
20733 // if null or undefined pass it through
20734 return (number == null)
20735 ? number
20736 : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
20737 fractionSize);
20738 };
20739}
20740
20741/**
20742 * Parse a number (as a string) into three components that can be used
20743 * for formatting the number.
20744 *
20745 * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
20746 *
20747 * @param {string} numStr The number to parse
20748 * @return {object} An object describing this number, containing the following keys:
20749 * - d : an array of digits containing leading zeros as necessary
20750 * - i : the number of the digits in `d` that are to the left of the decimal point
20751 * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
20752 *
20753 */
20754function parse(numStr) {
20755 var exponent = 0, digits, numberOfIntegerDigits;
20756 var i, j, zeros;
20757
20758 // Decimal point?
20759 if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
20760 numStr = numStr.replace(DECIMAL_SEP, '');
20761 }
20762
20763 // Exponential form?
20764 if ((i = numStr.search(/e/i)) > 0) {
20765 // Work out the exponent.
20766 if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
20767 numberOfIntegerDigits += +numStr.slice(i + 1);
20768 numStr = numStr.substring(0, i);
20769 } else if (numberOfIntegerDigits < 0) {
20770 // There was no decimal point or exponent so it is an integer.
20771 numberOfIntegerDigits = numStr.length;
20772 }
20773
20774 // Count the number of leading zeros.
20775 for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
20776
20777 if (i === (zeros = numStr.length)) {
20778 // The digits are all zero.
20779 digits = [0];
20780 numberOfIntegerDigits = 1;
20781 } else {
20782 // Count the number of trailing zeros
20783 zeros--;
20784 while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
20785
20786 // Trailing zeros are insignificant so ignore them
20787 numberOfIntegerDigits -= i;
20788 digits = [];
20789 // Convert string to array of digits without leading/trailing zeros.
20790 for (j = 0; i <= zeros; i++, j++) {
20791 digits[j] = +numStr.charAt(i);
20792 }
20793 }
20794
20795 // If the number overflows the maximum allowed digits then use an exponent.
20796 if (numberOfIntegerDigits > MAX_DIGITS) {
20797 digits = digits.splice(0, MAX_DIGITS - 1);
20798 exponent = numberOfIntegerDigits - 1;
20799 numberOfIntegerDigits = 1;
20800 }
20801
20802 return { d: digits, e: exponent, i: numberOfIntegerDigits };
20803}
20804
20805/**
20806 * Round the parsed number to the specified number of decimal places
20807 * This function changed the parsedNumber in-place
20808 */
20809function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
20810 var digits = parsedNumber.d;
20811 var fractionLen = digits.length - parsedNumber.i;
20812
20813 // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
20814 fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
20815
20816 // The index of the digit to where rounding is to occur
20817 var roundAt = fractionSize + parsedNumber.i;
20818 var digit = digits[roundAt];
20819
20820 if (roundAt > 0) {
20821 // Drop fractional digits beyond `roundAt`
20822 digits.splice(Math.max(parsedNumber.i, roundAt));
20823
20824 // Set non-fractional digits beyond `roundAt` to 0
20825 for (var j = roundAt; j < digits.length; j++) {
20826 digits[j] = 0;
20827 }
20828 } else {
20829 // We rounded to zero so reset the parsedNumber
20830 fractionLen = Math.max(0, fractionLen);
20831 parsedNumber.i = 1;
20832 digits.length = Math.max(1, roundAt = fractionSize + 1);
20833 digits[0] = 0;
20834 for (var i = 1; i < roundAt; i++) digits[i] = 0;
20835 }
20836
20837 if (digit >= 5) {
20838 if (roundAt - 1 < 0) {
20839 for (var k = 0; k > roundAt; k--) {
20840 digits.unshift(0);
20841 parsedNumber.i++;
20842 }
20843 digits.unshift(1);
20844 parsedNumber.i++;
20845 } else {
20846 digits[roundAt - 1]++;
20847 }
20848 }
20849
20850 // Pad out with zeros to get the required fraction length
20851 for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
20852
20853
20854 // Do any carrying, e.g. a digit was rounded up to 10
20855 var carry = digits.reduceRight(function(carry, d, i, digits) {
20856 d = d + carry;
20857 digits[i] = d % 10;
20858 return Math.floor(d / 10);
20859 }, 0);
20860 if (carry) {
20861 digits.unshift(carry);
20862 parsedNumber.i++;
20863 }
20864}
20865
20866/**
20867 * Format a number into a string
20868 * @param {number} number The number to format
20869 * @param {{
20870 * minFrac, // the minimum number of digits required in the fraction part of the number
20871 * maxFrac, // the maximum number of digits required in the fraction part of the number
20872 * gSize, // number of digits in each group of separated digits
20873 * lgSize, // number of digits in the last group of digits before the decimal separator
20874 * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
20875 * posPre, // the string to go in front of a positive number
20876 * negSuf, // the string to go after a negative number (e.g. `)`)
20877 * posSuf // the string to go after a positive number
20878 * }} pattern
20879 * @param {string} groupSep The string to separate groups of number (e.g. `,`)
20880 * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
20881 * @param {[type]} fractionSize The size of the fractional part of the number
20882 * @return {string} The number formatted as a string
20883 */
20884function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
20885
20886 if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
20887
20888 var isInfinity = !isFinite(number);
20889 var isZero = false;
20890 var numStr = Math.abs(number) + '',
20891 formattedText = '',
20892 parsedNumber;
20893
20894 if (isInfinity) {
20895 formattedText = '\u221e';
20896 } else {
20897 parsedNumber = parse(numStr);
20898
20899 roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
20900
20901 var digits = parsedNumber.d;
20902 var integerLen = parsedNumber.i;
20903 var exponent = parsedNumber.e;
20904 var decimals = [];
20905 isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
20906
20907 // pad zeros for small numbers
20908 while (integerLen < 0) {
20909 digits.unshift(0);
20910 integerLen++;
20911 }
20912
20913 // extract decimals digits
20914 if (integerLen > 0) {
20915 decimals = digits.splice(integerLen, digits.length);
20916 } else {
20917 decimals = digits;
20918 digits = [0];
20919 }
20920
20921 // format the integer digits with grouping separators
20922 var groups = [];
20923 if (digits.length >= pattern.lgSize) {
20924 groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
20925 }
20926 while (digits.length > pattern.gSize) {
20927 groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
20928 }
20929 if (digits.length) {
20930 groups.unshift(digits.join(''));
20931 }
20932 formattedText = groups.join(groupSep);
20933
20934 // append the decimal digits
20935 if (decimals.length) {
20936 formattedText += decimalSep + decimals.join('');
20937 }
20938
20939 if (exponent) {
20940 formattedText += 'e+' + exponent;
20941 }
20942 }
20943 if (number < 0 && !isZero) {
20944 return pattern.negPre + formattedText + pattern.negSuf;
20945 } else {
20946 return pattern.posPre + formattedText + pattern.posSuf;
20947 }
20948}
20949
20950function padNumber(num, digits, trim, negWrap) {
20951 var neg = '';
20952 if (num < 0 || (negWrap && num <= 0)) {
20953 if (negWrap) {
20954 num = -num + 1;
20955 } else {
20956 num = -num;
20957 neg = '-';
20958 }
20959 }
20960 num = '' + num;
20961 while (num.length < digits) num = ZERO_CHAR + num;
20962 if (trim) {
20963 num = num.substr(num.length - digits);
20964 }
20965 return neg + num;
20966}
20967
20968
20969function dateGetter(name, size, offset, trim, negWrap) {
20970 offset = offset || 0;
20971 return function(date) {
20972 var value = date['get' + name]();
20973 if (offset > 0 || value > -offset) {
20974 value += offset;
20975 }
20976 if (value === 0 && offset === -12) value = 12;
20977 return padNumber(value, size, trim, negWrap);
20978 };
20979}
20980
20981function dateStrGetter(name, shortForm, standAlone) {
20982 return function(date, formats) {
20983 var value = date['get' + name]();
20984 var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
20985 var get = uppercase(propPrefix + name);
20986
20987 return formats[get][value];
20988 };
20989}
20990
20991function timeZoneGetter(date, formats, offset) {
20992 var zone = -1 * offset;
20993 var paddedZone = (zone >= 0) ? '+' : '';
20994
20995 paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
20996 padNumber(Math.abs(zone % 60), 2);
20997
20998 return paddedZone;
20999}
21000
21001function getFirstThursdayOfYear(year) {
21002 // 0 = index of January
21003 var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
21004 // 4 = index of Thursday (+1 to account for 1st = 5)
21005 // 11 = index of *next* Thursday (+1 account for 1st = 12)
21006 return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
21007}
21008
21009function getThursdayThisWeek(datetime) {
21010 return new Date(datetime.getFullYear(), datetime.getMonth(),
21011 // 4 = index of Thursday
21012 datetime.getDate() + (4 - datetime.getDay()));
21013}
21014
21015function weekGetter(size) {
21016 return function(date) {
21017 var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
21018 thisThurs = getThursdayThisWeek(date);
21019
21020 var diff = +thisThurs - +firstThurs,
21021 result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
21022
21023 return padNumber(result, size);
21024 };
21025}
21026
21027function ampmGetter(date, formats) {
21028 return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
21029}
21030
21031function eraGetter(date, formats) {
21032 return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
21033}
21034
21035function longEraGetter(date, formats) {
21036 return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
21037}
21038
21039var DATE_FORMATS = {
21040 yyyy: dateGetter('FullYear', 4, 0, false, true),
21041 yy: dateGetter('FullYear', 2, 0, true, true),
21042 y: dateGetter('FullYear', 1, 0, false, true),
21043 MMMM: dateStrGetter('Month'),
21044 MMM: dateStrGetter('Month', true),
21045 MM: dateGetter('Month', 2, 1),
21046 M: dateGetter('Month', 1, 1),
21047 LLLL: dateStrGetter('Month', false, true),
21048 dd: dateGetter('Date', 2),
21049 d: dateGetter('Date', 1),
21050 HH: dateGetter('Hours', 2),
21051 H: dateGetter('Hours', 1),
21052 hh: dateGetter('Hours', 2, -12),
21053 h: dateGetter('Hours', 1, -12),
21054 mm: dateGetter('Minutes', 2),
21055 m: dateGetter('Minutes', 1),
21056 ss: dateGetter('Seconds', 2),
21057 s: dateGetter('Seconds', 1),
21058 // while ISO 8601 requires fractions to be prefixed with `.` or `,`
21059 // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
21060 sss: dateGetter('Milliseconds', 3),
21061 EEEE: dateStrGetter('Day'),
21062 EEE: dateStrGetter('Day', true),
21063 a: ampmGetter,
21064 Z: timeZoneGetter,
21065 ww: weekGetter(2),
21066 w: weekGetter(1),
21067 G: eraGetter,
21068 GG: eraGetter,
21069 GGG: eraGetter,
21070 GGGG: longEraGetter
21071};
21072
21073var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
21074 NUMBER_STRING = /^-?\d+$/;
21075
21076/**
21077 * @ngdoc filter
21078 * @name date
21079 * @kind function
21080 *
21081 * @description
21082 * Formats `date` to a string based on the requested `format`.
21083 *
21084 * `format` string can be composed of the following elements:
21085 *
21086 * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
21087 * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
21088 * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
21089 * * `'MMMM'`: Month in year (January-December)
21090 * * `'MMM'`: Month in year (Jan-Dec)
21091 * * `'MM'`: Month in year, padded (01-12)
21092 * * `'M'`: Month in year (1-12)
21093 * * `'LLLL'`: Stand-alone month in year (January-December)
21094 * * `'dd'`: Day in month, padded (01-31)
21095 * * `'d'`: Day in month (1-31)
21096 * * `'EEEE'`: Day in Week,(Sunday-Saturday)
21097 * * `'EEE'`: Day in Week, (Sun-Sat)
21098 * * `'HH'`: Hour in day, padded (00-23)
21099 * * `'H'`: Hour in day (0-23)
21100 * * `'hh'`: Hour in AM/PM, padded (01-12)
21101 * * `'h'`: Hour in AM/PM, (1-12)
21102 * * `'mm'`: Minute in hour, padded (00-59)
21103 * * `'m'`: Minute in hour (0-59)
21104 * * `'ss'`: Second in minute, padded (00-59)
21105 * * `'s'`: Second in minute (0-59)
21106 * * `'sss'`: Millisecond in second, padded (000-999)
21107 * * `'a'`: AM/PM marker
21108 * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
21109 * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
21110 * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
21111 * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
21112 * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
21113 *
21114 * `format` string can also be one of the following predefined
21115 * {@link guide/i18n localizable formats}:
21116 *
21117 * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
21118 * (e.g. Sep 3, 2010 12:05:08 PM)
21119 * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
21120 * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
21121 * (e.g. Friday, September 3, 2010)
21122 * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
21123 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
21124 * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
21125 * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
21126 * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
21127 *
21128 * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
21129 * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
21130 * (e.g. `"h 'o''clock'"`).
21131 *
21132 * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
21133 * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
21134 * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
21135 * specified in the string input, the time is considered to be in the local timezone.
21136 * @param {string=} format Formatting rules (see Description). If not specified,
21137 * `mediumDate` is used.
21138 * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
21139 * continental US time zone abbreviations, but for general use, use a time zone offset, for
21140 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
21141 * If not specified, the timezone of the browser will be used.
21142 * @returns {string} Formatted string or the input if input is not recognized as date/millis.
21143 *
21144 * @example
21145 <example name="filter-date">
21146 <file name="index.html">
21147 <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
21148 <span>{{1288323623006 | date:'medium'}}</span><br>
21149 <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
21150 <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
21151 <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
21152 <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
21153 <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
21154 <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
21155 </file>
21156 <file name="protractor.js" type="protractor">
21157 it('should format date', function() {
21158 expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
21159 toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
21160 expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
21161 toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
21162 expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
21163 toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
21164 expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
21165 toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
21166 });
21167 </file>
21168 </example>
21169 */
21170dateFilter.$inject = ['$locale'];
21171function dateFilter($locale) {
21172
21173
21174 var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
21175 // 1 2 3 4 5 6 7 8 9 10 11
21176 function jsonStringToDate(string) {
21177 var match;
21178 if ((match = string.match(R_ISO8601_STR))) {
21179 var date = new Date(0),
21180 tzHour = 0,
21181 tzMin = 0,
21182 dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
21183 timeSetter = match[8] ? date.setUTCHours : date.setHours;
21184
21185 if (match[9]) {
21186 tzHour = toInt(match[9] + match[10]);
21187 tzMin = toInt(match[9] + match[11]);
21188 }
21189 dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
21190 var h = toInt(match[4] || 0) - tzHour;
21191 var m = toInt(match[5] || 0) - tzMin;
21192 var s = toInt(match[6] || 0);
21193 var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
21194 timeSetter.call(date, h, m, s, ms);
21195 return date;
21196 }
21197 return string;
21198 }
21199
21200
21201 return function(date, format, timezone) {
21202 var text = '',
21203 parts = [],
21204 fn, match;
21205
21206 format = format || 'mediumDate';
21207 format = $locale.DATETIME_FORMATS[format] || format;
21208 if (isString(date)) {
21209 date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
21210 }
21211
21212 if (isNumber(date)) {
21213 date = new Date(date);
21214 }
21215
21216 if (!isDate(date) || !isFinite(date.getTime())) {
21217 return date;
21218 }
21219
21220 while (format) {
21221 match = DATE_FORMATS_SPLIT.exec(format);
21222 if (match) {
21223 parts = concat(parts, match, 1);
21224 format = parts.pop();
21225 } else {
21226 parts.push(format);
21227 format = null;
21228 }
21229 }
21230
21231 var dateTimezoneOffset = date.getTimezoneOffset();
21232 if (timezone) {
21233 dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
21234 date = convertTimezoneToLocal(date, timezone, true);
21235 }
21236 forEach(parts, function(value) {
21237 fn = DATE_FORMATS[value];
21238 text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
21239 : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
21240 });
21241
21242 return text;
21243 };
21244}
21245
21246
21247/**
21248 * @ngdoc filter
21249 * @name json
21250 * @kind function
21251 *
21252 * @description
21253 * Allows you to convert a JavaScript object into JSON string.
21254 *
21255 * This filter is mostly useful for debugging. When using the double curly {{value}} notation
21256 * the binding is automatically converted to JSON.
21257 *
21258 * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
21259 * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
21260 * @returns {string} JSON string.
21261 *
21262 *
21263 * @example
21264 <example name="filter-json">
21265 <file name="index.html">
21266 <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
21267 <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
21268 </file>
21269 <file name="protractor.js" type="protractor">
21270 it('should jsonify filtered objects', function() {
21271 expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
21272 expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
21273 });
21274 </file>
21275 </example>
21276 *
21277 */
21278function jsonFilter() {
21279 return function(object, spacing) {
21280 if (isUndefined(spacing)) {
21281 spacing = 2;
21282 }
21283 return toJson(object, spacing);
21284 };
21285}
21286
21287
21288/**
21289 * @ngdoc filter
21290 * @name lowercase
21291 * @kind function
21292 * @description
21293 * Converts string to lowercase.
21294 * @see angular.lowercase
21295 */
21296var lowercaseFilter = valueFn(lowercase);
21297
21298
21299/**
21300 * @ngdoc filter
21301 * @name uppercase
21302 * @kind function
21303 * @description
21304 * Converts string to uppercase.
21305 * @see angular.uppercase
21306 */
21307var uppercaseFilter = valueFn(uppercase);
21308
21309/**
21310 * @ngdoc filter
21311 * @name limitTo
21312 * @kind function
21313 *
21314 * @description
21315 * Creates a new array or string containing only a specified number of elements. The elements are
21316 * taken from either the beginning or the end of the source array, string or number, as specified by
21317 * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
21318 * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
21319 * it is converted to a string.
21320 *
21321 * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
21322 * @param {string|number} limit - The length of the returned array or string. If the `limit` number
21323 * is positive, `limit` number of items from the beginning of the source array/string are copied.
21324 * If the number is negative, `limit` number of items from the end of the source array/string
21325 * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
21326 * the input will be returned unchanged.
21327 * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
21328 * `begin` indicates an offset from the end of `input`. Defaults to `0`.
21329 * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
21330 * less than `limit` elements.
21331 *
21332 * @example
21333 <example module="limitToExample" name="limit-to-filter">
21334 <file name="index.html">
21335 <script>
21336 angular.module('limitToExample', [])
21337 .controller('ExampleController', ['$scope', function($scope) {
21338 $scope.numbers = [1,2,3,4,5,6,7,8,9];
21339 $scope.letters = "abcdefghi";
21340 $scope.longNumber = 2345432342;
21341 $scope.numLimit = 3;
21342 $scope.letterLimit = 3;
21343 $scope.longNumberLimit = 3;
21344 }]);
21345 </script>
21346 <div ng-controller="ExampleController">
21347 <label>
21348 Limit {{numbers}} to:
21349 <input type="number" step="1" ng-model="numLimit">
21350 </label>
21351 <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
21352 <label>
21353 Limit {{letters}} to:
21354 <input type="number" step="1" ng-model="letterLimit">
21355 </label>
21356 <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
21357 <label>
21358 Limit {{longNumber}} to:
21359 <input type="number" step="1" ng-model="longNumberLimit">
21360 </label>
21361 <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
21362 </div>
21363 </file>
21364 <file name="protractor.js" type="protractor">
21365 var numLimitInput = element(by.model('numLimit'));
21366 var letterLimitInput = element(by.model('letterLimit'));
21367 var longNumberLimitInput = element(by.model('longNumberLimit'));
21368 var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
21369 var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
21370 var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
21371
21372 it('should limit the number array to first three items', function() {
21373 expect(numLimitInput.getAttribute('value')).toBe('3');
21374 expect(letterLimitInput.getAttribute('value')).toBe('3');
21375 expect(longNumberLimitInput.getAttribute('value')).toBe('3');
21376 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
21377 expect(limitedLetters.getText()).toEqual('Output letters: abc');
21378 expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
21379 });
21380
21381 // There is a bug in safari and protractor that doesn't like the minus key
21382 // it('should update the output when -3 is entered', function() {
21383 // numLimitInput.clear();
21384 // numLimitInput.sendKeys('-3');
21385 // letterLimitInput.clear();
21386 // letterLimitInput.sendKeys('-3');
21387 // longNumberLimitInput.clear();
21388 // longNumberLimitInput.sendKeys('-3');
21389 // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
21390 // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
21391 // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
21392 // });
21393
21394 it('should not exceed the maximum size of input array', function() {
21395 numLimitInput.clear();
21396 numLimitInput.sendKeys('100');
21397 letterLimitInput.clear();
21398 letterLimitInput.sendKeys('100');
21399 longNumberLimitInput.clear();
21400 longNumberLimitInput.sendKeys('100');
21401 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
21402 expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
21403 expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
21404 });
21405 </file>
21406 </example>
21407*/
21408function limitToFilter() {
21409 return function(input, limit, begin) {
21410 if (Math.abs(Number(limit)) === Infinity) {
21411 limit = Number(limit);
21412 } else {
21413 limit = toInt(limit);
21414 }
21415 if (isNumberNaN(limit)) return input;
21416
21417 if (isNumber(input)) input = input.toString();
21418 if (!isArrayLike(input)) return input;
21419
21420 begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
21421 begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
21422
21423 if (limit >= 0) {
21424 return sliceFn(input, begin, begin + limit);
21425 } else {
21426 if (begin === 0) {
21427 return sliceFn(input, limit, input.length);
21428 } else {
21429 return sliceFn(input, Math.max(0, begin + limit), begin);
21430 }
21431 }
21432 };
21433}
21434
21435function sliceFn(input, begin, end) {
21436 if (isString(input)) return input.slice(begin, end);
21437
21438 return slice.call(input, begin, end);
21439}
21440
21441/**
21442 * @ngdoc filter
21443 * @name orderBy
21444 * @kind function
21445 *
21446 * @description
21447 * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
21448 * function based on the values computed using the `expression` predicate.
21449 *
21450 * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
21451 * `[{id: 'bar'}, {id: 'foo'}]`.
21452 *
21453 * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
21454 * String, etc).
21455 *
21456 * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
21457 * for the preceding one. The `expression` is evaluated against each item and the output is used
21458 * for comparing with other items.
21459 *
21460 * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
21461 * ascending order.
21462 *
21463 * The comparison is done using the `comparator` function. If none is specified, a default, built-in
21464 * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
21465 * strings alphabetically).
21466 *
21467 * ### Under the hood
21468 *
21469 * Ordering the specified `collection` happens in two phases:
21470 *
21471 * 1. All items are passed through the predicate (or predicates), and the returned values are saved
21472 * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
21473 * through a predicate that extracts the value of the `label` property, would be transformed to:
21474 * ```
21475 * {
21476 * value: 'foo',
21477 * type: 'string',
21478 * index: ...
21479 * }
21480 * ```
21481 * 2. The comparator function is used to sort the items, based on the derived values, types and
21482 * indices.
21483 *
21484 * If you use a custom comparator, it will be called with pairs of objects of the form
21485 * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
21486 * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
21487 * second, or `1` otherwise.
21488 *
21489 * In order to ensure that the sorting will be deterministic across platforms, if none of the
21490 * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
21491 * dummy predicate that returns the item's index as `value`.
21492 * (If you are using a custom comparator, make sure it can handle this predicate as well.)
21493 *
21494 * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
21495 * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
21496 * it to the comparator. The following rules govern the conversion:
21497 *
21498 * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
21499 * used instead.<br />
21500 * (If the object has a `valueOf()` method that returns another object, then the returned object
21501 * will be used in subsequent steps.)
21502 * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
21503 * returns a primitive, its return value will be used instead.<br />
21504 * (If the object has a `toString()` method that returns another object, then the returned object
21505 * will be used in subsequent steps.)
21506 * 3. No conversion; the object itself is used.
21507 *
21508 * ### The default comparator
21509 *
21510 * The default, built-in comparator should be sufficient for most usecases. In short, it compares
21511 * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
21512 * using their index in the original collection, and sorts values of different types by type.
21513 *
21514 * More specifically, it follows these steps to determine the relative order of items:
21515 *
21516 * 1. If the compared values are of different types, compare the types themselves alphabetically.
21517 * 2. If both values are of type `string`, compare them alphabetically in a case- and
21518 * locale-insensitive way.
21519 * 3. If both values are objects, compare their indices instead.
21520 * 4. Otherwise, return:
21521 * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
21522 * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
21523 * - `1`, otherwise.
21524 *
21525 * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
21526 * saved as numbers and not strings.
21527 * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
21528 * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
21529 * other values.
21530 *
21531 * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
21532 * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
21533 * predicates) to be used by the comparator to determine the order of elements.
21534 *
21535 * Can be one of:
21536 *
21537 * - `Function`: A getter function. This function will be called with each item as argument and
21538 * the return value will be used for sorting.
21539 * - `string`: An Angular expression. This expression will be evaluated against each item and the
21540 * result will be used for sorting. For example, use `'label'` to sort by a property called
21541 * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
21542 * property.<br />
21543 * (The result of a constant expression is interpreted as a property name to be used for
21544 * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
21545 * property called `special name`.)<br />
21546 * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
21547 * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
21548 * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
21549 * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
21550 * relative order of two items, the next predicate is used as a tie-breaker.
21551 *
21552 * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
21553 *
21554 * @param {boolean=} reverse - If `true`, reverse the sorting order.
21555 * @param {(Function)=} comparator - The comparator function used to determine the relative order of
21556 * value pairs. If omitted, the built-in comparator will be used.
21557 *
21558 * @returns {Array} - The sorted array.
21559 *
21560 *
21561 * @example
21562 * ### Ordering a table with `ngRepeat`
21563 *
21564 * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
21565 * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
21566 * it defaults to the built-in comparator.
21567 *
21568 <example name="orderBy-static" module="orderByExample1">
21569 <file name="index.html">
21570 <div ng-controller="ExampleController">
21571 <table class="friends">
21572 <tr>
21573 <th>Name</th>
21574 <th>Phone Number</th>
21575 <th>Age</th>
21576 </tr>
21577 <tr ng-repeat="friend in friends | orderBy:'-age'">
21578 <td>{{friend.name}}</td>
21579 <td>{{friend.phone}}</td>
21580 <td>{{friend.age}}</td>
21581 </tr>
21582 </table>
21583 </div>
21584 </file>
21585 <file name="script.js">
21586 angular.module('orderByExample1', [])
21587 .controller('ExampleController', ['$scope', function($scope) {
21588 $scope.friends = [
21589 {name: 'John', phone: '555-1212', age: 10},
21590 {name: 'Mary', phone: '555-9876', age: 19},
21591 {name: 'Mike', phone: '555-4321', age: 21},
21592 {name: 'Adam', phone: '555-5678', age: 35},
21593 {name: 'Julie', phone: '555-8765', age: 29}
21594 ];
21595 }]);
21596 </file>
21597 <file name="style.css">
21598 .friends {
21599 border-collapse: collapse;
21600 }
21601
21602 .friends th {
21603 border-bottom: 1px solid;
21604 }
21605 .friends td, .friends th {
21606 border-left: 1px solid;
21607 padding: 5px 10px;
21608 }
21609 .friends td:first-child, .friends th:first-child {
21610 border-left: none;
21611 }
21612 </file>
21613 <file name="protractor.js" type="protractor">
21614 // Element locators
21615 var names = element.all(by.repeater('friends').column('friend.name'));
21616
21617 it('should sort friends by age in reverse order', function() {
21618 expect(names.get(0).getText()).toBe('Adam');
21619 expect(names.get(1).getText()).toBe('Julie');
21620 expect(names.get(2).getText()).toBe('Mike');
21621 expect(names.get(3).getText()).toBe('Mary');
21622 expect(names.get(4).getText()).toBe('John');
21623 });
21624 </file>
21625 </example>
21626 * <hr />
21627 *
21628 * @example
21629 * ### Changing parameters dynamically
21630 *
21631 * All parameters can be changed dynamically. The next example shows how you can make the columns of
21632 * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
21633 *
21634 <example name="orderBy-dynamic" module="orderByExample2">
21635 <file name="index.html">
21636 <div ng-controller="ExampleController">
21637 <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
21638 <hr/>
21639 <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
21640 <hr/>
21641 <table class="friends">
21642 <tr>
21643 <th>
21644 <button ng-click="sortBy('name')">Name</button>
21645 <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
21646 </th>
21647 <th>
21648 <button ng-click="sortBy('phone')">Phone Number</button>
21649 <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
21650 </th>
21651 <th>
21652 <button ng-click="sortBy('age')">Age</button>
21653 <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
21654 </th>
21655 </tr>
21656 <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
21657 <td>{{friend.name}}</td>
21658 <td>{{friend.phone}}</td>
21659 <td>{{friend.age}}</td>
21660 </tr>
21661 </table>
21662 </div>
21663 </file>
21664 <file name="script.js">
21665 angular.module('orderByExample2', [])
21666 .controller('ExampleController', ['$scope', function($scope) {
21667 var friends = [
21668 {name: 'John', phone: '555-1212', age: 10},
21669 {name: 'Mary', phone: '555-9876', age: 19},
21670 {name: 'Mike', phone: '555-4321', age: 21},
21671 {name: 'Adam', phone: '555-5678', age: 35},
21672 {name: 'Julie', phone: '555-8765', age: 29}
21673 ];
21674
21675 $scope.propertyName = 'age';
21676 $scope.reverse = true;
21677 $scope.friends = friends;
21678
21679 $scope.sortBy = function(propertyName) {
21680 $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
21681 $scope.propertyName = propertyName;
21682 };
21683 }]);
21684 </file>
21685 <file name="style.css">
21686 .friends {
21687 border-collapse: collapse;
21688 }
21689
21690 .friends th {
21691 border-bottom: 1px solid;
21692 }
21693 .friends td, .friends th {
21694 border-left: 1px solid;
21695 padding: 5px 10px;
21696 }
21697 .friends td:first-child, .friends th:first-child {
21698 border-left: none;
21699 }
21700
21701 .sortorder:after {
21702 content: '\25b2'; // BLACK UP-POINTING TRIANGLE
21703 }
21704 .sortorder.reverse:after {
21705 content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
21706 }
21707 </file>
21708 <file name="protractor.js" type="protractor">
21709 // Element locators
21710 var unsortButton = element(by.partialButtonText('unsorted'));
21711 var nameHeader = element(by.partialButtonText('Name'));
21712 var phoneHeader = element(by.partialButtonText('Phone'));
21713 var ageHeader = element(by.partialButtonText('Age'));
21714 var firstName = element(by.repeater('friends').column('friend.name').row(0));
21715 var lastName = element(by.repeater('friends').column('friend.name').row(4));
21716
21717 it('should sort friends by some property, when clicking on the column header', function() {
21718 expect(firstName.getText()).toBe('Adam');
21719 expect(lastName.getText()).toBe('John');
21720
21721 phoneHeader.click();
21722 expect(firstName.getText()).toBe('John');
21723 expect(lastName.getText()).toBe('Mary');
21724
21725 nameHeader.click();
21726 expect(firstName.getText()).toBe('Adam');
21727 expect(lastName.getText()).toBe('Mike');
21728
21729 ageHeader.click();
21730 expect(firstName.getText()).toBe('John');
21731 expect(lastName.getText()).toBe('Adam');
21732 });
21733
21734 it('should sort friends in reverse order, when clicking on the same column', function() {
21735 expect(firstName.getText()).toBe('Adam');
21736 expect(lastName.getText()).toBe('John');
21737
21738 ageHeader.click();
21739 expect(firstName.getText()).toBe('John');
21740 expect(lastName.getText()).toBe('Adam');
21741
21742 ageHeader.click();
21743 expect(firstName.getText()).toBe('Adam');
21744 expect(lastName.getText()).toBe('John');
21745 });
21746
21747 it('should restore the original order, when clicking "Set to unsorted"', function() {
21748 expect(firstName.getText()).toBe('Adam');
21749 expect(lastName.getText()).toBe('John');
21750
21751 unsortButton.click();
21752 expect(firstName.getText()).toBe('John');
21753 expect(lastName.getText()).toBe('Julie');
21754 });
21755 </file>
21756 </example>
21757 * <hr />
21758 *
21759 * @example
21760 * ### Using `orderBy` inside a controller
21761 *
21762 * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
21763 * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
21764 * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
21765 *
21766 <example name="orderBy-call-manually" module="orderByExample3">
21767 <file name="index.html">
21768 <div ng-controller="ExampleController">
21769 <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
21770 <hr/>
21771 <button ng-click="sortBy(null)">Set to unsorted</button>
21772 <hr/>
21773 <table class="friends">
21774 <tr>
21775 <th>
21776 <button ng-click="sortBy('name')">Name</button>
21777 <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
21778 </th>
21779 <th>
21780 <button ng-click="sortBy('phone')">Phone Number</button>
21781 <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
21782 </th>
21783 <th>
21784 <button ng-click="sortBy('age')">Age</button>
21785 <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
21786 </th>
21787 </tr>
21788 <tr ng-repeat="friend in friends">
21789 <td>{{friend.name}}</td>
21790 <td>{{friend.phone}}</td>
21791 <td>{{friend.age}}</td>
21792 </tr>
21793 </table>
21794 </div>
21795 </file>
21796 <file name="script.js">
21797 angular.module('orderByExample3', [])
21798 .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
21799 var friends = [
21800 {name: 'John', phone: '555-1212', age: 10},
21801 {name: 'Mary', phone: '555-9876', age: 19},
21802 {name: 'Mike', phone: '555-4321', age: 21},
21803 {name: 'Adam', phone: '555-5678', age: 35},
21804 {name: 'Julie', phone: '555-8765', age: 29}
21805 ];
21806
21807 $scope.propertyName = 'age';
21808 $scope.reverse = true;
21809 $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
21810
21811 $scope.sortBy = function(propertyName) {
21812 $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
21813 ? !$scope.reverse : false;
21814 $scope.propertyName = propertyName;
21815 $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
21816 };
21817 }]);
21818 </file>
21819 <file name="style.css">
21820 .friends {
21821 border-collapse: collapse;
21822 }
21823
21824 .friends th {
21825 border-bottom: 1px solid;
21826 }
21827 .friends td, .friends th {
21828 border-left: 1px solid;
21829 padding: 5px 10px;
21830 }
21831 .friends td:first-child, .friends th:first-child {
21832 border-left: none;
21833 }
21834
21835 .sortorder:after {
21836 content: '\25b2'; // BLACK UP-POINTING TRIANGLE
21837 }
21838 .sortorder.reverse:after {
21839 content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
21840 }
21841 </file>
21842 <file name="protractor.js" type="protractor">
21843 // Element locators
21844 var unsortButton = element(by.partialButtonText('unsorted'));
21845 var nameHeader = element(by.partialButtonText('Name'));
21846 var phoneHeader = element(by.partialButtonText('Phone'));
21847 var ageHeader = element(by.partialButtonText('Age'));
21848 var firstName = element(by.repeater('friends').column('friend.name').row(0));
21849 var lastName = element(by.repeater('friends').column('friend.name').row(4));
21850
21851 it('should sort friends by some property, when clicking on the column header', function() {
21852 expect(firstName.getText()).toBe('Adam');
21853 expect(lastName.getText()).toBe('John');
21854
21855 phoneHeader.click();
21856 expect(firstName.getText()).toBe('John');
21857 expect(lastName.getText()).toBe('Mary');
21858
21859 nameHeader.click();
21860 expect(firstName.getText()).toBe('Adam');
21861 expect(lastName.getText()).toBe('Mike');
21862
21863 ageHeader.click();
21864 expect(firstName.getText()).toBe('John');
21865 expect(lastName.getText()).toBe('Adam');
21866 });
21867
21868 it('should sort friends in reverse order, when clicking on the same column', function() {
21869 expect(firstName.getText()).toBe('Adam');
21870 expect(lastName.getText()).toBe('John');
21871
21872 ageHeader.click();
21873 expect(firstName.getText()).toBe('John');
21874 expect(lastName.getText()).toBe('Adam');
21875
21876 ageHeader.click();
21877 expect(firstName.getText()).toBe('Adam');
21878 expect(lastName.getText()).toBe('John');
21879 });
21880
21881 it('should restore the original order, when clicking "Set to unsorted"', function() {
21882 expect(firstName.getText()).toBe('Adam');
21883 expect(lastName.getText()).toBe('John');
21884
21885 unsortButton.click();
21886 expect(firstName.getText()).toBe('John');
21887 expect(lastName.getText()).toBe('Julie');
21888 });
21889 </file>
21890 </example>
21891 * <hr />
21892 *
21893 * @example
21894 * ### Using a custom comparator
21895 *
21896 * If you have very specific requirements about the way items are sorted, you can pass your own
21897 * comparator function. For example, you might need to compare some strings in a locale-sensitive
21898 * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
21899 * argument - passing `false` retains the default sorting order, i.e. ascending.)
21900 *
21901 <example name="orderBy-custom-comparator" module="orderByExample4">
21902 <file name="index.html">
21903 <div ng-controller="ExampleController">
21904 <div class="friends-container custom-comparator">
21905 <h3>Locale-sensitive Comparator</h3>
21906 <table class="friends">
21907 <tr>
21908 <th>Name</th>
21909 <th>Favorite Letter</th>
21910 </tr>
21911 <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
21912 <td>{{friend.name}}</td>
21913 <td>{{friend.favoriteLetter}}</td>
21914 </tr>
21915 </table>
21916 </div>
21917 <div class="friends-container default-comparator">
21918 <h3>Default Comparator</h3>
21919 <table class="friends">
21920 <tr>
21921 <th>Name</th>
21922 <th>Favorite Letter</th>
21923 </tr>
21924 <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
21925 <td>{{friend.name}}</td>
21926 <td>{{friend.favoriteLetter}}</td>
21927 </tr>
21928 </table>
21929 </div>
21930 </div>
21931 </file>
21932 <file name="script.js">
21933 angular.module('orderByExample4', [])
21934 .controller('ExampleController', ['$scope', function($scope) {
21935 $scope.friends = [
21936 {name: 'John', favoriteLetter: 'Ä'},
21937 {name: 'Mary', favoriteLetter: 'Ü'},
21938 {name: 'Mike', favoriteLetter: 'Ö'},
21939 {name: 'Adam', favoriteLetter: 'H'},
21940 {name: 'Julie', favoriteLetter: 'Z'}
21941 ];
21942
21943 $scope.localeSensitiveComparator = function(v1, v2) {
21944 // If we don't get strings, just compare by index
21945 if (v1.type !== 'string' || v2.type !== 'string') {
21946 return (v1.index < v2.index) ? -1 : 1;
21947 }
21948
21949 // Compare strings alphabetically, taking locale into account
21950 return v1.value.localeCompare(v2.value);
21951 };
21952 }]);
21953 </file>
21954 <file name="style.css">
21955 .friends-container {
21956 display: inline-block;
21957 margin: 0 30px;
21958 }
21959
21960 .friends {
21961 border-collapse: collapse;
21962 }
21963
21964 .friends th {
21965 border-bottom: 1px solid;
21966 }
21967 .friends td, .friends th {
21968 border-left: 1px solid;
21969 padding: 5px 10px;
21970 }
21971 .friends td:first-child, .friends th:first-child {
21972 border-left: none;
21973 }
21974 </file>
21975 <file name="protractor.js" type="protractor">
21976 // Element locators
21977 var container = element(by.css('.custom-comparator'));
21978 var names = container.all(by.repeater('friends').column('friend.name'));
21979
21980 it('should sort friends by favorite letter (in correct alphabetical order)', function() {
21981 expect(names.get(0).getText()).toBe('John');
21982 expect(names.get(1).getText()).toBe('Adam');
21983 expect(names.get(2).getText()).toBe('Mike');
21984 expect(names.get(3).getText()).toBe('Mary');
21985 expect(names.get(4).getText()).toBe('Julie');
21986 });
21987 </file>
21988 </example>
21989 *
21990 */
21991orderByFilter.$inject = ['$parse'];
21992function orderByFilter($parse) {
21993 return function(array, sortPredicate, reverseOrder, compareFn) {
21994
21995 if (array == null) return array;
21996 if (!isArrayLike(array)) {
21997 throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
21998 }
21999
22000 if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
22001 if (sortPredicate.length === 0) { sortPredicate = ['+']; }
22002
22003 var predicates = processPredicates(sortPredicate);
22004
22005 var descending = reverseOrder ? -1 : 1;
22006
22007 // Define the `compare()` function. Use a default comparator if none is specified.
22008 var compare = isFunction(compareFn) ? compareFn : defaultCompare;
22009
22010 // The next three lines are a version of a Swartzian Transform idiom from Perl
22011 // (sometimes called the Decorate-Sort-Undecorate idiom)
22012 // See https://en.wikipedia.org/wiki/Schwartzian_transform
22013 var compareValues = Array.prototype.map.call(array, getComparisonObject);
22014 compareValues.sort(doComparison);
22015 array = compareValues.map(function(item) { return item.value; });
22016
22017 return array;
22018
22019 function getComparisonObject(value, index) {
22020 // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
22021 // This will be used to keep the sort stable when none of the input predicates can
22022 // distinguish between two elements.
22023 return {
22024 value: value,
22025 tieBreaker: {value: index, type: 'number', index: index},
22026 predicateValues: predicates.map(function(predicate) {
22027 return getPredicateValue(predicate.get(value), index);
22028 })
22029 };
22030 }
22031
22032 function doComparison(v1, v2) {
22033 for (var i = 0, ii = predicates.length; i < ii; i++) {
22034 var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
22035 if (result) {
22036 return result * predicates[i].descending * descending;
22037 }
22038 }
22039
22040 return compare(v1.tieBreaker, v2.tieBreaker) * descending;
22041 }
22042 };
22043
22044 function processPredicates(sortPredicates) {
22045 return sortPredicates.map(function(predicate) {
22046 var descending = 1, get = identity;
22047
22048 if (isFunction(predicate)) {
22049 get = predicate;
22050 } else if (isString(predicate)) {
22051 if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
22052 descending = predicate.charAt(0) === '-' ? -1 : 1;
22053 predicate = predicate.substring(1);
22054 }
22055 if (predicate !== '') {
22056 get = $parse(predicate);
22057 if (get.constant) {
22058 var key = get();
22059 get = function(value) { return value[key]; };
22060 }
22061 }
22062 }
22063 return {get: get, descending: descending};
22064 });
22065 }
22066
22067 function isPrimitive(value) {
22068 switch (typeof value) {
22069 case 'number': /* falls through */
22070 case 'boolean': /* falls through */
22071 case 'string':
22072 return true;
22073 default:
22074 return false;
22075 }
22076 }
22077
22078 function objectValue(value) {
22079 // If `valueOf` is a valid function use that
22080 if (isFunction(value.valueOf)) {
22081 value = value.valueOf();
22082 if (isPrimitive(value)) return value;
22083 }
22084 // If `toString` is a valid function and not the one from `Object.prototype` use that
22085 if (hasCustomToString(value)) {
22086 value = value.toString();
22087 if (isPrimitive(value)) return value;
22088 }
22089
22090 return value;
22091 }
22092
22093 function getPredicateValue(value, index) {
22094 var type = typeof value;
22095 if (value === null) {
22096 type = 'string';
22097 value = 'null';
22098 } else if (type === 'object') {
22099 value = objectValue(value);
22100 }
22101 return {value: value, type: type, index: index};
22102 }
22103
22104 function defaultCompare(v1, v2) {
22105 var result = 0;
22106 var type1 = v1.type;
22107 var type2 = v2.type;
22108
22109 if (type1 === type2) {
22110 var value1 = v1.value;
22111 var value2 = v2.value;
22112
22113 if (type1 === 'string') {
22114 // Compare strings case-insensitively
22115 value1 = value1.toLowerCase();
22116 value2 = value2.toLowerCase();
22117 } else if (type1 === 'object') {
22118 // For basic objects, use the position of the object
22119 // in the collection instead of the value
22120 if (isObject(value1)) value1 = v1.index;
22121 if (isObject(value2)) value2 = v2.index;
22122 }
22123
22124 if (value1 !== value2) {
22125 result = value1 < value2 ? -1 : 1;
22126 }
22127 } else {
22128 result = type1 < type2 ? -1 : 1;
22129 }
22130
22131 return result;
22132 }
22133}
22134
22135function ngDirective(directive) {
22136 if (isFunction(directive)) {
22137 directive = {
22138 link: directive
22139 };
22140 }
22141 directive.restrict = directive.restrict || 'AC';
22142 return valueFn(directive);
22143}
22144
22145/**
22146 * @ngdoc directive
22147 * @name a
22148 * @restrict E
22149 *
22150 * @description
22151 * Modifies the default behavior of the html a tag so that the default action is prevented when
22152 * the href attribute is empty.
22153 *
22154 * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
22155 */
22156var htmlAnchorDirective = valueFn({
22157 restrict: 'E',
22158 compile: function(element, attr) {
22159 if (!attr.href && !attr.xlinkHref) {
22160 return function(scope, element) {
22161 // If the linked element is not an anchor tag anymore, do nothing
22162 if (element[0].nodeName.toLowerCase() !== 'a') return;
22163
22164 // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
22165 var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
22166 'xlink:href' : 'href';
22167 element.on('click', function(event) {
22168 // if we have no href url, then don't navigate anywhere.
22169 if (!element.attr(href)) {
22170 event.preventDefault();
22171 }
22172 });
22173 };
22174 }
22175 }
22176});
22177
22178/**
22179 * @ngdoc directive
22180 * @name ngHref
22181 * @restrict A
22182 * @priority 99
22183 *
22184 * @description
22185 * Using Angular markup like `{{hash}}` in an href attribute will
22186 * make the link go to the wrong URL if the user clicks it before
22187 * Angular has a chance to replace the `{{hash}}` markup with its
22188 * value. Until Angular replaces the markup the link will be broken
22189 * and will most likely return a 404 error. The `ngHref` directive
22190 * solves this problem.
22191 *
22192 * The wrong way to write it:
22193 * ```html
22194 * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
22195 * ```
22196 *
22197 * The correct way to write it:
22198 * ```html
22199 * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
22200 * ```
22201 *
22202 * @element A
22203 * @param {template} ngHref any string which can contain `{{}}` markup.
22204 *
22205 * @example
22206 * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
22207 * in links and their different behaviors:
22208 <example name="ng-href">
22209 <file name="index.html">
22210 <input ng-model="value" /><br />
22211 <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
22212 <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
22213 <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
22214 <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
22215 <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
22216 <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
22217 </file>
22218 <file name="protractor.js" type="protractor">
22219 it('should execute ng-click but not reload when href without value', function() {
22220 element(by.id('link-1')).click();
22221 expect(element(by.model('value')).getAttribute('value')).toEqual('1');
22222 expect(element(by.id('link-1')).getAttribute('href')).toBe('');
22223 });
22224
22225 it('should execute ng-click but not reload when href empty string', function() {
22226 element(by.id('link-2')).click();
22227 expect(element(by.model('value')).getAttribute('value')).toEqual('2');
22228 expect(element(by.id('link-2')).getAttribute('href')).toBe('');
22229 });
22230
22231 it('should execute ng-click and change url when ng-href specified', function() {
22232 expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
22233
22234 element(by.id('link-3')).click();
22235
22236 // At this point, we navigate away from an Angular page, so we need
22237 // to use browser.driver to get the base webdriver.
22238
22239 browser.wait(function() {
22240 return browser.driver.getCurrentUrl().then(function(url) {
22241 return url.match(/\/123$/);
22242 });
22243 }, 5000, 'page should navigate to /123');
22244 });
22245
22246 it('should execute ng-click but not reload when href empty string and name specified', function() {
22247 element(by.id('link-4')).click();
22248 expect(element(by.model('value')).getAttribute('value')).toEqual('4');
22249 expect(element(by.id('link-4')).getAttribute('href')).toBe('');
22250 });
22251
22252 it('should execute ng-click but not reload when no href but name specified', function() {
22253 element(by.id('link-5')).click();
22254 expect(element(by.model('value')).getAttribute('value')).toEqual('5');
22255 expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
22256 });
22257
22258 it('should only change url when only ng-href', function() {
22259 element(by.model('value')).clear();
22260 element(by.model('value')).sendKeys('6');
22261 expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
22262
22263 element(by.id('link-6')).click();
22264
22265 // At this point, we navigate away from an Angular page, so we need
22266 // to use browser.driver to get the base webdriver.
22267 browser.wait(function() {
22268 return browser.driver.getCurrentUrl().then(function(url) {
22269 return url.match(/\/6$/);
22270 });
22271 }, 5000, 'page should navigate to /6');
22272 });
22273 </file>
22274 </example>
22275 */
22276
22277/**
22278 * @ngdoc directive
22279 * @name ngSrc
22280 * @restrict A
22281 * @priority 99
22282 *
22283 * @description
22284 * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
22285 * work right: The browser will fetch from the URL with the literal
22286 * text `{{hash}}` until Angular replaces the expression inside
22287 * `{{hash}}`. The `ngSrc` directive solves this problem.
22288 *
22289 * The buggy way to write it:
22290 * ```html
22291 * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
22292 * ```
22293 *
22294 * The correct way to write it:
22295 * ```html
22296 * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
22297 * ```
22298 *
22299 * @element IMG
22300 * @param {template} ngSrc any string which can contain `{{}}` markup.
22301 */
22302
22303/**
22304 * @ngdoc directive
22305 * @name ngSrcset
22306 * @restrict A
22307 * @priority 99
22308 *
22309 * @description
22310 * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
22311 * work right: The browser will fetch from the URL with the literal
22312 * text `{{hash}}` until Angular replaces the expression inside
22313 * `{{hash}}`. The `ngSrcset` directive solves this problem.
22314 *
22315 * The buggy way to write it:
22316 * ```html
22317 * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
22318 * ```
22319 *
22320 * The correct way to write it:
22321 * ```html
22322 * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
22323 * ```
22324 *
22325 * @element IMG
22326 * @param {template} ngSrcset any string which can contain `{{}}` markup.
22327 */
22328
22329/**
22330 * @ngdoc directive
22331 * @name ngDisabled
22332 * @restrict A
22333 * @priority 100
22334 *
22335 * @description
22336 *
22337 * This directive sets the `disabled` attribute on the element if the
22338 * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
22339 *
22340 * A special directive is necessary because we cannot use interpolation inside the `disabled`
22341 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
22342 *
22343 * @example
22344 <example name="ng-disabled">
22345 <file name="index.html">
22346 <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
22347 <button ng-model="button" ng-disabled="checked">Button</button>
22348 </file>
22349 <file name="protractor.js" type="protractor">
22350 it('should toggle button', function() {
22351 expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
22352 element(by.model('checked')).click();
22353 expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
22354 });
22355 </file>
22356 </example>
22357 *
22358 * @element INPUT
22359 * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
22360 * then the `disabled` attribute will be set on the element
22361 */
22362
22363
22364/**
22365 * @ngdoc directive
22366 * @name ngChecked
22367 * @restrict A
22368 * @priority 100
22369 *
22370 * @description
22371 * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
22372 *
22373 * Note that this directive should not be used together with {@link ngModel `ngModel`},
22374 * as this can lead to unexpected behavior.
22375 *
22376 * A special directive is necessary because we cannot use interpolation inside the `checked`
22377 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
22378 *
22379 * @example
22380 <example name="ng-checked">
22381 <file name="index.html">
22382 <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
22383 <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
22384 </file>
22385 <file name="protractor.js" type="protractor">
22386 it('should check both checkBoxes', function() {
22387 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
22388 element(by.model('master')).click();
22389 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
22390 });
22391 </file>
22392 </example>
22393 *
22394 * @element INPUT
22395 * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
22396 * then the `checked` attribute will be set on the element
22397 */
22398
22399
22400/**
22401 * @ngdoc directive
22402 * @name ngReadonly
22403 * @restrict A
22404 * @priority 100
22405 *
22406 * @description
22407 *
22408 * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
22409 * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
22410 * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
22411 *
22412 * A special directive is necessary because we cannot use interpolation inside the `readonly`
22413 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
22414 *
22415 * @example
22416 <example name="ng-readonly">
22417 <file name="index.html">
22418 <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
22419 <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
22420 </file>
22421 <file name="protractor.js" type="protractor">
22422 it('should toggle readonly attr', function() {
22423 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
22424 element(by.model('checked')).click();
22425 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
22426 });
22427 </file>
22428 </example>
22429 *
22430 * @element INPUT
22431 * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
22432 * then special attribute "readonly" will be set on the element
22433 */
22434
22435
22436/**
22437 * @ngdoc directive
22438 * @name ngSelected
22439 * @restrict A
22440 * @priority 100
22441 *
22442 * @description
22443 *
22444 * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
22445 *
22446 * A special directive is necessary because we cannot use interpolation inside the `selected`
22447 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
22448 *
22449 * <div class="alert alert-warning">
22450 * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
22451 * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
22452 * should not use `ngSelected` on the options, as `ngModel` will set the select value and
22453 * selected options.
22454 * </div>
22455 *
22456 * @example
22457 <example name="ng-selected">
22458 <file name="index.html">
22459 <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
22460 <select aria-label="ngSelected demo">
22461 <option>Hello!</option>
22462 <option id="greet" ng-selected="selected">Greetings!</option>
22463 </select>
22464 </file>
22465 <file name="protractor.js" type="protractor">
22466 it('should select Greetings!', function() {
22467 expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
22468 element(by.model('selected')).click();
22469 expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
22470 });
22471 </file>
22472 </example>
22473 *
22474 * @element OPTION
22475 * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
22476 * then special attribute "selected" will be set on the element
22477 */
22478
22479/**
22480 * @ngdoc directive
22481 * @name ngOpen
22482 * @restrict A
22483 * @priority 100
22484 *
22485 * @description
22486 *
22487 * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
22488 *
22489 * A special directive is necessary because we cannot use interpolation inside the `open`
22490 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
22491 *
22492 * ## A note about browser compatibility
22493 *
22494 * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
22495 * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
22496 *
22497 * @example
22498 <example name="ng-open">
22499 <file name="index.html">
22500 <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
22501 <details id="details" ng-open="open">
22502 <summary>Show/Hide me</summary>
22503 </details>
22504 </file>
22505 <file name="protractor.js" type="protractor">
22506 it('should toggle open', function() {
22507 expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
22508 element(by.model('open')).click();
22509 expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
22510 });
22511 </file>
22512 </example>
22513 *
22514 * @element DETAILS
22515 * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
22516 * then special attribute "open" will be set on the element
22517 */
22518
22519var ngAttributeAliasDirectives = {};
22520
22521// boolean attrs are evaluated
22522forEach(BOOLEAN_ATTR, function(propName, attrName) {
22523 // binding to multiple is not supported
22524 if (propName === 'multiple') return;
22525
22526 function defaultLinkFn(scope, element, attr) {
22527 scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
22528 attr.$set(attrName, !!value);
22529 });
22530 }
22531
22532 var normalized = directiveNormalize('ng-' + attrName);
22533 var linkFn = defaultLinkFn;
22534
22535 if (propName === 'checked') {
22536 linkFn = function(scope, element, attr) {
22537 // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
22538 if (attr.ngModel !== attr[normalized]) {
22539 defaultLinkFn(scope, element, attr);
22540 }
22541 };
22542 }
22543
22544 ngAttributeAliasDirectives[normalized] = function() {
22545 return {
22546 restrict: 'A',
22547 priority: 100,
22548 link: linkFn
22549 };
22550 };
22551});
22552
22553// aliased input attrs are evaluated
22554forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
22555 ngAttributeAliasDirectives[ngAttr] = function() {
22556 return {
22557 priority: 100,
22558 link: function(scope, element, attr) {
22559 //special case ngPattern when a literal regular expression value
22560 //is used as the expression (this way we don't have to watch anything).
22561 if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
22562 var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
22563 if (match) {
22564 attr.$set('ngPattern', new RegExp(match[1], match[2]));
22565 return;
22566 }
22567 }
22568
22569 scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
22570 attr.$set(ngAttr, value);
22571 });
22572 }
22573 };
22574 };
22575});
22576
22577// ng-src, ng-srcset, ng-href are interpolated
22578forEach(['src', 'srcset', 'href'], function(attrName) {
22579 var normalized = directiveNormalize('ng-' + attrName);
22580 ngAttributeAliasDirectives[normalized] = function() {
22581 return {
22582 priority: 99, // it needs to run after the attributes are interpolated
22583 link: function(scope, element, attr) {
22584 var propName = attrName,
22585 name = attrName;
22586
22587 if (attrName === 'href' &&
22588 toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
22589 name = 'xlinkHref';
22590 attr.$attr[name] = 'xlink:href';
22591 propName = null;
22592 }
22593
22594 attr.$observe(normalized, function(value) {
22595 if (!value) {
22596 if (attrName === 'href') {
22597 attr.$set(name, null);
22598 }
22599 return;
22600 }
22601
22602 attr.$set(name, value);
22603
22604 // Support: IE 9-11 only
22605 // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
22606 // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
22607 // to set the property as well to achieve the desired effect.
22608 // We use attr[attrName] value since $set can sanitize the url.
22609 if (msie && propName) element.prop(propName, attr[name]);
22610 });
22611 }
22612 };
22613 };
22614});
22615
22616/* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
22617 */
22618var nullFormCtrl = {
22619 $addControl: noop,
22620 $$renameControl: nullFormRenameControl,
22621 $removeControl: noop,
22622 $setValidity: noop,
22623 $setDirty: noop,
22624 $setPristine: noop,
22625 $setSubmitted: noop
22626},
22627PENDING_CLASS = 'ng-pending',
22628SUBMITTED_CLASS = 'ng-submitted';
22629
22630function nullFormRenameControl(control, name) {
22631 control.$name = name;
22632}
22633
22634/**
22635 * @ngdoc type
22636 * @name form.FormController
22637 *
22638 * @property {boolean} $pristine True if user has not interacted with the form yet.
22639 * @property {boolean} $dirty True if user has already interacted with the form.
22640 * @property {boolean} $valid True if all of the containing forms and controls are valid.
22641 * @property {boolean} $invalid True if at least one containing control or form is invalid.
22642 * @property {boolean} $pending True if at least one containing control or form is pending.
22643 * @property {boolean} $submitted True if user has submitted the form even if its invalid.
22644 *
22645 * @property {Object} $error Is an object hash, containing references to controls or
22646 * forms with failing validators, where:
22647 *
22648 * - keys are validation tokens (error names),
22649 * - values are arrays of controls or forms that have a failing validator for given error name.
22650 *
22651 * Built-in validation tokens:
22652 *
22653 * - `email`
22654 * - `max`
22655 * - `maxlength`
22656 * - `min`
22657 * - `minlength`
22658 * - `number`
22659 * - `pattern`
22660 * - `required`
22661 * - `url`
22662 * - `date`
22663 * - `datetimelocal`
22664 * - `time`
22665 * - `week`
22666 * - `month`
22667 *
22668 * @description
22669 * `FormController` keeps track of all its controls and nested forms as well as the state of them,
22670 * such as being valid/invalid or dirty/pristine.
22671 *
22672 * Each {@link ng.directive:form form} directive creates an instance
22673 * of `FormController`.
22674 *
22675 */
22676//asks for $scope to fool the BC controller module
22677FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
22678function FormController($element, $attrs, $scope, $animate, $interpolate) {
22679 this.$$controls = [];
22680
22681 // init state
22682 this.$error = {};
22683 this.$$success = {};
22684 this.$pending = undefined;
22685 this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
22686 this.$dirty = false;
22687 this.$pristine = true;
22688 this.$valid = true;
22689 this.$invalid = false;
22690 this.$submitted = false;
22691 this.$$parentForm = nullFormCtrl;
22692
22693 this.$$element = $element;
22694 this.$$animate = $animate;
22695
22696 setupValidity(this);
22697}
22698
22699FormController.prototype = {
22700 /**
22701 * @ngdoc method
22702 * @name form.FormController#$rollbackViewValue
22703 *
22704 * @description
22705 * Rollback all form controls pending updates to the `$modelValue`.
22706 *
22707 * Updates may be pending by a debounced event or because the input is waiting for a some future
22708 * event defined in `ng-model-options`. This method is typically needed by the reset button of
22709 * a form that uses `ng-model-options` to pend updates.
22710 */
22711 $rollbackViewValue: function() {
22712 forEach(this.$$controls, function(control) {
22713 control.$rollbackViewValue();
22714 });
22715 },
22716
22717 /**
22718 * @ngdoc method
22719 * @name form.FormController#$commitViewValue
22720 *
22721 * @description
22722 * Commit all form controls pending updates to the `$modelValue`.
22723 *
22724 * Updates may be pending by a debounced event or because the input is waiting for a some future
22725 * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
22726 * usually handles calling this in response to input events.
22727 */
22728 $commitViewValue: function() {
22729 forEach(this.$$controls, function(control) {
22730 control.$commitViewValue();
22731 });
22732 },
22733
22734 /**
22735 * @ngdoc method
22736 * @name form.FormController#$addControl
22737 * @param {object} control control object, either a {@link form.FormController} or an
22738 * {@link ngModel.NgModelController}
22739 *
22740 * @description
22741 * Register a control with the form. Input elements using ngModelController do this automatically
22742 * when they are linked.
22743 *
22744 * Note that the current state of the control will not be reflected on the new parent form. This
22745 * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
22746 * state.
22747 *
22748 * However, if the method is used programmatically, for example by adding dynamically created controls,
22749 * or controls that have been previously removed without destroying their corresponding DOM element,
22750 * it's the developers responsibility to make sure the current state propagates to the parent form.
22751 *
22752 * For example, if an input control is added that is already `$dirty` and has `$error` properties,
22753 * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
22754 */
22755 $addControl: function(control) {
22756 // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
22757 // and not added to the scope. Now we throw an error.
22758 assertNotHasOwnProperty(control.$name, 'input');
22759 this.$$controls.push(control);
22760
22761 if (control.$name) {
22762 this[control.$name] = control;
22763 }
22764
22765 control.$$parentForm = this;
22766 },
22767
22768 // Private API: rename a form control
22769 $$renameControl: function(control, newName) {
22770 var oldName = control.$name;
22771
22772 if (this[oldName] === control) {
22773 delete this[oldName];
22774 }
22775 this[newName] = control;
22776 control.$name = newName;
22777 },
22778
22779 /**
22780 * @ngdoc method
22781 * @name form.FormController#$removeControl
22782 * @param {object} control control object, either a {@link form.FormController} or an
22783 * {@link ngModel.NgModelController}
22784 *
22785 * @description
22786 * Deregister a control from the form.
22787 *
22788 * Input elements using ngModelController do this automatically when they are destroyed.
22789 *
22790 * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
22791 * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
22792 * different from case to case. For example, removing the only `$dirty` control from a form may or
22793 * may not mean that the form is still `$dirty`.
22794 */
22795 $removeControl: function(control) {
22796 if (control.$name && this[control.$name] === control) {
22797 delete this[control.$name];
22798 }
22799 forEach(this.$pending, function(value, name) {
22800 // eslint-disable-next-line no-invalid-this
22801 this.$setValidity(name, null, control);
22802 }, this);
22803 forEach(this.$error, function(value, name) {
22804 // eslint-disable-next-line no-invalid-this
22805 this.$setValidity(name, null, control);
22806 }, this);
22807 forEach(this.$$success, function(value, name) {
22808 // eslint-disable-next-line no-invalid-this
22809 this.$setValidity(name, null, control);
22810 }, this);
22811
22812 arrayRemove(this.$$controls, control);
22813 control.$$parentForm = nullFormCtrl;
22814 },
22815
22816 /**
22817 * @ngdoc method
22818 * @name form.FormController#$setDirty
22819 *
22820 * @description
22821 * Sets the form to a dirty state.
22822 *
22823 * This method can be called to add the 'ng-dirty' class and set the form to a dirty
22824 * state (ng-dirty class). This method will also propagate to parent forms.
22825 */
22826 $setDirty: function() {
22827 this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
22828 this.$$animate.addClass(this.$$element, DIRTY_CLASS);
22829 this.$dirty = true;
22830 this.$pristine = false;
22831 this.$$parentForm.$setDirty();
22832 },
22833
22834 /**
22835 * @ngdoc method
22836 * @name form.FormController#$setPristine
22837 *
22838 * @description
22839 * Sets the form to its pristine state.
22840 *
22841 * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
22842 * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
22843 * state to false.
22844 *
22845 * This method will also propagate to all the controls contained in this form.
22846 *
22847 * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
22848 * saving or resetting it.
22849 */
22850 $setPristine: function() {
22851 this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
22852 this.$dirty = false;
22853 this.$pristine = true;
22854 this.$submitted = false;
22855 forEach(this.$$controls, function(control) {
22856 control.$setPristine();
22857 });
22858 },
22859
22860 /**
22861 * @ngdoc method
22862 * @name form.FormController#$setUntouched
22863 *
22864 * @description
22865 * Sets the form to its untouched state.
22866 *
22867 * This method can be called to remove the 'ng-touched' class and set the form controls to their
22868 * untouched state (ng-untouched class).
22869 *
22870 * Setting a form controls back to their untouched state is often useful when setting the form
22871 * back to its pristine state.
22872 */
22873 $setUntouched: function() {
22874 forEach(this.$$controls, function(control) {
22875 control.$setUntouched();
22876 });
22877 },
22878
22879 /**
22880 * @ngdoc method
22881 * @name form.FormController#$setSubmitted
22882 *
22883 * @description
22884 * Sets the form to its submitted state.
22885 */
22886 $setSubmitted: function() {
22887 this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
22888 this.$submitted = true;
22889 this.$$parentForm.$setSubmitted();
22890 }
22891};
22892
22893/**
22894 * @ngdoc method
22895 * @name form.FormController#$setValidity
22896 *
22897 * @description
22898 * Sets the validity of a form control.
22899 *
22900 * This method will also propagate to parent forms.
22901 */
22902addSetValidityMethod({
22903 clazz: FormController,
22904 set: function(object, property, controller) {
22905 var list = object[property];
22906 if (!list) {
22907 object[property] = [controller];
22908 } else {
22909 var index = list.indexOf(controller);
22910 if (index === -1) {
22911 list.push(controller);
22912 }
22913 }
22914 },
22915 unset: function(object, property, controller) {
22916 var list = object[property];
22917 if (!list) {
22918 return;
22919 }
22920 arrayRemove(list, controller);
22921 if (list.length === 0) {
22922 delete object[property];
22923 }
22924 }
22925});
22926
22927/**
22928 * @ngdoc directive
22929 * @name ngForm
22930 * @restrict EAC
22931 *
22932 * @description
22933 * Nestable alias of {@link ng.directive:form `form`} directive. HTML
22934 * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
22935 * sub-group of controls needs to be determined.
22936 *
22937 * Note: the purpose of `ngForm` is to group controls,
22938 * but not to be a replacement for the `<form>` tag with all of its capabilities
22939 * (e.g. posting to the server, ...).
22940 *
22941 * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
22942 * related scope, under this name.
22943 *
22944 */
22945
22946 /**
22947 * @ngdoc directive
22948 * @name form
22949 * @restrict E
22950 *
22951 * @description
22952 * Directive that instantiates
22953 * {@link form.FormController FormController}.
22954 *
22955 * If the `name` attribute is specified, the form controller is published onto the current scope under
22956 * this name.
22957 *
22958 * # Alias: {@link ng.directive:ngForm `ngForm`}
22959 *
22960 * In Angular, forms can be nested. This means that the outer form is valid when all of the child
22961 * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
22962 * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
22963 * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
22964 * of controls needs to be determined.
22965 *
22966 * # CSS classes
22967 * - `ng-valid` is set if the form is valid.
22968 * - `ng-invalid` is set if the form is invalid.
22969 * - `ng-pending` is set if the form is pending.
22970 * - `ng-pristine` is set if the form is pristine.
22971 * - `ng-dirty` is set if the form is dirty.
22972 * - `ng-submitted` is set if the form was submitted.
22973 *
22974 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
22975 *
22976 *
22977 * # Submitting a form and preventing the default action
22978 *
22979 * Since the role of forms in client-side Angular applications is different than in classical
22980 * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
22981 * page reload that sends the data to the server. Instead some javascript logic should be triggered
22982 * to handle the form submission in an application-specific way.
22983 *
22984 * For this reason, Angular prevents the default action (form submission to the server) unless the
22985 * `<form>` element has an `action` attribute specified.
22986 *
22987 * You can use one of the following two ways to specify what javascript method should be called when
22988 * a form is submitted:
22989 *
22990 * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
22991 * - {@link ng.directive:ngClick ngClick} directive on the first
22992 * button or input field of type submit (input[type=submit])
22993 *
22994 * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
22995 * or {@link ng.directive:ngClick ngClick} directives.
22996 * This is because of the following form submission rules in the HTML specification:
22997 *
22998 * - If a form has only one input field then hitting enter in this field triggers form submit
22999 * (`ngSubmit`)
23000 * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
23001 * doesn't trigger submit
23002 * - if a form has one or more input fields and one or more buttons or input[type=submit] then
23003 * hitting enter in any of the input fields will trigger the click handler on the *first* button or
23004 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
23005 *
23006 * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
23007 * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
23008 * to have access to the updated model.
23009 *
23010 * ## Animation Hooks
23011 *
23012 * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
23013 * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
23014 * other validations that are performed within the form. Animations in ngForm are similar to how
23015 * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
23016 * as JS animations.
23017 *
23018 * The following example shows a simple way to utilize CSS transitions to style a form element
23019 * that has been rendered as invalid after it has been validated:
23020 *
23021 * <pre>
23022 * //be sure to include ngAnimate as a module to hook into more
23023 * //advanced animations
23024 * .my-form {
23025 * transition:0.5s linear all;
23026 * background: white;
23027 * }
23028 * .my-form.ng-invalid {
23029 * background: red;
23030 * color:white;
23031 * }
23032 * </pre>
23033 *
23034 * @example
23035 <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
23036 <file name="index.html">
23037 <script>
23038 angular.module('formExample', [])
23039 .controller('FormController', ['$scope', function($scope) {
23040 $scope.userType = 'guest';
23041 }]);
23042 </script>
23043 <style>
23044 .my-form {
23045 transition:all linear 0.5s;
23046 background: transparent;
23047 }
23048 .my-form.ng-invalid {
23049 background: red;
23050 }
23051 </style>
23052 <form name="myForm" ng-controller="FormController" class="my-form">
23053 userType: <input name="input" ng-model="userType" required>
23054 <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
23055 <code>userType = {{userType}}</code><br>
23056 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
23057 <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
23058 <code>myForm.$valid = {{myForm.$valid}}</code><br>
23059 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
23060 </form>
23061 </file>
23062 <file name="protractor.js" type="protractor">
23063 it('should initialize to model', function() {
23064 var userType = element(by.binding('userType'));
23065 var valid = element(by.binding('myForm.input.$valid'));
23066
23067 expect(userType.getText()).toContain('guest');
23068 expect(valid.getText()).toContain('true');
23069 });
23070
23071 it('should be invalid if empty', function() {
23072 var userType = element(by.binding('userType'));
23073 var valid = element(by.binding('myForm.input.$valid'));
23074 var userInput = element(by.model('userType'));
23075
23076 userInput.clear();
23077 userInput.sendKeys('');
23078
23079 expect(userType.getText()).toEqual('userType =');
23080 expect(valid.getText()).toContain('false');
23081 });
23082 </file>
23083 </example>
23084 *
23085 * @param {string=} name Name of the form. If specified, the form controller will be published into
23086 * related scope, under this name.
23087 */
23088var formDirectiveFactory = function(isNgForm) {
23089 return ['$timeout', '$parse', function($timeout, $parse) {
23090 var formDirective = {
23091 name: 'form',
23092 restrict: isNgForm ? 'EAC' : 'E',
23093 require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
23094 controller: FormController,
23095 compile: function ngFormCompile(formElement, attr) {
23096 // Setup initial state of the control
23097 formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
23098
23099 var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
23100
23101 return {
23102 pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
23103 var controller = ctrls[0];
23104
23105 // if `action` attr is not present on the form, prevent the default action (submission)
23106 if (!('action' in attr)) {
23107 // we can't use jq events because if a form is destroyed during submission the default
23108 // action is not prevented. see #1238
23109 //
23110 // IE 9 is not affected because it doesn't fire a submit event and try to do a full
23111 // page reload if the form was destroyed by submission of the form via a click handler
23112 // on a button in the form. Looks like an IE9 specific bug.
23113 var handleFormSubmission = function(event) {
23114 scope.$apply(function() {
23115 controller.$commitViewValue();
23116 controller.$setSubmitted();
23117 });
23118
23119 event.preventDefault();
23120 };
23121
23122 formElement[0].addEventListener('submit', handleFormSubmission);
23123
23124 // unregister the preventDefault listener so that we don't not leak memory but in a
23125 // way that will achieve the prevention of the default action.
23126 formElement.on('$destroy', function() {
23127 $timeout(function() {
23128 formElement[0].removeEventListener('submit', handleFormSubmission);
23129 }, 0, false);
23130 });
23131 }
23132
23133 var parentFormCtrl = ctrls[1] || controller.$$parentForm;
23134 parentFormCtrl.$addControl(controller);
23135
23136 var setter = nameAttr ? getSetter(controller.$name) : noop;
23137
23138 if (nameAttr) {
23139 setter(scope, controller);
23140 attr.$observe(nameAttr, function(newValue) {
23141 if (controller.$name === newValue) return;
23142 setter(scope, undefined);
23143 controller.$$parentForm.$$renameControl(controller, newValue);
23144 setter = getSetter(controller.$name);
23145 setter(scope, controller);
23146 });
23147 }
23148 formElement.on('$destroy', function() {
23149 controller.$$parentForm.$removeControl(controller);
23150 setter(scope, undefined);
23151 extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
23152 });
23153 }
23154 };
23155 }
23156 };
23157
23158 return formDirective;
23159
23160 function getSetter(expression) {
23161 if (expression === '') {
23162 //create an assignable expression, so forms with an empty name can be renamed later
23163 return $parse('this[""]').assign;
23164 }
23165 return $parse(expression).assign || noop;
23166 }
23167 }];
23168};
23169
23170var formDirective = formDirectiveFactory();
23171var ngFormDirective = formDirectiveFactory(true);
23172
23173
23174
23175// helper methods
23176function setupValidity(instance) {
23177 instance.$$classCache = {};
23178 instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
23179}
23180function addSetValidityMethod(context) {
23181 var clazz = context.clazz,
23182 set = context.set,
23183 unset = context.unset;
23184
23185 clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
23186 if (isUndefined(state)) {
23187 createAndSet(this, '$pending', validationErrorKey, controller);
23188 } else {
23189 unsetAndCleanup(this, '$pending', validationErrorKey, controller);
23190 }
23191 if (!isBoolean(state)) {
23192 unset(this.$error, validationErrorKey, controller);
23193 unset(this.$$success, validationErrorKey, controller);
23194 } else {
23195 if (state) {
23196 unset(this.$error, validationErrorKey, controller);
23197 set(this.$$success, validationErrorKey, controller);
23198 } else {
23199 set(this.$error, validationErrorKey, controller);
23200 unset(this.$$success, validationErrorKey, controller);
23201 }
23202 }
23203 if (this.$pending) {
23204 cachedToggleClass(this, PENDING_CLASS, true);
23205 this.$valid = this.$invalid = undefined;
23206 toggleValidationCss(this, '', null);
23207 } else {
23208 cachedToggleClass(this, PENDING_CLASS, false);
23209 this.$valid = isObjectEmpty(this.$error);
23210 this.$invalid = !this.$valid;
23211 toggleValidationCss(this, '', this.$valid);
23212 }
23213
23214 // re-read the state as the set/unset methods could have
23215 // combined state in this.$error[validationError] (used for forms),
23216 // where setting/unsetting only increments/decrements the value,
23217 // and does not replace it.
23218 var combinedState;
23219 if (this.$pending && this.$pending[validationErrorKey]) {
23220 combinedState = undefined;
23221 } else if (this.$error[validationErrorKey]) {
23222 combinedState = false;
23223 } else if (this.$$success[validationErrorKey]) {
23224 combinedState = true;
23225 } else {
23226 combinedState = null;
23227 }
23228
23229 toggleValidationCss(this, validationErrorKey, combinedState);
23230 this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
23231 };
23232
23233 function createAndSet(ctrl, name, value, controller) {
23234 if (!ctrl[name]) {
23235 ctrl[name] = {};
23236 }
23237 set(ctrl[name], value, controller);
23238 }
23239
23240 function unsetAndCleanup(ctrl, name, value, controller) {
23241 if (ctrl[name]) {
23242 unset(ctrl[name], value, controller);
23243 }
23244 if (isObjectEmpty(ctrl[name])) {
23245 ctrl[name] = undefined;
23246 }
23247 }
23248
23249 function cachedToggleClass(ctrl, className, switchValue) {
23250 if (switchValue && !ctrl.$$classCache[className]) {
23251 ctrl.$$animate.addClass(ctrl.$$element, className);
23252 ctrl.$$classCache[className] = true;
23253 } else if (!switchValue && ctrl.$$classCache[className]) {
23254 ctrl.$$animate.removeClass(ctrl.$$element, className);
23255 ctrl.$$classCache[className] = false;
23256 }
23257 }
23258
23259 function toggleValidationCss(ctrl, validationErrorKey, isValid) {
23260 validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
23261
23262 cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
23263 cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
23264 }
23265}
23266
23267function isObjectEmpty(obj) {
23268 if (obj) {
23269 for (var prop in obj) {
23270 if (obj.hasOwnProperty(prop)) {
23271 return false;
23272 }
23273 }
23274 }
23275 return true;
23276}
23277
23278/* global
23279 VALID_CLASS: false,
23280 INVALID_CLASS: false,
23281 PRISTINE_CLASS: false,
23282 DIRTY_CLASS: false,
23283 ngModelMinErr: false
23284*/
23285
23286// Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
23287var 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)$/;
23288// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
23289// Note: We are being more lenient, because browsers are too.
23290// 1. Scheme
23291// 2. Slashes
23292// 3. Username
23293// 4. Password
23294// 5. Hostname
23295// 6. Port
23296// 7. Path
23297// 8. Query
23298// 9. Fragment
23299// 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
23300var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
23301// eslint-disable-next-line max-len
23302var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
23303var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
23304var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
23305var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
23306var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
23307var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
23308var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
23309
23310var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
23311var PARTIAL_VALIDATION_TYPES = createMap();
23312forEach('date,datetime-local,month,time,week'.split(','), function(type) {
23313 PARTIAL_VALIDATION_TYPES[type] = true;
23314});
23315
23316var inputType = {
23317
23318 /**
23319 * @ngdoc input
23320 * @name input[text]
23321 *
23322 * @description
23323 * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
23324 *
23325 *
23326 * @param {string} ngModel Assignable angular expression to data-bind to.
23327 * @param {string=} name Property name of the form under which the control is published.
23328 * @param {string=} required Adds `required` validation error key if the value is not entered.
23329 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23330 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23331 * `required` when you want to data-bind to the `required` attribute.
23332 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
23333 * minlength.
23334 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
23335 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
23336 * any length.
23337 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
23338 * that contains the regular expression body that will be converted to a regular expression
23339 * as in the ngPattern directive.
23340 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
23341 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
23342 * If the expression evaluates to a RegExp object, then this is used directly.
23343 * If the expression evaluates to a string, then it will be converted to a RegExp
23344 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
23345 * `new RegExp('^abc$')`.<br />
23346 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
23347 * start at the index of the last search's match, thus not taking the whole input value into
23348 * account.
23349 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23350 * interaction with the input element.
23351 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
23352 * This parameter is ignored for input[type=password] controls, which will never trim the
23353 * input.
23354 *
23355 * @example
23356 <example name="text-input-directive" module="textInputExample">
23357 <file name="index.html">
23358 <script>
23359 angular.module('textInputExample', [])
23360 .controller('ExampleController', ['$scope', function($scope) {
23361 $scope.example = {
23362 text: 'guest',
23363 word: /^\s*\w*\s*$/
23364 };
23365 }]);
23366 </script>
23367 <form name="myForm" ng-controller="ExampleController">
23368 <label>Single word:
23369 <input type="text" name="input" ng-model="example.text"
23370 ng-pattern="example.word" required ng-trim="false">
23371 </label>
23372 <div role="alert">
23373 <span class="error" ng-show="myForm.input.$error.required">
23374 Required!</span>
23375 <span class="error" ng-show="myForm.input.$error.pattern">
23376 Single word only!</span>
23377 </div>
23378 <code>text = {{example.text}}</code><br/>
23379 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
23380 <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
23381 <code>myForm.$valid = {{myForm.$valid}}</code><br/>
23382 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
23383 </form>
23384 </file>
23385 <file name="protractor.js" type="protractor">
23386 var text = element(by.binding('example.text'));
23387 var valid = element(by.binding('myForm.input.$valid'));
23388 var input = element(by.model('example.text'));
23389
23390 it('should initialize to model', function() {
23391 expect(text.getText()).toContain('guest');
23392 expect(valid.getText()).toContain('true');
23393 });
23394
23395 it('should be invalid if empty', function() {
23396 input.clear();
23397 input.sendKeys('');
23398
23399 expect(text.getText()).toEqual('text =');
23400 expect(valid.getText()).toContain('false');
23401 });
23402
23403 it('should be invalid if multi word', function() {
23404 input.clear();
23405 input.sendKeys('hello world');
23406
23407 expect(valid.getText()).toContain('false');
23408 });
23409 </file>
23410 </example>
23411 */
23412 'text': textInputType,
23413
23414 /**
23415 * @ngdoc input
23416 * @name input[date]
23417 *
23418 * @description
23419 * Input with date validation and transformation. In browsers that do not yet support
23420 * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
23421 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
23422 * modern browsers do not yet support this input type, it is important to provide cues to users on the
23423 * expected input format via a placeholder or label.
23424 *
23425 * The model must always be a Date object, otherwise Angular will throw an error.
23426 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
23427 *
23428 * The timezone to be used to read/write the `Date` instance in the model can be defined using
23429 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
23430 *
23431 * @param {string} ngModel Assignable angular expression to data-bind to.
23432 * @param {string=} name Property name of the form under which the control is published.
23433 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
23434 * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
23435 * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
23436 * constraint validation.
23437 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
23438 * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
23439 * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
23440 * constraint validation.
23441 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
23442 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
23443 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
23444 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
23445 * @param {string=} required Sets `required` validation error key if the value is not entered.
23446 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23447 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23448 * `required` when you want to data-bind to the `required` attribute.
23449 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23450 * interaction with the input element.
23451 *
23452 * @example
23453 <example name="date-input-directive" module="dateInputExample">
23454 <file name="index.html">
23455 <script>
23456 angular.module('dateInputExample', [])
23457 .controller('DateController', ['$scope', function($scope) {
23458 $scope.example = {
23459 value: new Date(2013, 9, 22)
23460 };
23461 }]);
23462 </script>
23463 <form name="myForm" ng-controller="DateController as dateCtrl">
23464 <label for="exampleInput">Pick a date in 2013:</label>
23465 <input type="date" id="exampleInput" name="input" ng-model="example.value"
23466 placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
23467 <div role="alert">
23468 <span class="error" ng-show="myForm.input.$error.required">
23469 Required!</span>
23470 <span class="error" ng-show="myForm.input.$error.date">
23471 Not a valid date!</span>
23472 </div>
23473 <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
23474 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
23475 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
23476 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
23477 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
23478 </form>
23479 </file>
23480 <file name="protractor.js" type="protractor">
23481 var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
23482 var valid = element(by.binding('myForm.input.$valid'));
23483
23484 // currently protractor/webdriver does not support
23485 // sending keys to all known HTML5 input controls
23486 // for various browsers (see https://github.com/angular/protractor/issues/562).
23487 function setInput(val) {
23488 // set the value of the element and force validation.
23489 var scr = "var ipt = document.getElementById('exampleInput'); " +
23490 "ipt.value = '" + val + "';" +
23491 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
23492 browser.executeScript(scr);
23493 }
23494
23495 it('should initialize to model', function() {
23496 expect(value.getText()).toContain('2013-10-22');
23497 expect(valid.getText()).toContain('myForm.input.$valid = true');
23498 });
23499
23500 it('should be invalid if empty', function() {
23501 setInput('');
23502 expect(value.getText()).toEqual('value =');
23503 expect(valid.getText()).toContain('myForm.input.$valid = false');
23504 });
23505
23506 it('should be invalid if over max', function() {
23507 setInput('2015-01-01');
23508 expect(value.getText()).toContain('');
23509 expect(valid.getText()).toContain('myForm.input.$valid = false');
23510 });
23511 </file>
23512 </example>
23513 */
23514 'date': createDateInputType('date', DATE_REGEXP,
23515 createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
23516 'yyyy-MM-dd'),
23517
23518 /**
23519 * @ngdoc input
23520 * @name input[datetime-local]
23521 *
23522 * @description
23523 * Input with datetime validation and transformation. In browsers that do not yet support
23524 * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
23525 * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
23526 *
23527 * The model must always be a Date object, otherwise Angular will throw an error.
23528 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
23529 *
23530 * The timezone to be used to read/write the `Date` instance in the model can be defined using
23531 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
23532 *
23533 * @param {string} ngModel Assignable angular expression to data-bind to.
23534 * @param {string=} name Property name of the form under which the control is published.
23535 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
23536 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
23537 * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
23538 * Note that `min` will also add native HTML5 constraint validation.
23539 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
23540 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
23541 * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
23542 * Note that `max` will also add native HTML5 constraint validation.
23543 * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
23544 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
23545 * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
23546 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
23547 * @param {string=} required Sets `required` validation error key if the value is not entered.
23548 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23549 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23550 * `required` when you want to data-bind to the `required` attribute.
23551 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23552 * interaction with the input element.
23553 *
23554 * @example
23555 <example name="datetimelocal-input-directive" module="dateExample">
23556 <file name="index.html">
23557 <script>
23558 angular.module('dateExample', [])
23559 .controller('DateController', ['$scope', function($scope) {
23560 $scope.example = {
23561 value: new Date(2010, 11, 28, 14, 57)
23562 };
23563 }]);
23564 </script>
23565 <form name="myForm" ng-controller="DateController as dateCtrl">
23566 <label for="exampleInput">Pick a date between in 2013:</label>
23567 <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
23568 placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
23569 <div role="alert">
23570 <span class="error" ng-show="myForm.input.$error.required">
23571 Required!</span>
23572 <span class="error" ng-show="myForm.input.$error.datetimelocal">
23573 Not a valid date!</span>
23574 </div>
23575 <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
23576 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
23577 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
23578 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
23579 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
23580 </form>
23581 </file>
23582 <file name="protractor.js" type="protractor">
23583 var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
23584 var valid = element(by.binding('myForm.input.$valid'));
23585
23586 // currently protractor/webdriver does not support
23587 // sending keys to all known HTML5 input controls
23588 // for various browsers (https://github.com/angular/protractor/issues/562).
23589 function setInput(val) {
23590 // set the value of the element and force validation.
23591 var scr = "var ipt = document.getElementById('exampleInput'); " +
23592 "ipt.value = '" + val + "';" +
23593 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
23594 browser.executeScript(scr);
23595 }
23596
23597 it('should initialize to model', function() {
23598 expect(value.getText()).toContain('2010-12-28T14:57:00');
23599 expect(valid.getText()).toContain('myForm.input.$valid = true');
23600 });
23601
23602 it('should be invalid if empty', function() {
23603 setInput('');
23604 expect(value.getText()).toEqual('value =');
23605 expect(valid.getText()).toContain('myForm.input.$valid = false');
23606 });
23607
23608 it('should be invalid if over max', function() {
23609 setInput('2015-01-01T23:59:00');
23610 expect(value.getText()).toContain('');
23611 expect(valid.getText()).toContain('myForm.input.$valid = false');
23612 });
23613 </file>
23614 </example>
23615 */
23616 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
23617 createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
23618 'yyyy-MM-ddTHH:mm:ss.sss'),
23619
23620 /**
23621 * @ngdoc input
23622 * @name input[time]
23623 *
23624 * @description
23625 * Input with time validation and transformation. In browsers that do not yet support
23626 * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
23627 * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
23628 * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
23629 *
23630 * The model must always be a Date object, otherwise Angular will throw an error.
23631 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
23632 *
23633 * The timezone to be used to read/write the `Date` instance in the model can be defined using
23634 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
23635 *
23636 * @param {string} ngModel Assignable angular expression to data-bind to.
23637 * @param {string=} name Property name of the form under which the control is published.
23638 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
23639 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
23640 * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
23641 * native HTML5 constraint validation.
23642 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
23643 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
23644 * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
23645 * native HTML5 constraint validation.
23646 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
23647 * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
23648 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
23649 * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
23650 * @param {string=} required Sets `required` validation error key if the value is not entered.
23651 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23652 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23653 * `required` when you want to data-bind to the `required` attribute.
23654 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23655 * interaction with the input element.
23656 *
23657 * @example
23658 <example name="time-input-directive" module="timeExample">
23659 <file name="index.html">
23660 <script>
23661 angular.module('timeExample', [])
23662 .controller('DateController', ['$scope', function($scope) {
23663 $scope.example = {
23664 value: new Date(1970, 0, 1, 14, 57, 0)
23665 };
23666 }]);
23667 </script>
23668 <form name="myForm" ng-controller="DateController as dateCtrl">
23669 <label for="exampleInput">Pick a time between 8am and 5pm:</label>
23670 <input type="time" id="exampleInput" name="input" ng-model="example.value"
23671 placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
23672 <div role="alert">
23673 <span class="error" ng-show="myForm.input.$error.required">
23674 Required!</span>
23675 <span class="error" ng-show="myForm.input.$error.time">
23676 Not a valid date!</span>
23677 </div>
23678 <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
23679 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
23680 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
23681 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
23682 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
23683 </form>
23684 </file>
23685 <file name="protractor.js" type="protractor">
23686 var value = element(by.binding('example.value | date: "HH:mm:ss"'));
23687 var valid = element(by.binding('myForm.input.$valid'));
23688
23689 // currently protractor/webdriver does not support
23690 // sending keys to all known HTML5 input controls
23691 // for various browsers (https://github.com/angular/protractor/issues/562).
23692 function setInput(val) {
23693 // set the value of the element and force validation.
23694 var scr = "var ipt = document.getElementById('exampleInput'); " +
23695 "ipt.value = '" + val + "';" +
23696 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
23697 browser.executeScript(scr);
23698 }
23699
23700 it('should initialize to model', function() {
23701 expect(value.getText()).toContain('14:57:00');
23702 expect(valid.getText()).toContain('myForm.input.$valid = true');
23703 });
23704
23705 it('should be invalid if empty', function() {
23706 setInput('');
23707 expect(value.getText()).toEqual('value =');
23708 expect(valid.getText()).toContain('myForm.input.$valid = false');
23709 });
23710
23711 it('should be invalid if over max', function() {
23712 setInput('23:59:00');
23713 expect(value.getText()).toContain('');
23714 expect(valid.getText()).toContain('myForm.input.$valid = false');
23715 });
23716 </file>
23717 </example>
23718 */
23719 'time': createDateInputType('time', TIME_REGEXP,
23720 createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
23721 'HH:mm:ss.sss'),
23722
23723 /**
23724 * @ngdoc input
23725 * @name input[week]
23726 *
23727 * @description
23728 * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
23729 * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
23730 * week format (yyyy-W##), for example: `2013-W02`.
23731 *
23732 * The model must always be a Date object, otherwise Angular will throw an error.
23733 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
23734 *
23735 * The timezone to be used to read/write the `Date` instance in the model can be defined using
23736 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
23737 *
23738 * @param {string} ngModel Assignable angular expression to data-bind to.
23739 * @param {string=} name Property name of the form under which the control is published.
23740 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
23741 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
23742 * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
23743 * native HTML5 constraint validation.
23744 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
23745 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
23746 * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
23747 * native HTML5 constraint validation.
23748 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
23749 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
23750 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
23751 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
23752 * @param {string=} required Sets `required` validation error key if the value is not entered.
23753 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23754 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23755 * `required` when you want to data-bind to the `required` attribute.
23756 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23757 * interaction with the input element.
23758 *
23759 * @example
23760 <example name="week-input-directive" module="weekExample">
23761 <file name="index.html">
23762 <script>
23763 angular.module('weekExample', [])
23764 .controller('DateController', ['$scope', function($scope) {
23765 $scope.example = {
23766 value: new Date(2013, 0, 3)
23767 };
23768 }]);
23769 </script>
23770 <form name="myForm" ng-controller="DateController as dateCtrl">
23771 <label>Pick a date between in 2013:
23772 <input id="exampleInput" type="week" name="input" ng-model="example.value"
23773 placeholder="YYYY-W##" min="2012-W32"
23774 max="2013-W52" required />
23775 </label>
23776 <div role="alert">
23777 <span class="error" ng-show="myForm.input.$error.required">
23778 Required!</span>
23779 <span class="error" ng-show="myForm.input.$error.week">
23780 Not a valid date!</span>
23781 </div>
23782 <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
23783 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
23784 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
23785 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
23786 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
23787 </form>
23788 </file>
23789 <file name="protractor.js" type="protractor">
23790 var value = element(by.binding('example.value | date: "yyyy-Www"'));
23791 var valid = element(by.binding('myForm.input.$valid'));
23792
23793 // currently protractor/webdriver does not support
23794 // sending keys to all known HTML5 input controls
23795 // for various browsers (https://github.com/angular/protractor/issues/562).
23796 function setInput(val) {
23797 // set the value of the element and force validation.
23798 var scr = "var ipt = document.getElementById('exampleInput'); " +
23799 "ipt.value = '" + val + "';" +
23800 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
23801 browser.executeScript(scr);
23802 }
23803
23804 it('should initialize to model', function() {
23805 expect(value.getText()).toContain('2013-W01');
23806 expect(valid.getText()).toContain('myForm.input.$valid = true');
23807 });
23808
23809 it('should be invalid if empty', function() {
23810 setInput('');
23811 expect(value.getText()).toEqual('value =');
23812 expect(valid.getText()).toContain('myForm.input.$valid = false');
23813 });
23814
23815 it('should be invalid if over max', function() {
23816 setInput('2015-W01');
23817 expect(value.getText()).toContain('');
23818 expect(valid.getText()).toContain('myForm.input.$valid = false');
23819 });
23820 </file>
23821 </example>
23822 */
23823 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
23824
23825 /**
23826 * @ngdoc input
23827 * @name input[month]
23828 *
23829 * @description
23830 * Input with month validation and transformation. In browsers that do not yet support
23831 * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
23832 * month format (yyyy-MM), for example: `2009-01`.
23833 *
23834 * The model must always be a Date object, otherwise Angular will throw an error.
23835 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
23836 * If the model is not set to the first of the month, the next view to model update will set it
23837 * to the first of the month.
23838 *
23839 * The timezone to be used to read/write the `Date` instance in the model can be defined using
23840 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
23841 *
23842 * @param {string} ngModel Assignable angular expression to data-bind to.
23843 * @param {string=} name Property name of the form under which the control is published.
23844 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
23845 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
23846 * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
23847 * native HTML5 constraint validation.
23848 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
23849 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
23850 * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
23851 * native HTML5 constraint validation.
23852 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
23853 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
23854 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
23855 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
23856
23857 * @param {string=} required Sets `required` validation error key if the value is not entered.
23858 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23859 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23860 * `required` when you want to data-bind to the `required` attribute.
23861 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23862 * interaction with the input element.
23863 *
23864 * @example
23865 <example name="month-input-directive" module="monthExample">
23866 <file name="index.html">
23867 <script>
23868 angular.module('monthExample', [])
23869 .controller('DateController', ['$scope', function($scope) {
23870 $scope.example = {
23871 value: new Date(2013, 9, 1)
23872 };
23873 }]);
23874 </script>
23875 <form name="myForm" ng-controller="DateController as dateCtrl">
23876 <label for="exampleInput">Pick a month in 2013:</label>
23877 <input id="exampleInput" type="month" name="input" ng-model="example.value"
23878 placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
23879 <div role="alert">
23880 <span class="error" ng-show="myForm.input.$error.required">
23881 Required!</span>
23882 <span class="error" ng-show="myForm.input.$error.month">
23883 Not a valid month!</span>
23884 </div>
23885 <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
23886 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
23887 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
23888 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
23889 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
23890 </form>
23891 </file>
23892 <file name="protractor.js" type="protractor">
23893 var value = element(by.binding('example.value | date: "yyyy-MM"'));
23894 var valid = element(by.binding('myForm.input.$valid'));
23895
23896 // currently protractor/webdriver does not support
23897 // sending keys to all known HTML5 input controls
23898 // for various browsers (https://github.com/angular/protractor/issues/562).
23899 function setInput(val) {
23900 // set the value of the element and force validation.
23901 var scr = "var ipt = document.getElementById('exampleInput'); " +
23902 "ipt.value = '" + val + "';" +
23903 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
23904 browser.executeScript(scr);
23905 }
23906
23907 it('should initialize to model', function() {
23908 expect(value.getText()).toContain('2013-10');
23909 expect(valid.getText()).toContain('myForm.input.$valid = true');
23910 });
23911
23912 it('should be invalid if empty', function() {
23913 setInput('');
23914 expect(value.getText()).toEqual('value =');
23915 expect(valid.getText()).toContain('myForm.input.$valid = false');
23916 });
23917
23918 it('should be invalid if over max', function() {
23919 setInput('2015-01');
23920 expect(value.getText()).toContain('');
23921 expect(valid.getText()).toContain('myForm.input.$valid = false');
23922 });
23923 </file>
23924 </example>
23925 */
23926 'month': createDateInputType('month', MONTH_REGEXP,
23927 createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
23928 'yyyy-MM'),
23929
23930 /**
23931 * @ngdoc input
23932 * @name input[number]
23933 *
23934 * @description
23935 * Text input with number validation and transformation. Sets the `number` validation
23936 * error if not a valid number.
23937 *
23938 * <div class="alert alert-warning">
23939 * The model must always be of type `number` otherwise Angular will throw an error.
23940 * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
23941 * error docs for more information and an example of how to convert your model if necessary.
23942 * </div>
23943 *
23944 * ## Issues with HTML5 constraint validation
23945 *
23946 * In browsers that follow the
23947 * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
23948 * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
23949 * If a non-number is entered in the input, the browser will report the value as an empty string,
23950 * which means the view / model values in `ngModel` and subsequently the scope value
23951 * will also be an empty string.
23952 *
23953 *
23954 * @param {string} ngModel Assignable angular expression to data-bind to.
23955 * @param {string=} name Property name of the form under which the control is published.
23956 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
23957 * Can be interpolated.
23958 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
23959 * Can be interpolated.
23960 * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
23961 * but does not trigger HTML5 native validation. Takes an expression.
23962 * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
23963 * but does not trigger HTML5 native validation. Takes an expression.
23964 * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
23965 * Can be interpolated.
23966 * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
23967 * but does not trigger HTML5 native validation. Takes an expression.
23968 * @param {string=} required Sets `required` validation error key if the value is not entered.
23969 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23970 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23971 * `required` when you want to data-bind to the `required` attribute.
23972 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
23973 * minlength.
23974 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
23975 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
23976 * any length.
23977 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
23978 * that contains the regular expression body that will be converted to a regular expression
23979 * as in the ngPattern directive.
23980 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
23981 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
23982 * If the expression evaluates to a RegExp object, then this is used directly.
23983 * If the expression evaluates to a string, then it will be converted to a RegExp
23984 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
23985 * `new RegExp('^abc$')`.<br />
23986 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
23987 * start at the index of the last search's match, thus not taking the whole input value into
23988 * account.
23989 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23990 * interaction with the input element.
23991 *
23992 * @example
23993 <example name="number-input-directive" module="numberExample">
23994 <file name="index.html">
23995 <script>
23996 angular.module('numberExample', [])
23997 .controller('ExampleController', ['$scope', function($scope) {
23998 $scope.example = {
23999 value: 12
24000 };
24001 }]);
24002 </script>
24003 <form name="myForm" ng-controller="ExampleController">
24004 <label>Number:
24005 <input type="number" name="input" ng-model="example.value"
24006 min="0" max="99" required>
24007 </label>
24008 <div role="alert">
24009 <span class="error" ng-show="myForm.input.$error.required">
24010 Required!</span>
24011 <span class="error" ng-show="myForm.input.$error.number">
24012 Not valid number!</span>
24013 </div>
24014 <tt>value = {{example.value}}</tt><br/>
24015 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
24016 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
24017 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
24018 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
24019 </form>
24020 </file>
24021 <file name="protractor.js" type="protractor">
24022 var value = element(by.binding('example.value'));
24023 var valid = element(by.binding('myForm.input.$valid'));
24024 var input = element(by.model('example.value'));
24025
24026 it('should initialize to model', function() {
24027 expect(value.getText()).toContain('12');
24028 expect(valid.getText()).toContain('true');
24029 });
24030
24031 it('should be invalid if empty', function() {
24032 input.clear();
24033 input.sendKeys('');
24034 expect(value.getText()).toEqual('value =');
24035 expect(valid.getText()).toContain('false');
24036 });
24037
24038 it('should be invalid if over max', function() {
24039 input.clear();
24040 input.sendKeys('123');
24041 expect(value.getText()).toEqual('value =');
24042 expect(valid.getText()).toContain('false');
24043 });
24044 </file>
24045 </example>
24046 */
24047 'number': numberInputType,
24048
24049
24050 /**
24051 * @ngdoc input
24052 * @name input[url]
24053 *
24054 * @description
24055 * Text input with URL validation. Sets the `url` validation error key if the content is not a
24056 * valid URL.
24057 *
24058 * <div class="alert alert-warning">
24059 * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
24060 * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
24061 * the built-in validators (see the {@link guide/forms Forms guide})
24062 * </div>
24063 *
24064 * @param {string} ngModel Assignable angular expression to data-bind to.
24065 * @param {string=} name Property name of the form under which the control is published.
24066 * @param {string=} required Sets `required` validation error key if the value is not entered.
24067 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
24068 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
24069 * `required` when you want to data-bind to the `required` attribute.
24070 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
24071 * minlength.
24072 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
24073 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
24074 * any length.
24075 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
24076 * that contains the regular expression body that will be converted to a regular expression
24077 * as in the ngPattern directive.
24078 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
24079 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
24080 * If the expression evaluates to a RegExp object, then this is used directly.
24081 * If the expression evaluates to a string, then it will be converted to a RegExp
24082 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
24083 * `new RegExp('^abc$')`.<br />
24084 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
24085 * start at the index of the last search's match, thus not taking the whole input value into
24086 * account.
24087 * @param {string=} ngChange Angular expression to be executed when input changes due to user
24088 * interaction with the input element.
24089 *
24090 * @example
24091 <example name="url-input-directive" module="urlExample">
24092 <file name="index.html">
24093 <script>
24094 angular.module('urlExample', [])
24095 .controller('ExampleController', ['$scope', function($scope) {
24096 $scope.url = {
24097 text: 'http://google.com'
24098 };
24099 }]);
24100 </script>
24101 <form name="myForm" ng-controller="ExampleController">
24102 <label>URL:
24103 <input type="url" name="input" ng-model="url.text" required>
24104 <label>
24105 <div role="alert">
24106 <span class="error" ng-show="myForm.input.$error.required">
24107 Required!</span>
24108 <span class="error" ng-show="myForm.input.$error.url">
24109 Not valid url!</span>
24110 </div>
24111 <tt>text = {{url.text}}</tt><br/>
24112 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
24113 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
24114 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
24115 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
24116 <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
24117 </form>
24118 </file>
24119 <file name="protractor.js" type="protractor">
24120 var text = element(by.binding('url.text'));
24121 var valid = element(by.binding('myForm.input.$valid'));
24122 var input = element(by.model('url.text'));
24123
24124 it('should initialize to model', function() {
24125 expect(text.getText()).toContain('http://google.com');
24126 expect(valid.getText()).toContain('true');
24127 });
24128
24129 it('should be invalid if empty', function() {
24130 input.clear();
24131 input.sendKeys('');
24132
24133 expect(text.getText()).toEqual('text =');
24134 expect(valid.getText()).toContain('false');
24135 });
24136
24137 it('should be invalid if not url', function() {
24138 input.clear();
24139 input.sendKeys('box');
24140
24141 expect(valid.getText()).toContain('false');
24142 });
24143 </file>
24144 </example>
24145 */
24146 'url': urlInputType,
24147
24148
24149 /**
24150 * @ngdoc input
24151 * @name input[email]
24152 *
24153 * @description
24154 * Text input with email validation. Sets the `email` validation error key if not a valid email
24155 * address.
24156 *
24157 * <div class="alert alert-warning">
24158 * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
24159 * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
24160 * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
24161 * </div>
24162 *
24163 * @param {string} ngModel Assignable angular expression to data-bind to.
24164 * @param {string=} name Property name of the form under which the control is published.
24165 * @param {string=} required Sets `required` validation error key if the value is not entered.
24166 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
24167 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
24168 * `required` when you want to data-bind to the `required` attribute.
24169 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
24170 * minlength.
24171 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
24172 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
24173 * any length.
24174 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
24175 * that contains the regular expression body that will be converted to a regular expression
24176 * as in the ngPattern directive.
24177 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
24178 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
24179 * If the expression evaluates to a RegExp object, then this is used directly.
24180 * If the expression evaluates to a string, then it will be converted to a RegExp
24181 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
24182 * `new RegExp('^abc$')`.<br />
24183 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
24184 * start at the index of the last search's match, thus not taking the whole input value into
24185 * account.
24186 * @param {string=} ngChange Angular expression to be executed when input changes due to user
24187 * interaction with the input element.
24188 *
24189 * @example
24190 <example name="email-input-directive" module="emailExample">
24191 <file name="index.html">
24192 <script>
24193 angular.module('emailExample', [])
24194 .controller('ExampleController', ['$scope', function($scope) {
24195 $scope.email = {
24196 text: 'me@example.com'
24197 };
24198 }]);
24199 </script>
24200 <form name="myForm" ng-controller="ExampleController">
24201 <label>Email:
24202 <input type="email" name="input" ng-model="email.text" required>
24203 </label>
24204 <div role="alert">
24205 <span class="error" ng-show="myForm.input.$error.required">
24206 Required!</span>
24207 <span class="error" ng-show="myForm.input.$error.email">
24208 Not valid email!</span>
24209 </div>
24210 <tt>text = {{email.text}}</tt><br/>
24211 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
24212 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
24213 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
24214 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
24215 <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
24216 </form>
24217 </file>
24218 <file name="protractor.js" type="protractor">
24219 var text = element(by.binding('email.text'));
24220 var valid = element(by.binding('myForm.input.$valid'));
24221 var input = element(by.model('email.text'));
24222
24223 it('should initialize to model', function() {
24224 expect(text.getText()).toContain('me@example.com');
24225 expect(valid.getText()).toContain('true');
24226 });
24227
24228 it('should be invalid if empty', function() {
24229 input.clear();
24230 input.sendKeys('');
24231 expect(text.getText()).toEqual('text =');
24232 expect(valid.getText()).toContain('false');
24233 });
24234
24235 it('should be invalid if not email', function() {
24236 input.clear();
24237 input.sendKeys('xxx');
24238
24239 expect(valid.getText()).toContain('false');
24240 });
24241 </file>
24242 </example>
24243 */
24244 'email': emailInputType,
24245
24246
24247 /**
24248 * @ngdoc input
24249 * @name input[radio]
24250 *
24251 * @description
24252 * HTML radio button.
24253 *
24254 * @param {string} ngModel Assignable angular expression to data-bind to.
24255 * @param {string} value The value to which the `ngModel` expression should be set when selected.
24256 * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
24257 * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
24258 * @param {string=} name Property name of the form under which the control is published.
24259 * @param {string=} ngChange Angular expression to be executed when input changes due to user
24260 * interaction with the input element.
24261 * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
24262 * is selected. Should be used instead of the `value` attribute if you need
24263 * a non-string `ngModel` (`boolean`, `array`, ...).
24264 *
24265 * @example
24266 <example name="radio-input-directive" module="radioExample">
24267 <file name="index.html">
24268 <script>
24269 angular.module('radioExample', [])
24270 .controller('ExampleController', ['$scope', function($scope) {
24271 $scope.color = {
24272 name: 'blue'
24273 };
24274 $scope.specialValue = {
24275 "id": "12345",
24276 "value": "green"
24277 };
24278 }]);
24279 </script>
24280 <form name="myForm" ng-controller="ExampleController">
24281 <label>
24282 <input type="radio" ng-model="color.name" value="red">
24283 Red
24284 </label><br/>
24285 <label>
24286 <input type="radio" ng-model="color.name" ng-value="specialValue">
24287 Green
24288 </label><br/>
24289 <label>
24290 <input type="radio" ng-model="color.name" value="blue">
24291 Blue
24292 </label><br/>
24293 <tt>color = {{color.name | json}}</tt><br/>
24294 </form>
24295 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
24296 </file>
24297 <file name="protractor.js" type="protractor">
24298 it('should change state', function() {
24299 var inputs = element.all(by.model('color.name'));
24300 var color = element(by.binding('color.name'));
24301
24302 expect(color.getText()).toContain('blue');
24303
24304 inputs.get(0).click();
24305 expect(color.getText()).toContain('red');
24306
24307 inputs.get(1).click();
24308 expect(color.getText()).toContain('green');
24309 });
24310 </file>
24311 </example>
24312 */
24313 'radio': radioInputType,
24314
24315 /**
24316 * @ngdoc input
24317 * @name input[range]
24318 *
24319 * @description
24320 * Native range input with validation and transformation.
24321 *
24322 * The model for the range input must always be a `Number`.
24323 *
24324 * IE9 and other browsers that do not support the `range` type fall back
24325 * to a text input without any default values for `min`, `max` and `step`. Model binding,
24326 * validation and number parsing are nevertheless supported.
24327 *
24328 * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
24329 * in a way that never allows the input to hold an invalid value. That means:
24330 * - any non-numerical value is set to `(max + min) / 2`.
24331 * - any numerical value that is less than the current min val, or greater than the current max val
24332 * is set to the min / max val respectively.
24333 * - additionally, the current `step` is respected, so the nearest value that satisfies a step
24334 * is used.
24335 *
24336 * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
24337 * for more info.
24338 *
24339 * This has the following consequences for Angular:
24340 *
24341 * Since the element value should always reflect the current model value, a range input
24342 * will set the bound ngModel expression to the value that the browser has set for the
24343 * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
24344 * if the application sets `model.value = null`, the browser will set the input to `'50'`.
24345 * Angular will then set the model to `50`, to prevent input and model value being out of sync.
24346 *
24347 * That means the model for range will immediately be set to `50` after `ngModel` has been
24348 * initialized. It also means a range input can never have the required error.
24349 *
24350 * This does not only affect changes to the model value, but also to the values of the `min`,
24351 * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
24352 * the input value, Angular will also update the model value.
24353 *
24354 * Automatic value adjustment also means that a range input element can never have the `required`,
24355 * `min`, or `max` errors.
24356 *
24357 * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
24358 * when the step value changes dynamically - they do not adjust the element value correctly, but
24359 * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
24360 * error on the input, and set the model to `undefined`.
24361 *
24362 * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
24363 * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
24364 * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
24365 *
24366 * @param {string} ngModel Assignable angular expression to data-bind to.
24367 * @param {string=} name Property name of the form under which the control is published.
24368 * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
24369 * than `min`. Can be interpolated.
24370 * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
24371 * Can be interpolated.
24372 * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
24373 * Can be interpolated.
24374 * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
24375 * to user interaction with the input element.
24376 * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
24377 * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
24378 * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
24379 *
24380 * @example
24381 <example name="range-input-directive" module="rangeExample">
24382 <file name="index.html">
24383 <script>
24384 angular.module('rangeExample', [])
24385 .controller('ExampleController', ['$scope', function($scope) {
24386 $scope.value = 75;
24387 $scope.min = 10;
24388 $scope.max = 90;
24389 }]);
24390 </script>
24391 <form name="myForm" ng-controller="ExampleController">
24392
24393 Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
24394 <hr>
24395 Model as number: <input type="number" ng-model="value"><br>
24396 Min: <input type="number" ng-model="min"><br>
24397 Max: <input type="number" ng-model="max"><br>
24398 value = <code>{{value}}</code><br/>
24399 myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
24400 myForm.range.$error = <code>{{myForm.range.$error}}</code>
24401 </form>
24402 </file>
24403 </example>
24404
24405 * ## Range Input with ngMin & ngMax attributes
24406
24407 * @example
24408 <example name="range-input-directive-ng" module="rangeExample">
24409 <file name="index.html">
24410 <script>
24411 angular.module('rangeExample', [])
24412 .controller('ExampleController', ['$scope', function($scope) {
24413 $scope.value = 75;
24414 $scope.min = 10;
24415 $scope.max = 90;
24416 }]);
24417 </script>
24418 <form name="myForm" ng-controller="ExampleController">
24419 Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
24420 <hr>
24421 Model as number: <input type="number" ng-model="value"><br>
24422 Min: <input type="number" ng-model="min"><br>
24423 Max: <input type="number" ng-model="max"><br>
24424 value = <code>{{value}}</code><br/>
24425 myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
24426 myForm.range.$error = <code>{{myForm.range.$error}}</code>
24427 </form>
24428 </file>
24429 </example>
24430
24431 */
24432 'range': rangeInputType,
24433
24434 /**
24435 * @ngdoc input
24436 * @name input[checkbox]
24437 *
24438 * @description
24439 * HTML checkbox.
24440 *
24441 * @param {string} ngModel Assignable angular expression to data-bind to.
24442 * @param {string=} name Property name of the form under which the control is published.
24443 * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
24444 * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
24445 * @param {string=} ngChange Angular expression to be executed when input changes due to user
24446 * interaction with the input element.
24447 *
24448 * @example
24449 <example name="checkbox-input-directive" module="checkboxExample">
24450 <file name="index.html">
24451 <script>
24452 angular.module('checkboxExample', [])
24453 .controller('ExampleController', ['$scope', function($scope) {
24454 $scope.checkboxModel = {
24455 value1 : true,
24456 value2 : 'YES'
24457 };
24458 }]);
24459 </script>
24460 <form name="myForm" ng-controller="ExampleController">
24461 <label>Value1:
24462 <input type="checkbox" ng-model="checkboxModel.value1">
24463 </label><br/>
24464 <label>Value2:
24465 <input type="checkbox" ng-model="checkboxModel.value2"
24466 ng-true-value="'YES'" ng-false-value="'NO'">
24467 </label><br/>
24468 <tt>value1 = {{checkboxModel.value1}}</tt><br/>
24469 <tt>value2 = {{checkboxModel.value2}}</tt><br/>
24470 </form>
24471 </file>
24472 <file name="protractor.js" type="protractor">
24473 it('should change state', function() {
24474 var value1 = element(by.binding('checkboxModel.value1'));
24475 var value2 = element(by.binding('checkboxModel.value2'));
24476
24477 expect(value1.getText()).toContain('true');
24478 expect(value2.getText()).toContain('YES');
24479
24480 element(by.model('checkboxModel.value1')).click();
24481 element(by.model('checkboxModel.value2')).click();
24482
24483 expect(value1.getText()).toContain('false');
24484 expect(value2.getText()).toContain('NO');
24485 });
24486 </file>
24487 </example>
24488 */
24489 'checkbox': checkboxInputType,
24490
24491 'hidden': noop,
24492 'button': noop,
24493 'submit': noop,
24494 'reset': noop,
24495 'file': noop
24496};
24497
24498function stringBasedInputType(ctrl) {
24499 ctrl.$formatters.push(function(value) {
24500 return ctrl.$isEmpty(value) ? value : value.toString();
24501 });
24502}
24503
24504function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
24505 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
24506 stringBasedInputType(ctrl);
24507}
24508
24509function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
24510 var type = lowercase(element[0].type);
24511
24512 // In composition mode, users are still inputting intermediate text buffer,
24513 // hold the listener until composition is done.
24514 // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
24515 if (!$sniffer.android) {
24516 var composing = false;
24517
24518 element.on('compositionstart', function() {
24519 composing = true;
24520 });
24521
24522 element.on('compositionend', function() {
24523 composing = false;
24524 listener();
24525 });
24526 }
24527
24528 var timeout;
24529
24530 var listener = function(ev) {
24531 if (timeout) {
24532 $browser.defer.cancel(timeout);
24533 timeout = null;
24534 }
24535 if (composing) return;
24536 var value = element.val(),
24537 event = ev && ev.type;
24538
24539 // By default we will trim the value
24540 // If the attribute ng-trim exists we will avoid trimming
24541 // If input type is 'password', the value is never trimmed
24542 if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
24543 value = trim(value);
24544 }
24545
24546 // If a control is suffering from bad input (due to native validators), browsers discard its
24547 // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
24548 // control's value is the same empty value twice in a row.
24549 if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
24550 ctrl.$setViewValue(value, event);
24551 }
24552 };
24553
24554 // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
24555 // input event on backspace, delete or cut
24556 if ($sniffer.hasEvent('input')) {
24557 element.on('input', listener);
24558 } else {
24559 var deferListener = function(ev, input, origValue) {
24560 if (!timeout) {
24561 timeout = $browser.defer(function() {
24562 timeout = null;
24563 if (!input || input.value !== origValue) {
24564 listener(ev);
24565 }
24566 });
24567 }
24568 };
24569
24570 element.on('keydown', /** @this */ function(event) {
24571 var key = event.keyCode;
24572
24573 // ignore
24574 // command modifiers arrows
24575 if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
24576
24577 deferListener(event, this, this.value);
24578 });
24579
24580 // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
24581 if ($sniffer.hasEvent('paste')) {
24582 element.on('paste cut', deferListener);
24583 }
24584 }
24585
24586 // if user paste into input using mouse on older browser
24587 // or form autocomplete on newer browser, we need "change" event to catch it
24588 element.on('change', listener);
24589
24590 // Some native input types (date-family) have the ability to change validity without
24591 // firing any input/change events.
24592 // For these event types, when native validators are present and the browser supports the type,
24593 // check for validity changes on various DOM events.
24594 if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
24595 element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
24596 if (!timeout) {
24597 var validity = this[VALIDITY_STATE_PROPERTY];
24598 var origBadInput = validity.badInput;
24599 var origTypeMismatch = validity.typeMismatch;
24600 timeout = $browser.defer(function() {
24601 timeout = null;
24602 if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
24603 listener(ev);
24604 }
24605 });
24606 }
24607 });
24608 }
24609
24610 ctrl.$render = function() {
24611 // Workaround for Firefox validation #12102.
24612 var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
24613 if (element.val() !== value) {
24614 element.val(value);
24615 }
24616 };
24617}
24618
24619function weekParser(isoWeek, existingDate) {
24620 if (isDate(isoWeek)) {
24621 return isoWeek;
24622 }
24623
24624 if (isString(isoWeek)) {
24625 WEEK_REGEXP.lastIndex = 0;
24626 var parts = WEEK_REGEXP.exec(isoWeek);
24627 if (parts) {
24628 var year = +parts[1],
24629 week = +parts[2],
24630 hours = 0,
24631 minutes = 0,
24632 seconds = 0,
24633 milliseconds = 0,
24634 firstThurs = getFirstThursdayOfYear(year),
24635 addDays = (week - 1) * 7;
24636
24637 if (existingDate) {
24638 hours = existingDate.getHours();
24639 minutes = existingDate.getMinutes();
24640 seconds = existingDate.getSeconds();
24641 milliseconds = existingDate.getMilliseconds();
24642 }
24643
24644 return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
24645 }
24646 }
24647
24648 return NaN;
24649}
24650
24651function createDateParser(regexp, mapping) {
24652 return function(iso, date) {
24653 var parts, map;
24654
24655 if (isDate(iso)) {
24656 return iso;
24657 }
24658
24659 if (isString(iso)) {
24660 // When a date is JSON'ified to wraps itself inside of an extra
24661 // set of double quotes. This makes the date parsing code unable
24662 // to match the date string and parse it as a date.
24663 if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
24664 iso = iso.substring(1, iso.length - 1);
24665 }
24666 if (ISO_DATE_REGEXP.test(iso)) {
24667 return new Date(iso);
24668 }
24669 regexp.lastIndex = 0;
24670 parts = regexp.exec(iso);
24671
24672 if (parts) {
24673 parts.shift();
24674 if (date) {
24675 map = {
24676 yyyy: date.getFullYear(),
24677 MM: date.getMonth() + 1,
24678 dd: date.getDate(),
24679 HH: date.getHours(),
24680 mm: date.getMinutes(),
24681 ss: date.getSeconds(),
24682 sss: date.getMilliseconds() / 1000
24683 };
24684 } else {
24685 map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
24686 }
24687
24688 forEach(parts, function(part, index) {
24689 if (index < mapping.length) {
24690 map[mapping[index]] = +part;
24691 }
24692 });
24693 return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
24694 }
24695 }
24696
24697 return NaN;
24698 };
24699}
24700
24701function createDateInputType(type, regexp, parseDate, format) {
24702 return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
24703 badInputChecker(scope, element, attr, ctrl);
24704 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
24705 var timezone = ctrl && ctrl.$options.getOption('timezone');
24706 var previousDate;
24707
24708 ctrl.$$parserName = type;
24709 ctrl.$parsers.push(function(value) {
24710 if (ctrl.$isEmpty(value)) return null;
24711 if (regexp.test(value)) {
24712 // Note: We cannot read ctrl.$modelValue, as there might be a different
24713 // parser/formatter in the processing chain so that the model
24714 // contains some different data format!
24715 var parsedDate = parseDate(value, previousDate);
24716 if (timezone) {
24717 parsedDate = convertTimezoneToLocal(parsedDate, timezone);
24718 }
24719 return parsedDate;
24720 }
24721 return undefined;
24722 });
24723
24724 ctrl.$formatters.push(function(value) {
24725 if (value && !isDate(value)) {
24726 throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
24727 }
24728 if (isValidDate(value)) {
24729 previousDate = value;
24730 if (previousDate && timezone) {
24731 previousDate = convertTimezoneToLocal(previousDate, timezone, true);
24732 }
24733 return $filter('date')(value, format, timezone);
24734 } else {
24735 previousDate = null;
24736 return '';
24737 }
24738 });
24739
24740 if (isDefined(attr.min) || attr.ngMin) {
24741 var minVal;
24742 ctrl.$validators.min = function(value) {
24743 return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
24744 };
24745 attr.$observe('min', function(val) {
24746 minVal = parseObservedDateValue(val);
24747 ctrl.$validate();
24748 });
24749 }
24750
24751 if (isDefined(attr.max) || attr.ngMax) {
24752 var maxVal;
24753 ctrl.$validators.max = function(value) {
24754 return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
24755 };
24756 attr.$observe('max', function(val) {
24757 maxVal = parseObservedDateValue(val);
24758 ctrl.$validate();
24759 });
24760 }
24761
24762 function isValidDate(value) {
24763 // Invalid Date: getTime() returns NaN
24764 return value && !(value.getTime && value.getTime() !== value.getTime());
24765 }
24766
24767 function parseObservedDateValue(val) {
24768 return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
24769 }
24770 };
24771}
24772
24773function badInputChecker(scope, element, attr, ctrl) {
24774 var node = element[0];
24775 var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
24776 if (nativeValidation) {
24777 ctrl.$parsers.push(function(value) {
24778 var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
24779 return validity.badInput || validity.typeMismatch ? undefined : value;
24780 });
24781 }
24782}
24783
24784function numberFormatterParser(ctrl) {
24785 ctrl.$$parserName = 'number';
24786 ctrl.$parsers.push(function(value) {
24787 if (ctrl.$isEmpty(value)) return null;
24788 if (NUMBER_REGEXP.test(value)) return parseFloat(value);
24789 return undefined;
24790 });
24791
24792 ctrl.$formatters.push(function(value) {
24793 if (!ctrl.$isEmpty(value)) {
24794 if (!isNumber(value)) {
24795 throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
24796 }
24797 value = value.toString();
24798 }
24799 return value;
24800 });
24801}
24802
24803function parseNumberAttrVal(val) {
24804 if (isDefined(val) && !isNumber(val)) {
24805 val = parseFloat(val);
24806 }
24807 return !isNumberNaN(val) ? val : undefined;
24808}
24809
24810function isNumberInteger(num) {
24811 // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
24812 // (minus the assumption that `num` is a number)
24813
24814 // eslint-disable-next-line no-bitwise
24815 return (num | 0) === num;
24816}
24817
24818function countDecimals(num) {
24819 var numString = num.toString();
24820 var decimalSymbolIndex = numString.indexOf('.');
24821
24822 if (decimalSymbolIndex === -1) {
24823 if (-1 < num && num < 1) {
24824 // It may be in the exponential notation format (`1e-X`)
24825 var match = /e-(\d+)$/.exec(numString);
24826
24827 if (match) {
24828 return Number(match[1]);
24829 }
24830 }
24831
24832 return 0;
24833 }
24834
24835 return numString.length - decimalSymbolIndex - 1;
24836}
24837
24838function isValidForStep(viewValue, stepBase, step) {
24839 // At this point `stepBase` and `step` are expected to be non-NaN values
24840 // and `viewValue` is expected to be a valid stringified number.
24841 var value = Number(viewValue);
24842
24843 // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
24844 // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
24845 if (!isNumberInteger(value) || !isNumberInteger(stepBase) || !isNumberInteger(step)) {
24846 var decimalCount = Math.max(countDecimals(value), countDecimals(stepBase), countDecimals(step));
24847 var multiplier = Math.pow(10, decimalCount);
24848
24849 value = value * multiplier;
24850 stepBase = stepBase * multiplier;
24851 step = step * multiplier;
24852 }
24853
24854 return (value - stepBase) % step === 0;
24855}
24856
24857function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
24858 badInputChecker(scope, element, attr, ctrl);
24859 numberFormatterParser(ctrl);
24860 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
24861
24862 var minVal;
24863 var maxVal;
24864
24865 if (isDefined(attr.min) || attr.ngMin) {
24866 ctrl.$validators.min = function(value) {
24867 return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
24868 };
24869
24870 attr.$observe('min', function(val) {
24871 minVal = parseNumberAttrVal(val);
24872 // TODO(matsko): implement validateLater to reduce number of validations
24873 ctrl.$validate();
24874 });
24875 }
24876
24877 if (isDefined(attr.max) || attr.ngMax) {
24878 ctrl.$validators.max = function(value) {
24879 return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
24880 };
24881
24882 attr.$observe('max', function(val) {
24883 maxVal = parseNumberAttrVal(val);
24884 // TODO(matsko): implement validateLater to reduce number of validations
24885 ctrl.$validate();
24886 });
24887 }
24888
24889 if (isDefined(attr.step) || attr.ngStep) {
24890 var stepVal;
24891 ctrl.$validators.step = function(modelValue, viewValue) {
24892 return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
24893 isValidForStep(viewValue, minVal || 0, stepVal);
24894 };
24895
24896 attr.$observe('step', function(val) {
24897 stepVal = parseNumberAttrVal(val);
24898 // TODO(matsko): implement validateLater to reduce number of validations
24899 ctrl.$validate();
24900 });
24901 }
24902}
24903
24904function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
24905 badInputChecker(scope, element, attr, ctrl);
24906 numberFormatterParser(ctrl);
24907 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
24908
24909 var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
24910 minVal = supportsRange ? 0 : undefined,
24911 maxVal = supportsRange ? 100 : undefined,
24912 stepVal = supportsRange ? 1 : undefined,
24913 validity = element[0].validity,
24914 hasMinAttr = isDefined(attr.min),
24915 hasMaxAttr = isDefined(attr.max),
24916 hasStepAttr = isDefined(attr.step);
24917
24918 var originalRender = ctrl.$render;
24919
24920 ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
24921 //Browsers that implement range will set these values automatically, but reading the adjusted values after
24922 //$render would cause the min / max validators to be applied with the wrong value
24923 function rangeRender() {
24924 originalRender();
24925 ctrl.$setViewValue(element.val());
24926 } :
24927 originalRender;
24928
24929 if (hasMinAttr) {
24930 ctrl.$validators.min = supportsRange ?
24931 // Since all browsers set the input to a valid value, we don't need to check validity
24932 function noopMinValidator() { return true; } :
24933 // non-support browsers validate the min val
24934 function minValidator(modelValue, viewValue) {
24935 return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
24936 };
24937
24938 setInitialValueAndObserver('min', minChange);
24939 }
24940
24941 if (hasMaxAttr) {
24942 ctrl.$validators.max = supportsRange ?
24943 // Since all browsers set the input to a valid value, we don't need to check validity
24944 function noopMaxValidator() { return true; } :
24945 // non-support browsers validate the max val
24946 function maxValidator(modelValue, viewValue) {
24947 return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
24948 };
24949
24950 setInitialValueAndObserver('max', maxChange);
24951 }
24952
24953 if (hasStepAttr) {
24954 ctrl.$validators.step = supportsRange ?
24955 function nativeStepValidator() {
24956 // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
24957 // input element value to a valid value). It's possible that other browsers set the stepMismatch
24958 // validity error instead, so we can at least report an error in that case.
24959 return !validity.stepMismatch;
24960 } :
24961 // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
24962 function stepValidator(modelValue, viewValue) {
24963 return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
24964 isValidForStep(viewValue, minVal || 0, stepVal);
24965 };
24966
24967 setInitialValueAndObserver('step', stepChange);
24968 }
24969
24970 function setInitialValueAndObserver(htmlAttrName, changeFn) {
24971 // interpolated attributes set the attribute value only after a digest, but we need the
24972 // attribute value when the input is first rendered, so that the browser can adjust the
24973 // input value based on the min/max value
24974 element.attr(htmlAttrName, attr[htmlAttrName]);
24975 attr.$observe(htmlAttrName, changeFn);
24976 }
24977
24978 function minChange(val) {
24979 minVal = parseNumberAttrVal(val);
24980 // ignore changes before model is initialized
24981 if (isNumberNaN(ctrl.$modelValue)) {
24982 return;
24983 }
24984
24985 if (supportsRange) {
24986 var elVal = element.val();
24987 // IE11 doesn't set the el val correctly if the minVal is greater than the element value
24988 if (minVal > elVal) {
24989 elVal = minVal;
24990 element.val(elVal);
24991 }
24992 ctrl.$setViewValue(elVal);
24993 } else {
24994 // TODO(matsko): implement validateLater to reduce number of validations
24995 ctrl.$validate();
24996 }
24997 }
24998
24999 function maxChange(val) {
25000 maxVal = parseNumberAttrVal(val);
25001 // ignore changes before model is initialized
25002 if (isNumberNaN(ctrl.$modelValue)) {
25003 return;
25004 }
25005
25006 if (supportsRange) {
25007 var elVal = element.val();
25008 // IE11 doesn't set the el val correctly if the maxVal is less than the element value
25009 if (maxVal < elVal) {
25010 element.val(maxVal);
25011 // IE11 and Chrome don't set the value to the minVal when max < min
25012 elVal = maxVal < minVal ? minVal : maxVal;
25013 }
25014 ctrl.$setViewValue(elVal);
25015 } else {
25016 // TODO(matsko): implement validateLater to reduce number of validations
25017 ctrl.$validate();
25018 }
25019 }
25020
25021 function stepChange(val) {
25022 stepVal = parseNumberAttrVal(val);
25023 // ignore changes before model is initialized
25024 if (isNumberNaN(ctrl.$modelValue)) {
25025 return;
25026 }
25027
25028 // Some browsers don't adjust the input value correctly, but set the stepMismatch error
25029 if (supportsRange && ctrl.$viewValue !== element.val()) {
25030 ctrl.$setViewValue(element.val());
25031 } else {
25032 // TODO(matsko): implement validateLater to reduce number of validations
25033 ctrl.$validate();
25034 }
25035 }
25036}
25037
25038function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
25039 // Note: no badInputChecker here by purpose as `url` is only a validation
25040 // in browsers, i.e. we can always read out input.value even if it is not valid!
25041 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
25042 stringBasedInputType(ctrl);
25043
25044 ctrl.$$parserName = 'url';
25045 ctrl.$validators.url = function(modelValue, viewValue) {
25046 var value = modelValue || viewValue;
25047 return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
25048 };
25049}
25050
25051function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
25052 // Note: no badInputChecker here by purpose as `url` is only a validation
25053 // in browsers, i.e. we can always read out input.value even if it is not valid!
25054 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
25055 stringBasedInputType(ctrl);
25056
25057 ctrl.$$parserName = 'email';
25058 ctrl.$validators.email = function(modelValue, viewValue) {
25059 var value = modelValue || viewValue;
25060 return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
25061 };
25062}
25063
25064function radioInputType(scope, element, attr, ctrl) {
25065 var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
25066 // make the name unique, if not defined
25067 if (isUndefined(attr.name)) {
25068 element.attr('name', nextUid());
25069 }
25070
25071 var listener = function(ev) {
25072 var value;
25073 if (element[0].checked) {
25074 value = attr.value;
25075 if (doTrim) {
25076 value = trim(value);
25077 }
25078 ctrl.$setViewValue(value, ev && ev.type);
25079 }
25080 };
25081
25082 element.on('click', listener);
25083
25084 ctrl.$render = function() {
25085 var value = attr.value;
25086 if (doTrim) {
25087 value = trim(value);
25088 }
25089 element[0].checked = (value === ctrl.$viewValue);
25090 };
25091
25092 attr.$observe('value', ctrl.$render);
25093}
25094
25095function parseConstantExpr($parse, context, name, expression, fallback) {
25096 var parseFn;
25097 if (isDefined(expression)) {
25098 parseFn = $parse(expression);
25099 if (!parseFn.constant) {
25100 throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
25101 '`{1}`.', name, expression);
25102 }
25103 return parseFn(context);
25104 }
25105 return fallback;
25106}
25107
25108function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
25109 var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
25110 var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
25111
25112 var listener = function(ev) {
25113 ctrl.$setViewValue(element[0].checked, ev && ev.type);
25114 };
25115
25116 element.on('click', listener);
25117
25118 ctrl.$render = function() {
25119 element[0].checked = ctrl.$viewValue;
25120 };
25121
25122 // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
25123 // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
25124 // it to a boolean.
25125 ctrl.$isEmpty = function(value) {
25126 return value === false;
25127 };
25128
25129 ctrl.$formatters.push(function(value) {
25130 return equals(value, trueValue);
25131 });
25132
25133 ctrl.$parsers.push(function(value) {
25134 return value ? trueValue : falseValue;
25135 });
25136}
25137
25138
25139/**
25140 * @ngdoc directive
25141 * @name textarea
25142 * @restrict E
25143 *
25144 * @description
25145 * HTML textarea element control with angular data-binding. The data-binding and validation
25146 * properties of this element are exactly the same as those of the
25147 * {@link ng.directive:input input element}.
25148 *
25149 * @param {string} ngModel Assignable angular expression to data-bind to.
25150 * @param {string=} name Property name of the form under which the control is published.
25151 * @param {string=} required Sets `required` validation error key if the value is not entered.
25152 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
25153 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
25154 * `required` when you want to data-bind to the `required` attribute.
25155 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
25156 * minlength.
25157 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
25158 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
25159 * length.
25160 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
25161 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
25162 * If the expression evaluates to a RegExp object, then this is used directly.
25163 * If the expression evaluates to a string, then it will be converted to a RegExp
25164 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
25165 * `new RegExp('^abc$')`.<br />
25166 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
25167 * start at the index of the last search's match, thus not taking the whole input value into
25168 * account.
25169 * @param {string=} ngChange Angular expression to be executed when input changes due to user
25170 * interaction with the input element.
25171 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
25172 *
25173 * @knownIssue
25174 *
25175 * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
25176 * insert the placeholder value as the textarea's content. If the placeholder value contains
25177 * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
25178 * the value of the by-then-removed text node. This doesn't affect the functionality of the
25179 * textarea, but can be undesirable.
25180 *
25181 * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
25182 * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
25183 * find more details on `ngAttr` in the
25184 * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
25185 * Developer Guide.
25186 */
25187
25188
25189/**
25190 * @ngdoc directive
25191 * @name input
25192 * @restrict E
25193 *
25194 * @description
25195 * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
25196 * input state control, and validation.
25197 * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
25198 *
25199 * <div class="alert alert-warning">
25200 * **Note:** Not every feature offered is available for all input types.
25201 * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
25202 * </div>
25203 *
25204 * @param {string} ngModel Assignable angular expression to data-bind to.
25205 * @param {string=} name Property name of the form under which the control is published.
25206 * @param {string=} required Sets `required` validation error key if the value is not entered.
25207 * @param {boolean=} ngRequired Sets `required` attribute if set to true
25208 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
25209 * minlength.
25210 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
25211 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
25212 * length.
25213 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
25214 * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
25215 * If the expression evaluates to a RegExp object, then this is used directly.
25216 * If the expression evaluates to a string, then it will be converted to a RegExp
25217 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
25218 * `new RegExp('^abc$')`.<br />
25219 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
25220 * start at the index of the last search's match, thus not taking the whole input value into
25221 * account.
25222 * @param {string=} ngChange Angular expression to be executed when input changes due to user
25223 * interaction with the input element.
25224 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
25225 * This parameter is ignored for input[type=password] controls, which will never trim the
25226 * input.
25227 *
25228 * @example
25229 <example name="input-directive" module="inputExample">
25230 <file name="index.html">
25231 <script>
25232 angular.module('inputExample', [])
25233 .controller('ExampleController', ['$scope', function($scope) {
25234 $scope.user = {name: 'guest', last: 'visitor'};
25235 }]);
25236 </script>
25237 <div ng-controller="ExampleController">
25238 <form name="myForm">
25239 <label>
25240 User name:
25241 <input type="text" name="userName" ng-model="user.name" required>
25242 </label>
25243 <div role="alert">
25244 <span class="error" ng-show="myForm.userName.$error.required">
25245 Required!</span>
25246 </div>
25247 <label>
25248 Last name:
25249 <input type="text" name="lastName" ng-model="user.last"
25250 ng-minlength="3" ng-maxlength="10">
25251 </label>
25252 <div role="alert">
25253 <span class="error" ng-show="myForm.lastName.$error.minlength">
25254 Too short!</span>
25255 <span class="error" ng-show="myForm.lastName.$error.maxlength">
25256 Too long!</span>
25257 </div>
25258 </form>
25259 <hr>
25260 <tt>user = {{user}}</tt><br/>
25261 <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
25262 <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
25263 <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
25264 <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
25265 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
25266 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
25267 <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
25268 <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
25269 </div>
25270 </file>
25271 <file name="protractor.js" type="protractor">
25272 var user = element(by.exactBinding('user'));
25273 var userNameValid = element(by.binding('myForm.userName.$valid'));
25274 var lastNameValid = element(by.binding('myForm.lastName.$valid'));
25275 var lastNameError = element(by.binding('myForm.lastName.$error'));
25276 var formValid = element(by.binding('myForm.$valid'));
25277 var userNameInput = element(by.model('user.name'));
25278 var userLastInput = element(by.model('user.last'));
25279
25280 it('should initialize to model', function() {
25281 expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
25282 expect(userNameValid.getText()).toContain('true');
25283 expect(formValid.getText()).toContain('true');
25284 });
25285
25286 it('should be invalid if empty when required', function() {
25287 userNameInput.clear();
25288 userNameInput.sendKeys('');
25289
25290 expect(user.getText()).toContain('{"last":"visitor"}');
25291 expect(userNameValid.getText()).toContain('false');
25292 expect(formValid.getText()).toContain('false');
25293 });
25294
25295 it('should be valid if empty when min length is set', function() {
25296 userLastInput.clear();
25297 userLastInput.sendKeys('');
25298
25299 expect(user.getText()).toContain('{"name":"guest","last":""}');
25300 expect(lastNameValid.getText()).toContain('true');
25301 expect(formValid.getText()).toContain('true');
25302 });
25303
25304 it('should be invalid if less than required min length', function() {
25305 userLastInput.clear();
25306 userLastInput.sendKeys('xx');
25307
25308 expect(user.getText()).toContain('{"name":"guest"}');
25309 expect(lastNameValid.getText()).toContain('false');
25310 expect(lastNameError.getText()).toContain('minlength');
25311 expect(formValid.getText()).toContain('false');
25312 });
25313
25314 it('should be invalid if longer than max length', function() {
25315 userLastInput.clear();
25316 userLastInput.sendKeys('some ridiculously long name');
25317
25318 expect(user.getText()).toContain('{"name":"guest"}');
25319 expect(lastNameValid.getText()).toContain('false');
25320 expect(lastNameError.getText()).toContain('maxlength');
25321 expect(formValid.getText()).toContain('false');
25322 });
25323 </file>
25324 </example>
25325 */
25326var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
25327 function($browser, $sniffer, $filter, $parse) {
25328 return {
25329 restrict: 'E',
25330 require: ['?ngModel'],
25331 link: {
25332 pre: function(scope, element, attr, ctrls) {
25333 if (ctrls[0]) {
25334 (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
25335 $browser, $filter, $parse);
25336 }
25337 }
25338 }
25339 };
25340}];
25341
25342
25343
25344var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
25345/**
25346 * @ngdoc directive
25347 * @name ngValue
25348 *
25349 * @description
25350 * Binds the given expression to the value of the element.
25351 *
25352 * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
25353 * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
25354 * {@link select `select`} parent element) is set to the bound value. It is especially useful
25355 * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
25356 *
25357 * It can also be used to achieve one-way binding of a given expression to an input element
25358 * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
25359 *
25360 * @element input
25361 * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
25362 * and `value` property of the element.
25363 *
25364 * @example
25365 <example name="ngValue-directive" module="valueExample">
25366 <file name="index.html">
25367 <script>
25368 angular.module('valueExample', [])
25369 .controller('ExampleController', ['$scope', function($scope) {
25370 $scope.names = ['pizza', 'unicorns', 'robots'];
25371 $scope.my = { favorite: 'unicorns' };
25372 }]);
25373 </script>
25374 <form ng-controller="ExampleController">
25375 <h2>Which is your favorite?</h2>
25376 <label ng-repeat="name in names" for="{{name}}">
25377 {{name}}
25378 <input type="radio"
25379 ng-model="my.favorite"
25380 ng-value="name"
25381 id="{{name}}"
25382 name="favorite">
25383 </label>
25384 <div>You chose {{my.favorite}}</div>
25385 </form>
25386 </file>
25387 <file name="protractor.js" type="protractor">
25388 var favorite = element(by.binding('my.favorite'));
25389
25390 it('should initialize to model', function() {
25391 expect(favorite.getText()).toContain('unicorns');
25392 });
25393 it('should bind the values to the inputs', function() {
25394 element.all(by.model('my.favorite')).get(0).click();
25395 expect(favorite.getText()).toContain('pizza');
25396 });
25397 </file>
25398 </example>
25399 */
25400var ngValueDirective = function() {
25401 /**
25402 * inputs use the value attribute as their default value if the value property is not set.
25403 * Once the value property has been set (by adding input), it will not react to changes to
25404 * the value attribute anymore. Setting both attribute and property fixes this behavior, and
25405 * makes it possible to use ngValue as a sort of one-way bind.
25406 */
25407 function updateElementValue(element, attr, value) {
25408 element.prop('value', value);
25409 attr.$set('value', value);
25410 }
25411
25412 return {
25413 restrict: 'A',
25414 priority: 100,
25415 compile: function(tpl, tplAttr) {
25416 if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
25417 return function ngValueConstantLink(scope, elm, attr) {
25418 var value = scope.$eval(attr.ngValue);
25419 updateElementValue(elm, attr, value);
25420 };
25421 } else {
25422 return function ngValueLink(scope, elm, attr) {
25423 scope.$watch(attr.ngValue, function valueWatchAction(value) {
25424 updateElementValue(elm, attr, value);
25425 });
25426 };
25427 }
25428 }
25429 };
25430};
25431
25432/**
25433 * @ngdoc directive
25434 * @name ngBind
25435 * @restrict AC
25436 *
25437 * @description
25438 * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
25439 * with the value of a given expression, and to update the text content when the value of that
25440 * expression changes.
25441 *
25442 * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
25443 * `{{ expression }}` which is similar but less verbose.
25444 *
25445 * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
25446 * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
25447 * element attribute, it makes the bindings invisible to the user while the page is loading.
25448 *
25449 * An alternative solution to this problem would be using the
25450 * {@link ng.directive:ngCloak ngCloak} directive.
25451 *
25452 *
25453 * @element ANY
25454 * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
25455 *
25456 * @example
25457 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
25458 <example module="bindExample" name="ng-bind">
25459 <file name="index.html">
25460 <script>
25461 angular.module('bindExample', [])
25462 .controller('ExampleController', ['$scope', function($scope) {
25463 $scope.name = 'Whirled';
25464 }]);
25465 </script>
25466 <div ng-controller="ExampleController">
25467 <label>Enter name: <input type="text" ng-model="name"></label><br>
25468 Hello <span ng-bind="name"></span>!
25469 </div>
25470 </file>
25471 <file name="protractor.js" type="protractor">
25472 it('should check ng-bind', function() {
25473 var nameInput = element(by.model('name'));
25474
25475 expect(element(by.binding('name')).getText()).toBe('Whirled');
25476 nameInput.clear();
25477 nameInput.sendKeys('world');
25478 expect(element(by.binding('name')).getText()).toBe('world');
25479 });
25480 </file>
25481 </example>
25482 */
25483var ngBindDirective = ['$compile', function($compile) {
25484 return {
25485 restrict: 'AC',
25486 compile: function ngBindCompile(templateElement) {
25487 $compile.$$addBindingClass(templateElement);
25488 return function ngBindLink(scope, element, attr) {
25489 $compile.$$addBindingInfo(element, attr.ngBind);
25490 element = element[0];
25491 scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
25492 element.textContent = stringify(value);
25493 });
25494 };
25495 }
25496 };
25497}];
25498
25499
25500/**
25501 * @ngdoc directive
25502 * @name ngBindTemplate
25503 *
25504 * @description
25505 * The `ngBindTemplate` directive specifies that the element
25506 * text content should be replaced with the interpolation of the template
25507 * in the `ngBindTemplate` attribute.
25508 * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
25509 * expressions. This directive is needed since some HTML elements
25510 * (such as TITLE and OPTION) cannot contain SPAN elements.
25511 *
25512 * @element ANY
25513 * @param {string} ngBindTemplate template of form
25514 * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
25515 *
25516 * @example
25517 * Try it here: enter text in text box and watch the greeting change.
25518 <example module="bindExample" name="ng-bind-template">
25519 <file name="index.html">
25520 <script>
25521 angular.module('bindExample', [])
25522 .controller('ExampleController', ['$scope', function($scope) {
25523 $scope.salutation = 'Hello';
25524 $scope.name = 'World';
25525 }]);
25526 </script>
25527 <div ng-controller="ExampleController">
25528 <label>Salutation: <input type="text" ng-model="salutation"></label><br>
25529 <label>Name: <input type="text" ng-model="name"></label><br>
25530 <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
25531 </div>
25532 </file>
25533 <file name="protractor.js" type="protractor">
25534 it('should check ng-bind', function() {
25535 var salutationElem = element(by.binding('salutation'));
25536 var salutationInput = element(by.model('salutation'));
25537 var nameInput = element(by.model('name'));
25538
25539 expect(salutationElem.getText()).toBe('Hello World!');
25540
25541 salutationInput.clear();
25542 salutationInput.sendKeys('Greetings');
25543 nameInput.clear();
25544 nameInput.sendKeys('user');
25545
25546 expect(salutationElem.getText()).toBe('Greetings user!');
25547 });
25548 </file>
25549 </example>
25550 */
25551var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
25552 return {
25553 compile: function ngBindTemplateCompile(templateElement) {
25554 $compile.$$addBindingClass(templateElement);
25555 return function ngBindTemplateLink(scope, element, attr) {
25556 var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
25557 $compile.$$addBindingInfo(element, interpolateFn.expressions);
25558 element = element[0];
25559 attr.$observe('ngBindTemplate', function(value) {
25560 element.textContent = isUndefined(value) ? '' : value;
25561 });
25562 };
25563 }
25564 };
25565}];
25566
25567
25568/**
25569 * @ngdoc directive
25570 * @name ngBindHtml
25571 *
25572 * @description
25573 * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
25574 * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
25575 * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
25576 * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
25577 * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
25578 *
25579 * You may also bypass sanitization for values you know are safe. To do so, bind to
25580 * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
25581 * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
25582 *
25583 * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
25584 * will have an exception (instead of an exploit.)
25585 *
25586 * @element ANY
25587 * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
25588 *
25589 * @example
25590
25591 <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
25592 <file name="index.html">
25593 <div ng-controller="ExampleController">
25594 <p ng-bind-html="myHTML"></p>
25595 </div>
25596 </file>
25597
25598 <file name="script.js">
25599 angular.module('bindHtmlExample', ['ngSanitize'])
25600 .controller('ExampleController', ['$scope', function($scope) {
25601 $scope.myHTML =
25602 'I am an <code>HTML</code>string with ' +
25603 '<a href="#">links!</a> and other <em>stuff</em>';
25604 }]);
25605 </file>
25606
25607 <file name="protractor.js" type="protractor">
25608 it('should check ng-bind-html', function() {
25609 expect(element(by.binding('myHTML')).getText()).toBe(
25610 'I am an HTMLstring with links! and other stuff');
25611 });
25612 </file>
25613 </example>
25614 */
25615var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
25616 return {
25617 restrict: 'A',
25618 compile: function ngBindHtmlCompile(tElement, tAttrs) {
25619 var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
25620 var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
25621 // Unwrap the value to compare the actual inner safe value, not the wrapper object.
25622 return $sce.valueOf(val);
25623 });
25624 $compile.$$addBindingClass(tElement);
25625
25626 return function ngBindHtmlLink(scope, element, attr) {
25627 $compile.$$addBindingInfo(element, attr.ngBindHtml);
25628
25629 scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
25630 // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
25631 var value = ngBindHtmlGetter(scope);
25632 element.html($sce.getTrustedHtml(value) || '');
25633 });
25634 };
25635 }
25636 };
25637}];
25638
25639/**
25640 * @ngdoc directive
25641 * @name ngChange
25642 *
25643 * @description
25644 * Evaluate the given expression when the user changes the input.
25645 * The expression is evaluated immediately, unlike the JavaScript onchange event
25646 * which only triggers at the end of a change (usually, when the user leaves the
25647 * form element or presses the return key).
25648 *
25649 * The `ngChange` expression is only evaluated when a change in the input value causes
25650 * a new value to be committed to the model.
25651 *
25652 * It will not be evaluated:
25653 * * if the value returned from the `$parsers` transformation pipeline has not changed
25654 * * if the input has continued to be invalid since the model will stay `null`
25655 * * if the model is changed programmatically and not by a change to the input value
25656 *
25657 *
25658 * Note, this directive requires `ngModel` to be present.
25659 *
25660 * @element input
25661 * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
25662 * in input value.
25663 *
25664 * @example
25665 * <example name="ngChange-directive" module="changeExample">
25666 * <file name="index.html">
25667 * <script>
25668 * angular.module('changeExample', [])
25669 * .controller('ExampleController', ['$scope', function($scope) {
25670 * $scope.counter = 0;
25671 * $scope.change = function() {
25672 * $scope.counter++;
25673 * };
25674 * }]);
25675 * </script>
25676 * <div ng-controller="ExampleController">
25677 * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
25678 * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
25679 * <label for="ng-change-example2">Confirmed</label><br />
25680 * <tt>debug = {{confirmed}}</tt><br/>
25681 * <tt>counter = {{counter}}</tt><br/>
25682 * </div>
25683 * </file>
25684 * <file name="protractor.js" type="protractor">
25685 * var counter = element(by.binding('counter'));
25686 * var debug = element(by.binding('confirmed'));
25687 *
25688 * it('should evaluate the expression if changing from view', function() {
25689 * expect(counter.getText()).toContain('0');
25690 *
25691 * element(by.id('ng-change-example1')).click();
25692 *
25693 * expect(counter.getText()).toContain('1');
25694 * expect(debug.getText()).toContain('true');
25695 * });
25696 *
25697 * it('should not evaluate the expression if changing from model', function() {
25698 * element(by.id('ng-change-example2')).click();
25699
25700 * expect(counter.getText()).toContain('0');
25701 * expect(debug.getText()).toContain('true');
25702 * });
25703 * </file>
25704 * </example>
25705 */
25706var ngChangeDirective = valueFn({
25707 restrict: 'A',
25708 require: 'ngModel',
25709 link: function(scope, element, attr, ctrl) {
25710 ctrl.$viewChangeListeners.push(function() {
25711 scope.$eval(attr.ngChange);
25712 });
25713 }
25714});
25715
25716/* exported
25717 ngClassDirective,
25718 ngClassEvenDirective,
25719 ngClassOddDirective
25720*/
25721
25722function classDirective(name, selector) {
25723 name = 'ngClass' + name;
25724 var indexWatchExpression;
25725
25726 return ['$parse', function($parse) {
25727 return {
25728 restrict: 'AC',
25729 link: function(scope, element, attr) {
25730 var expression = attr[name].trim();
25731 var isOneTime = (expression.charAt(0) === ':') && (expression.charAt(1) === ':');
25732
25733 var watchInterceptor = isOneTime ? toFlatValue : toClassString;
25734 var watchExpression = $parse(expression, watchInterceptor);
25735 var watchAction = isOneTime ? ngClassOneTimeWatchAction : ngClassWatchAction;
25736
25737 var classCounts = element.data('$classCounts');
25738 var oldModulo = true;
25739 var oldClassString;
25740
25741 if (!classCounts) {
25742 // Use createMap() to prevent class assumptions involving property
25743 // names in Object.prototype
25744 classCounts = createMap();
25745 element.data('$classCounts', classCounts);
25746 }
25747
25748 if (name !== 'ngClass') {
25749 if (!indexWatchExpression) {
25750 indexWatchExpression = $parse('$index', function moduloTwo($index) {
25751 // eslint-disable-next-line no-bitwise
25752 return $index & 1;
25753 });
25754 }
25755
25756 scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
25757 }
25758
25759 scope.$watch(watchExpression, watchAction, isOneTime);
25760
25761 function addClasses(classString) {
25762 classString = digestClassCounts(split(classString), 1);
25763 attr.$addClass(classString);
25764 }
25765
25766 function removeClasses(classString) {
25767 classString = digestClassCounts(split(classString), -1);
25768 attr.$removeClass(classString);
25769 }
25770
25771 function updateClasses(oldClassString, newClassString) {
25772 var oldClassArray = split(oldClassString);
25773 var newClassArray = split(newClassString);
25774
25775 var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
25776 var toAddArray = arrayDifference(newClassArray, oldClassArray);
25777
25778 var toRemoveString = digestClassCounts(toRemoveArray, -1);
25779 var toAddString = digestClassCounts(toAddArray, 1);
25780
25781 attr.$addClass(toAddString);
25782 attr.$removeClass(toRemoveString);
25783 }
25784
25785 function digestClassCounts(classArray, count) {
25786 var classesToUpdate = [];
25787
25788 forEach(classArray, function(className) {
25789 if (count > 0 || classCounts[className]) {
25790 classCounts[className] = (classCounts[className] || 0) + count;
25791 if (classCounts[className] === +(count > 0)) {
25792 classesToUpdate.push(className);
25793 }
25794 }
25795 });
25796
25797 return classesToUpdate.join(' ');
25798 }
25799
25800 function ngClassIndexWatchAction(newModulo) {
25801 // This watch-action should run before the `ngClass[OneTime]WatchAction()`, thus it
25802 // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
25803 // `ngClass[OneTime]WatchAction()` will update the classes.
25804 if (newModulo === selector) {
25805 addClasses(oldClassString);
25806 } else {
25807 removeClasses(oldClassString);
25808 }
25809
25810 oldModulo = newModulo;
25811 }
25812
25813 function ngClassOneTimeWatchAction(newClassValue) {
25814 var newClassString = toClassString(newClassValue);
25815
25816 if (newClassString !== oldClassString) {
25817 ngClassWatchAction(newClassString);
25818 }
25819 }
25820
25821 function ngClassWatchAction(newClassString) {
25822 if (oldModulo === selector) {
25823 updateClasses(oldClassString, newClassString);
25824 }
25825
25826 oldClassString = newClassString;
25827 }
25828 }
25829 };
25830 }];
25831
25832 // Helpers
25833 function arrayDifference(tokens1, tokens2) {
25834 if (!tokens1 || !tokens1.length) return [];
25835 if (!tokens2 || !tokens2.length) return tokens1;
25836
25837 var values = [];
25838
25839 outer:
25840 for (var i = 0; i < tokens1.length; i++) {
25841 var token = tokens1[i];
25842 for (var j = 0; j < tokens2.length; j++) {
25843 if (token === tokens2[j]) continue outer;
25844 }
25845 values.push(token);
25846 }
25847
25848 return values;
25849 }
25850
25851 function split(classString) {
25852 return classString && classString.split(' ');
25853 }
25854
25855 function toClassString(classValue) {
25856 var classString = classValue;
25857
25858 if (isArray(classValue)) {
25859 classString = classValue.map(toClassString).join(' ');
25860 } else if (isObject(classValue)) {
25861 classString = Object.keys(classValue).
25862 filter(function(key) { return classValue[key]; }).
25863 join(' ');
25864 }
25865
25866 return classString;
25867 }
25868
25869 function toFlatValue(classValue) {
25870 var flatValue = classValue;
25871
25872 if (isArray(classValue)) {
25873 flatValue = classValue.map(toFlatValue);
25874 } else if (isObject(classValue)) {
25875 var hasUndefined = false;
25876
25877 flatValue = Object.keys(classValue).filter(function(key) {
25878 var value = classValue[key];
25879
25880 if (!hasUndefined && isUndefined(value)) {
25881 hasUndefined = true;
25882 }
25883
25884 return value;
25885 });
25886
25887 if (hasUndefined) {
25888 // Prevent the `oneTimeLiteralWatchInterceptor` from unregistering
25889 // the watcher, by including at least one `undefined` value.
25890 flatValue.push(undefined);
25891 }
25892 }
25893
25894 return flatValue;
25895 }
25896}
25897
25898/**
25899 * @ngdoc directive
25900 * @name ngClass
25901 * @restrict AC
25902 *
25903 * @description
25904 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
25905 * an expression that represents all classes to be added.
25906 *
25907 * The directive operates in three different ways, depending on which of three types the expression
25908 * evaluates to:
25909 *
25910 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
25911 * names.
25912 *
25913 * 2. If the expression evaluates to an object, then for each key-value pair of the
25914 * object with a truthy value the corresponding key is used as a class name.
25915 *
25916 * 3. If the expression evaluates to an array, each element of the array should either be a string as in
25917 * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
25918 * to give you more control over what CSS classes appear. See the code below for an example of this.
25919 *
25920 *
25921 * The directive won't add duplicate classes if a particular class was already set.
25922 *
25923 * When the expression changes, the previously added classes are removed and only then are the
25924 * new classes added.
25925 *
25926 * @knownIssue
25927 * You should not use {@link guide/interpolation interpolation} in the value of the `class`
25928 * attribute, when using the `ngClass` directive on the same element.
25929 * See {@link guide/interpolation#known-issues here} for more info.
25930 *
25931 * @animations
25932 * | Animation | Occurs |
25933 * |----------------------------------|-------------------------------------|
25934 * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
25935 * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
25936 *
25937 * @element ANY
25938 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
25939 * of the evaluation can be a string representing space delimited class
25940 * names, an array, or a map of class names to boolean values. In the case of a map, the
25941 * names of the properties whose values are truthy will be added as css classes to the
25942 * element.
25943 *
25944 * @example Example that demonstrates basic bindings via ngClass directive.
25945 <example name="ng-class">
25946 <file name="index.html">
25947 <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
25948 <label>
25949 <input type="checkbox" ng-model="deleted">
25950 deleted (apply "strike" class)
25951 </label><br>
25952 <label>
25953 <input type="checkbox" ng-model="important">
25954 important (apply "bold" class)
25955 </label><br>
25956 <label>
25957 <input type="checkbox" ng-model="error">
25958 error (apply "has-error" class)
25959 </label>
25960 <hr>
25961 <p ng-class="style">Using String Syntax</p>
25962 <input type="text" ng-model="style"
25963 placeholder="Type: bold strike red" aria-label="Type: bold strike red">
25964 <hr>
25965 <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
25966 <input ng-model="style1"
25967 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
25968 <input ng-model="style2"
25969 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
25970 <input ng-model="style3"
25971 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
25972 <hr>
25973 <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
25974 <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
25975 <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
25976 </file>
25977 <file name="style.css">
25978 .strike {
25979 text-decoration: line-through;
25980 }
25981 .bold {
25982 font-weight: bold;
25983 }
25984 .red {
25985 color: red;
25986 }
25987 .has-error {
25988 color: red;
25989 background-color: yellow;
25990 }
25991 .orange {
25992 color: orange;
25993 }
25994 </file>
25995 <file name="protractor.js" type="protractor">
25996 var ps = element.all(by.css('p'));
25997
25998 it('should let you toggle the class', function() {
25999
26000 expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
26001 expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
26002
26003 element(by.model('important')).click();
26004 expect(ps.first().getAttribute('class')).toMatch(/bold/);
26005
26006 element(by.model('error')).click();
26007 expect(ps.first().getAttribute('class')).toMatch(/has-error/);
26008 });
26009
26010 it('should let you toggle string example', function() {
26011 expect(ps.get(1).getAttribute('class')).toBe('');
26012 element(by.model('style')).clear();
26013 element(by.model('style')).sendKeys('red');
26014 expect(ps.get(1).getAttribute('class')).toBe('red');
26015 });
26016
26017 it('array example should have 3 classes', function() {
26018 expect(ps.get(2).getAttribute('class')).toBe('');
26019 element(by.model('style1')).sendKeys('bold');
26020 element(by.model('style2')).sendKeys('strike');
26021 element(by.model('style3')).sendKeys('red');
26022 expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
26023 });
26024
26025 it('array with map example should have 2 classes', function() {
26026 expect(ps.last().getAttribute('class')).toBe('');
26027 element(by.model('style4')).sendKeys('bold');
26028 element(by.model('warning')).click();
26029 expect(ps.last().getAttribute('class')).toBe('bold orange');
26030 });
26031 </file>
26032 </example>
26033
26034 ## Animations
26035
26036 The example below demonstrates how to perform animations using ngClass.
26037
26038 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
26039 <file name="index.html">
26040 <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
26041 <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
26042 <br>
26043 <span class="base-class" ng-class="myVar">Sample Text</span>
26044 </file>
26045 <file name="style.css">
26046 .base-class {
26047 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
26048 }
26049
26050 .base-class.my-class {
26051 color: red;
26052 font-size:3em;
26053 }
26054 </file>
26055 <file name="protractor.js" type="protractor">
26056 it('should check ng-class', function() {
26057 expect(element(by.css('.base-class')).getAttribute('class')).not.
26058 toMatch(/my-class/);
26059
26060 element(by.id('setbtn')).click();
26061
26062 expect(element(by.css('.base-class')).getAttribute('class')).
26063 toMatch(/my-class/);
26064
26065 element(by.id('clearbtn')).click();
26066
26067 expect(element(by.css('.base-class')).getAttribute('class')).not.
26068 toMatch(/my-class/);
26069 });
26070 </file>
26071 </example>
26072
26073
26074 ## ngClass and pre-existing CSS3 Transitions/Animations
26075 The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
26076 Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
26077 any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
26078 to view the step by step details of {@link $animate#addClass $animate.addClass} and
26079 {@link $animate#removeClass $animate.removeClass}.
26080 */
26081var ngClassDirective = classDirective('', true);
26082
26083/**
26084 * @ngdoc directive
26085 * @name ngClassOdd
26086 * @restrict AC
26087 *
26088 * @description
26089 * The `ngClassOdd` and `ngClassEven` directives work exactly as
26090 * {@link ng.directive:ngClass ngClass}, except they work in
26091 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
26092 *
26093 * This directive can be applied only within the scope of an
26094 * {@link ng.directive:ngRepeat ngRepeat}.
26095 *
26096 * @element ANY
26097 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
26098 * of the evaluation can be a string representing space delimited class names or an array.
26099 *
26100 * @example
26101 <example name="ng-class-odd">
26102 <file name="index.html">
26103 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
26104 <li ng-repeat="name in names">
26105 <span ng-class-odd="'odd'" ng-class-even="'even'">
26106 {{name}}
26107 </span>
26108 </li>
26109 </ol>
26110 </file>
26111 <file name="style.css">
26112 .odd {
26113 color: red;
26114 }
26115 .even {
26116 color: blue;
26117 }
26118 </file>
26119 <file name="protractor.js" type="protractor">
26120 it('should check ng-class-odd and ng-class-even', function() {
26121 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
26122 toMatch(/odd/);
26123 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
26124 toMatch(/even/);
26125 });
26126 </file>
26127 </example>
26128 */
26129var ngClassOddDirective = classDirective('Odd', 0);
26130
26131/**
26132 * @ngdoc directive
26133 * @name ngClassEven
26134 * @restrict AC
26135 *
26136 * @description
26137 * The `ngClassOdd` and `ngClassEven` directives work exactly as
26138 * {@link ng.directive:ngClass ngClass}, except they work in
26139 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
26140 *
26141 * This directive can be applied only within the scope of an
26142 * {@link ng.directive:ngRepeat ngRepeat}.
26143 *
26144 * @element ANY
26145 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
26146 * result of the evaluation can be a string representing space delimited class names or an array.
26147 *
26148 * @example
26149 <example name="ng-class-even">
26150 <file name="index.html">
26151 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
26152 <li ng-repeat="name in names">
26153 <span ng-class-odd="'odd'" ng-class-even="'even'">
26154 {{name}}
26155 </span>
26156 </li>
26157 </ol>
26158 </file>
26159 <file name="style.css">
26160 .odd {
26161 color: red;
26162 }
26163 .even {
26164 color: blue;
26165 }
26166 </file>
26167 <file name="protractor.js" type="protractor">
26168 it('should check ng-class-odd and ng-class-even', function() {
26169 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
26170 toMatch(/odd/);
26171 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
26172 toMatch(/even/);
26173 });
26174 </file>
26175 </example>
26176 */
26177var ngClassEvenDirective = classDirective('Even', 1);
26178
26179/**
26180 * @ngdoc directive
26181 * @name ngCloak
26182 * @restrict AC
26183 *
26184 * @description
26185 * The `ngCloak` directive is used to prevent the Angular html template from being briefly
26186 * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
26187 * directive to avoid the undesirable flicker effect caused by the html template display.
26188 *
26189 * The directive can be applied to the `<body>` element, but the preferred usage is to apply
26190 * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
26191 * of the browser view.
26192 *
26193 * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
26194 * `angular.min.js`.
26195 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
26196 *
26197 * ```css
26198 * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
26199 * display: none !important;
26200 * }
26201 * ```
26202 *
26203 * When this css rule is loaded by the browser, all html elements (including their children) that
26204 * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
26205 * during the compilation of the template it deletes the `ngCloak` element attribute, making
26206 * the compiled element visible.
26207 *
26208 * For the best result, the `angular.js` script must be loaded in the head section of the html
26209 * document; alternatively, the css rule above must be included in the external stylesheet of the
26210 * application.
26211 *
26212 * @element ANY
26213 *
26214 * @example
26215 <example name="ng-cloak">
26216 <file name="index.html">
26217 <div id="template1" ng-cloak>{{ 'hello' }}</div>
26218 <div id="template2" class="ng-cloak">{{ 'world' }}</div>
26219 </file>
26220 <file name="protractor.js" type="protractor">
26221 it('should remove the template directive and css class', function() {
26222 expect($('#template1').getAttribute('ng-cloak')).
26223 toBeNull();
26224 expect($('#template2').getAttribute('ng-cloak')).
26225 toBeNull();
26226 });
26227 </file>
26228 </example>
26229 *
26230 */
26231var ngCloakDirective = ngDirective({
26232 compile: function(element, attr) {
26233 attr.$set('ngCloak', undefined);
26234 element.removeClass('ng-cloak');
26235 }
26236});
26237
26238/**
26239 * @ngdoc directive
26240 * @name ngController
26241 *
26242 * @description
26243 * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
26244 * supports the principles behind the Model-View-Controller design pattern.
26245 *
26246 * MVC components in angular:
26247 *
26248 * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
26249 * are accessed through bindings.
26250 * * View — The template (HTML with data bindings) that is rendered into the View.
26251 * * Controller — The `ngController` directive specifies a Controller class; the class contains business
26252 * logic behind the application to decorate the scope with functions and values
26253 *
26254 * Note that you can also attach controllers to the DOM by declaring it in a route definition
26255 * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
26256 * again using `ng-controller` in the template itself. This will cause the controller to be attached
26257 * and executed twice.
26258 *
26259 * @element ANY
26260 * @scope
26261 * @priority 500
26262 * @param {expression} ngController Name of a constructor function registered with the current
26263 * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
26264 * that on the current scope evaluates to a constructor function.
26265 *
26266 * The controller instance can be published into a scope property by specifying
26267 * `ng-controller="as propertyName"`.
26268 *
26269 * If the current `$controllerProvider` is configured to use globals (via
26270 * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
26271 * also be the name of a globally accessible constructor function (deprecated, not recommended).
26272 *
26273 * @example
26274 * Here is a simple form for editing user contact information. Adding, removing, clearing, and
26275 * greeting are methods declared on the controller (see source tab). These methods can
26276 * easily be called from the angular markup. Any changes to the data are automatically reflected
26277 * in the View without the need for a manual update.
26278 *
26279 * Two different declaration styles are included below:
26280 *
26281 * * one binds methods and properties directly onto the controller using `this`:
26282 * `ng-controller="SettingsController1 as settings"`
26283 * * one injects `$scope` into the controller:
26284 * `ng-controller="SettingsController2"`
26285 *
26286 * The second option is more common in the Angular community, and is generally used in boilerplates
26287 * and in this guide. However, there are advantages to binding properties directly to the controller
26288 * and avoiding scope.
26289 *
26290 * * Using `controller as` makes it obvious which controller you are accessing in the template when
26291 * multiple controllers apply to an element.
26292 * * If you are writing your controllers as classes you have easier access to the properties and
26293 * methods, which will appear on the scope, from inside the controller code.
26294 * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
26295 * inheritance masking primitives.
26296 *
26297 * This example demonstrates the `controller as` syntax.
26298 *
26299 * <example name="ngControllerAs" module="controllerAsExample">
26300 * <file name="index.html">
26301 * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
26302 * <label>Name: <input type="text" ng-model="settings.name"/></label>
26303 * <button ng-click="settings.greet()">greet</button><br/>
26304 * Contact:
26305 * <ul>
26306 * <li ng-repeat="contact in settings.contacts">
26307 * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
26308 * <option>phone</option>
26309 * <option>email</option>
26310 * </select>
26311 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
26312 * <button ng-click="settings.clearContact(contact)">clear</button>
26313 * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
26314 * </li>
26315 * <li><button ng-click="settings.addContact()">add</button></li>
26316 * </ul>
26317 * </div>
26318 * </file>
26319 * <file name="app.js">
26320 * angular.module('controllerAsExample', [])
26321 * .controller('SettingsController1', SettingsController1);
26322 *
26323 * function SettingsController1() {
26324 * this.name = 'John Smith';
26325 * this.contacts = [
26326 * {type: 'phone', value: '408 555 1212'},
26327 * {type: 'email', value: 'john.smith@example.org'}
26328 * ];
26329 * }
26330 *
26331 * SettingsController1.prototype.greet = function() {
26332 * alert(this.name);
26333 * };
26334 *
26335 * SettingsController1.prototype.addContact = function() {
26336 * this.contacts.push({type: 'email', value: 'yourname@example.org'});
26337 * };
26338 *
26339 * SettingsController1.prototype.removeContact = function(contactToRemove) {
26340 * var index = this.contacts.indexOf(contactToRemove);
26341 * this.contacts.splice(index, 1);
26342 * };
26343 *
26344 * SettingsController1.prototype.clearContact = function(contact) {
26345 * contact.type = 'phone';
26346 * contact.value = '';
26347 * };
26348 * </file>
26349 * <file name="protractor.js" type="protractor">
26350 * it('should check controller as', function() {
26351 * var container = element(by.id('ctrl-as-exmpl'));
26352 * expect(container.element(by.model('settings.name'))
26353 * .getAttribute('value')).toBe('John Smith');
26354 *
26355 * var firstRepeat =
26356 * container.element(by.repeater('contact in settings.contacts').row(0));
26357 * var secondRepeat =
26358 * container.element(by.repeater('contact in settings.contacts').row(1));
26359 *
26360 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
26361 * .toBe('408 555 1212');
26362 *
26363 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
26364 * .toBe('john.smith@example.org');
26365 *
26366 * firstRepeat.element(by.buttonText('clear')).click();
26367 *
26368 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
26369 * .toBe('');
26370 *
26371 * container.element(by.buttonText('add')).click();
26372 *
26373 * expect(container.element(by.repeater('contact in settings.contacts').row(2))
26374 * .element(by.model('contact.value'))
26375 * .getAttribute('value'))
26376 * .toBe('yourname@example.org');
26377 * });
26378 * </file>
26379 * </example>
26380 *
26381 * This example demonstrates the "attach to `$scope`" style of controller.
26382 *
26383 * <example name="ngController" module="controllerExample">
26384 * <file name="index.html">
26385 * <div id="ctrl-exmpl" ng-controller="SettingsController2">
26386 * <label>Name: <input type="text" ng-model="name"/></label>
26387 * <button ng-click="greet()">greet</button><br/>
26388 * Contact:
26389 * <ul>
26390 * <li ng-repeat="contact in contacts">
26391 * <select ng-model="contact.type" id="select_{{$index}}">
26392 * <option>phone</option>
26393 * <option>email</option>
26394 * </select>
26395 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
26396 * <button ng-click="clearContact(contact)">clear</button>
26397 * <button ng-click="removeContact(contact)">X</button>
26398 * </li>
26399 * <li>[ <button ng-click="addContact()">add</button> ]</li>
26400 * </ul>
26401 * </div>
26402 * </file>
26403 * <file name="app.js">
26404 * angular.module('controllerExample', [])
26405 * .controller('SettingsController2', ['$scope', SettingsController2]);
26406 *
26407 * function SettingsController2($scope) {
26408 * $scope.name = 'John Smith';
26409 * $scope.contacts = [
26410 * {type:'phone', value:'408 555 1212'},
26411 * {type:'email', value:'john.smith@example.org'}
26412 * ];
26413 *
26414 * $scope.greet = function() {
26415 * alert($scope.name);
26416 * };
26417 *
26418 * $scope.addContact = function() {
26419 * $scope.contacts.push({type:'email', value:'yourname@example.org'});
26420 * };
26421 *
26422 * $scope.removeContact = function(contactToRemove) {
26423 * var index = $scope.contacts.indexOf(contactToRemove);
26424 * $scope.contacts.splice(index, 1);
26425 * };
26426 *
26427 * $scope.clearContact = function(contact) {
26428 * contact.type = 'phone';
26429 * contact.value = '';
26430 * };
26431 * }
26432 * </file>
26433 * <file name="protractor.js" type="protractor">
26434 * it('should check controller', function() {
26435 * var container = element(by.id('ctrl-exmpl'));
26436 *
26437 * expect(container.element(by.model('name'))
26438 * .getAttribute('value')).toBe('John Smith');
26439 *
26440 * var firstRepeat =
26441 * container.element(by.repeater('contact in contacts').row(0));
26442 * var secondRepeat =
26443 * container.element(by.repeater('contact in contacts').row(1));
26444 *
26445 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
26446 * .toBe('408 555 1212');
26447 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
26448 * .toBe('john.smith@example.org');
26449 *
26450 * firstRepeat.element(by.buttonText('clear')).click();
26451 *
26452 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
26453 * .toBe('');
26454 *
26455 * container.element(by.buttonText('add')).click();
26456 *
26457 * expect(container.element(by.repeater('contact in contacts').row(2))
26458 * .element(by.model('contact.value'))
26459 * .getAttribute('value'))
26460 * .toBe('yourname@example.org');
26461 * });
26462 * </file>
26463 *</example>
26464
26465 */
26466var ngControllerDirective = [function() {
26467 return {
26468 restrict: 'A',
26469 scope: true,
26470 controller: '@',
26471 priority: 500
26472 };
26473}];
26474
26475/**
26476 * @ngdoc directive
26477 * @name ngCsp
26478 *
26479 * @restrict A
26480 * @element ANY
26481 * @description
26482 *
26483 * Angular has some features that can conflict with certain restrictions that are applied when using
26484 * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
26485 *
26486 * If you intend to implement CSP with these rules then you must tell Angular not to use these
26487 * features.
26488 *
26489 * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
26490 *
26491 *
26492 * The following default rules in CSP affect Angular:
26493 *
26494 * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
26495 * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to
26496 * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be
26497 * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
26498 * weaken the protections offered by CSP.)
26499 *
26500 * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
26501 * This prevents apps from injecting custom styles directly into the document. Angular makes use of
26502 * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
26503 * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
26504 * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
26505 * it is generally not recommended as it would weaken the protections offered by CSP.)
26506 *
26507 * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code
26508 * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
26509 * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
26510 * CSP error to be logged in the console:
26511 *
26512 * ```
26513 * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
26514 * script in the following Content Security Policy directive: "default-src 'self'". Note that
26515 * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
26516 * ```
26517 *
26518 * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
26519 * directive on an element of the HTML document that appears before the `<script>` tag that loads
26520 * the `angular.js` file.
26521 *
26522 * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
26523 *
26524 * You can specify which of the CSP related Angular features should be deactivated by providing
26525 * a value for the `ng-csp` attribute. The options are as follows:
26526 *
26527 * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
26528 *
26529 * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
26530 *
26531 * You can use these values in the following combinations:
26532 *
26533 *
26534 * * No declaration means that Angular will assume that you can do inline styles, but it will do
26535 * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
26536 * versions of Angular.
26537 *
26538 * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
26539 * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
26540 * versions of Angular.
26541 *
26542 * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can
26543 * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
26544 *
26545 * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
26546 * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
26547 *
26548 * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
26549 * styles nor use eval, which is the same as an empty: ng-csp.
26550 * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
26551 *
26552 * @example
26553 * This example shows how to apply the `ngCsp` directive to the `html` tag.
26554 ```html
26555 <!doctype html>
26556 <html ng-app ng-csp>
26557 ...
26558 ...
26559 </html>
26560 ```
26561 * @example
26562 <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
26563 <example name="example.csp" module="cspExample" ng-csp="true">
26564 <file name="index.html">
26565 <div ng-controller="MainController as ctrl">
26566 <div>
26567 <button ng-click="ctrl.inc()" id="inc">Increment</button>
26568 <span id="counter">
26569 {{ctrl.counter}}
26570 </span>
26571 </div>
26572
26573 <div>
26574 <button ng-click="ctrl.evil()" id="evil">Evil</button>
26575 <span id="evilError">
26576 {{ctrl.evilError}}
26577 </span>
26578 </div>
26579 </div>
26580 </file>
26581 <file name="script.js">
26582 angular.module('cspExample', [])
26583 .controller('MainController', function MainController() {
26584 this.counter = 0;
26585 this.inc = function() {
26586 this.counter++;
26587 };
26588 this.evil = function() {
26589 try {
26590 eval('1+2'); // eslint-disable-line no-eval
26591 } catch (e) {
26592 this.evilError = e.message;
26593 }
26594 };
26595 });
26596 </file>
26597 <file name="protractor.js" type="protractor">
26598 var util, webdriver;
26599
26600 var incBtn = element(by.id('inc'));
26601 var counter = element(by.id('counter'));
26602 var evilBtn = element(by.id('evil'));
26603 var evilError = element(by.id('evilError'));
26604
26605 function getAndClearSevereErrors() {
26606 return browser.manage().logs().get('browser').then(function(browserLog) {
26607 return browserLog.filter(function(logEntry) {
26608 return logEntry.level.value > webdriver.logging.Level.WARNING.value;
26609 });
26610 });
26611 }
26612
26613 function clearErrors() {
26614 getAndClearSevereErrors();
26615 }
26616
26617 function expectNoErrors() {
26618 getAndClearSevereErrors().then(function(filteredLog) {
26619 expect(filteredLog.length).toEqual(0);
26620 if (filteredLog.length) {
26621 console.log('browser console errors: ' + util.inspect(filteredLog));
26622 }
26623 });
26624 }
26625
26626 function expectError(regex) {
26627 getAndClearSevereErrors().then(function(filteredLog) {
26628 var found = false;
26629 filteredLog.forEach(function(log) {
26630 if (log.message.match(regex)) {
26631 found = true;
26632 }
26633 });
26634 if (!found) {
26635 throw new Error('expected an error that matches ' + regex);
26636 }
26637 });
26638 }
26639
26640 beforeEach(function() {
26641 util = require('util');
26642 webdriver = require('selenium-webdriver');
26643 });
26644
26645 // For now, we only test on Chrome,
26646 // as Safari does not load the page with Protractor's injected scripts,
26647 // and Firefox webdriver always disables content security policy (#6358)
26648 if (browser.params.browser !== 'chrome') {
26649 return;
26650 }
26651
26652 it('should not report errors when the page is loaded', function() {
26653 // clear errors so we are not dependent on previous tests
26654 clearErrors();
26655 // Need to reload the page as the page is already loaded when
26656 // we come here
26657 browser.driver.getCurrentUrl().then(function(url) {
26658 browser.get(url);
26659 });
26660 expectNoErrors();
26661 });
26662
26663 it('should evaluate expressions', function() {
26664 expect(counter.getText()).toEqual('0');
26665 incBtn.click();
26666 expect(counter.getText()).toEqual('1');
26667 expectNoErrors();
26668 });
26669
26670 it('should throw and report an error when using "eval"', function() {
26671 evilBtn.click();
26672 expect(evilError.getText()).toMatch(/Content Security Policy/);
26673 expectError(/Content Security Policy/);
26674 });
26675 </file>
26676 </example>
26677 */
26678
26679// `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
26680// we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
26681// fn that looks for the `ng-csp` attribute anywhere in the current doc.
26682
26683/**
26684 * @ngdoc directive
26685 * @name ngClick
26686 *
26687 * @description
26688 * The ngClick directive allows you to specify custom behavior when
26689 * an element is clicked.
26690 *
26691 * @element ANY
26692 * @priority 0
26693 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
26694 * click. ({@link guide/expression#-event- Event object is available as `$event`})
26695 *
26696 * @example
26697 <example name="ng-click">
26698 <file name="index.html">
26699 <button ng-click="count = count + 1" ng-init="count=0">
26700 Increment
26701 </button>
26702 <span>
26703 count: {{count}}
26704 </span>
26705 </file>
26706 <file name="protractor.js" type="protractor">
26707 it('should check ng-click', function() {
26708 expect(element(by.binding('count')).getText()).toMatch('0');
26709 element(by.css('button')).click();
26710 expect(element(by.binding('count')).getText()).toMatch('1');
26711 });
26712 </file>
26713 </example>
26714 */
26715/*
26716 * A collection of directives that allows creation of custom event handlers that are defined as
26717 * angular expressions and are compiled and executed within the current scope.
26718 */
26719var ngEventDirectives = {};
26720
26721// For events that might fire synchronously during DOM manipulation
26722// we need to execute their event handlers asynchronously using $evalAsync,
26723// so that they are not executed in an inconsistent state.
26724var forceAsyncEvents = {
26725 'blur': true,
26726 'focus': true
26727};
26728forEach(
26729 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
26730 function(eventName) {
26731 var directiveName = directiveNormalize('ng-' + eventName);
26732 ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
26733 return {
26734 restrict: 'A',
26735 compile: function($element, attr) {
26736 // We expose the powerful $event object on the scope that provides access to the Window,
26737 // etc. that isn't protected by the fast paths in $parse. We explicitly request better
26738 // checks at the cost of speed since event handler expressions are not executed as
26739 // frequently as regular change detection.
26740 var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
26741 return function ngEventHandler(scope, element) {
26742 element.on(eventName, function(event) {
26743 var callback = function() {
26744 fn(scope, {$event:event});
26745 };
26746 if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
26747 scope.$evalAsync(callback);
26748 } else {
26749 scope.$apply(callback);
26750 }
26751 });
26752 };
26753 }
26754 };
26755 }];
26756 }
26757);
26758
26759/**
26760 * @ngdoc directive
26761 * @name ngDblclick
26762 *
26763 * @description
26764 * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
26765 *
26766 * @element ANY
26767 * @priority 0
26768 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
26769 * a dblclick. (The Event object is available as `$event`)
26770 *
26771 * @example
26772 <example name="ng-dblclick">
26773 <file name="index.html">
26774 <button ng-dblclick="count = count + 1" ng-init="count=0">
26775 Increment (on double click)
26776 </button>
26777 count: {{count}}
26778 </file>
26779 </example>
26780 */
26781
26782
26783/**
26784 * @ngdoc directive
26785 * @name ngMousedown
26786 *
26787 * @description
26788 * The ngMousedown directive allows you to specify custom behavior on mousedown event.
26789 *
26790 * @element ANY
26791 * @priority 0
26792 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
26793 * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
26794 *
26795 * @example
26796 <example name="ng-mousedown">
26797 <file name="index.html">
26798 <button ng-mousedown="count = count + 1" ng-init="count=0">
26799 Increment (on mouse down)
26800 </button>
26801 count: {{count}}
26802 </file>
26803 </example>
26804 */
26805
26806
26807/**
26808 * @ngdoc directive
26809 * @name ngMouseup
26810 *
26811 * @description
26812 * Specify custom behavior on mouseup event.
26813 *
26814 * @element ANY
26815 * @priority 0
26816 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
26817 * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
26818 *
26819 * @example
26820 <example name="ng-mouseup">
26821 <file name="index.html">
26822 <button ng-mouseup="count = count + 1" ng-init="count=0">
26823 Increment (on mouse up)
26824 </button>
26825 count: {{count}}
26826 </file>
26827 </example>
26828 */
26829
26830/**
26831 * @ngdoc directive
26832 * @name ngMouseover
26833 *
26834 * @description
26835 * Specify custom behavior on mouseover event.
26836 *
26837 * @element ANY
26838 * @priority 0
26839 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
26840 * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
26841 *
26842 * @example
26843 <example name="ng-mouseover">
26844 <file name="index.html">
26845 <button ng-mouseover="count = count + 1" ng-init="count=0">
26846 Increment (when mouse is over)
26847 </button>
26848 count: {{count}}
26849 </file>
26850 </example>
26851 */
26852
26853
26854/**
26855 * @ngdoc directive
26856 * @name ngMouseenter
26857 *
26858 * @description
26859 * Specify custom behavior on mouseenter event.
26860 *
26861 * @element ANY
26862 * @priority 0
26863 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
26864 * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
26865 *
26866 * @example
26867 <example name="ng-mouseenter">
26868 <file name="index.html">
26869 <button ng-mouseenter="count = count + 1" ng-init="count=0">
26870 Increment (when mouse enters)
26871 </button>
26872 count: {{count}}
26873 </file>
26874 </example>
26875 */
26876
26877
26878/**
26879 * @ngdoc directive
26880 * @name ngMouseleave
26881 *
26882 * @description
26883 * Specify custom behavior on mouseleave event.
26884 *
26885 * @element ANY
26886 * @priority 0
26887 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
26888 * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
26889 *
26890 * @example
26891 <example name="ng-mouseleave">
26892 <file name="index.html">
26893 <button ng-mouseleave="count = count + 1" ng-init="count=0">
26894 Increment (when mouse leaves)
26895 </button>
26896 count: {{count}}
26897 </file>
26898 </example>
26899 */
26900
26901
26902/**
26903 * @ngdoc directive
26904 * @name ngMousemove
26905 *
26906 * @description
26907 * Specify custom behavior on mousemove event.
26908 *
26909 * @element ANY
26910 * @priority 0
26911 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
26912 * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
26913 *
26914 * @example
26915 <example name="ng-mousemove">
26916 <file name="index.html">
26917 <button ng-mousemove="count = count + 1" ng-init="count=0">
26918 Increment (when mouse moves)
26919 </button>
26920 count: {{count}}
26921 </file>
26922 </example>
26923 */
26924
26925
26926/**
26927 * @ngdoc directive
26928 * @name ngKeydown
26929 *
26930 * @description
26931 * Specify custom behavior on keydown event.
26932 *
26933 * @element ANY
26934 * @priority 0
26935 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
26936 * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
26937 *
26938 * @example
26939 <example name="ng-keydown">
26940 <file name="index.html">
26941 <input ng-keydown="count = count + 1" ng-init="count=0">
26942 key down count: {{count}}
26943 </file>
26944 </example>
26945 */
26946
26947
26948/**
26949 * @ngdoc directive
26950 * @name ngKeyup
26951 *
26952 * @description
26953 * Specify custom behavior on keyup event.
26954 *
26955 * @element ANY
26956 * @priority 0
26957 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
26958 * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
26959 *
26960 * @example
26961 <example name="ng-keyup">
26962 <file name="index.html">
26963 <p>Typing in the input box below updates the key count</p>
26964 <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
26965
26966 <p>Typing in the input box below updates the keycode</p>
26967 <input ng-keyup="event=$event">
26968 <p>event keyCode: {{ event.keyCode }}</p>
26969 <p>event altKey: {{ event.altKey }}</p>
26970 </file>
26971 </example>
26972 */
26973
26974
26975/**
26976 * @ngdoc directive
26977 * @name ngKeypress
26978 *
26979 * @description
26980 * Specify custom behavior on keypress event.
26981 *
26982 * @element ANY
26983 * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
26984 * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
26985 * and can be interrogated for keyCode, altKey, etc.)
26986 *
26987 * @example
26988 <example name="ng-keypress">
26989 <file name="index.html">
26990 <input ng-keypress="count = count + 1" ng-init="count=0">
26991 key press count: {{count}}
26992 </file>
26993 </example>
26994 */
26995
26996
26997/**
26998 * @ngdoc directive
26999 * @name ngSubmit
27000 *
27001 * @description
27002 * Enables binding angular expressions to onsubmit events.
27003 *
27004 * Additionally it prevents the default action (which for form means sending the request to the
27005 * server and reloading the current page), but only if the form does not contain `action`,
27006 * `data-action`, or `x-action` attributes.
27007 *
27008 * <div class="alert alert-warning">
27009 * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
27010 * `ngSubmit` handlers together. See the
27011 * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
27012 * for a detailed discussion of when `ngSubmit` may be triggered.
27013 * </div>
27014 *
27015 * @element form
27016 * @priority 0
27017 * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
27018 * ({@link guide/expression#-event- Event object is available as `$event`})
27019 *
27020 * @example
27021 <example module="submitExample" name="ng-submit">
27022 <file name="index.html">
27023 <script>
27024 angular.module('submitExample', [])
27025 .controller('ExampleController', ['$scope', function($scope) {
27026 $scope.list = [];
27027 $scope.text = 'hello';
27028 $scope.submit = function() {
27029 if ($scope.text) {
27030 $scope.list.push(this.text);
27031 $scope.text = '';
27032 }
27033 };
27034 }]);
27035 </script>
27036 <form ng-submit="submit()" ng-controller="ExampleController">
27037 Enter text and hit enter:
27038 <input type="text" ng-model="text" name="text" />
27039 <input type="submit" id="submit" value="Submit" />
27040 <pre>list={{list}}</pre>
27041 </form>
27042 </file>
27043 <file name="protractor.js" type="protractor">
27044 it('should check ng-submit', function() {
27045 expect(element(by.binding('list')).getText()).toBe('list=[]');
27046 element(by.css('#submit')).click();
27047 expect(element(by.binding('list')).getText()).toContain('hello');
27048 expect(element(by.model('text')).getAttribute('value')).toBe('');
27049 });
27050 it('should ignore empty strings', function() {
27051 expect(element(by.binding('list')).getText()).toBe('list=[]');
27052 element(by.css('#submit')).click();
27053 element(by.css('#submit')).click();
27054 expect(element(by.binding('list')).getText()).toContain('hello');
27055 });
27056 </file>
27057 </example>
27058 */
27059
27060/**
27061 * @ngdoc directive
27062 * @name ngFocus
27063 *
27064 * @description
27065 * Specify custom behavior on focus event.
27066 *
27067 * Note: As the `focus` event is executed synchronously when calling `input.focus()`
27068 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
27069 * during an `$apply` to ensure a consistent state.
27070 *
27071 * @element window, input, select, textarea, a
27072 * @priority 0
27073 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
27074 * focus. ({@link guide/expression#-event- Event object is available as `$event`})
27075 *
27076 * @example
27077 * See {@link ng.directive:ngClick ngClick}
27078 */
27079
27080/**
27081 * @ngdoc directive
27082 * @name ngBlur
27083 *
27084 * @description
27085 * Specify custom behavior on blur event.
27086 *
27087 * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
27088 * an element has lost focus.
27089 *
27090 * Note: As the `blur` event is executed synchronously also during DOM manipulations
27091 * (e.g. removing a focussed input),
27092 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
27093 * during an `$apply` to ensure a consistent state.
27094 *
27095 * @element window, input, select, textarea, a
27096 * @priority 0
27097 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
27098 * blur. ({@link guide/expression#-event- Event object is available as `$event`})
27099 *
27100 * @example
27101 * See {@link ng.directive:ngClick ngClick}
27102 */
27103
27104/**
27105 * @ngdoc directive
27106 * @name ngCopy
27107 *
27108 * @description
27109 * Specify custom behavior on copy event.
27110 *
27111 * @element window, input, select, textarea, a
27112 * @priority 0
27113 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
27114 * copy. ({@link guide/expression#-event- Event object is available as `$event`})
27115 *
27116 * @example
27117 <example name="ng-copy">
27118 <file name="index.html">
27119 <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
27120 copied: {{copied}}
27121 </file>
27122 </example>
27123 */
27124
27125/**
27126 * @ngdoc directive
27127 * @name ngCut
27128 *
27129 * @description
27130 * Specify custom behavior on cut event.
27131 *
27132 * @element window, input, select, textarea, a
27133 * @priority 0
27134 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
27135 * cut. ({@link guide/expression#-event- Event object is available as `$event`})
27136 *
27137 * @example
27138 <example name="ng-cut">
27139 <file name="index.html">
27140 <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
27141 cut: {{cut}}
27142 </file>
27143 </example>
27144 */
27145
27146/**
27147 * @ngdoc directive
27148 * @name ngPaste
27149 *
27150 * @description
27151 * Specify custom behavior on paste event.
27152 *
27153 * @element window, input, select, textarea, a
27154 * @priority 0
27155 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
27156 * paste. ({@link guide/expression#-event- Event object is available as `$event`})
27157 *
27158 * @example
27159 <example name="ng-paste">
27160 <file name="index.html">
27161 <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
27162 pasted: {{paste}}
27163 </file>
27164 </example>
27165 */
27166
27167/**
27168 * @ngdoc directive
27169 * @name ngIf
27170 * @restrict A
27171 * @multiElement
27172 *
27173 * @description
27174 * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
27175 * {expression}. If the expression assigned to `ngIf` evaluates to a false
27176 * value then the element is removed from the DOM, otherwise a clone of the
27177 * element is reinserted into the DOM.
27178 *
27179 * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
27180 * element in the DOM rather than changing its visibility via the `display` css property. A common
27181 * case when this difference is significant is when using css selectors that rely on an element's
27182 * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
27183 *
27184 * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
27185 * is created when the element is restored. The scope created within `ngIf` inherits from
27186 * its parent scope using
27187 * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
27188 * An important implication of this is if `ngModel` is used within `ngIf` to bind to
27189 * a javascript primitive defined in the parent scope. In this case any modifications made to the
27190 * variable within the child scope will override (hide) the value in the parent scope.
27191 *
27192 * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
27193 * is if an element's class attribute is directly modified after it's compiled, using something like
27194 * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
27195 * the added class will be lost because the original compiled state is used to regenerate the element.
27196 *
27197 * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
27198 * and `leave` effects.
27199 *
27200 * @animations
27201 * | Animation | Occurs |
27202 * |----------------------------------|-------------------------------------|
27203 * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
27204 * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
27205 *
27206 * @element ANY
27207 * @scope
27208 * @priority 600
27209 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
27210 * the element is removed from the DOM tree. If it is truthy a copy of the compiled
27211 * element is added to the DOM tree.
27212 *
27213 * @example
27214 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
27215 <file name="index.html">
27216 <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
27217 Show when checked:
27218 <span ng-if="checked" class="animate-if">
27219 This is removed when the checkbox is unchecked.
27220 </span>
27221 </file>
27222 <file name="animations.css">
27223 .animate-if {
27224 background:white;
27225 border:1px solid black;
27226 padding:10px;
27227 }
27228
27229 .animate-if.ng-enter, .animate-if.ng-leave {
27230 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
27231 }
27232
27233 .animate-if.ng-enter,
27234 .animate-if.ng-leave.ng-leave-active {
27235 opacity:0;
27236 }
27237
27238 .animate-if.ng-leave,
27239 .animate-if.ng-enter.ng-enter-active {
27240 opacity:1;
27241 }
27242 </file>
27243 </example>
27244 */
27245var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
27246 return {
27247 multiElement: true,
27248 transclude: 'element',
27249 priority: 600,
27250 terminal: true,
27251 restrict: 'A',
27252 $$tlb: true,
27253 link: function($scope, $element, $attr, ctrl, $transclude) {
27254 var block, childScope, previousElements;
27255 $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
27256
27257 if (value) {
27258 if (!childScope) {
27259 $transclude(function(clone, newScope) {
27260 childScope = newScope;
27261 clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
27262 // Note: We only need the first/last node of the cloned nodes.
27263 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
27264 // by a directive with templateUrl when its template arrives.
27265 block = {
27266 clone: clone
27267 };
27268 $animate.enter(clone, $element.parent(), $element);
27269 });
27270 }
27271 } else {
27272 if (previousElements) {
27273 previousElements.remove();
27274 previousElements = null;
27275 }
27276 if (childScope) {
27277 childScope.$destroy();
27278 childScope = null;
27279 }
27280 if (block) {
27281 previousElements = getBlockNodes(block.clone);
27282 $animate.leave(previousElements).done(function(response) {
27283 if (response !== false) previousElements = null;
27284 });
27285 block = null;
27286 }
27287 }
27288 });
27289 }
27290 };
27291}];
27292
27293/**
27294 * @ngdoc directive
27295 * @name ngInclude
27296 * @restrict ECA
27297 *
27298 * @description
27299 * Fetches, compiles and includes an external HTML fragment.
27300 *
27301 * By default, the template URL is restricted to the same domain and protocol as the
27302 * application document. This is done by calling {@link $sce#getTrustedResourceUrl
27303 * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
27304 * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
27305 * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
27306 * ng.$sce Strict Contextual Escaping}.
27307 *
27308 * In addition, the browser's
27309 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
27310 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
27311 * policy may further restrict whether the template is successfully loaded.
27312 * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
27313 * access on some browsers.
27314 *
27315 * @animations
27316 * | Animation | Occurs |
27317 * |----------------------------------|-------------------------------------|
27318 * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
27319 * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
27320 *
27321 * The enter and leave animation occur concurrently.
27322 *
27323 * @scope
27324 * @priority 400
27325 *
27326 * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
27327 * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
27328 * @param {string=} onload Expression to evaluate when a new partial is loaded.
27329 * <div class="alert alert-warning">
27330 * **Note:** When using onload on SVG elements in IE11, the browser will try to call
27331 * a function with the name on the window element, which will usually throw a
27332 * "function is undefined" error. To fix this, you can instead use `data-onload` or a
27333 * different form that {@link guide/directive#normalization matches} `onload`.
27334 * </div>
27335 *
27336 * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
27337 * $anchorScroll} to scroll the viewport after the content is loaded.
27338 *
27339 * - If the attribute is not set, disable scrolling.
27340 * - If the attribute is set without value, enable scrolling.
27341 * - Otherwise enable scrolling only if the expression evaluates to truthy value.
27342 *
27343 * @example
27344 <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
27345 <file name="index.html">
27346 <div ng-controller="ExampleController">
27347 <select ng-model="template" ng-options="t.name for t in templates">
27348 <option value="">(blank)</option>
27349 </select>
27350 url of the template: <code>{{template.url}}</code>
27351 <hr/>
27352 <div class="slide-animate-container">
27353 <div class="slide-animate" ng-include="template.url"></div>
27354 </div>
27355 </div>
27356 </file>
27357 <file name="script.js">
27358 angular.module('includeExample', ['ngAnimate'])
27359 .controller('ExampleController', ['$scope', function($scope) {
27360 $scope.templates =
27361 [{ name: 'template1.html', url: 'template1.html'},
27362 { name: 'template2.html', url: 'template2.html'}];
27363 $scope.template = $scope.templates[0];
27364 }]);
27365 </file>
27366 <file name="template1.html">
27367 Content of template1.html
27368 </file>
27369 <file name="template2.html">
27370 Content of template2.html
27371 </file>
27372 <file name="animations.css">
27373 .slide-animate-container {
27374 position:relative;
27375 background:white;
27376 border:1px solid black;
27377 height:40px;
27378 overflow:hidden;
27379 }
27380
27381 .slide-animate {
27382 padding:10px;
27383 }
27384
27385 .slide-animate.ng-enter, .slide-animate.ng-leave {
27386 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
27387
27388 position:absolute;
27389 top:0;
27390 left:0;
27391 right:0;
27392 bottom:0;
27393 display:block;
27394 padding:10px;
27395 }
27396
27397 .slide-animate.ng-enter {
27398 top:-50px;
27399 }
27400 .slide-animate.ng-enter.ng-enter-active {
27401 top:0;
27402 }
27403
27404 .slide-animate.ng-leave {
27405 top:0;
27406 }
27407 .slide-animate.ng-leave.ng-leave-active {
27408 top:50px;
27409 }
27410 </file>
27411 <file name="protractor.js" type="protractor">
27412 var templateSelect = element(by.model('template'));
27413 var includeElem = element(by.css('[ng-include]'));
27414
27415 it('should load template1.html', function() {
27416 expect(includeElem.getText()).toMatch(/Content of template1.html/);
27417 });
27418
27419 it('should load template2.html', function() {
27420 if (browser.params.browser === 'firefox') {
27421 // Firefox can't handle using selects
27422 // See https://github.com/angular/protractor/issues/480
27423 return;
27424 }
27425 templateSelect.click();
27426 templateSelect.all(by.css('option')).get(2).click();
27427 expect(includeElem.getText()).toMatch(/Content of template2.html/);
27428 });
27429
27430 it('should change to blank', function() {
27431 if (browser.params.browser === 'firefox') {
27432 // Firefox can't handle using selects
27433 return;
27434 }
27435 templateSelect.click();
27436 templateSelect.all(by.css('option')).get(0).click();
27437 expect(includeElem.isPresent()).toBe(false);
27438 });
27439 </file>
27440 </example>
27441 */
27442
27443
27444/**
27445 * @ngdoc event
27446 * @name ngInclude#$includeContentRequested
27447 * @eventType emit on the scope ngInclude was declared in
27448 * @description
27449 * Emitted every time the ngInclude content is requested.
27450 *
27451 * @param {Object} angularEvent Synthetic event object.
27452 * @param {String} src URL of content to load.
27453 */
27454
27455
27456/**
27457 * @ngdoc event
27458 * @name ngInclude#$includeContentLoaded
27459 * @eventType emit on the current ngInclude scope
27460 * @description
27461 * Emitted every time the ngInclude content is reloaded.
27462 *
27463 * @param {Object} angularEvent Synthetic event object.
27464 * @param {String} src URL of content to load.
27465 */
27466
27467
27468/**
27469 * @ngdoc event
27470 * @name ngInclude#$includeContentError
27471 * @eventType emit on the scope ngInclude was declared in
27472 * @description
27473 * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
27474 *
27475 * @param {Object} angularEvent Synthetic event object.
27476 * @param {String} src URL of content to load.
27477 */
27478var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
27479 function($templateRequest, $anchorScroll, $animate) {
27480 return {
27481 restrict: 'ECA',
27482 priority: 400,
27483 terminal: true,
27484 transclude: 'element',
27485 controller: angular.noop,
27486 compile: function(element, attr) {
27487 var srcExp = attr.ngInclude || attr.src,
27488 onloadExp = attr.onload || '',
27489 autoScrollExp = attr.autoscroll;
27490
27491 return function(scope, $element, $attr, ctrl, $transclude) {
27492 var changeCounter = 0,
27493 currentScope,
27494 previousElement,
27495 currentElement;
27496
27497 var cleanupLastIncludeContent = function() {
27498 if (previousElement) {
27499 previousElement.remove();
27500 previousElement = null;
27501 }
27502 if (currentScope) {
27503 currentScope.$destroy();
27504 currentScope = null;
27505 }
27506 if (currentElement) {
27507 $animate.leave(currentElement).done(function(response) {
27508 if (response !== false) previousElement = null;
27509 });
27510 previousElement = currentElement;
27511 currentElement = null;
27512 }
27513 };
27514
27515 scope.$watch(srcExp, function ngIncludeWatchAction(src) {
27516 var afterAnimation = function(response) {
27517 if (response !== false && isDefined(autoScrollExp) &&
27518 (!autoScrollExp || scope.$eval(autoScrollExp))) {
27519 $anchorScroll();
27520 }
27521 };
27522 var thisChangeId = ++changeCounter;
27523
27524 if (src) {
27525 //set the 2nd param to true to ignore the template request error so that the inner
27526 //contents and scope can be cleaned up.
27527 $templateRequest(src, true).then(function(response) {
27528 if (scope.$$destroyed) return;
27529
27530 if (thisChangeId !== changeCounter) return;
27531 var newScope = scope.$new();
27532 ctrl.template = response;
27533
27534 // Note: This will also link all children of ng-include that were contained in the original
27535 // html. If that content contains controllers, ... they could pollute/change the scope.
27536 // However, using ng-include on an element with additional content does not make sense...
27537 // Note: We can't remove them in the cloneAttchFn of $transclude as that
27538 // function is called before linking the content, which would apply child
27539 // directives to non existing elements.
27540 var clone = $transclude(newScope, function(clone) {
27541 cleanupLastIncludeContent();
27542 $animate.enter(clone, null, $element).done(afterAnimation);
27543 });
27544
27545 currentScope = newScope;
27546 currentElement = clone;
27547
27548 currentScope.$emit('$includeContentLoaded', src);
27549 scope.$eval(onloadExp);
27550 }, function() {
27551 if (scope.$$destroyed) return;
27552
27553 if (thisChangeId === changeCounter) {
27554 cleanupLastIncludeContent();
27555 scope.$emit('$includeContentError', src);
27556 }
27557 });
27558 scope.$emit('$includeContentRequested', src);
27559 } else {
27560 cleanupLastIncludeContent();
27561 ctrl.template = null;
27562 }
27563 });
27564 };
27565 }
27566 };
27567}];
27568
27569// This directive is called during the $transclude call of the first `ngInclude` directive.
27570// It will replace and compile the content of the element with the loaded template.
27571// We need this directive so that the element content is already filled when
27572// the link function of another directive on the same element as ngInclude
27573// is called.
27574var ngIncludeFillContentDirective = ['$compile',
27575 function($compile) {
27576 return {
27577 restrict: 'ECA',
27578 priority: -400,
27579 require: 'ngInclude',
27580 link: function(scope, $element, $attr, ctrl) {
27581 if (toString.call($element[0]).match(/SVG/)) {
27582 // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
27583 // support innerHTML, so detect this here and try to generate the contents
27584 // specially.
27585 $element.empty();
27586 $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
27587 function namespaceAdaptedClone(clone) {
27588 $element.append(clone);
27589 }, {futureParentElement: $element});
27590 return;
27591 }
27592
27593 $element.html(ctrl.template);
27594 $compile($element.contents())(scope);
27595 }
27596 };
27597 }];
27598
27599/**
27600 * @ngdoc directive
27601 * @name ngInit
27602 * @restrict AC
27603 *
27604 * @description
27605 * The `ngInit` directive allows you to evaluate an expression in the
27606 * current scope.
27607 *
27608 * <div class="alert alert-danger">
27609 * This directive can be abused to add unnecessary amounts of logic into your templates.
27610 * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
27611 * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
27612 * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
27613 * rather than `ngInit` to initialize values on a scope.
27614 * </div>
27615 *
27616 * <div class="alert alert-warning">
27617 * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
27618 * sure you have parentheses to ensure correct operator precedence:
27619 * <pre class="prettyprint">
27620 * `<div ng-init="test1 = ($index | toString)"></div>`
27621 * </pre>
27622 * </div>
27623 *
27624 * @priority 450
27625 *
27626 * @element ANY
27627 * @param {expression} ngInit {@link guide/expression Expression} to eval.
27628 *
27629 * @example
27630 <example module="initExample" name="ng-init">
27631 <file name="index.html">
27632 <script>
27633 angular.module('initExample', [])
27634 .controller('ExampleController', ['$scope', function($scope) {
27635 $scope.list = [['a', 'b'], ['c', 'd']];
27636 }]);
27637 </script>
27638 <div ng-controller="ExampleController">
27639 <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
27640 <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
27641 <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
27642 </div>
27643 </div>
27644 </div>
27645 </file>
27646 <file name="protractor.js" type="protractor">
27647 it('should alias index positions', function() {
27648 var elements = element.all(by.css('.example-init'));
27649 expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
27650 expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
27651 expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
27652 expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
27653 });
27654 </file>
27655 </example>
27656 */
27657var ngInitDirective = ngDirective({
27658 priority: 450,
27659 compile: function() {
27660 return {
27661 pre: function(scope, element, attrs) {
27662 scope.$eval(attrs.ngInit);
27663 }
27664 };
27665 }
27666});
27667
27668/**
27669 * @ngdoc directive
27670 * @name ngList
27671 *
27672 * @description
27673 * Text input that converts between a delimited string and an array of strings. The default
27674 * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
27675 * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
27676 *
27677 * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
27678 * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
27679 * list item is respected. This implies that the user of the directive is responsible for
27680 * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
27681 * tab or newline character.
27682 * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
27683 * when joining the list items back together) and whitespace around each list item is stripped
27684 * before it is added to the model.
27685 *
27686 * ### Example with Validation
27687 *
27688 * <example name="ngList-directive" module="listExample">
27689 * <file name="app.js">
27690 * angular.module('listExample', [])
27691 * .controller('ExampleController', ['$scope', function($scope) {
27692 * $scope.names = ['morpheus', 'neo', 'trinity'];
27693 * }]);
27694 * </file>
27695 * <file name="index.html">
27696 * <form name="myForm" ng-controller="ExampleController">
27697 * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
27698 * <span role="alert">
27699 * <span class="error" ng-show="myForm.namesInput.$error.required">
27700 * Required!</span>
27701 * </span>
27702 * <br>
27703 * <tt>names = {{names}}</tt><br/>
27704 * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
27705 * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
27706 * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
27707 * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
27708 * </form>
27709 * </file>
27710 * <file name="protractor.js" type="protractor">
27711 * var listInput = element(by.model('names'));
27712 * var names = element(by.exactBinding('names'));
27713 * var valid = element(by.binding('myForm.namesInput.$valid'));
27714 * var error = element(by.css('span.error'));
27715 *
27716 * it('should initialize to model', function() {
27717 * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
27718 * expect(valid.getText()).toContain('true');
27719 * expect(error.getCssValue('display')).toBe('none');
27720 * });
27721 *
27722 * it('should be invalid if empty', function() {
27723 * listInput.clear();
27724 * listInput.sendKeys('');
27725 *
27726 * expect(names.getText()).toContain('');
27727 * expect(valid.getText()).toContain('false');
27728 * expect(error.getCssValue('display')).not.toBe('none');
27729 * });
27730 * </file>
27731 * </example>
27732 *
27733 * ### Example - splitting on newline
27734 * <example name="ngList-directive-newlines">
27735 * <file name="index.html">
27736 * <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
27737 * <pre>{{ list | json }}</pre>
27738 * </file>
27739 * <file name="protractor.js" type="protractor">
27740 * it("should split the text by newlines", function() {
27741 * var listInput = element(by.model('list'));
27742 * var output = element(by.binding('list | json'));
27743 * listInput.sendKeys('abc\ndef\nghi');
27744 * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
27745 * });
27746 * </file>
27747 * </example>
27748 *
27749 * @element input
27750 * @param {string=} ngList optional delimiter that should be used to split the value.
27751 */
27752var ngListDirective = function() {
27753 return {
27754 restrict: 'A',
27755 priority: 100,
27756 require: 'ngModel',
27757 link: function(scope, element, attr, ctrl) {
27758 var ngList = attr.ngList || ', ';
27759 var trimValues = attr.ngTrim !== 'false';
27760 var separator = trimValues ? trim(ngList) : ngList;
27761
27762 var parse = function(viewValue) {
27763 // If the viewValue is invalid (say required but empty) it will be `undefined`
27764 if (isUndefined(viewValue)) return;
27765
27766 var list = [];
27767
27768 if (viewValue) {
27769 forEach(viewValue.split(separator), function(value) {
27770 if (value) list.push(trimValues ? trim(value) : value);
27771 });
27772 }
27773
27774 return list;
27775 };
27776
27777 ctrl.$parsers.push(parse);
27778 ctrl.$formatters.push(function(value) {
27779 if (isArray(value)) {
27780 return value.join(ngList);
27781 }
27782
27783 return undefined;
27784 });
27785
27786 // Override the standard $isEmpty because an empty array means the input is empty.
27787 ctrl.$isEmpty = function(value) {
27788 return !value || !value.length;
27789 };
27790 }
27791 };
27792};
27793
27794/* global VALID_CLASS: true,
27795 INVALID_CLASS: true,
27796 PRISTINE_CLASS: true,
27797 DIRTY_CLASS: true,
27798 UNTOUCHED_CLASS: true,
27799 TOUCHED_CLASS: true,
27800 PENDING_CLASS: true,
27801 addSetValidityMethod: true,
27802 setupValidity: true,
27803 defaultModelOptions: false
27804*/
27805
27806
27807var VALID_CLASS = 'ng-valid',
27808 INVALID_CLASS = 'ng-invalid',
27809 PRISTINE_CLASS = 'ng-pristine',
27810 DIRTY_CLASS = 'ng-dirty',
27811 UNTOUCHED_CLASS = 'ng-untouched',
27812 TOUCHED_CLASS = 'ng-touched',
27813 EMPTY_CLASS = 'ng-empty',
27814 NOT_EMPTY_CLASS = 'ng-not-empty';
27815
27816var ngModelMinErr = minErr('ngModel');
27817
27818/**
27819 * @ngdoc type
27820 * @name ngModel.NgModelController
27821 *
27822 * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
27823 * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
27824 * is set.
27825 * @property {*} $modelValue The value in the model that the control is bound to.
27826 * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
27827 the control reads value from the DOM. The functions are called in array order, each passing
27828 its return value through to the next. The last return value is forwarded to the
27829 {@link ngModel.NgModelController#$validators `$validators`} collection.
27830
27831Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
27832`$viewValue`}.
27833
27834Returning `undefined` from a parser means a parse error occurred. In that case,
27835no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
27836will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
27837is set to `true`. The parse error is stored in `ngModel.$error.parse`.
27838
27839 *
27840 * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
27841 the model value changes. The functions are called in reverse array order, each passing the value through to the
27842 next. The last return value is used as the actual DOM value.
27843 Used to format / convert values for display in the control.
27844 * ```js
27845 * function formatter(value) {
27846 * if (value) {
27847 * return value.toUpperCase();
27848 * }
27849 * }
27850 * ngModel.$formatters.push(formatter);
27851 * ```
27852 *
27853 * @property {Object.<string, function>} $validators A collection of validators that are applied
27854 * whenever the model value changes. The key value within the object refers to the name of the
27855 * validator while the function refers to the validation operation. The validation operation is
27856 * provided with the model value as an argument and must return a true or false value depending
27857 * on the response of that validation.
27858 *
27859 * ```js
27860 * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
27861 * var value = modelValue || viewValue;
27862 * return /[0-9]+/.test(value) &&
27863 * /[a-z]+/.test(value) &&
27864 * /[A-Z]+/.test(value) &&
27865 * /\W+/.test(value);
27866 * };
27867 * ```
27868 *
27869 * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
27870 * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
27871 * is expected to return a promise when it is run during the model validation process. Once the promise
27872 * is delivered then the validation status will be set to true when fulfilled and false when rejected.
27873 * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
27874 * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
27875 * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
27876 * will only run once all synchronous validators have passed.
27877 *
27878 * Please note that if $http is used then it is important that the server returns a success HTTP response code
27879 * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
27880 *
27881 * ```js
27882 * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
27883 * var value = modelValue || viewValue;
27884 *
27885 * // Lookup user by username
27886 * return $http.get('/api/users/' + value).
27887 * then(function resolved() {
27888 * //username exists, this means validation fails
27889 * return $q.reject('exists');
27890 * }, function rejected() {
27891 * //username does not exist, therefore this validation passes
27892 * return true;
27893 * });
27894 * };
27895 * ```
27896 *
27897 * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
27898 * view value has changed. It is called with no arguments, and its return value is ignored.
27899 * This can be used in place of additional $watches against the model value.
27900 *
27901 * @property {Object} $error An object hash with all failing validator ids as keys.
27902 * @property {Object} $pending An object hash with all pending validator ids as keys.
27903 *
27904 * @property {boolean} $untouched True if control has not lost focus yet.
27905 * @property {boolean} $touched True if control has lost focus.
27906 * @property {boolean} $pristine True if user has not interacted with the control yet.
27907 * @property {boolean} $dirty True if user has already interacted with the control.
27908 * @property {boolean} $valid True if there is no error.
27909 * @property {boolean} $invalid True if at least one error on the control.
27910 * @property {string} $name The name attribute of the control.
27911 *
27912 * @description
27913 *
27914 * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
27915 * The controller contains services for data-binding, validation, CSS updates, and value formatting
27916 * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
27917 * listening to DOM events.
27918 * Such DOM related logic should be provided by other directives which make use of
27919 * `NgModelController` for data-binding to control elements.
27920 * Angular provides this DOM logic for most {@link input `input`} elements.
27921 * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
27922 * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
27923 *
27924 * @example
27925 * ### Custom Control Example
27926 * This example shows how to use `NgModelController` with a custom control to achieve
27927 * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
27928 * collaborate together to achieve the desired result.
27929 *
27930 * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
27931 * contents be edited in place by the user.
27932 *
27933 * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
27934 * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
27935 * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
27936 * that content using the `$sce` service.
27937 *
27938 * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
27939 <file name="style.css">
27940 [contenteditable] {
27941 border: 1px solid black;
27942 background-color: white;
27943 min-height: 20px;
27944 }
27945
27946 .ng-invalid {
27947 border: 1px solid red;
27948 }
27949
27950 </file>
27951 <file name="script.js">
27952 angular.module('customControl', ['ngSanitize']).
27953 directive('contenteditable', ['$sce', function($sce) {
27954 return {
27955 restrict: 'A', // only activate on element attribute
27956 require: '?ngModel', // get a hold of NgModelController
27957 link: function(scope, element, attrs, ngModel) {
27958 if (!ngModel) return; // do nothing if no ng-model
27959
27960 // Specify how UI should be updated
27961 ngModel.$render = function() {
27962 element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
27963 };
27964
27965 // Listen for change events to enable binding
27966 element.on('blur keyup change', function() {
27967 scope.$evalAsync(read);
27968 });
27969 read(); // initialize
27970
27971 // Write data to the model
27972 function read() {
27973 var html = element.html();
27974 // When we clear the content editable the browser leaves a <br> behind
27975 // If strip-br attribute is provided then we strip this out
27976 if (attrs.stripBr && html === '<br>') {
27977 html = '';
27978 }
27979 ngModel.$setViewValue(html);
27980 }
27981 }
27982 };
27983 }]);
27984 </file>
27985 <file name="index.html">
27986 <form name="myForm">
27987 <div contenteditable
27988 name="myWidget" ng-model="userContent"
27989 strip-br="true"
27990 required>Change me!</div>
27991 <span ng-show="myForm.myWidget.$error.required">Required!</span>
27992 <hr>
27993 <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
27994 </form>
27995 </file>
27996 <file name="protractor.js" type="protractor">
27997 it('should data-bind and become invalid', function() {
27998 if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
27999 // SafariDriver can't handle contenteditable
28000 // and Firefox driver can't clear contenteditables very well
28001 return;
28002 }
28003 var contentEditable = element(by.css('[contenteditable]'));
28004 var content = 'Change me!';
28005
28006 expect(contentEditable.getText()).toEqual(content);
28007
28008 contentEditable.clear();
28009 contentEditable.sendKeys(protractor.Key.BACK_SPACE);
28010 expect(contentEditable.getText()).toEqual('');
28011 expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
28012 });
28013 </file>
28014 * </example>
28015 *
28016 *
28017 */
28018NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
28019function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
28020 this.$viewValue = Number.NaN;
28021 this.$modelValue = Number.NaN;
28022 this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
28023 this.$validators = {};
28024 this.$asyncValidators = {};
28025 this.$parsers = [];
28026 this.$formatters = [];
28027 this.$viewChangeListeners = [];
28028 this.$untouched = true;
28029 this.$touched = false;
28030 this.$pristine = true;
28031 this.$dirty = false;
28032 this.$valid = true;
28033 this.$invalid = false;
28034 this.$error = {}; // keep invalid keys here
28035 this.$$success = {}; // keep valid keys here
28036 this.$pending = undefined; // keep pending keys here
28037 this.$name = $interpolate($attr.name || '', false)($scope);
28038 this.$$parentForm = nullFormCtrl;
28039 this.$options = defaultModelOptions;
28040
28041 this.$$parsedNgModel = $parse($attr.ngModel);
28042 this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
28043 this.$$ngModelGet = this.$$parsedNgModel;
28044 this.$$ngModelSet = this.$$parsedNgModelAssign;
28045 this.$$pendingDebounce = null;
28046 this.$$parserValid = undefined;
28047
28048 this.$$currentValidationRunId = 0;
28049
28050 this.$$scope = $scope;
28051 this.$$attr = $attr;
28052 this.$$element = $element;
28053 this.$$animate = $animate;
28054 this.$$timeout = $timeout;
28055 this.$$parse = $parse;
28056 this.$$q = $q;
28057 this.$$exceptionHandler = $exceptionHandler;
28058
28059 setupValidity(this);
28060 setupModelWatcher(this);
28061}
28062
28063NgModelController.prototype = {
28064 $$initGetterSetters: function() {
28065 if (this.$options.getOption('getterSetter')) {
28066 var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
28067 invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
28068
28069 this.$$ngModelGet = function($scope) {
28070 var modelValue = this.$$parsedNgModel($scope);
28071 if (isFunction(modelValue)) {
28072 modelValue = invokeModelGetter($scope);
28073 }
28074 return modelValue;
28075 };
28076 this.$$ngModelSet = function($scope, newValue) {
28077 if (isFunction(this.$$parsedNgModel($scope))) {
28078 invokeModelSetter($scope, {$$$p: newValue});
28079 } else {
28080 this.$$parsedNgModelAssign($scope, newValue);
28081 }
28082 };
28083 } else if (!this.$$parsedNgModel.assign) {
28084 throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
28085 this.$$attr.ngModel, startingTag(this.$$element));
28086 }
28087 },
28088
28089
28090 /**
28091 * @ngdoc method
28092 * @name ngModel.NgModelController#$render
28093 *
28094 * @description
28095 * Called when the view needs to be updated. It is expected that the user of the ng-model
28096 * directive will implement this method.
28097 *
28098 * The `$render()` method is invoked in the following situations:
28099 *
28100 * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
28101 * committed value then `$render()` is called to update the input control.
28102 * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
28103 * the `$viewValue` are different from last time.
28104 *
28105 * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
28106 * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
28107 * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
28108 * invoked if you only change a property on the objects.
28109 */
28110 $render: noop,
28111
28112 /**
28113 * @ngdoc method
28114 * @name ngModel.NgModelController#$isEmpty
28115 *
28116 * @description
28117 * This is called when we need to determine if the value of an input is empty.
28118 *
28119 * For instance, the required directive does this to work out if the input has data or not.
28120 *
28121 * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
28122 *
28123 * You can override this for input directives whose concept of being empty is different from the
28124 * default. The `checkboxInputType` directive does this because in its case a value of `false`
28125 * implies empty.
28126 *
28127 * @param {*} value The value of the input to check for emptiness.
28128 * @returns {boolean} True if `value` is "empty".
28129 */
28130 $isEmpty: function(value) {
28131 // eslint-disable-next-line no-self-compare
28132 return isUndefined(value) || value === '' || value === null || value !== value;
28133 },
28134
28135 $$updateEmptyClasses: function(value) {
28136 if (this.$isEmpty(value)) {
28137 this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
28138 this.$$animate.addClass(this.$$element, EMPTY_CLASS);
28139 } else {
28140 this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
28141 this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
28142 }
28143 },
28144
28145 /**
28146 * @ngdoc method
28147 * @name ngModel.NgModelController#$setPristine
28148 *
28149 * @description
28150 * Sets the control to its pristine state.
28151 *
28152 * This method can be called to remove the `ng-dirty` class and set the control to its pristine
28153 * state (`ng-pristine` class). A model is considered to be pristine when the control
28154 * has not been changed from when first compiled.
28155 */
28156 $setPristine: function() {
28157 this.$dirty = false;
28158 this.$pristine = true;
28159 this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
28160 this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
28161 },
28162
28163 /**
28164 * @ngdoc method
28165 * @name ngModel.NgModelController#$setDirty
28166 *
28167 * @description
28168 * Sets the control to its dirty state.
28169 *
28170 * This method can be called to remove the `ng-pristine` class and set the control to its dirty
28171 * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
28172 * from when first compiled.
28173 */
28174 $setDirty: function() {
28175 this.$dirty = true;
28176 this.$pristine = false;
28177 this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
28178 this.$$animate.addClass(this.$$element, DIRTY_CLASS);
28179 this.$$parentForm.$setDirty();
28180 },
28181
28182 /**
28183 * @ngdoc method
28184 * @name ngModel.NgModelController#$setUntouched
28185 *
28186 * @description
28187 * Sets the control to its untouched state.
28188 *
28189 * This method can be called to remove the `ng-touched` class and set the control to its
28190 * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
28191 * by default, however this function can be used to restore that state if the model has
28192 * already been touched by the user.
28193 */
28194 $setUntouched: function() {
28195 this.$touched = false;
28196 this.$untouched = true;
28197 this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
28198 },
28199
28200 /**
28201 * @ngdoc method
28202 * @name ngModel.NgModelController#$setTouched
28203 *
28204 * @description
28205 * Sets the control to its touched state.
28206 *
28207 * This method can be called to remove the `ng-untouched` class and set the control to its
28208 * touched state (`ng-touched` class). A model is considered to be touched when the user has
28209 * first focused the control element and then shifted focus away from the control (blur event).
28210 */
28211 $setTouched: function() {
28212 this.$touched = true;
28213 this.$untouched = false;
28214 this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
28215 },
28216
28217 /**
28218 * @ngdoc method
28219 * @name ngModel.NgModelController#$rollbackViewValue
28220 *
28221 * @description
28222 * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
28223 * which may be caused by a pending debounced event or because the input is waiting for some
28224 * future event.
28225 *
28226 * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
28227 * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
28228 * sync with the ngModel's `$modelValue`.
28229 *
28230 * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
28231 * and reset the input to the last committed view value.
28232 *
28233 * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
28234 * programmatically before these debounced/future events have resolved/occurred, because Angular's
28235 * dirty checking mechanism is not able to tell whether the model has actually changed or not.
28236 *
28237 * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
28238 * input which may have such events pending. This is important in order to make sure that the
28239 * input field will be updated with the new model value and any pending operations are cancelled.
28240 *
28241 * <example name="ng-model-cancel-update" module="cancel-update-example">
28242 * <file name="app.js">
28243 * angular.module('cancel-update-example', [])
28244 *
28245 * .controller('CancelUpdateController', ['$scope', function($scope) {
28246 * $scope.model = {value1: '', value2: ''};
28247 *
28248 * $scope.setEmpty = function(e, value, rollback) {
28249 * if (e.keyCode === 27) {
28250 * e.preventDefault();
28251 * if (rollback) {
28252 * $scope.myForm[value].$rollbackViewValue();
28253 * }
28254 * $scope.model[value] = '';
28255 * }
28256 * };
28257 * }]);
28258 * </file>
28259 * <file name="index.html">
28260 * <div ng-controller="CancelUpdateController">
28261 * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
28262 * empty them. Follow these steps and observe the difference:</p>
28263 * <ol>
28264 * <li>Type something in the input. You will see that the model is not yet updated</li>
28265 * <li>Press the Escape key.
28266 * <ol>
28267 * <li> In the first example, nothing happens, because the model is already '', and no
28268 * update is detected. If you blur the input, the model will be set to the current view.
28269 * </li>
28270 * <li> In the second example, the pending update is cancelled, and the input is set back
28271 * to the last committed view value (''). Blurring the input does nothing.
28272 * </li>
28273 * </ol>
28274 * </li>
28275 * </ol>
28276 *
28277 * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
28278 * <div>
28279 * <p id="inputDescription1">Without $rollbackViewValue():</p>
28280 * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
28281 * ng-keydown="setEmpty($event, 'value1')">
28282 * value1: "{{ model.value1 }}"
28283 * </div>
28284 *
28285 * <div>
28286 * <p id="inputDescription2">With $rollbackViewValue():</p>
28287 * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
28288 * ng-keydown="setEmpty($event, 'value2', true)">
28289 * value2: "{{ model.value2 }}"
28290 * </div>
28291 * </form>
28292 * </div>
28293 * </file>
28294 <file name="style.css">
28295 div {
28296 display: table-cell;
28297 }
28298 div:nth-child(1) {
28299 padding-right: 30px;
28300 }
28301
28302 </file>
28303 * </example>
28304 */
28305 $rollbackViewValue: function() {
28306 this.$$timeout.cancel(this.$$pendingDebounce);
28307 this.$viewValue = this.$$lastCommittedViewValue;
28308 this.$render();
28309 },
28310
28311 /**
28312 * @ngdoc method
28313 * @name ngModel.NgModelController#$validate
28314 *
28315 * @description
28316 * Runs each of the registered validators (first synchronous validators and then
28317 * asynchronous validators).
28318 * If the validity changes to invalid, the model will be set to `undefined`,
28319 * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
28320 * If the validity changes to valid, it will set the model to the last available valid
28321 * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
28322 */
28323 $validate: function() {
28324 // ignore $validate before model is initialized
28325 if (isNumberNaN(this.$modelValue)) {
28326 return;
28327 }
28328
28329 var viewValue = this.$$lastCommittedViewValue;
28330 // Note: we use the $$rawModelValue as $modelValue might have been
28331 // set to undefined during a view -> model update that found validation
28332 // errors. We can't parse the view here, since that could change
28333 // the model although neither viewValue nor the model on the scope changed
28334 var modelValue = this.$$rawModelValue;
28335
28336 var prevValid = this.$valid;
28337 var prevModelValue = this.$modelValue;
28338
28339 var allowInvalid = this.$options.getOption('allowInvalid');
28340
28341 var that = this;
28342 this.$$runValidators(modelValue, viewValue, function(allValid) {
28343 // If there was no change in validity, don't update the model
28344 // This prevents changing an invalid modelValue to undefined
28345 if (!allowInvalid && prevValid !== allValid) {
28346 // Note: Don't check this.$valid here, as we could have
28347 // external validators (e.g. calculated on the server),
28348 // that just call $setValidity and need the model value
28349 // to calculate their validity.
28350 that.$modelValue = allValid ? modelValue : undefined;
28351
28352 if (that.$modelValue !== prevModelValue) {
28353 that.$$writeModelToScope();
28354 }
28355 }
28356 });
28357 },
28358
28359 $$runValidators: function(modelValue, viewValue, doneCallback) {
28360 this.$$currentValidationRunId++;
28361 var localValidationRunId = this.$$currentValidationRunId;
28362 var that = this;
28363
28364 // check parser error
28365 if (!processParseErrors()) {
28366 validationDone(false);
28367 return;
28368 }
28369 if (!processSyncValidators()) {
28370 validationDone(false);
28371 return;
28372 }
28373 processAsyncValidators();
28374
28375 function processParseErrors() {
28376 var errorKey = that.$$parserName || 'parse';
28377 if (isUndefined(that.$$parserValid)) {
28378 setValidity(errorKey, null);
28379 } else {
28380 if (!that.$$parserValid) {
28381 forEach(that.$validators, function(v, name) {
28382 setValidity(name, null);
28383 });
28384 forEach(that.$asyncValidators, function(v, name) {
28385 setValidity(name, null);
28386 });
28387 }
28388 // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
28389 setValidity(errorKey, that.$$parserValid);
28390 return that.$$parserValid;
28391 }
28392 return true;
28393 }
28394
28395 function processSyncValidators() {
28396 var syncValidatorsValid = true;
28397 forEach(that.$validators, function(validator, name) {
28398 var result = Boolean(validator(modelValue, viewValue));
28399 syncValidatorsValid = syncValidatorsValid && result;
28400 setValidity(name, result);
28401 });
28402 if (!syncValidatorsValid) {
28403 forEach(that.$asyncValidators, function(v, name) {
28404 setValidity(name, null);
28405 });
28406 return false;
28407 }
28408 return true;
28409 }
28410
28411 function processAsyncValidators() {
28412 var validatorPromises = [];
28413 var allValid = true;
28414 forEach(that.$asyncValidators, function(validator, name) {
28415 var promise = validator(modelValue, viewValue);
28416 if (!isPromiseLike(promise)) {
28417 throw ngModelMinErr('nopromise',
28418 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
28419 }
28420 setValidity(name, undefined);
28421 validatorPromises.push(promise.then(function() {
28422 setValidity(name, true);
28423 }, function() {
28424 allValid = false;
28425 setValidity(name, false);
28426 }));
28427 });
28428 if (!validatorPromises.length) {
28429 validationDone(true);
28430 } else {
28431 that.$$q.all(validatorPromises).then(function() {
28432 validationDone(allValid);
28433 }, noop);
28434 }
28435 }
28436
28437 function setValidity(name, isValid) {
28438 if (localValidationRunId === that.$$currentValidationRunId) {
28439 that.$setValidity(name, isValid);
28440 }
28441 }
28442
28443 function validationDone(allValid) {
28444 if (localValidationRunId === that.$$currentValidationRunId) {
28445
28446 doneCallback(allValid);
28447 }
28448 }
28449 },
28450
28451 /**
28452 * @ngdoc method
28453 * @name ngModel.NgModelController#$commitViewValue
28454 *
28455 * @description
28456 * Commit a pending update to the `$modelValue`.
28457 *
28458 * Updates may be pending by a debounced event or because the input is waiting for a some future
28459 * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
28460 * usually handles calling this in response to input events.
28461 */
28462 $commitViewValue: function() {
28463 var viewValue = this.$viewValue;
28464
28465 this.$$timeout.cancel(this.$$pendingDebounce);
28466
28467 // If the view value has not changed then we should just exit, except in the case where there is
28468 // a native validator on the element. In this case the validation state may have changed even though
28469 // the viewValue has stayed empty.
28470 if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
28471 return;
28472 }
28473 this.$$updateEmptyClasses(viewValue);
28474 this.$$lastCommittedViewValue = viewValue;
28475
28476 // change to dirty
28477 if (this.$pristine) {
28478 this.$setDirty();
28479 }
28480 this.$$parseAndValidate();
28481 },
28482
28483 $$parseAndValidate: function() {
28484 var viewValue = this.$$lastCommittedViewValue;
28485 var modelValue = viewValue;
28486 var that = this;
28487
28488 this.$$parserValid = isUndefined(modelValue) ? undefined : true;
28489
28490 if (this.$$parserValid) {
28491 for (var i = 0; i < this.$parsers.length; i++) {
28492 modelValue = this.$parsers[i](modelValue);
28493 if (isUndefined(modelValue)) {
28494 this.$$parserValid = false;
28495 break;
28496 }
28497 }
28498 }
28499 if (isNumberNaN(this.$modelValue)) {
28500 // this.$modelValue has not been touched yet...
28501 this.$modelValue = this.$$ngModelGet(this.$$scope);
28502 }
28503 var prevModelValue = this.$modelValue;
28504 var allowInvalid = this.$options.getOption('allowInvalid');
28505 this.$$rawModelValue = modelValue;
28506
28507 if (allowInvalid) {
28508 this.$modelValue = modelValue;
28509 writeToModelIfNeeded();
28510 }
28511
28512 // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
28513 // This can happen if e.g. $setViewValue is called from inside a parser
28514 this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
28515 if (!allowInvalid) {
28516 // Note: Don't check this.$valid here, as we could have
28517 // external validators (e.g. calculated on the server),
28518 // that just call $setValidity and need the model value
28519 // to calculate their validity.
28520 that.$modelValue = allValid ? modelValue : undefined;
28521 writeToModelIfNeeded();
28522 }
28523 });
28524
28525 function writeToModelIfNeeded() {
28526 if (that.$modelValue !== prevModelValue) {
28527 that.$$writeModelToScope();
28528 }
28529 }
28530 },
28531
28532 $$writeModelToScope: function() {
28533 this.$$ngModelSet(this.$$scope, this.$modelValue);
28534 forEach(this.$viewChangeListeners, function(listener) {
28535 try {
28536 listener();
28537 } catch (e) {
28538 // eslint-disable-next-line no-invalid-this
28539 this.$$exceptionHandler(e);
28540 }
28541 }, this);
28542 },
28543
28544 /**
28545 * @ngdoc method
28546 * @name ngModel.NgModelController#$setViewValue
28547 *
28548 * @description
28549 * Update the view value.
28550 *
28551 * This method should be called when a control wants to change the view value; typically,
28552 * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
28553 * directive calls it when the value of the input changes and {@link ng.directive:select select}
28554 * calls it when an option is selected.
28555 *
28556 * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
28557 * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
28558 * value sent directly for processing, finally to be applied to `$modelValue` and then the
28559 * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
28560 * in the `$viewChangeListeners` list, are called.
28561 *
28562 * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
28563 * and the `default` trigger is not listed, all those actions will remain pending until one of the
28564 * `updateOn` events is triggered on the DOM element.
28565 * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
28566 * directive is used with a custom debounce for this particular event.
28567 * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
28568 * is specified, once the timer runs out.
28569 *
28570 * When used with standard inputs, the view value will always be a string (which is in some cases
28571 * parsed into another type, such as a `Date` object for `input[date]`.)
28572 * However, custom controls might also pass objects to this method. In this case, we should make
28573 * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
28574 * perform a deep watch of objects, it only looks for a change of identity. If you only change
28575 * the property of the object then ngModel will not realize that the object has changed and
28576 * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
28577 * not change properties of the copy once it has been passed to `$setViewValue`.
28578 * Otherwise you may cause the model value on the scope to change incorrectly.
28579 *
28580 * <div class="alert alert-info">
28581 * In any case, the value passed to the method should always reflect the current value
28582 * of the control. For example, if you are calling `$setViewValue` for an input element,
28583 * you should pass the input DOM value. Otherwise, the control and the scope model become
28584 * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
28585 * the control's DOM value in any way. If we want to change the control's DOM value
28586 * programmatically, we should update the `ngModel` scope expression. Its new value will be
28587 * picked up by the model controller, which will run it through the `$formatters`, `$render` it
28588 * to update the DOM, and finally call `$validate` on it.
28589 * </div>
28590 *
28591 * @param {*} value value from the view.
28592 * @param {string} trigger Event that triggered the update.
28593 */
28594 $setViewValue: function(value, trigger) {
28595 this.$viewValue = value;
28596 if (this.$options.getOption('updateOnDefault')) {
28597 this.$$debounceViewValueCommit(trigger);
28598 }
28599 },
28600
28601 $$debounceViewValueCommit: function(trigger) {
28602 var debounceDelay = this.$options.getOption('debounce');
28603
28604 if (isNumber(debounceDelay[trigger])) {
28605 debounceDelay = debounceDelay[trigger];
28606 } else if (isNumber(debounceDelay['default'])) {
28607 debounceDelay = debounceDelay['default'];
28608 }
28609
28610 this.$$timeout.cancel(this.$$pendingDebounce);
28611 var that = this;
28612 if (debounceDelay > 0) { // this fails if debounceDelay is an object
28613 this.$$pendingDebounce = this.$$timeout(function() {
28614 that.$commitViewValue();
28615 }, debounceDelay);
28616 } else if (this.$$scope.$root.$$phase) {
28617 this.$commitViewValue();
28618 } else {
28619 this.$$scope.$apply(function() {
28620 that.$commitViewValue();
28621 });
28622 }
28623 }
28624};
28625
28626function setupModelWatcher(ctrl) {
28627 // model -> value
28628 // Note: we cannot use a normal scope.$watch as we want to detect the following:
28629 // 1. scope value is 'a'
28630 // 2. user enters 'b'
28631 // 3. ng-change kicks in and reverts scope value to 'a'
28632 // -> scope value did not change since the last digest as
28633 // ng-change executes in apply phase
28634 // 4. view should be changed back to 'a'
28635 ctrl.$$scope.$watch(function ngModelWatch() {
28636 var modelValue = ctrl.$$ngModelGet(ctrl.$$scope);
28637
28638 // if scope model value and ngModel value are out of sync
28639 // TODO(perf): why not move this to the action fn?
28640 if (modelValue !== ctrl.$modelValue &&
28641 // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
28642 // eslint-disable-next-line no-self-compare
28643 (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
28644 ) {
28645 ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
28646 ctrl.$$parserValid = undefined;
28647
28648 var formatters = ctrl.$formatters,
28649 idx = formatters.length;
28650
28651 var viewValue = modelValue;
28652 while (idx--) {
28653 viewValue = formatters[idx](viewValue);
28654 }
28655 if (ctrl.$viewValue !== viewValue) {
28656 ctrl.$$updateEmptyClasses(viewValue);
28657 ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
28658 ctrl.$render();
28659
28660 // It is possible that model and view value have been updated during render
28661 ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
28662 }
28663 }
28664
28665 return modelValue;
28666 });
28667}
28668
28669/**
28670 * @ngdoc method
28671 * @name ngModel.NgModelController#$setValidity
28672 *
28673 * @description
28674 * Change the validity state, and notify the form.
28675 *
28676 * This method can be called within $parsers/$formatters or a custom validation implementation.
28677 * However, in most cases it should be sufficient to use the `ngModel.$validators` and
28678 * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
28679 *
28680 * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
28681 * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
28682 * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
28683 * The `validationErrorKey` should be in camelCase and will get converted into dash-case
28684 * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
28685 * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
28686 * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
28687 * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
28688 * Skipped is used by Angular when validators do not run because of parse errors and
28689 * when `$asyncValidators` do not run because any of the `$validators` failed.
28690 */
28691addSetValidityMethod({
28692 clazz: NgModelController,
28693 set: function(object, property) {
28694 object[property] = true;
28695 },
28696 unset: function(object, property) {
28697 delete object[property];
28698 }
28699});
28700
28701
28702/**
28703 * @ngdoc directive
28704 * @name ngModel
28705 *
28706 * @element input
28707 * @priority 1
28708 *
28709 * @description
28710 * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
28711 * property on the scope using {@link ngModel.NgModelController NgModelController},
28712 * which is created and exposed by this directive.
28713 *
28714 * `ngModel` is responsible for:
28715 *
28716 * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
28717 * require.
28718 * - Providing validation behavior (i.e. required, number, email, url).
28719 * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
28720 * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
28721 * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
28722 * - Registering the control with its parent {@link ng.directive:form form}.
28723 *
28724 * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
28725 * current scope. If the property doesn't already exist on this scope, it will be created
28726 * implicitly and added to the scope.
28727 *
28728 * For best practices on using `ngModel`, see:
28729 *
28730 * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
28731 *
28732 * For basic examples, how to use `ngModel`, see:
28733 *
28734 * - {@link ng.directive:input input}
28735 * - {@link input[text] text}
28736 * - {@link input[checkbox] checkbox}
28737 * - {@link input[radio] radio}
28738 * - {@link input[number] number}
28739 * - {@link input[email] email}
28740 * - {@link input[url] url}
28741 * - {@link input[date] date}
28742 * - {@link input[datetime-local] datetime-local}
28743 * - {@link input[time] time}
28744 * - {@link input[month] month}
28745 * - {@link input[week] week}
28746 * - {@link ng.directive:select select}
28747 * - {@link ng.directive:textarea textarea}
28748 *
28749 * # Complex Models (objects or collections)
28750 *
28751 * By default, `ngModel` watches the model by reference, not value. This is important to know when
28752 * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
28753 * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
28754 *
28755 * The model must be assigned an entirely new object or collection before a re-rendering will occur.
28756 *
28757 * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
28758 * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
28759 * if the select is given the `multiple` attribute.
28760 *
28761 * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
28762 * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
28763 * not trigger a re-rendering of the model.
28764 *
28765 * # CSS classes
28766 * The following CSS classes are added and removed on the associated input/select/textarea element
28767 * depending on the validity of the model.
28768 *
28769 * - `ng-valid`: the model is valid
28770 * - `ng-invalid`: the model is invalid
28771 * - `ng-valid-[key]`: for each valid key added by `$setValidity`
28772 * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
28773 * - `ng-pristine`: the control hasn't been interacted with yet
28774 * - `ng-dirty`: the control has been interacted with
28775 * - `ng-touched`: the control has been blurred
28776 * - `ng-untouched`: the control hasn't been blurred
28777 * - `ng-pending`: any `$asyncValidators` are unfulfilled
28778 * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
28779 * by the {@link ngModel.NgModelController#$isEmpty} method
28780 * - `ng-not-empty`: the view contains a non-empty value
28781 *
28782 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
28783 *
28784 * ## Animation Hooks
28785 *
28786 * Animations within models are triggered when any of the associated CSS classes are added and removed
28787 * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
28788 * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
28789 * The animations that are triggered within ngModel are similar to how they work in ngClass and
28790 * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
28791 *
28792 * The following example shows a simple way to utilize CSS transitions to style an input element
28793 * that has been rendered as invalid after it has been validated:
28794 *
28795 * <pre>
28796 * //be sure to include ngAnimate as a module to hook into more
28797 * //advanced animations
28798 * .my-input {
28799 * transition:0.5s linear all;
28800 * background: white;
28801 * }
28802 * .my-input.ng-invalid {
28803 * background: red;
28804 * color:white;
28805 * }
28806 * </pre>
28807 *
28808 * @example
28809 * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
28810 <file name="index.html">
28811 <script>
28812 angular.module('inputExample', [])
28813 .controller('ExampleController', ['$scope', function($scope) {
28814 $scope.val = '1';
28815 }]);
28816 </script>
28817 <style>
28818 .my-input {
28819 transition:all linear 0.5s;
28820 background: transparent;
28821 }
28822 .my-input.ng-invalid {
28823 color:white;
28824 background: red;
28825 }
28826 </style>
28827 <p id="inputDescription">
28828 Update input to see transitions when valid/invalid.
28829 Integer is a valid value.
28830 </p>
28831 <form name="testForm" ng-controller="ExampleController">
28832 <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
28833 aria-describedby="inputDescription" />
28834 </form>
28835 </file>
28836 * </example>
28837 *
28838 * ## Binding to a getter/setter
28839 *
28840 * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
28841 * function that returns a representation of the model when called with zero arguments, and sets
28842 * the internal state of a model when called with an argument. It's sometimes useful to use this
28843 * for models that have an internal representation that's different from what the model exposes
28844 * to the view.
28845 *
28846 * <div class="alert alert-success">
28847 * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
28848 * frequently than other parts of your code.
28849 * </div>
28850 *
28851 * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
28852 * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
28853 * a `<form>`, which will enable this behavior for all `<input>`s within it. See
28854 * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
28855 *
28856 * The following example shows how to use `ngModel` with a getter/setter:
28857 *
28858 * @example
28859 * <example name="ngModel-getter-setter" module="getterSetterExample">
28860 <file name="index.html">
28861 <div ng-controller="ExampleController">
28862 <form name="userForm">
28863 <label>Name:
28864 <input type="text" name="userName"
28865 ng-model="user.name"
28866 ng-model-options="{ getterSetter: true }" />
28867 </label>
28868 </form>
28869 <pre>user.name = <span ng-bind="user.name()"></span></pre>
28870 </div>
28871 </file>
28872 <file name="app.js">
28873 angular.module('getterSetterExample', [])
28874 .controller('ExampleController', ['$scope', function($scope) {
28875 var _name = 'Brian';
28876 $scope.user = {
28877 name: function(newName) {
28878 // Note that newName can be undefined for two reasons:
28879 // 1. Because it is called as a getter and thus called with no arguments
28880 // 2. Because the property should actually be set to undefined. This happens e.g. if the
28881 // input is invalid
28882 return arguments.length ? (_name = newName) : _name;
28883 }
28884 };
28885 }]);
28886 </file>
28887 * </example>
28888 */
28889var ngModelDirective = ['$rootScope', function($rootScope) {
28890 return {
28891 restrict: 'A',
28892 require: ['ngModel', '^?form', '^?ngModelOptions'],
28893 controller: NgModelController,
28894 // Prelink needs to run before any input directive
28895 // so that we can set the NgModelOptions in NgModelController
28896 // before anyone else uses it.
28897 priority: 1,
28898 compile: function ngModelCompile(element) {
28899 // Setup initial state of the control
28900 element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
28901
28902 return {
28903 pre: function ngModelPreLink(scope, element, attr, ctrls) {
28904 var modelCtrl = ctrls[0],
28905 formCtrl = ctrls[1] || modelCtrl.$$parentForm,
28906 optionsCtrl = ctrls[2];
28907
28908 if (optionsCtrl) {
28909 modelCtrl.$options = optionsCtrl.$options;
28910 }
28911
28912 modelCtrl.$$initGetterSetters();
28913
28914 // notify others, especially parent forms
28915 formCtrl.$addControl(modelCtrl);
28916
28917 attr.$observe('name', function(newValue) {
28918 if (modelCtrl.$name !== newValue) {
28919 modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
28920 }
28921 });
28922
28923 scope.$on('$destroy', function() {
28924 modelCtrl.$$parentForm.$removeControl(modelCtrl);
28925 });
28926 },
28927 post: function ngModelPostLink(scope, element, attr, ctrls) {
28928 var modelCtrl = ctrls[0];
28929 if (modelCtrl.$options.getOption('updateOn')) {
28930 element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
28931 modelCtrl.$$debounceViewValueCommit(ev && ev.type);
28932 });
28933 }
28934
28935 function setTouched() {
28936 modelCtrl.$setTouched();
28937 }
28938
28939 element.on('blur', function() {
28940 if (modelCtrl.$touched) return;
28941
28942 if ($rootScope.$$phase) {
28943 scope.$evalAsync(setTouched);
28944 } else {
28945 scope.$apply(setTouched);
28946 }
28947 });
28948 }
28949 };
28950 }
28951 };
28952}];
28953
28954/* exported defaultModelOptions */
28955var defaultModelOptions;
28956var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
28957
28958/**
28959 * @ngdoc type
28960 * @name ModelOptions
28961 * @description
28962 * A container for the options set by the {@link ngModelOptions} directive
28963 */
28964function ModelOptions(options) {
28965 this.$$options = options;
28966}
28967
28968ModelOptions.prototype = {
28969
28970 /**
28971 * @ngdoc method
28972 * @name ModelOptions#getOption
28973 * @param {string} name the name of the option to retrieve
28974 * @returns {*} the value of the option
28975 * @description
28976 * Returns the value of the given option
28977 */
28978 getOption: function(name) {
28979 return this.$$options[name];
28980 },
28981
28982 /**
28983 * @ngdoc method
28984 * @name ModelOptions#createChild
28985 * @param {Object} options a hash of options for the new child that will override the parent's options
28986 * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
28987 */
28988 createChild: function(options) {
28989 var inheritAll = false;
28990
28991 // make a shallow copy
28992 options = extend({}, options);
28993
28994 // Inherit options from the parent if specified by the value `"$inherit"`
28995 forEach(options, /* @this */ function(option, key) {
28996 if (option === '$inherit') {
28997 if (key === '*') {
28998 inheritAll = true;
28999 } else {
29000 options[key] = this.$$options[key];
29001 // `updateOn` is special so we must also inherit the `updateOnDefault` option
29002 if (key === 'updateOn') {
29003 options.updateOnDefault = this.$$options.updateOnDefault;
29004 }
29005 }
29006 } else {
29007 if (key === 'updateOn') {
29008 // If the `updateOn` property contains the `default` event then we have to remove
29009 // it from the event list and set the `updateOnDefault` flag.
29010 options.updateOnDefault = false;
29011 options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
29012 options.updateOnDefault = true;
29013 return ' ';
29014 }));
29015 }
29016 }
29017 }, this);
29018
29019 if (inheritAll) {
29020 // We have a property of the form: `"*": "$inherit"`
29021 delete options['*'];
29022 defaults(options, this.$$options);
29023 }
29024
29025 // Finally add in any missing defaults
29026 defaults(options, defaultModelOptions.$$options);
29027
29028 return new ModelOptions(options);
29029 }
29030};
29031
29032
29033defaultModelOptions = new ModelOptions({
29034 updateOn: '',
29035 updateOnDefault: true,
29036 debounce: 0,
29037 getterSetter: false,
29038 allowInvalid: false,
29039 timezone: null
29040});
29041
29042
29043/**
29044 * @ngdoc directive
29045 * @name ngModelOptions
29046 *
29047 * @description
29048 * This directive allows you to modify the behaviour of {@link ngModel} directives within your
29049 * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
29050 * directives will use the options of their nearest `ngModelOptions` ancestor.
29051 *
29052 * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
29053 * an Angular expression. This expression should evaluate to an object, whose properties contain
29054 * the settings. For example: `<div "ng-model-options"="{ debounce: 100 }"`.
29055 *
29056 * ## Inheriting Options
29057 *
29058 * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
29059 * directive by giving it the value of `"$inherit"`.
29060 * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
29061 * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
29062 * will be used.
29063 *
29064 * For example given the following fragment of HTML
29065 *
29066 *
29067 * ```html
29068 * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
29069 * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
29070 * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
29071 * </form>
29072 * </div>
29073 * ```
29074 *
29075 * the `input` element will have the following settings
29076 *
29077 * ```js
29078 * { allowInvalid: true, updateOn: 'default', debounce: 0 }
29079 * ```
29080 *
29081 * Notice that the `debounce` setting was not inherited and used the default value instead.
29082 *
29083 * You can specify that all undefined settings are automatically inherited from an ancestor by
29084 * including a property with key of `"*"` and value of `"$inherit"`.
29085 *
29086 * For example given the following fragment of HTML
29087 *
29088 *
29089 * ```html
29090 * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
29091 * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
29092 * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
29093 * </form>
29094 * </div>
29095 * ```
29096 *
29097 * the `input` element will have the following settings
29098 *
29099 * ```js
29100 * { allowInvalid: true, updateOn: 'default', debounce: 200 }
29101 * ```
29102 *
29103 * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
29104 *
29105 * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
29106 * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
29107 *
29108 *
29109 * ## Triggering and debouncing model updates
29110 *
29111 * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
29112 * trigger a model update and/or a debouncing delay so that the actual update only takes place when
29113 * a timer expires; this timer will be reset after another change takes place.
29114 *
29115 * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
29116 * be different from the value in the actual model. This means that if you update the model you
29117 * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
29118 * order to make sure it is synchronized with the model and that any debounced action is canceled.
29119 *
29120 * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
29121 * method is by making sure the input is placed inside a form that has a `name` attribute. This is
29122 * important because `form` controllers are published to the related scope under the name in their
29123 * `name` attribute.
29124 *
29125 * Any pending changes will take place immediately when an enclosing form is submitted via the
29126 * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
29127 * to have access to the updated model.
29128 *
29129 * The following example shows how to override immediate updates. Changes on the inputs within the
29130 * form will update the model only when the control loses focus (blur event). If `escape` key is
29131 * pressed while the input field is focused, the value is reset to the value in the current model.
29132 *
29133 * <example name="ngModelOptions-directive-blur" module="optionsExample">
29134 * <file name="index.html">
29135 * <div ng-controller="ExampleController">
29136 * <form name="userForm">
29137 * <label>
29138 * Name:
29139 * <input type="text" name="userName"
29140 * ng-model="user.name"
29141 * ng-model-options="{ updateOn: 'blur' }"
29142 * ng-keyup="cancel($event)" />
29143 * </label><br />
29144 * <label>
29145 * Other data:
29146 * <input type="text" ng-model="user.data" />
29147 * </label><br />
29148 * </form>
29149 * <pre>user.name = <span ng-bind="user.name"></span></pre>
29150 * </div>
29151 * </file>
29152 * <file name="app.js">
29153 * angular.module('optionsExample', [])
29154 * .controller('ExampleController', ['$scope', function($scope) {
29155 * $scope.user = { name: 'say', data: '' };
29156 *
29157 * $scope.cancel = function(e) {
29158 * if (e.keyCode === 27) {
29159 * $scope.userForm.userName.$rollbackViewValue();
29160 * }
29161 * };
29162 * }]);
29163 * </file>
29164 * <file name="protractor.js" type="protractor">
29165 * var model = element(by.binding('user.name'));
29166 * var input = element(by.model('user.name'));
29167 * var other = element(by.model('user.data'));
29168 *
29169 * it('should allow custom events', function() {
29170 * input.sendKeys(' hello');
29171 * input.click();
29172 * expect(model.getText()).toEqual('say');
29173 * other.click();
29174 * expect(model.getText()).toEqual('say hello');
29175 * });
29176 *
29177 * it('should $rollbackViewValue when model changes', function() {
29178 * input.sendKeys(' hello');
29179 * expect(input.getAttribute('value')).toEqual('say hello');
29180 * input.sendKeys(protractor.Key.ESCAPE);
29181 * expect(input.getAttribute('value')).toEqual('say');
29182 * other.click();
29183 * expect(model.getText()).toEqual('say');
29184 * });
29185 * </file>
29186 * </example>
29187 *
29188 * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
29189 * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
29190 *
29191 * <example name="ngModelOptions-directive-debounce" module="optionsExample">
29192 * <file name="index.html">
29193 * <div ng-controller="ExampleController">
29194 * <form name="userForm">
29195 * Name:
29196 * <input type="text" name="userName"
29197 * ng-model="user.name"
29198 * ng-model-options="{ debounce: 1000 }" />
29199 * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
29200 * </form>
29201 * <pre>user.name = <span ng-bind="user.name"></span></pre>
29202 * </div>
29203 * </file>
29204 * <file name="app.js">
29205 * angular.module('optionsExample', [])
29206 * .controller('ExampleController', ['$scope', function($scope) {
29207 * $scope.user = { name: 'say' };
29208 * }]);
29209 * </file>
29210 * </example>
29211 *
29212 * ## Model updates and validation
29213 *
29214 * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
29215 * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
29216 * the model will still be updated even if the value is invalid.
29217 *
29218 *
29219 * ## Connecting to the scope
29220 *
29221 * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
29222 * on the scope refers to a "getter/setter" function rather than the value itself.
29223 *
29224 * The following example shows how to bind to getter/setters:
29225 *
29226 * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
29227 * <file name="index.html">
29228 * <div ng-controller="ExampleController">
29229 * <form name="userForm">
29230 * <label>
29231 * Name:
29232 * <input type="text" name="userName"
29233 * ng-model="user.name"
29234 * ng-model-options="{ getterSetter: true }" />
29235 * </label>
29236 * </form>
29237 * <pre>user.name = <span ng-bind="user.name()"></span></pre>
29238 * </div>
29239 * </file>
29240 * <file name="app.js">
29241 * angular.module('getterSetterExample', [])
29242 * .controller('ExampleController', ['$scope', function($scope) {
29243 * var _name = 'Brian';
29244 * $scope.user = {
29245 * name: function(newName) {
29246 * return angular.isDefined(newName) ? (_name = newName) : _name;
29247 * }
29248 * };
29249 * }]);
29250 * </file>
29251 * </example>
29252 *
29253 *
29254 * ## Specifying timezones
29255 *
29256 * You can specify the timezone that date/time input directives expect by providing its name in the
29257 * `timezone` property.
29258 *
29259 * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
29260 * and its descendents. Valid keys are:
29261 * - `updateOn`: string specifying which event should the input be bound to. You can set several
29262 * events using an space delimited list. There is a special event called `default` that
29263 * matches the default events belonging to the control.
29264 * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
29265 * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
29266 * custom value for each event. For example:
29267 * ```
29268 * ng-model-options="{
29269 * updateOn: 'default blur',
29270 * debounce: { 'default': 500, 'blur': 0 }
29271 * }"
29272 * ```
29273 * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
29274 * not validate correctly instead of the default behavior of setting the model to undefined.
29275 * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
29276 * `ngModel` as getters/setters.
29277 * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
29278 * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
29279 * continental US time zone abbreviations, but for general use, use a time zone offset, for
29280 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
29281 * If not specified, the timezone of the browser will be used.
29282 *
29283 */
29284var ngModelOptionsDirective = function() {
29285 NgModelOptionsController.$inject = ['$attrs', '$scope'];
29286 function NgModelOptionsController($attrs, $scope) {
29287 this.$$attrs = $attrs;
29288 this.$$scope = $scope;
29289 }
29290 NgModelOptionsController.prototype = {
29291 $onInit: function() {
29292 var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
29293 var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
29294
29295 this.$options = parentOptions.createChild(modelOptionsDefinition);
29296 }
29297 };
29298
29299 return {
29300 restrict: 'A',
29301 // ngModelOptions needs to run before ngModel and input directives
29302 priority: 10,
29303 require: {parentCtrl: '?^^ngModelOptions'},
29304 bindToController: true,
29305 controller: NgModelOptionsController
29306 };
29307};
29308
29309
29310// shallow copy over values from `src` that are not already specified on `dst`
29311function defaults(dst, src) {
29312 forEach(src, function(value, key) {
29313 if (!isDefined(dst[key])) {
29314 dst[key] = value;
29315 }
29316 });
29317}
29318
29319/**
29320 * @ngdoc directive
29321 * @name ngNonBindable
29322 * @restrict AC
29323 * @priority 1000
29324 *
29325 * @description
29326 * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
29327 * DOM element. This is useful if the element contains what appears to be Angular directives and
29328 * bindings but which should be ignored by Angular. This could be the case if you have a site that
29329 * displays snippets of code, for instance.
29330 *
29331 * @element ANY
29332 *
29333 * @example
29334 * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
29335 * but the one wrapped in `ngNonBindable` is left alone.
29336 *
29337 * @example
29338 <example name="ng-non-bindable">
29339 <file name="index.html">
29340 <div>Normal: {{1 + 2}}</div>
29341 <div ng-non-bindable>Ignored: {{1 + 2}}</div>
29342 </file>
29343 <file name="protractor.js" type="protractor">
29344 it('should check ng-non-bindable', function() {
29345 expect(element(by.binding('1 + 2')).getText()).toContain('3');
29346 expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
29347 });
29348 </file>
29349 </example>
29350 */
29351var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
29352
29353/* exported ngOptionsDirective */
29354
29355/* global jqLiteRemove */
29356
29357var ngOptionsMinErr = minErr('ngOptions');
29358
29359/**
29360 * @ngdoc directive
29361 * @name ngOptions
29362 * @restrict A
29363 *
29364 * @description
29365 *
29366 * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
29367 * elements for the `<select>` element using the array or object obtained by evaluating the
29368 * `ngOptions` comprehension expression.
29369 *
29370 * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
29371 * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
29372 * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
29373 * comprehension expression
29374 * - reduced memory consumption by not creating a new scope for each repeated instance
29375 * - increased render speed by creating the options in a documentFragment instead of individually
29376 *
29377 * When an item in the `<select>` menu is selected, the array element or object property
29378 * represented by the selected option will be bound to the model identified by the `ngModel`
29379 * directive.
29380 *
29381 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
29382 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
29383 * option. See example below for demonstration.
29384 *
29385 * ## Complex Models (objects or collections)
29386 *
29387 * By default, `ngModel` watches the model by reference, not value. This is important to know when
29388 * binding the select to a model that is an object or a collection.
29389 *
29390 * One issue occurs if you want to preselect an option. For example, if you set
29391 * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
29392 * because the objects are not identical. So by default, you should always reference the item in your collection
29393 * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
29394 *
29395 * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
29396 * of the item not by reference, but by the result of the `track by` expression. For example, if your
29397 * collection items have an id property, you would `track by item.id`.
29398 *
29399 * A different issue with objects or collections is that ngModel won't detect if an object property or
29400 * a collection item changes. For that reason, `ngOptions` additionally watches the model using
29401 * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
29402 * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
29403 * has not changed identity, but only a property on the object or an item in the collection changes.
29404 *
29405 * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
29406 * if the model is an array). This means that changing a property deeper than the first level inside the
29407 * object/collection will not trigger a re-rendering.
29408 *
29409 * ## `select` **`as`**
29410 *
29411 * Using `select` **`as`** will bind the result of the `select` expression to the model, but
29412 * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
29413 * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
29414 * is used, the result of that expression will be set as the value of the `option` and `select` elements.
29415 *
29416 *
29417 * ### `select` **`as`** and **`track by`**
29418 *
29419 * <div class="alert alert-warning">
29420 * Be careful when using `select` **`as`** and **`track by`** in the same expression.
29421 * </div>
29422 *
29423 * Given this array of items on the $scope:
29424 *
29425 * ```js
29426 * $scope.items = [{
29427 * id: 1,
29428 * label: 'aLabel',
29429 * subItem: { name: 'aSubItem' }
29430 * }, {
29431 * id: 2,
29432 * label: 'bLabel',
29433 * subItem: { name: 'bSubItem' }
29434 * }];
29435 * ```
29436 *
29437 * This will work:
29438 *
29439 * ```html
29440 * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
29441 * ```
29442 * ```js
29443 * $scope.selected = $scope.items[0];
29444 * ```
29445 *
29446 * but this will not work:
29447 *
29448 * ```html
29449 * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
29450 * ```
29451 * ```js
29452 * $scope.selected = $scope.items[0].subItem;
29453 * ```
29454 *
29455 * In both examples, the **`track by`** expression is applied successfully to each `item` in the
29456 * `items` array. Because the selected option has been set programmatically in the controller, the
29457 * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
29458 * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
29459 * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
29460 * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
29461 * is not matched against any `<option>` and the `<select>` appears as having no selected value.
29462 *
29463 *
29464 * @param {string} ngModel Assignable angular expression to data-bind to.
29465 * @param {string=} name Property name of the form under which the control is published.
29466 * @param {string=} required The control is considered valid only if value is entered.
29467 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
29468 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
29469 * `required` when you want to data-bind to the `required` attribute.
29470 * @param {comprehension_expression=} ngOptions in one of the following forms:
29471 *
29472 * * for array data sources:
29473 * * `label` **`for`** `value` **`in`** `array`
29474 * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
29475 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
29476 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
29477 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
29478 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
29479 * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
29480 * (for including a filter with `track by`)
29481 * * for object data sources:
29482 * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
29483 * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
29484 * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
29485 * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
29486 * * `select` **`as`** `label` **`group by`** `group`
29487 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
29488 * * `select` **`as`** `label` **`disable when`** `disable`
29489 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
29490 *
29491 * Where:
29492 *
29493 * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
29494 * * `value`: local variable which will refer to each item in the `array` or each property value
29495 * of `object` during iteration.
29496 * * `key`: local variable which will refer to a property name in `object` during iteration.
29497 * * `label`: The result of this expression will be the label for `<option>` element. The
29498 * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
29499 * * `select`: The result of this expression will be bound to the model of the parent `<select>`
29500 * element. If not specified, `select` expression will default to `value`.
29501 * * `group`: The result of this expression will be used to group options using the `<optgroup>`
29502 * DOM element.
29503 * * `disable`: The result of this expression will be used to disable the rendered `<option>`
29504 * element. Return `true` to disable.
29505 * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
29506 * used to identify the objects in the array. The `trackexpr` will most likely refer to the
29507 * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
29508 * even when the options are recreated (e.g. reloaded from the server).
29509 *
29510 * @example
29511 <example module="selectExample" name="select">
29512 <file name="index.html">
29513 <script>
29514 angular.module('selectExample', [])
29515 .controller('ExampleController', ['$scope', function($scope) {
29516 $scope.colors = [
29517 {name:'black', shade:'dark'},
29518 {name:'white', shade:'light', notAnOption: true},
29519 {name:'red', shade:'dark'},
29520 {name:'blue', shade:'dark', notAnOption: true},
29521 {name:'yellow', shade:'light', notAnOption: false}
29522 ];
29523 $scope.myColor = $scope.colors[2]; // red
29524 }]);
29525 </script>
29526 <div ng-controller="ExampleController">
29527 <ul>
29528 <li ng-repeat="color in colors">
29529 <label>Name: <input ng-model="color.name"></label>
29530 <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
29531 <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
29532 </li>
29533 <li>
29534 <button ng-click="colors.push({})">add</button>
29535 </li>
29536 </ul>
29537 <hr/>
29538 <label>Color (null not allowed):
29539 <select ng-model="myColor" ng-options="color.name for color in colors"></select>
29540 </label><br/>
29541 <label>Color (null allowed):
29542 <span class="nullable">
29543 <select ng-model="myColor" ng-options="color.name for color in colors">
29544 <option value="">-- choose color --</option>
29545 </select>
29546 </span></label><br/>
29547
29548 <label>Color grouped by shade:
29549 <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
29550 </select>
29551 </label><br/>
29552
29553 <label>Color grouped by shade, with some disabled:
29554 <select ng-model="myColor"
29555 ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
29556 </select>
29557 </label><br/>
29558
29559
29560
29561 Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
29562 <br/>
29563 <hr/>
29564 Currently selected: {{ {selected_color:myColor} }}
29565 <div style="border:solid 1px black; height:20px"
29566 ng-style="{'background-color':myColor.name}">
29567 </div>
29568 </div>
29569 </file>
29570 <file name="protractor.js" type="protractor">
29571 it('should check ng-options', function() {
29572 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
29573 element.all(by.model('myColor')).first().click();
29574 element.all(by.css('select[ng-model="myColor"] option')).first().click();
29575 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
29576 element(by.css('.nullable select[ng-model="myColor"]')).click();
29577 element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
29578 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
29579 });
29580 </file>
29581 </example>
29582 */
29583
29584/* eslint-disable max-len */
29585// //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
29586var 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]+?))?$/;
29587 // 1: value expression (valueFn)
29588 // 2: label expression (displayFn)
29589 // 3: group by expression (groupByFn)
29590 // 4: disable when expression (disableWhenFn)
29591 // 5: array item variable name
29592 // 6: object item key variable name
29593 // 7: object item value variable name
29594 // 8: collection expression
29595 // 9: track by expression
29596/* eslint-enable */
29597
29598
29599var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
29600
29601 function parseOptionsExpression(optionsExp, selectElement, scope) {
29602
29603 var match = optionsExp.match(NG_OPTIONS_REGEXP);
29604 if (!(match)) {
29605 throw ngOptionsMinErr('iexp',
29606 'Expected expression in form of ' +
29607 '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
29608 ' but got \'{0}\'. Element: {1}',
29609 optionsExp, startingTag(selectElement));
29610 }
29611
29612 // Extract the parts from the ngOptions expression
29613
29614 // The variable name for the value of the item in the collection
29615 var valueName = match[5] || match[7];
29616 // The variable name for the key of the item in the collection
29617 var keyName = match[6];
29618
29619 // An expression that generates the viewValue for an option if there is a label expression
29620 var selectAs = / as /.test(match[0]) && match[1];
29621 // An expression that is used to track the id of each object in the options collection
29622 var trackBy = match[9];
29623 // An expression that generates the viewValue for an option if there is no label expression
29624 var valueFn = $parse(match[2] ? match[1] : valueName);
29625 var selectAsFn = selectAs && $parse(selectAs);
29626 var viewValueFn = selectAsFn || valueFn;
29627 var trackByFn = trackBy && $parse(trackBy);
29628
29629 // Get the value by which we are going to track the option
29630 // if we have a trackFn then use that (passing scope and locals)
29631 // otherwise just hash the given viewValue
29632 var getTrackByValueFn = trackBy ?
29633 function(value, locals) { return trackByFn(scope, locals); } :
29634 function getHashOfValue(value) { return hashKey(value); };
29635 var getTrackByValue = function(value, key) {
29636 return getTrackByValueFn(value, getLocals(value, key));
29637 };
29638
29639 var displayFn = $parse(match[2] || match[1]);
29640 var groupByFn = $parse(match[3] || '');
29641 var disableWhenFn = $parse(match[4] || '');
29642 var valuesFn = $parse(match[8]);
29643
29644 var locals = {};
29645 var getLocals = keyName ? function(value, key) {
29646 locals[keyName] = key;
29647 locals[valueName] = value;
29648 return locals;
29649 } : function(value) {
29650 locals[valueName] = value;
29651 return locals;
29652 };
29653
29654
29655 function Option(selectValue, viewValue, label, group, disabled) {
29656 this.selectValue = selectValue;
29657 this.viewValue = viewValue;
29658 this.label = label;
29659 this.group = group;
29660 this.disabled = disabled;
29661 }
29662
29663 function getOptionValuesKeys(optionValues) {
29664 var optionValuesKeys;
29665
29666 if (!keyName && isArrayLike(optionValues)) {
29667 optionValuesKeys = optionValues;
29668 } else {
29669 // if object, extract keys, in enumeration order, unsorted
29670 optionValuesKeys = [];
29671 for (var itemKey in optionValues) {
29672 if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
29673 optionValuesKeys.push(itemKey);
29674 }
29675 }
29676 }
29677 return optionValuesKeys;
29678 }
29679
29680 return {
29681 trackBy: trackBy,
29682 getTrackByValue: getTrackByValue,
29683 getWatchables: $parse(valuesFn, function(optionValues) {
29684 // Create a collection of things that we would like to watch (watchedArray)
29685 // so that they can all be watched using a single $watchCollection
29686 // that only runs the handler once if anything changes
29687 var watchedArray = [];
29688 optionValues = optionValues || [];
29689
29690 var optionValuesKeys = getOptionValuesKeys(optionValues);
29691 var optionValuesLength = optionValuesKeys.length;
29692 for (var index = 0; index < optionValuesLength; index++) {
29693 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
29694 var value = optionValues[key];
29695
29696 var locals = getLocals(value, key);
29697 var selectValue = getTrackByValueFn(value, locals);
29698 watchedArray.push(selectValue);
29699
29700 // Only need to watch the displayFn if there is a specific label expression
29701 if (match[2] || match[1]) {
29702 var label = displayFn(scope, locals);
29703 watchedArray.push(label);
29704 }
29705
29706 // Only need to watch the disableWhenFn if there is a specific disable expression
29707 if (match[4]) {
29708 var disableWhen = disableWhenFn(scope, locals);
29709 watchedArray.push(disableWhen);
29710 }
29711 }
29712 return watchedArray;
29713 }),
29714
29715 getOptions: function() {
29716
29717 var optionItems = [];
29718 var selectValueMap = {};
29719
29720 // The option values were already computed in the `getWatchables` fn,
29721 // which must have been called to trigger `getOptions`
29722 var optionValues = valuesFn(scope) || [];
29723 var optionValuesKeys = getOptionValuesKeys(optionValues);
29724 var optionValuesLength = optionValuesKeys.length;
29725
29726 for (var index = 0; index < optionValuesLength; index++) {
29727 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
29728 var value = optionValues[key];
29729 var locals = getLocals(value, key);
29730 var viewValue = viewValueFn(scope, locals);
29731 var selectValue = getTrackByValueFn(viewValue, locals);
29732 var label = displayFn(scope, locals);
29733 var group = groupByFn(scope, locals);
29734 var disabled = disableWhenFn(scope, locals);
29735 var optionItem = new Option(selectValue, viewValue, label, group, disabled);
29736
29737 optionItems.push(optionItem);
29738 selectValueMap[selectValue] = optionItem;
29739 }
29740
29741 return {
29742 items: optionItems,
29743 selectValueMap: selectValueMap,
29744 getOptionFromViewValue: function(value) {
29745 return selectValueMap[getTrackByValue(value)];
29746 },
29747 getViewValueFromOption: function(option) {
29748 // If the viewValue could be an object that may be mutated by the application,
29749 // we need to make a copy and not return the reference to the value on the option.
29750 return trackBy ? copy(option.viewValue) : option.viewValue;
29751 }
29752 };
29753 }
29754 };
29755 }
29756
29757
29758 // we can't just jqLite('<option>') since jqLite is not smart enough
29759 // to create it in <select> and IE barfs otherwise.
29760 var optionTemplate = window.document.createElement('option'),
29761 optGroupTemplate = window.document.createElement('optgroup');
29762
29763 function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
29764
29765 var selectCtrl = ctrls[0];
29766 var ngModelCtrl = ctrls[1];
29767 var multiple = attr.multiple;
29768
29769 // The emptyOption allows the application developer to provide their own custom "empty"
29770 // option when the viewValue does not match any of the option values.
29771 for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
29772 if (children[i].value === '') {
29773 selectCtrl.hasEmptyOption = true;
29774 selectCtrl.emptyOption = children.eq(i);
29775 break;
29776 }
29777 }
29778
29779 var providedEmptyOption = !!selectCtrl.emptyOption;
29780
29781 var unknownOption = jqLite(optionTemplate.cloneNode(false));
29782 unknownOption.val('?');
29783
29784 var options;
29785 var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
29786 // This stores the newly created options before they are appended to the select.
29787 // Since the contents are removed from the fragment when it is appended,
29788 // we only need to create it once.
29789 var listFragment = $document[0].createDocumentFragment();
29790
29791 // Overwrite the implementation. ngOptions doesn't use hashes
29792 selectCtrl.generateUnknownOptionValue = function(val) {
29793 return '?';
29794 };
29795
29796 // Update the controller methods for multiple selectable options
29797 if (!multiple) {
29798
29799 selectCtrl.writeValue = function writeNgOptionsValue(value) {
29800 var selectedOption = options.selectValueMap[selectElement.val()];
29801 var option = options.getOptionFromViewValue(value);
29802
29803 // Make sure to remove the selected attribute from the previously selected option
29804 // Otherwise, screen readers might get confused
29805 if (selectedOption) selectedOption.element.removeAttribute('selected');
29806
29807 if (option) {
29808 // Don't update the option when it is already selected.
29809 // For example, the browser will select the first option by default. In that case,
29810 // most properties are set automatically - except the `selected` attribute, which we
29811 // set always
29812
29813 if (selectElement[0].value !== option.selectValue) {
29814 selectCtrl.removeUnknownOption();
29815 selectCtrl.unselectEmptyOption();
29816
29817 selectElement[0].value = option.selectValue;
29818 option.element.selected = true;
29819 }
29820
29821 option.element.setAttribute('selected', 'selected');
29822 } else {
29823
29824 if (providedEmptyOption) {
29825 selectCtrl.selectEmptyOption();
29826 } else if (selectCtrl.unknownOption.parent().length) {
29827 selectCtrl.updateUnknownOption(value);
29828 } else {
29829 selectCtrl.renderUnknownOption(value);
29830 }
29831 }
29832 };
29833
29834 selectCtrl.readValue = function readNgOptionsValue() {
29835
29836 var selectedOption = options.selectValueMap[selectElement.val()];
29837
29838 if (selectedOption && !selectedOption.disabled) {
29839 selectCtrl.unselectEmptyOption();
29840 selectCtrl.removeUnknownOption();
29841 return options.getViewValueFromOption(selectedOption);
29842 }
29843 return null;
29844 };
29845
29846 // If we are using `track by` then we must watch the tracked value on the model
29847 // since ngModel only watches for object identity change
29848 // FIXME: When a user selects an option, this watch will fire needlessly
29849 if (ngOptions.trackBy) {
29850 scope.$watch(
29851 function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
29852 function() { ngModelCtrl.$render(); }
29853 );
29854 }
29855
29856 } else {
29857
29858 selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
29859 // Only set `<option>.selected` if necessary, in order to prevent some browsers from
29860 // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
29861
29862 var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
29863
29864 options.items.forEach(function(option) {
29865 if (option.element.selected && !includes(selectedOptions, option)) {
29866 option.element.selected = false;
29867 }
29868 });
29869 };
29870
29871
29872 selectCtrl.readValue = function readNgOptionsMultiple() {
29873 var selectedValues = selectElement.val() || [],
29874 selections = [];
29875
29876 forEach(selectedValues, function(value) {
29877 var option = options.selectValueMap[value];
29878 if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
29879 });
29880
29881 return selections;
29882 };
29883
29884 // If we are using `track by` then we must watch these tracked values on the model
29885 // since ngModel only watches for object identity change
29886 if (ngOptions.trackBy) {
29887
29888 scope.$watchCollection(function() {
29889 if (isArray(ngModelCtrl.$viewValue)) {
29890 return ngModelCtrl.$viewValue.map(function(value) {
29891 return ngOptions.getTrackByValue(value);
29892 });
29893 }
29894 }, function() {
29895 ngModelCtrl.$render();
29896 });
29897
29898 }
29899 }
29900
29901 if (providedEmptyOption) {
29902
29903 // we need to remove it before calling selectElement.empty() because otherwise IE will
29904 // remove the label from the element. wtf?
29905 selectCtrl.emptyOption.remove();
29906
29907 // compile the element since there might be bindings in it
29908 $compile(selectCtrl.emptyOption)(scope);
29909
29910 if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
29911 // This means the empty option has currently no actual DOM node, probably because
29912 // it has been modified by a transclusion directive.
29913 selectCtrl.hasEmptyOption = false;
29914
29915 // Redefine the registerOption function, which will catch
29916 // options that are added by ngIf etc. (rendering of the node is async because of
29917 // lazy transclusion)
29918 selectCtrl.registerOption = function(optionScope, optionEl) {
29919 if (optionEl.val() === '') {
29920 selectCtrl.hasEmptyOption = true;
29921 selectCtrl.emptyOption = optionEl;
29922 selectCtrl.emptyOption.removeClass('ng-scope');
29923 // This ensures the new empty option is selected if previously no option was selected
29924 ngModelCtrl.$render();
29925
29926 optionEl.on('$destroy', function() {
29927 selectCtrl.hasEmptyOption = false;
29928 selectCtrl.emptyOption = undefined;
29929 });
29930 }
29931 };
29932
29933 } else {
29934 // remove the class, which is added automatically because we recompile the element and it
29935 // becomes the compilation root
29936 selectCtrl.emptyOption.removeClass('ng-scope');
29937 }
29938
29939 }
29940
29941 selectElement.empty();
29942
29943 // We need to do this here to ensure that the options object is defined
29944 // when we first hit it in writeNgOptionsValue
29945 updateOptions();
29946
29947 // We will re-render the option elements if the option values or labels change
29948 scope.$watchCollection(ngOptions.getWatchables, updateOptions);
29949
29950 // ------------------------------------------------------------------ //
29951
29952 function addOptionElement(option, parent) {
29953 var optionElement = optionTemplate.cloneNode(false);
29954 parent.appendChild(optionElement);
29955 updateOptionElement(option, optionElement);
29956 }
29957
29958 function getAndUpdateSelectedOption(viewValue) {
29959 var option = options.getOptionFromViewValue(viewValue);
29960 var element = option && option.element;
29961
29962 if (element && !element.selected) element.selected = true;
29963
29964 return option;
29965 }
29966
29967 function updateOptionElement(option, element) {
29968 option.element = element;
29969 element.disabled = option.disabled;
29970 // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
29971 // selects in certain circumstances when multiple selects are next to each other and display
29972 // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
29973 // See https://github.com/angular/angular.js/issues/11314 for more info.
29974 // This is unfortunately untestable with unit / e2e tests
29975 if (option.label !== element.label) {
29976 element.label = option.label;
29977 element.textContent = option.label;
29978 }
29979 element.value = option.selectValue;
29980 }
29981
29982 function updateOptions() {
29983 var previousValue = options && selectCtrl.readValue();
29984
29985 // We must remove all current options, but cannot simply set innerHTML = null
29986 // since the providedEmptyOption might have an ngIf on it that inserts comments which we
29987 // must preserve.
29988 // Instead, iterate over the current option elements and remove them or their optgroup
29989 // parents
29990 if (options) {
29991
29992 for (var i = options.items.length - 1; i >= 0; i--) {
29993 var option = options.items[i];
29994 if (isDefined(option.group)) {
29995 jqLiteRemove(option.element.parentNode);
29996 } else {
29997 jqLiteRemove(option.element);
29998 }
29999 }
30000 }
30001
30002 options = ngOptions.getOptions();
30003
30004 var groupElementMap = {};
30005
30006 // Ensure that the empty option is always there if it was explicitly provided
30007 if (providedEmptyOption) {
30008 selectElement.prepend(selectCtrl.emptyOption);
30009 }
30010
30011 options.items.forEach(function addOption(option) {
30012 var groupElement;
30013
30014 if (isDefined(option.group)) {
30015
30016 // This option is to live in a group
30017 // See if we have already created this group
30018 groupElement = groupElementMap[option.group];
30019
30020 if (!groupElement) {
30021
30022 groupElement = optGroupTemplate.cloneNode(false);
30023 listFragment.appendChild(groupElement);
30024
30025 // Update the label on the group element
30026 // "null" is special cased because of Safari
30027 groupElement.label = option.group === null ? 'null' : option.group;
30028
30029 // Store it for use later
30030 groupElementMap[option.group] = groupElement;
30031 }
30032
30033 addOptionElement(option, groupElement);
30034
30035 } else {
30036
30037 // This option is not in a group
30038 addOptionElement(option, listFragment);
30039 }
30040 });
30041
30042 selectElement[0].appendChild(listFragment);
30043
30044 ngModelCtrl.$render();
30045
30046 // Check to see if the value has changed due to the update to the options
30047 if (!ngModelCtrl.$isEmpty(previousValue)) {
30048 var nextValue = selectCtrl.readValue();
30049 var isNotPrimitive = ngOptions.trackBy || multiple;
30050 if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
30051 ngModelCtrl.$setViewValue(nextValue);
30052 ngModelCtrl.$render();
30053 }
30054 }
30055
30056 }
30057 }
30058
30059 return {
30060 restrict: 'A',
30061 terminal: true,
30062 require: ['select', 'ngModel'],
30063 link: {
30064 pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
30065 // Deactivate the SelectController.register method to prevent
30066 // option directives from accidentally registering themselves
30067 // (and unwanted $destroy handlers etc.)
30068 ctrls[0].registerOption = noop;
30069 },
30070 post: ngOptionsPostLink
30071 }
30072 };
30073}];
30074
30075/**
30076 * @ngdoc directive
30077 * @name ngPluralize
30078 * @restrict EA
30079 *
30080 * @description
30081 * `ngPluralize` is a directive that displays messages according to en-US localization rules.
30082 * These rules are bundled with angular.js, but can be overridden
30083 * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
30084 * by specifying the mappings between
30085 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
30086 * and the strings to be displayed.
30087 *
30088 * # Plural categories and explicit number rules
30089 * There are two
30090 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
30091 * in Angular's default en-US locale: "one" and "other".
30092 *
30093 * While a plural category may match many numbers (for example, in en-US locale, "other" can match
30094 * any number that is not 1), an explicit number rule can only match one number. For example, the
30095 * explicit number rule for "3" matches the number 3. There are examples of plural categories
30096 * and explicit number rules throughout the rest of this documentation.
30097 *
30098 * # Configuring ngPluralize
30099 * You configure ngPluralize by providing 2 attributes: `count` and `when`.
30100 * You can also provide an optional attribute, `offset`.
30101 *
30102 * The value of the `count` attribute can be either a string or an {@link guide/expression
30103 * Angular expression}; these are evaluated on the current scope for its bound value.
30104 *
30105 * The `when` attribute specifies the mappings between plural categories and the actual
30106 * string to be displayed. The value of the attribute should be a JSON object.
30107 *
30108 * The following example shows how to configure ngPluralize:
30109 *
30110 * ```html
30111 * <ng-pluralize count="personCount"
30112 when="{'0': 'Nobody is viewing.',
30113 * 'one': '1 person is viewing.',
30114 * 'other': '{} people are viewing.'}">
30115 * </ng-pluralize>
30116 *```
30117 *
30118 * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
30119 * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
30120 * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
30121 * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
30122 * show "a dozen people are viewing".
30123 *
30124 * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
30125 * into pluralized strings. In the previous example, Angular will replace `{}` with
30126 * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
30127 * for <span ng-non-bindable>{{numberExpression}}</span>.
30128 *
30129 * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
30130 * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
30131 *
30132 * # Configuring ngPluralize with offset
30133 * The `offset` attribute allows further customization of pluralized text, which can result in
30134 * a better user experience. For example, instead of the message "4 people are viewing this document",
30135 * you might display "John, Kate and 2 others are viewing this document".
30136 * The offset attribute allows you to offset a number by any desired value.
30137 * Let's take a look at an example:
30138 *
30139 * ```html
30140 * <ng-pluralize count="personCount" offset=2
30141 * when="{'0': 'Nobody is viewing.',
30142 * '1': '{{person1}} is viewing.',
30143 * '2': '{{person1}} and {{person2}} are viewing.',
30144 * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
30145 * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
30146 * </ng-pluralize>
30147 * ```
30148 *
30149 * Notice that we are still using two plural categories(one, other), but we added
30150 * three explicit number rules 0, 1 and 2.
30151 * When one person, perhaps John, views the document, "John is viewing" will be shown.
30152 * When three people view the document, no explicit number rule is found, so
30153 * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
30154 * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
30155 * is shown.
30156 *
30157 * Note that when you specify offsets, you must provide explicit number rules for
30158 * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
30159 * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
30160 * plural categories "one" and "other".
30161 *
30162 * @param {string|expression} count The variable to be bound to.
30163 * @param {string} when The mapping between plural category to its corresponding strings.
30164 * @param {number=} offset Offset to deduct from the total number.
30165 *
30166 * @example
30167 <example module="pluralizeExample" name="ng-pluralize">
30168 <file name="index.html">
30169 <script>
30170 angular.module('pluralizeExample', [])
30171 .controller('ExampleController', ['$scope', function($scope) {
30172 $scope.person1 = 'Igor';
30173 $scope.person2 = 'Misko';
30174 $scope.personCount = 1;
30175 }]);
30176 </script>
30177 <div ng-controller="ExampleController">
30178 <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
30179 <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
30180 <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
30181
30182 <!--- Example with simple pluralization rules for en locale --->
30183 Without Offset:
30184 <ng-pluralize count="personCount"
30185 when="{'0': 'Nobody is viewing.',
30186 'one': '1 person is viewing.',
30187 'other': '{} people are viewing.'}">
30188 </ng-pluralize><br>
30189
30190 <!--- Example with offset --->
30191 With Offset(2):
30192 <ng-pluralize count="personCount" offset=2
30193 when="{'0': 'Nobody is viewing.',
30194 '1': '{{person1}} is viewing.',
30195 '2': '{{person1}} and {{person2}} are viewing.',
30196 'one': '{{person1}}, {{person2}} and one other person are viewing.',
30197 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
30198 </ng-pluralize>
30199 </div>
30200 </file>
30201 <file name="protractor.js" type="protractor">
30202 it('should show correct pluralized string', function() {
30203 var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
30204 var withOffset = element.all(by.css('ng-pluralize')).get(1);
30205 var countInput = element(by.model('personCount'));
30206
30207 expect(withoutOffset.getText()).toEqual('1 person is viewing.');
30208 expect(withOffset.getText()).toEqual('Igor is viewing.');
30209
30210 countInput.clear();
30211 countInput.sendKeys('0');
30212
30213 expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
30214 expect(withOffset.getText()).toEqual('Nobody is viewing.');
30215
30216 countInput.clear();
30217 countInput.sendKeys('2');
30218
30219 expect(withoutOffset.getText()).toEqual('2 people are viewing.');
30220 expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
30221
30222 countInput.clear();
30223 countInput.sendKeys('3');
30224
30225 expect(withoutOffset.getText()).toEqual('3 people are viewing.');
30226 expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
30227
30228 countInput.clear();
30229 countInput.sendKeys('4');
30230
30231 expect(withoutOffset.getText()).toEqual('4 people are viewing.');
30232 expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
30233 });
30234 it('should show data-bound names', function() {
30235 var withOffset = element.all(by.css('ng-pluralize')).get(1);
30236 var personCount = element(by.model('personCount'));
30237 var person1 = element(by.model('person1'));
30238 var person2 = element(by.model('person2'));
30239 personCount.clear();
30240 personCount.sendKeys('4');
30241 person1.clear();
30242 person1.sendKeys('Di');
30243 person2.clear();
30244 person2.sendKeys('Vojta');
30245 expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
30246 });
30247 </file>
30248 </example>
30249 */
30250var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
30251 var BRACE = /{}/g,
30252 IS_WHEN = /^when(Minus)?(.+)$/;
30253
30254 return {
30255 link: function(scope, element, attr) {
30256 var numberExp = attr.count,
30257 whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
30258 offset = attr.offset || 0,
30259 whens = scope.$eval(whenExp) || {},
30260 whensExpFns = {},
30261 startSymbol = $interpolate.startSymbol(),
30262 endSymbol = $interpolate.endSymbol(),
30263 braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
30264 watchRemover = angular.noop,
30265 lastCount;
30266
30267 forEach(attr, function(expression, attributeName) {
30268 var tmpMatch = IS_WHEN.exec(attributeName);
30269 if (tmpMatch) {
30270 var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
30271 whens[whenKey] = element.attr(attr.$attr[attributeName]);
30272 }
30273 });
30274 forEach(whens, function(expression, key) {
30275 whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
30276
30277 });
30278
30279 scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
30280 var count = parseFloat(newVal);
30281 var countIsNaN = isNumberNaN(count);
30282
30283 if (!countIsNaN && !(count in whens)) {
30284 // If an explicit number rule such as 1, 2, 3... is defined, just use it.
30285 // Otherwise, check it against pluralization rules in $locale service.
30286 count = $locale.pluralCat(count - offset);
30287 }
30288
30289 // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
30290 // In JS `NaN !== NaN`, so we have to explicitly check.
30291 if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
30292 watchRemover();
30293 var whenExpFn = whensExpFns[count];
30294 if (isUndefined(whenExpFn)) {
30295 if (newVal != null) {
30296 $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
30297 }
30298 watchRemover = noop;
30299 updateElementText();
30300 } else {
30301 watchRemover = scope.$watch(whenExpFn, updateElementText);
30302 }
30303 lastCount = count;
30304 }
30305 });
30306
30307 function updateElementText(newText) {
30308 element.text(newText || '');
30309 }
30310 }
30311 };
30312}];
30313
30314/* exported ngRepeatDirective */
30315
30316/**
30317 * @ngdoc directive
30318 * @name ngRepeat
30319 * @multiElement
30320 *
30321 * @description
30322 * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
30323 * instance gets its own scope, where the given loop variable is set to the current collection item,
30324 * and `$index` is set to the item index or key.
30325 *
30326 * Special properties are exposed on the local scope of each template instance, including:
30327 *
30328 * | Variable | Type | Details |
30329 * |-----------|-----------------|-----------------------------------------------------------------------------|
30330 * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
30331 * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
30332 * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
30333 * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
30334 * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
30335 * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
30336 *
30337 * <div class="alert alert-info">
30338 * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
30339 * This may be useful when, for instance, nesting ngRepeats.
30340 * </div>
30341 *
30342 *
30343 * # Iterating over object properties
30344 *
30345 * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
30346 * syntax:
30347 *
30348 * ```js
30349 * <div ng-repeat="(key, value) in myObj"> ... </div>
30350 * ```
30351 *
30352 * However, there are a few limitations compared to array iteration:
30353 *
30354 * - The JavaScript specification does not define the order of keys
30355 * returned for an object, so Angular relies on the order returned by the browser
30356 * when running `for key in myObj`. Browsers generally follow the strategy of providing
30357 * keys in the order in which they were defined, although there are exceptions when keys are deleted
30358 * and reinstated. See the
30359 * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
30360 *
30361 * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
30362 * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
30363 *
30364 * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
30365 * objects, and will throw an error if used with one.
30366 *
30367 * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
30368 * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
30369 * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
30370 * or implement a `$watch` on the object yourself.
30371 *
30372 *
30373 * # Tracking and Duplicates
30374 *
30375 * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
30376 * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
30377 *
30378 * * When an item is added, a new instance of the template is added to the DOM.
30379 * * When an item is removed, its template instance is removed from the DOM.
30380 * * When items are reordered, their respective templates are reordered in the DOM.
30381 *
30382 * To minimize creation of DOM elements, `ngRepeat` uses a function
30383 * to "keep track" of all items in the collection and their corresponding DOM elements.
30384 * For example, if an item is added to the collection, `ngRepeat` will know that all other items
30385 * already have DOM elements, and will not re-render them.
30386 *
30387 * The default tracking function (which tracks items by their identity) does not allow
30388 * duplicate items in arrays. This is because when there are duplicates, it is not possible
30389 * to maintain a one-to-one mapping between collection items and DOM elements.
30390 *
30391 * If you do need to repeat duplicate items, you can substitute the default tracking behavior
30392 * with your own using the `track by` expression.
30393 *
30394 * For example, you may track items by the index of each item in the collection, using the
30395 * special scope property `$index`:
30396 * ```html
30397 * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
30398 * {{n}}
30399 * </div>
30400 * ```
30401 *
30402 * You may also use arbitrary expressions in `track by`, including references to custom functions
30403 * on the scope:
30404 * ```html
30405 * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
30406 * {{n}}
30407 * </div>
30408 * ```
30409 *
30410 * <div class="alert alert-success">
30411 * If you are working with objects that have a unique identifier property, you should track
30412 * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`
30413 * will not have to rebuild the DOM elements for items it has already rendered, even if the
30414 * JavaScript objects in the collection have been substituted for new ones. For large collections,
30415 * this significantly improves rendering performance. If you don't have a unique identifier,
30416 * `track by $index` can also provide a performance boost.
30417 * </div>
30418 *
30419 * ```html
30420 * <div ng-repeat="model in collection track by model.id">
30421 * {{model.name}}
30422 * </div>
30423 * ```
30424 *
30425 * <br />
30426 * <div class="alert alert-warning">
30427 * Avoid using `track by $index` when the repeated template contains
30428 * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM
30429 * element will always be matched with the `nth` item of the array, so the bindings on that element
30430 * will not be updated even when the corresponding item changes, essentially causing the view to get
30431 * out-of-sync with the underlying data.
30432 * </div>
30433 *
30434 * When no `track by` expression is provided, it is equivalent to tracking by the built-in
30435 * `$id` function, which tracks items by their identity:
30436 * ```html
30437 * <div ng-repeat="obj in collection track by $id(obj)">
30438 * {{obj.prop}}
30439 * </div>
30440 * ```
30441 *
30442 * <br />
30443 * <div class="alert alert-warning">
30444 * **Note:** `track by` must always be the last expression:
30445 * </div>
30446 * ```
30447 * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
30448 * {{model.name}}
30449 * </div>
30450 * ```
30451 *
30452 *
30453 * # Special repeat start and end points
30454 * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
30455 * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
30456 * 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)
30457 * up to and including the ending HTML tag where **ng-repeat-end** is placed.
30458 *
30459 * The example below makes use of this feature:
30460 * ```html
30461 * <header ng-repeat-start="item in items">
30462 * Header {{ item }}
30463 * </header>
30464 * <div class="body">
30465 * Body {{ item }}
30466 * </div>
30467 * <footer ng-repeat-end>
30468 * Footer {{ item }}
30469 * </footer>
30470 * ```
30471 *
30472 * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
30473 * ```html
30474 * <header>
30475 * Header A
30476 * </header>
30477 * <div class="body">
30478 * Body A
30479 * </div>
30480 * <footer>
30481 * Footer A
30482 * </footer>
30483 * <header>
30484 * Header B
30485 * </header>
30486 * <div class="body">
30487 * Body B
30488 * </div>
30489 * <footer>
30490 * Footer B
30491 * </footer>
30492 * ```
30493 *
30494 * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
30495 * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
30496 *
30497 * @animations
30498 * | Animation | Occurs |
30499 * |----------------------------------|-------------------------------------|
30500 * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
30501 * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
30502 * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
30503 *
30504 * See the example below for defining CSS animations with ngRepeat.
30505 *
30506 * @element ANY
30507 * @scope
30508 * @priority 1000
30509 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
30510 * formats are currently supported:
30511 *
30512 * * `variable in expression` – where variable is the user defined loop variable and `expression`
30513 * is a scope expression giving the collection to enumerate.
30514 *
30515 * For example: `album in artist.albums`.
30516 *
30517 * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
30518 * and `expression` is the scope expression giving the collection to enumerate.
30519 *
30520 * For example: `(name, age) in {'adam':10, 'amalie':12}`.
30521 *
30522 * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
30523 * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
30524 * is specified, ng-repeat associates elements by identity. It is an error to have
30525 * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
30526 * mapped to the same DOM element, which is not possible.)
30527 *
30528 * Note that the tracking expression must come last, after any filters, and the alias expression.
30529 *
30530 * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
30531 * will be associated by item identity in the array.
30532 *
30533 * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
30534 * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
30535 * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
30536 * element in the same way in the DOM.
30537 *
30538 * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
30539 * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
30540 * property is same.
30541 *
30542 * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
30543 * to items in conjunction with a tracking expression.
30544 *
30545 * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
30546 * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
30547 * when a filter is active on the repeater, but the filtered result set is empty.
30548 *
30549 * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
30550 * the items have been processed through the filter.
30551 *
30552 * 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
30553 * (and not as operator, inside an expression).
30554 *
30555 * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
30556 *
30557 * @example
30558 * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
30559 * results by name or by age. New (entering) and removed (leaving) items are animated.
30560 <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat">
30561 <file name="index.html">
30562 <div ng-controller="repeatController">
30563 I have {{friends.length}} friends. They are:
30564 <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
30565 <ul class="example-animate-container">
30566 <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
30567 [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
30568 </li>
30569 <li class="animate-repeat" ng-if="results.length === 0">
30570 <strong>No results found...</strong>
30571 </li>
30572 </ul>
30573 </div>
30574 </file>
30575 <file name="script.js">
30576 angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
30577 $scope.friends = [
30578 {name:'John', age:25, gender:'boy'},
30579 {name:'Jessie', age:30, gender:'girl'},
30580 {name:'Johanna', age:28, gender:'girl'},
30581 {name:'Joy', age:15, gender:'girl'},
30582 {name:'Mary', age:28, gender:'girl'},
30583 {name:'Peter', age:95, gender:'boy'},
30584 {name:'Sebastian', age:50, gender:'boy'},
30585 {name:'Erika', age:27, gender:'girl'},
30586 {name:'Patrick', age:40, gender:'boy'},
30587 {name:'Samantha', age:60, gender:'girl'}
30588 ];
30589 });
30590 </file>
30591 <file name="animations.css">
30592 .example-animate-container {
30593 background:white;
30594 border:1px solid black;
30595 list-style:none;
30596 margin:0;
30597 padding:0 10px;
30598 }
30599
30600 .animate-repeat {
30601 line-height:30px;
30602 list-style:none;
30603 box-sizing:border-box;
30604 }
30605
30606 .animate-repeat.ng-move,
30607 .animate-repeat.ng-enter,
30608 .animate-repeat.ng-leave {
30609 transition:all linear 0.5s;
30610 }
30611
30612 .animate-repeat.ng-leave.ng-leave-active,
30613 .animate-repeat.ng-move,
30614 .animate-repeat.ng-enter {
30615 opacity:0;
30616 max-height:0;
30617 }
30618
30619 .animate-repeat.ng-leave,
30620 .animate-repeat.ng-move.ng-move-active,
30621 .animate-repeat.ng-enter.ng-enter-active {
30622 opacity:1;
30623 max-height:30px;
30624 }
30625 </file>
30626 <file name="protractor.js" type="protractor">
30627 var friends = element.all(by.repeater('friend in friends'));
30628
30629 it('should render initial data set', function() {
30630 expect(friends.count()).toBe(10);
30631 expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
30632 expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
30633 expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
30634 expect(element(by.binding('friends.length')).getText())
30635 .toMatch("I have 10 friends. They are:");
30636 });
30637
30638 it('should update repeater when filter predicate changes', function() {
30639 expect(friends.count()).toBe(10);
30640
30641 element(by.model('q')).sendKeys('ma');
30642
30643 expect(friends.count()).toBe(2);
30644 expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
30645 expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
30646 });
30647 </file>
30648 </example>
30649 */
30650var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
30651 var NG_REMOVED = '$$NG_REMOVED';
30652 var ngRepeatMinErr = minErr('ngRepeat');
30653
30654 var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
30655 // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
30656 scope[valueIdentifier] = value;
30657 if (keyIdentifier) scope[keyIdentifier] = key;
30658 scope.$index = index;
30659 scope.$first = (index === 0);
30660 scope.$last = (index === (arrayLength - 1));
30661 scope.$middle = !(scope.$first || scope.$last);
30662 // eslint-disable-next-line no-bitwise
30663 scope.$odd = !(scope.$even = (index & 1) === 0);
30664 };
30665
30666 var getBlockStart = function(block) {
30667 return block.clone[0];
30668 };
30669
30670 var getBlockEnd = function(block) {
30671 return block.clone[block.clone.length - 1];
30672 };
30673
30674
30675 return {
30676 restrict: 'A',
30677 multiElement: true,
30678 transclude: 'element',
30679 priority: 1000,
30680 terminal: true,
30681 $$tlb: true,
30682 compile: function ngRepeatCompile($element, $attr) {
30683 var expression = $attr.ngRepeat;
30684 var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
30685
30686 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*$/);
30687
30688 if (!match) {
30689 throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
30690 expression);
30691 }
30692
30693 var lhs = match[1];
30694 var rhs = match[2];
30695 var aliasAs = match[3];
30696 var trackByExp = match[4];
30697
30698 match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
30699
30700 if (!match) {
30701 throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
30702 lhs);
30703 }
30704 var valueIdentifier = match[3] || match[1];
30705 var keyIdentifier = match[2];
30706
30707 if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
30708 /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
30709 throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
30710 aliasAs);
30711 }
30712
30713 var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
30714 var hashFnLocals = {$id: hashKey};
30715
30716 if (trackByExp) {
30717 trackByExpGetter = $parse(trackByExp);
30718 } else {
30719 trackByIdArrayFn = function(key, value) {
30720 return hashKey(value);
30721 };
30722 trackByIdObjFn = function(key) {
30723 return key;
30724 };
30725 }
30726
30727 return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
30728
30729 if (trackByExpGetter) {
30730 trackByIdExpFn = function(key, value, index) {
30731 // assign key, value, and $index to the locals so that they can be used in hash functions
30732 if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
30733 hashFnLocals[valueIdentifier] = value;
30734 hashFnLocals.$index = index;
30735 return trackByExpGetter($scope, hashFnLocals);
30736 };
30737 }
30738
30739 // Store a list of elements from previous run. This is a hash where key is the item from the
30740 // iterator, and the value is objects with following properties.
30741 // - scope: bound scope
30742 // - element: previous element.
30743 // - index: position
30744 //
30745 // We are using no-proto object so that we don't need to guard against inherited props via
30746 // hasOwnProperty.
30747 var lastBlockMap = createMap();
30748
30749 //watch props
30750 $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
30751 var index, length,
30752 previousNode = $element[0], // node that cloned nodes should be inserted after
30753 // initialized to the comment node anchor
30754 nextNode,
30755 // Same as lastBlockMap but it has the current state. It will become the
30756 // lastBlockMap on the next iteration.
30757 nextBlockMap = createMap(),
30758 collectionLength,
30759 key, value, // key/value of iteration
30760 trackById,
30761 trackByIdFn,
30762 collectionKeys,
30763 block, // last object information {scope, element, id}
30764 nextBlockOrder,
30765 elementsToRemove;
30766
30767 if (aliasAs) {
30768 $scope[aliasAs] = collection;
30769 }
30770
30771 if (isArrayLike(collection)) {
30772 collectionKeys = collection;
30773 trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
30774 } else {
30775 trackByIdFn = trackByIdExpFn || trackByIdObjFn;
30776 // if object, extract keys, in enumeration order, unsorted
30777 collectionKeys = [];
30778 for (var itemKey in collection) {
30779 if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
30780 collectionKeys.push(itemKey);
30781 }
30782 }
30783 }
30784
30785 collectionLength = collectionKeys.length;
30786 nextBlockOrder = new Array(collectionLength);
30787
30788 // locate existing items
30789 for (index = 0; index < collectionLength; index++) {
30790 key = (collection === collectionKeys) ? index : collectionKeys[index];
30791 value = collection[key];
30792 trackById = trackByIdFn(key, value, index);
30793 if (lastBlockMap[trackById]) {
30794 // found previously seen block
30795 block = lastBlockMap[trackById];
30796 delete lastBlockMap[trackById];
30797 nextBlockMap[trackById] = block;
30798 nextBlockOrder[index] = block;
30799 } else if (nextBlockMap[trackById]) {
30800 // if collision detected. restore lastBlockMap and throw an error
30801 forEach(nextBlockOrder, function(block) {
30802 if (block && block.scope) lastBlockMap[block.id] = block;
30803 });
30804 throw ngRepeatMinErr('dupes',
30805 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
30806 expression, trackById, value);
30807 } else {
30808 // new never before seen block
30809 nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
30810 nextBlockMap[trackById] = true;
30811 }
30812 }
30813
30814 // remove leftover items
30815 for (var blockKey in lastBlockMap) {
30816 block = lastBlockMap[blockKey];
30817 elementsToRemove = getBlockNodes(block.clone);
30818 $animate.leave(elementsToRemove);
30819 if (elementsToRemove[0].parentNode) {
30820 // if the element was not removed yet because of pending animation, mark it as deleted
30821 // so that we can ignore it later
30822 for (index = 0, length = elementsToRemove.length; index < length; index++) {
30823 elementsToRemove[index][NG_REMOVED] = true;
30824 }
30825 }
30826 block.scope.$destroy();
30827 }
30828
30829 // we are not using forEach for perf reasons (trying to avoid #call)
30830 for (index = 0; index < collectionLength; index++) {
30831 key = (collection === collectionKeys) ? index : collectionKeys[index];
30832 value = collection[key];
30833 block = nextBlockOrder[index];
30834
30835 if (block.scope) {
30836 // if we have already seen this object, then we need to reuse the
30837 // associated scope/element
30838
30839 nextNode = previousNode;
30840
30841 // skip nodes that are already pending removal via leave animation
30842 do {
30843 nextNode = nextNode.nextSibling;
30844 } while (nextNode && nextNode[NG_REMOVED]);
30845
30846 if (getBlockStart(block) !== nextNode) {
30847 // existing item which got moved
30848 $animate.move(getBlockNodes(block.clone), null, previousNode);
30849 }
30850 previousNode = getBlockEnd(block);
30851 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
30852 } else {
30853 // new item which we don't know about
30854 $transclude(function ngRepeatTransclude(clone, scope) {
30855 block.scope = scope;
30856 // http://jsperf.com/clone-vs-createcomment
30857 var endNode = ngRepeatEndComment.cloneNode(false);
30858 clone[clone.length++] = endNode;
30859
30860 $animate.enter(clone, null, previousNode);
30861 previousNode = endNode;
30862 // Note: We only need the first/last node of the cloned nodes.
30863 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
30864 // by a directive with templateUrl when its template arrives.
30865 block.clone = clone;
30866 nextBlockMap[block.id] = block;
30867 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
30868 });
30869 }
30870 }
30871 lastBlockMap = nextBlockMap;
30872 });
30873 };
30874 }
30875 };
30876}];
30877
30878var NG_HIDE_CLASS = 'ng-hide';
30879var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
30880/**
30881 * @ngdoc directive
30882 * @name ngShow
30883 * @multiElement
30884 *
30885 * @description
30886 * The `ngShow` directive shows or hides the given HTML element based on the expression
30887 * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
30888 * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
30889 * in AngularJS and sets the display style to none (using an !important flag).
30890 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
30891 *
30892 * ```html
30893 * <!-- when $scope.myValue is truthy (element is visible) -->
30894 * <div ng-show="myValue"></div>
30895 *
30896 * <!-- when $scope.myValue is falsy (element is hidden) -->
30897 * <div ng-show="myValue" class="ng-hide"></div>
30898 * ```
30899 *
30900 * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
30901 * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
30902 * from the element causing the element not to appear hidden.
30903 *
30904 * ## Why is !important used?
30905 *
30906 * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
30907 * can be easily overridden by heavier selectors. For example, something as simple
30908 * as changing the display style on a HTML list item would make hidden elements appear visible.
30909 * This also becomes a bigger issue when dealing with CSS frameworks.
30910 *
30911 * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
30912 * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
30913 * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
30914 *
30915 * ### Overriding `.ng-hide`
30916 *
30917 * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
30918 * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
30919 * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
30920 * with extra animation classes that can be added.
30921 *
30922 * ```css
30923 * .ng-hide:not(.ng-hide-animate) {
30924 * /* this is just another form of hiding an element */
30925 * display: block!important;
30926 * position: absolute;
30927 * top: -9999px;
30928 * left: -9999px;
30929 * }
30930 * ```
30931 *
30932 * By default you don't need to override in CSS anything and the animations will work around the display style.
30933 *
30934 * ## A note about animations with `ngShow`
30935 *
30936 * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
30937 * is true and false. This system works like the animation system present with ngClass except that
30938 * you must also include the !important flag to override the display property
30939 * so that you can perform an animation when the element is hidden during the time of the animation.
30940 *
30941 * ```css
30942 * //
30943 * //a working example can be found at the bottom of this page
30944 * //
30945 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
30946 * /* this is required as of 1.3x to properly
30947 * apply all styling in a show/hide animation */
30948 * transition: 0s linear all;
30949 * }
30950 *
30951 * .my-element.ng-hide-add-active,
30952 * .my-element.ng-hide-remove-active {
30953 * /* the transition is defined in the active class */
30954 * transition: 1s linear all;
30955 * }
30956 *
30957 * .my-element.ng-hide-add { ... }
30958 * .my-element.ng-hide-add.ng-hide-add-active { ... }
30959 * .my-element.ng-hide-remove { ... }
30960 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
30961 * ```
30962 *
30963 * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
30964 * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
30965 *
30966 * @animations
30967 * | Animation | Occurs |
30968 * |----------------------------------|-------------------------------------|
30969 * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden |
30970 * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
30971 *
30972 * @element ANY
30973 * @param {expression} ngShow If the {@link guide/expression expression} is truthy
30974 * then the element is shown or hidden respectively.
30975 *
30976 * @example
30977 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show">
30978 <file name="index.html">
30979 Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
30980 <div>
30981 Show:
30982 <div class="check-element animate-show" ng-show="checked">
30983 <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
30984 </div>
30985 </div>
30986 <div>
30987 Hide:
30988 <div class="check-element animate-show" ng-hide="checked">
30989 <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
30990 </div>
30991 </div>
30992 </file>
30993 <file name="glyphicons.css">
30994 @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
30995 </file>
30996 <file name="animations.css">
30997 .animate-show {
30998 line-height: 20px;
30999 opacity: 1;
31000 padding: 10px;
31001 border: 1px solid black;
31002 background: white;
31003 }
31004
31005 .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
31006 transition: all linear 0.5s;
31007 }
31008
31009 .animate-show.ng-hide {
31010 line-height: 0;
31011 opacity: 0;
31012 padding: 0 10px;
31013 }
31014
31015 .check-element {
31016 padding: 10px;
31017 border: 1px solid black;
31018 background: white;
31019 }
31020 </file>
31021 <file name="protractor.js" type="protractor">
31022 var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
31023 var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
31024
31025 it('should check ng-show / ng-hide', function() {
31026 expect(thumbsUp.isDisplayed()).toBeFalsy();
31027 expect(thumbsDown.isDisplayed()).toBeTruthy();
31028
31029 element(by.model('checked')).click();
31030
31031 expect(thumbsUp.isDisplayed()).toBeTruthy();
31032 expect(thumbsDown.isDisplayed()).toBeFalsy();
31033 });
31034 </file>
31035 </example>
31036 */
31037var ngShowDirective = ['$animate', function($animate) {
31038 return {
31039 restrict: 'A',
31040 multiElement: true,
31041 link: function(scope, element, attr) {
31042 scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
31043 // we're adding a temporary, animation-specific class for ng-hide since this way
31044 // we can control when the element is actually displayed on screen without having
31045 // to have a global/greedy CSS selector that breaks when other animations are run.
31046 // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
31047 $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
31048 tempClasses: NG_HIDE_IN_PROGRESS_CLASS
31049 });
31050 });
31051 }
31052 };
31053}];
31054
31055
31056/**
31057 * @ngdoc directive
31058 * @name ngHide
31059 * @multiElement
31060 *
31061 * @description
31062 * The `ngHide` directive shows or hides the given HTML element based on the expression
31063 * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
31064 * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
31065 * in AngularJS and sets the display style to none (using an !important flag).
31066 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
31067 *
31068 * ```html
31069 * <!-- when $scope.myValue is truthy (element is hidden) -->
31070 * <div ng-hide="myValue" class="ng-hide"></div>
31071 *
31072 * <!-- when $scope.myValue is falsy (element is visible) -->
31073 * <div ng-hide="myValue"></div>
31074 * ```
31075 *
31076 * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
31077 * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
31078 * from the element causing the element not to appear hidden.
31079 *
31080 * ## Why is !important used?
31081 *
31082 * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
31083 * can be easily overridden by heavier selectors. For example, something as simple
31084 * as changing the display style on a HTML list item would make hidden elements appear visible.
31085 * This also becomes a bigger issue when dealing with CSS frameworks.
31086 *
31087 * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
31088 * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
31089 * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
31090 *
31091 * ### Overriding `.ng-hide`
31092 *
31093 * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
31094 * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
31095 * class in CSS:
31096 *
31097 * ```css
31098 * .ng-hide {
31099 * /* this is just another form of hiding an element */
31100 * display: block!important;
31101 * position: absolute;
31102 * top: -9999px;
31103 * left: -9999px;
31104 * }
31105 * ```
31106 *
31107 * By default you don't need to override in CSS anything and the animations will work around the display style.
31108 *
31109 * ## A note about animations with `ngHide`
31110 *
31111 * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
31112 * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
31113 * CSS class is added and removed for you instead of your own CSS class.
31114 *
31115 * ```css
31116 * //
31117 * //a working example can be found at the bottom of this page
31118 * //
31119 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
31120 * transition: 0.5s linear all;
31121 * }
31122 *
31123 * .my-element.ng-hide-add { ... }
31124 * .my-element.ng-hide-add.ng-hide-add-active { ... }
31125 * .my-element.ng-hide-remove { ... }
31126 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
31127 * ```
31128 *
31129 * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
31130 * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
31131 *
31132 * @animations
31133 * | Animation | Occurs |
31134 * |----------------------------------|-------------------------------------|
31135 * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
31136 * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
31137 *
31138 *
31139 * @element ANY
31140 * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
31141 * the element is shown or hidden respectively.
31142 *
31143 * @example
31144 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide">
31145 <file name="index.html">
31146 Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
31147 <div>
31148 Show:
31149 <div class="check-element animate-hide" ng-show="checked">
31150 <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
31151 </div>
31152 </div>
31153 <div>
31154 Hide:
31155 <div class="check-element animate-hide" ng-hide="checked">
31156 <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
31157 </div>
31158 </div>
31159 </file>
31160 <file name="glyphicons.css">
31161 @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
31162 </file>
31163 <file name="animations.css">
31164 .animate-hide {
31165 transition: all linear 0.5s;
31166 line-height: 20px;
31167 opacity: 1;
31168 padding: 10px;
31169 border: 1px solid black;
31170 background: white;
31171 }
31172
31173 .animate-hide.ng-hide {
31174 line-height: 0;
31175 opacity: 0;
31176 padding: 0 10px;
31177 }
31178
31179 .check-element {
31180 padding: 10px;
31181 border: 1px solid black;
31182 background: white;
31183 }
31184 </file>
31185 <file name="protractor.js" type="protractor">
31186 var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
31187 var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
31188
31189 it('should check ng-show / ng-hide', function() {
31190 expect(thumbsUp.isDisplayed()).toBeFalsy();
31191 expect(thumbsDown.isDisplayed()).toBeTruthy();
31192
31193 element(by.model('checked')).click();
31194
31195 expect(thumbsUp.isDisplayed()).toBeTruthy();
31196 expect(thumbsDown.isDisplayed()).toBeFalsy();
31197 });
31198 </file>
31199 </example>
31200 */
31201var ngHideDirective = ['$animate', function($animate) {
31202 return {
31203 restrict: 'A',
31204 multiElement: true,
31205 link: function(scope, element, attr) {
31206 scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
31207 // The comment inside of the ngShowDirective explains why we add and
31208 // remove a temporary class for the show/hide animation
31209 $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
31210 tempClasses: NG_HIDE_IN_PROGRESS_CLASS
31211 });
31212 });
31213 }
31214 };
31215}];
31216
31217/**
31218 * @ngdoc directive
31219 * @name ngStyle
31220 * @restrict AC
31221 *
31222 * @description
31223 * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
31224 *
31225 * @knownIssue
31226 * You should not use {@link guide/interpolation interpolation} in the value of the `style`
31227 * attribute, when using the `ngStyle` directive on the same element.
31228 * See {@link guide/interpolation#known-issues here} for more info.
31229 *
31230 * @element ANY
31231 * @param {expression} ngStyle
31232 *
31233 * {@link guide/expression Expression} which evals to an
31234 * object whose keys are CSS style names and values are corresponding values for those CSS
31235 * keys.
31236 *
31237 * Since some CSS style names are not valid keys for an object, they must be quoted.
31238 * See the 'background-color' style in the example below.
31239 *
31240 * @example
31241 <example name="ng-style">
31242 <file name="index.html">
31243 <input type="button" value="set color" ng-click="myStyle={color:'red'}">
31244 <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
31245 <input type="button" value="clear" ng-click="myStyle={}">
31246 <br/>
31247 <span ng-style="myStyle">Sample Text</span>
31248 <pre>myStyle={{myStyle}}</pre>
31249 </file>
31250 <file name="style.css">
31251 span {
31252 color: black;
31253 }
31254 </file>
31255 <file name="protractor.js" type="protractor">
31256 var colorSpan = element(by.css('span'));
31257
31258 it('should check ng-style', function() {
31259 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
31260 element(by.css('input[value=\'set color\']')).click();
31261 expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
31262 element(by.css('input[value=clear]')).click();
31263 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
31264 });
31265 </file>
31266 </example>
31267 */
31268var ngStyleDirective = ngDirective(function(scope, element, attr) {
31269 scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
31270 if (oldStyles && (newStyles !== oldStyles)) {
31271 forEach(oldStyles, function(val, style) { element.css(style, '');});
31272 }
31273 if (newStyles) element.css(newStyles);
31274 }, true);
31275});
31276
31277/**
31278 * @ngdoc directive
31279 * @name ngSwitch
31280 * @restrict EA
31281 *
31282 * @description
31283 * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
31284 * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
31285 * as specified in the template.
31286 *
31287 * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
31288 * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
31289 * matches the value obtained from the evaluated expression. In other words, you define a container element
31290 * (where you place the directive), place an expression on the **`on="..."` attribute**
31291 * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
31292 * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
31293 * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
31294 * attribute is displayed.
31295 *
31296 * <div class="alert alert-info">
31297 * Be aware that the attribute values to match against cannot be expressions. They are interpreted
31298 * as literal string values to match against.
31299 * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
31300 * value of the expression `$scope.someVal`.
31301 * </div>
31302
31303 * @animations
31304 * | Animation | Occurs |
31305 * |----------------------------------|-------------------------------------|
31306 * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
31307 * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
31308 *
31309 * @usage
31310 *
31311 * ```
31312 * <ANY ng-switch="expression">
31313 * <ANY ng-switch-when="matchValue1">...</ANY>
31314 * <ANY ng-switch-when="matchValue2">...</ANY>
31315 * <ANY ng-switch-default>...</ANY>
31316 * </ANY>
31317 * ```
31318 *
31319 *
31320 * @scope
31321 * @priority 1200
31322 * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
31323 * On child elements add:
31324 *
31325 * * `ngSwitchWhen`: the case statement to match against. If match then this
31326 * case will be displayed. If the same match appears multiple times, all the
31327 * elements will be displayed. It is possible to associate multiple values to
31328 * the same `ngSwitchWhen` by defining the optional attribute
31329 * `ngSwitchWhenSeparator`. The separator will be used to split the value of
31330 * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
31331 * if any of the `ngSwitch` evaluates to any of these tokens.
31332 * * `ngSwitchDefault`: the default case when no other case match. If there
31333 * are multiple default cases, all of them will be displayed when no other
31334 * case match.
31335 *
31336 *
31337 * @example
31338 <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
31339 <file name="index.html">
31340 <div ng-controller="ExampleController">
31341 <select ng-model="selection" ng-options="item for item in items">
31342 </select>
31343 <code>selection={{selection}}</code>
31344 <hr/>
31345 <div class="animate-switch-container"
31346 ng-switch on="selection">
31347 <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
31348 <div class="animate-switch" ng-switch-when="home">Home Span</div>
31349 <div class="animate-switch" ng-switch-default>default</div>
31350 </div>
31351 </div>
31352 </file>
31353 <file name="script.js">
31354 angular.module('switchExample', ['ngAnimate'])
31355 .controller('ExampleController', ['$scope', function($scope) {
31356 $scope.items = ['settings', 'home', 'options', 'other'];
31357 $scope.selection = $scope.items[0];
31358 }]);
31359 </file>
31360 <file name="animations.css">
31361 .animate-switch-container {
31362 position:relative;
31363 background:white;
31364 border:1px solid black;
31365 height:40px;
31366 overflow:hidden;
31367 }
31368
31369 .animate-switch {
31370 padding:10px;
31371 }
31372
31373 .animate-switch.ng-animate {
31374 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
31375
31376 position:absolute;
31377 top:0;
31378 left:0;
31379 right:0;
31380 bottom:0;
31381 }
31382
31383 .animate-switch.ng-leave.ng-leave-active,
31384 .animate-switch.ng-enter {
31385 top:-50px;
31386 }
31387 .animate-switch.ng-leave,
31388 .animate-switch.ng-enter.ng-enter-active {
31389 top:0;
31390 }
31391 </file>
31392 <file name="protractor.js" type="protractor">
31393 var switchElem = element(by.css('[ng-switch]'));
31394 var select = element(by.model('selection'));
31395
31396 it('should start in settings', function() {
31397 expect(switchElem.getText()).toMatch(/Settings Div/);
31398 });
31399 it('should change to home', function() {
31400 select.all(by.css('option')).get(1).click();
31401 expect(switchElem.getText()).toMatch(/Home Span/);
31402 });
31403 it('should change to settings via "options"', function() {
31404 select.all(by.css('option')).get(2).click();
31405 expect(switchElem.getText()).toMatch(/Settings Div/);
31406 });
31407 it('should select default', function() {
31408 select.all(by.css('option')).get(3).click();
31409 expect(switchElem.getText()).toMatch(/default/);
31410 });
31411 </file>
31412 </example>
31413 */
31414var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
31415 return {
31416 require: 'ngSwitch',
31417
31418 // asks for $scope to fool the BC controller module
31419 controller: ['$scope', function NgSwitchController() {
31420 this.cases = {};
31421 }],
31422 link: function(scope, element, attr, ngSwitchController) {
31423 var watchExpr = attr.ngSwitch || attr.on,
31424 selectedTranscludes = [],
31425 selectedElements = [],
31426 previousLeaveAnimations = [],
31427 selectedScopes = [];
31428
31429 var spliceFactory = function(array, index) {
31430 return function(response) {
31431 if (response !== false) array.splice(index, 1);
31432 };
31433 };
31434
31435 scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
31436 var i, ii;
31437
31438 // Start with the last, in case the array is modified during the loop
31439 while (previousLeaveAnimations.length) {
31440 $animate.cancel(previousLeaveAnimations.pop());
31441 }
31442
31443 for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
31444 var selected = getBlockNodes(selectedElements[i].clone);
31445 selectedScopes[i].$destroy();
31446 var runner = previousLeaveAnimations[i] = $animate.leave(selected);
31447 runner.done(spliceFactory(previousLeaveAnimations, i));
31448 }
31449
31450 selectedElements.length = 0;
31451 selectedScopes.length = 0;
31452
31453 if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
31454 forEach(selectedTranscludes, function(selectedTransclude) {
31455 selectedTransclude.transclude(function(caseElement, selectedScope) {
31456 selectedScopes.push(selectedScope);
31457 var anchor = selectedTransclude.element;
31458 caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
31459 var block = { clone: caseElement };
31460
31461 selectedElements.push(block);
31462 $animate.enter(caseElement, anchor.parent(), anchor);
31463 });
31464 });
31465 }
31466 });
31467 }
31468 };
31469}];
31470
31471var ngSwitchWhenDirective = ngDirective({
31472 transclude: 'element',
31473 priority: 1200,
31474 require: '^ngSwitch',
31475 multiElement: true,
31476 link: function(scope, element, attrs, ctrl, $transclude) {
31477
31478 var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
31479 // Filter duplicate cases
31480 function(element, index, array) { return array[index - 1] !== element; }
31481 );
31482
31483 forEach(cases, function(whenCase) {
31484 ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
31485 ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
31486 });
31487 }
31488});
31489
31490var ngSwitchDefaultDirective = ngDirective({
31491 transclude: 'element',
31492 priority: 1200,
31493 require: '^ngSwitch',
31494 multiElement: true,
31495 link: function(scope, element, attr, ctrl, $transclude) {
31496 ctrl.cases['?'] = (ctrl.cases['?'] || []);
31497 ctrl.cases['?'].push({ transclude: $transclude, element: element });
31498 }
31499});
31500
31501/**
31502 * @ngdoc directive
31503 * @name ngTransclude
31504 * @restrict EAC
31505 *
31506 * @description
31507 * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
31508 *
31509 * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
31510 * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
31511 *
31512 * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
31513 * content of this element will be removed before the transcluded content is inserted.
31514 * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
31515 * content in the case that no transcluded content is provided.
31516 *
31517 * @element ANY
31518 *
31519 * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
31520 * or its value is the same as the name of the attribute then the default slot is used.
31521 *
31522 * @example
31523 * ### Basic transclusion
31524 * This example demonstrates basic transclusion of content into a component directive.
31525 * <example name="simpleTranscludeExample" module="transcludeExample">
31526 * <file name="index.html">
31527 * <script>
31528 * angular.module('transcludeExample', [])
31529 * .directive('pane', function(){
31530 * return {
31531 * restrict: 'E',
31532 * transclude: true,
31533 * scope: { title:'@' },
31534 * template: '<div style="border: 1px solid black;">' +
31535 * '<div style="background-color: gray">{{title}}</div>' +
31536 * '<ng-transclude></ng-transclude>' +
31537 * '</div>'
31538 * };
31539 * })
31540 * .controller('ExampleController', ['$scope', function($scope) {
31541 * $scope.title = 'Lorem Ipsum';
31542 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
31543 * }]);
31544 * </script>
31545 * <div ng-controller="ExampleController">
31546 * <input ng-model="title" aria-label="title"> <br/>
31547 * <textarea ng-model="text" aria-label="text"></textarea> <br/>
31548 * <pane title="{{title}}"><span>{{text}}</span></pane>
31549 * </div>
31550 * </file>
31551 * <file name="protractor.js" type="protractor">
31552 * it('should have transcluded', function() {
31553 * var titleElement = element(by.model('title'));
31554 * titleElement.clear();
31555 * titleElement.sendKeys('TITLE');
31556 * var textElement = element(by.model('text'));
31557 * textElement.clear();
31558 * textElement.sendKeys('TEXT');
31559 * expect(element(by.binding('title')).getText()).toEqual('TITLE');
31560 * expect(element(by.binding('text')).getText()).toEqual('TEXT');
31561 * });
31562 * </file>
31563 * </example>
31564 *
31565 * @example
31566 * ### Transclude fallback content
31567 * This example shows how to use `NgTransclude` with fallback content, that
31568 * is displayed if no transcluded content is provided.
31569 *
31570 * <example module="transcludeFallbackContentExample" name="ng-transclude">
31571 * <file name="index.html">
31572 * <script>
31573 * angular.module('transcludeFallbackContentExample', [])
31574 * .directive('myButton', function(){
31575 * return {
31576 * restrict: 'E',
31577 * transclude: true,
31578 * scope: true,
31579 * template: '<button style="cursor: pointer;">' +
31580 * '<ng-transclude>' +
31581 * '<b style="color: red;">Button1</b>' +
31582 * '</ng-transclude>' +
31583 * '</button>'
31584 * };
31585 * });
31586 * </script>
31587 * <!-- fallback button content -->
31588 * <my-button id="fallback"></my-button>
31589 * <!-- modified button content -->
31590 * <my-button id="modified">
31591 * <i style="color: green;">Button2</i>
31592 * </my-button>
31593 * </file>
31594 * <file name="protractor.js" type="protractor">
31595 * it('should have different transclude element content', function() {
31596 * expect(element(by.id('fallback')).getText()).toBe('Button1');
31597 * expect(element(by.id('modified')).getText()).toBe('Button2');
31598 * });
31599 * </file>
31600 * </example>
31601 *
31602 * @example
31603 * ### Multi-slot transclusion
31604 * This example demonstrates using multi-slot transclusion in a component directive.
31605 * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
31606 * <file name="index.html">
31607 * <style>
31608 * .title, .footer {
31609 * background-color: gray
31610 * }
31611 * </style>
31612 * <div ng-controller="ExampleController">
31613 * <input ng-model="title" aria-label="title"> <br/>
31614 * <textarea ng-model="text" aria-label="text"></textarea> <br/>
31615 * <pane>
31616 * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
31617 * <pane-body><p>{{text}}</p></pane-body>
31618 * </pane>
31619 * </div>
31620 * </file>
31621 * <file name="app.js">
31622 * angular.module('multiSlotTranscludeExample', [])
31623 * .directive('pane', function() {
31624 * return {
31625 * restrict: 'E',
31626 * transclude: {
31627 * 'title': '?paneTitle',
31628 * 'body': 'paneBody',
31629 * 'footer': '?paneFooter'
31630 * },
31631 * template: '<div style="border: 1px solid black;">' +
31632 * '<div class="title" ng-transclude="title">Fallback Title</div>' +
31633 * '<div ng-transclude="body"></div>' +
31634 * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
31635 * '</div>'
31636 * };
31637 * })
31638 * .controller('ExampleController', ['$scope', function($scope) {
31639 * $scope.title = 'Lorem Ipsum';
31640 * $scope.link = 'https://google.com';
31641 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
31642 * }]);
31643 * </file>
31644 * <file name="protractor.js" type="protractor">
31645 * it('should have transcluded the title and the body', function() {
31646 * var titleElement = element(by.model('title'));
31647 * titleElement.clear();
31648 * titleElement.sendKeys('TITLE');
31649 * var textElement = element(by.model('text'));
31650 * textElement.clear();
31651 * textElement.sendKeys('TEXT');
31652 * expect(element(by.css('.title')).getText()).toEqual('TITLE');
31653 * expect(element(by.binding('text')).getText()).toEqual('TEXT');
31654 * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
31655 * });
31656 * </file>
31657 * </example>
31658 */
31659var ngTranscludeMinErr = minErr('ngTransclude');
31660var ngTranscludeDirective = ['$compile', function($compile) {
31661 return {
31662 restrict: 'EAC',
31663 terminal: true,
31664 compile: function ngTranscludeCompile(tElement) {
31665
31666 // Remove and cache any original content to act as a fallback
31667 var fallbackLinkFn = $compile(tElement.contents());
31668 tElement.empty();
31669
31670 return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
31671
31672 if (!$transclude) {
31673 throw ngTranscludeMinErr('orphan',
31674 'Illegal use of ngTransclude directive in the template! ' +
31675 'No parent directive that requires a transclusion found. ' +
31676 'Element: {0}',
31677 startingTag($element));
31678 }
31679
31680
31681 // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
31682 if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
31683 $attrs.ngTransclude = '';
31684 }
31685 var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
31686
31687 // If the slot is required and no transclusion content is provided then this call will throw an error
31688 $transclude(ngTranscludeCloneAttachFn, null, slotName);
31689
31690 // If the slot is optional and no transclusion content is provided then use the fallback content
31691 if (slotName && !$transclude.isSlotFilled(slotName)) {
31692 useFallbackContent();
31693 }
31694
31695 function ngTranscludeCloneAttachFn(clone, transcludedScope) {
31696 if (clone.length && notWhitespace(clone)) {
31697 $element.append(clone);
31698 } else {
31699 useFallbackContent();
31700 // There is nothing linked against the transcluded scope since no content was available,
31701 // so it should be safe to clean up the generated scope.
31702 transcludedScope.$destroy();
31703 }
31704 }
31705
31706 function useFallbackContent() {
31707 // Since this is the fallback content rather than the transcluded content,
31708 // we link against the scope of this directive rather than the transcluded scope
31709 fallbackLinkFn($scope, function(clone) {
31710 $element.append(clone);
31711 });
31712 }
31713
31714 function notWhitespace(nodes) {
31715 for (var i = 0, ii = nodes.length; i < ii; i++) {
31716 var node = nodes[i];
31717 if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
31718 return true;
31719 }
31720 }
31721 }
31722 };
31723 }
31724 };
31725}];
31726
31727/**
31728 * @ngdoc directive
31729 * @name script
31730 * @restrict E
31731 *
31732 * @description
31733 * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
31734 * template can be used by {@link ng.directive:ngInclude `ngInclude`},
31735 * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
31736 * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
31737 * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
31738 *
31739 * @param {string} type Must be set to `'text/ng-template'`.
31740 * @param {string} id Cache name of the template.
31741 *
31742 * @example
31743 <example name="script-tag">
31744 <file name="index.html">
31745 <script type="text/ng-template" id="/tpl.html">
31746 Content of the template.
31747 </script>
31748
31749 <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
31750 <div id="tpl-content" ng-include src="currentTpl"></div>
31751 </file>
31752 <file name="protractor.js" type="protractor">
31753 it('should load template defined inside script tag', function() {
31754 element(by.css('#tpl-link')).click();
31755 expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
31756 });
31757 </file>
31758 </example>
31759 */
31760var scriptDirective = ['$templateCache', function($templateCache) {
31761 return {
31762 restrict: 'E',
31763 terminal: true,
31764 compile: function(element, attr) {
31765 if (attr.type === 'text/ng-template') {
31766 var templateUrl = attr.id,
31767 text = element[0].text;
31768
31769 $templateCache.put(templateUrl, text);
31770 }
31771 }
31772 };
31773}];
31774
31775/* exported selectDirective, optionDirective */
31776
31777var noopNgModelController = { $setViewValue: noop, $render: noop };
31778
31779/**
31780 * @ngdoc type
31781 * @name select.SelectController
31782 * @description
31783 * The controller for the `<select>` directive. This provides support for reading
31784 * and writing the selected value(s) of the control and also coordinates dynamically
31785 * added `<option>` elements, perhaps by an `ngRepeat` directive.
31786 */
31787var SelectController =
31788 ['$element', '$scope', /** @this */ function($element, $scope) {
31789
31790 var self = this,
31791 optionsMap = new HashMap();
31792
31793 self.selectValueMap = {}; // Keys are the hashed values, values the original values
31794
31795 // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
31796 self.ngModelCtrl = noopNgModelController;
31797 self.multiple = false;
31798
31799 // The "unknown" option is one that is prepended to the list if the viewValue
31800 // does not match any of the options. When it is rendered the value of the unknown
31801 // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
31802 //
31803 // We can't just jqLite('<option>') since jqLite is not smart enough
31804 // to create it in <select> and IE barfs otherwise.
31805 self.unknownOption = jqLite(window.document.createElement('option'));
31806
31807 // The empty option is an option with the value '' that te application developer can
31808 // provide inside the select. When the model changes to a value that doesn't match an option,
31809 // it is selected - so if an empty option is provided, no unknown option is generated.
31810 // However, the empty option is not removed when the model matches an option. It is always selectable
31811 // and indicates that a "null" selection has been made.
31812 self.hasEmptyOption = false;
31813 self.emptyOption = undefined;
31814
31815 self.renderUnknownOption = function(val) {
31816 var unknownVal = self.generateUnknownOptionValue(val);
31817 self.unknownOption.val(unknownVal);
31818 $element.prepend(self.unknownOption);
31819 setOptionAsSelected(self.unknownOption);
31820 $element.val(unknownVal);
31821 };
31822
31823 self.updateUnknownOption = function(val) {
31824 var unknownVal = self.generateUnknownOptionValue(val);
31825 self.unknownOption.val(unknownVal);
31826 setOptionAsSelected(self.unknownOption);
31827 $element.val(unknownVal);
31828 };
31829
31830 self.generateUnknownOptionValue = function(val) {
31831 return '? ' + hashKey(val) + ' ?';
31832 };
31833
31834 self.removeUnknownOption = function() {
31835 if (self.unknownOption.parent()) self.unknownOption.remove();
31836 };
31837
31838 self.selectEmptyOption = function() {
31839 if (self.emptyOption) {
31840 $element.val('');
31841 setOptionAsSelected(self.emptyOption);
31842 }
31843 };
31844
31845 self.unselectEmptyOption = function() {
31846 if (self.hasEmptyOption) {
31847 self.emptyOption.removeAttr('selected');
31848 }
31849 };
31850
31851 $scope.$on('$destroy', function() {
31852 // disable unknown option so that we don't do work when the whole select is being destroyed
31853 self.renderUnknownOption = noop;
31854 });
31855
31856 // Read the value of the select control, the implementation of this changes depending
31857 // upon whether the select can have multiple values and whether ngOptions is at work.
31858 self.readValue = function readSingleValue() {
31859 var val = $element.val();
31860 // ngValue added option values are stored in the selectValueMap, normal interpolations are not
31861 var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
31862
31863 if (self.hasOption(realVal)) {
31864 return realVal;
31865 }
31866
31867 return null;
31868 };
31869
31870
31871 // Write the value to the select control, the implementation of this changes depending
31872 // upon whether the select can have multiple values and whether ngOptions is at work.
31873 self.writeValue = function writeSingleValue(value) {
31874 // Make sure to remove the selected attribute from the previously selected option
31875 // Otherwise, screen readers might get confused
31876 var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
31877 if (currentlySelectedOption) currentlySelectedOption.removeAttribute('selected');
31878
31879 if (self.hasOption(value)) {
31880 self.removeUnknownOption();
31881
31882 var hashedVal = hashKey(value);
31883 $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
31884
31885 // Set selected attribute and property on selected option for screen readers
31886 var selectedOption = $element[0].options[$element[0].selectedIndex];
31887 setOptionAsSelected(jqLite(selectedOption));
31888 } else {
31889 if (value == null && self.emptyOption) {
31890 self.removeUnknownOption();
31891 self.selectEmptyOption();
31892 } else if (self.unknownOption.parent().length) {
31893 self.updateUnknownOption(value);
31894 } else {
31895 self.renderUnknownOption(value);
31896 }
31897 }
31898 };
31899
31900
31901 // Tell the select control that an option, with the given value, has been added
31902 self.addOption = function(value, element) {
31903 // Skip comment nodes, as they only pollute the `optionsMap`
31904 if (element[0].nodeType === NODE_TYPE_COMMENT) return;
31905
31906 assertNotHasOwnProperty(value, '"option value"');
31907 if (value === '') {
31908 self.hasEmptyOption = true;
31909 self.emptyOption = element;
31910 }
31911 var count = optionsMap.get(value) || 0;
31912 optionsMap.put(value, count + 1);
31913 // Only render at the end of a digest. This improves render performance when many options
31914 // are added during a digest and ensures all relevant options are correctly marked as selected
31915 scheduleRender();
31916 };
31917
31918 // Tell the select control that an option, with the given value, has been removed
31919 self.removeOption = function(value) {
31920 var count = optionsMap.get(value);
31921 if (count) {
31922 if (count === 1) {
31923 optionsMap.remove(value);
31924 if (value === '') {
31925 self.hasEmptyOption = false;
31926 self.emptyOption = undefined;
31927 }
31928 } else {
31929 optionsMap.put(value, count - 1);
31930 }
31931 }
31932 };
31933
31934 // Check whether the select control has an option matching the given value
31935 self.hasOption = function(value) {
31936 return !!optionsMap.get(value);
31937 };
31938
31939
31940 var renderScheduled = false;
31941 function scheduleRender() {
31942 if (renderScheduled) return;
31943 renderScheduled = true;
31944 $scope.$$postDigest(function() {
31945 renderScheduled = false;
31946 self.ngModelCtrl.$render();
31947 });
31948 }
31949
31950 var updateScheduled = false;
31951 function scheduleViewValueUpdate(renderAfter) {
31952 if (updateScheduled) return;
31953
31954 updateScheduled = true;
31955
31956 $scope.$$postDigest(function() {
31957 if ($scope.$$destroyed) return;
31958
31959 updateScheduled = false;
31960 self.ngModelCtrl.$setViewValue(self.readValue());
31961 if (renderAfter) self.ngModelCtrl.$render();
31962 });
31963 }
31964
31965
31966 self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
31967
31968 if (optionAttrs.$attr.ngValue) {
31969 // The value attribute is set by ngValue
31970 var oldVal, hashedVal = NaN;
31971 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
31972
31973 var removal;
31974 var previouslySelected = optionElement.prop('selected');
31975
31976 if (isDefined(hashedVal)) {
31977 self.removeOption(oldVal);
31978 delete self.selectValueMap[hashedVal];
31979 removal = true;
31980 }
31981
31982 hashedVal = hashKey(newVal);
31983 oldVal = newVal;
31984 self.selectValueMap[hashedVal] = newVal;
31985 self.addOption(newVal, optionElement);
31986 // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
31987 // from firing a second time. Other $observers on value will also get the result of the
31988 // ngValue expression, not the hashed value
31989 optionElement.attr('value', hashedVal);
31990
31991 if (removal && previouslySelected) {
31992 scheduleViewValueUpdate();
31993 }
31994
31995 });
31996 } else if (interpolateValueFn) {
31997 // The value attribute is interpolated
31998 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
31999 // This method is overwritten in ngOptions and has side-effects!
32000 self.readValue();
32001
32002 var removal;
32003 var previouslySelected = optionElement.prop('selected');
32004
32005 if (isDefined(oldVal)) {
32006 self.removeOption(oldVal);
32007 removal = true;
32008 }
32009 oldVal = newVal;
32010 self.addOption(newVal, optionElement);
32011
32012 if (removal && previouslySelected) {
32013 scheduleViewValueUpdate();
32014 }
32015 });
32016 } else if (interpolateTextFn) {
32017 // The text content is interpolated
32018 optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
32019 optionAttrs.$set('value', newVal);
32020 var previouslySelected = optionElement.prop('selected');
32021 if (oldVal !== newVal) {
32022 self.removeOption(oldVal);
32023 }
32024 self.addOption(newVal, optionElement);
32025
32026 if (oldVal && previouslySelected) {
32027 scheduleViewValueUpdate();
32028 }
32029 });
32030 } else {
32031 // The value attribute is static
32032 self.addOption(optionAttrs.value, optionElement);
32033 }
32034
32035
32036 optionAttrs.$observe('disabled', function(newVal) {
32037
32038 // Since model updates will also select disabled options (like ngOptions),
32039 // we only have to handle options becoming disabled, not enabled
32040
32041 if (newVal === 'true' || newVal && optionElement.prop('selected')) {
32042 if (self.multiple) {
32043 scheduleViewValueUpdate(true);
32044 } else {
32045 self.ngModelCtrl.$setViewValue(null);
32046 self.ngModelCtrl.$render();
32047 }
32048 }
32049 });
32050
32051 optionElement.on('$destroy', function() {
32052 var currentValue = self.readValue();
32053 var removeValue = optionAttrs.value;
32054
32055 self.removeOption(removeValue);
32056 self.ngModelCtrl.$render();
32057
32058 if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
32059 currentValue === removeValue
32060 ) {
32061 // When multiple (selected) options are destroyed at the same time, we don't want
32062 // to run a model update for each of them. Instead, run a single update in the $$postDigest
32063 scheduleViewValueUpdate(true);
32064 }
32065 });
32066 };
32067
32068 function setOptionAsSelected(optionEl) {
32069 optionEl.prop('selected', true); // needed for IE
32070 optionEl.attr('selected', true);
32071 }
32072}];
32073
32074/**
32075 * @ngdoc directive
32076 * @name select
32077 * @restrict E
32078 *
32079 * @description
32080 * HTML `select` element with angular data-binding.
32081 *
32082 * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
32083 * between the scope and the `<select>` control (including setting default values).
32084 * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
32085 * {@link ngOptions `ngOptions`} directives.
32086 *
32087 * When an item in the `<select>` menu is selected, the value of the selected option will be bound
32088 * to the model identified by the `ngModel` directive. With static or repeated options, this is
32089 * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
32090 * Value and textContent can be interpolated.
32091 *
32092 * ## Matching model and option values
32093 *
32094 * In general, the match between the model and an option is evaluated by strictly comparing the model
32095 * value against the value of the available options.
32096 *
32097 * If you are setting the option value with the option's `value` attribute, or textContent, the
32098 * value will always be a `string` which means that the model value must also be a string.
32099 * Otherwise the `select` directive cannot match them correctly.
32100 *
32101 * To bind the model to a non-string value, you can use one of the following strategies:
32102 * - the {@link ng.ngOptions `ngOptions`} directive
32103 * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
32104 * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
32105 * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
32106 * - model $parsers / $formatters to convert the string value
32107 * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
32108 *
32109 * If the viewValue of `ngModel` does not match any of the options, then the control
32110 * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
32111 *
32112 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
32113 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
32114 * option. See example below for demonstration.
32115 *
32116 * ## Choosing between `ngRepeat` and `ngOptions`
32117 *
32118 * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
32119 * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
32120 * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
32121 * comprehension expression
32122 * - reduced memory consumption by not creating a new scope for each repeated instance
32123 * - increased render speed by creating the options in a documentFragment instead of individually
32124 *
32125 * Specifically, select with repeated options slows down significantly starting at 2000 options in
32126 * Chrome and Internet Explorer / Edge.
32127 *
32128 *
32129 * @param {string} ngModel Assignable angular expression to data-bind to.
32130 * @param {string=} name Property name of the form under which the control is published.
32131 * @param {string=} multiple Allows multiple options to be selected. The selected values will be
32132 * bound to the model as an array.
32133 * @param {string=} required Sets `required` validation error key if the value is not entered.
32134 * @param {string=} ngRequired Adds required attribute and required validation constraint to
32135 * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
32136 * when you want to data-bind to the required attribute.
32137 * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
32138 * interaction with the select element.
32139 * @param {string=} ngOptions sets the options that the select is populated with and defines what is
32140 * set on the model on selection. See {@link ngOptions `ngOptions`}.
32141 *
32142 * @example
32143 * ### Simple `select` elements with static options
32144 *
32145 * <example name="static-select" module="staticSelect">
32146 * <file name="index.html">
32147 * <div ng-controller="ExampleController">
32148 * <form name="myForm">
32149 * <label for="singleSelect"> Single select: </label><br>
32150 * <select name="singleSelect" ng-model="data.singleSelect">
32151 * <option value="option-1">Option 1</option>
32152 * <option value="option-2">Option 2</option>
32153 * </select><br>
32154 *
32155 * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
32156 * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
32157 * <option value="">---Please select---</option> <!-- not selected / blank option -->
32158 * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
32159 * <option value="option-2">Option 2</option>
32160 * </select><br>
32161 * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
32162 * <tt>singleSelect = {{data.singleSelect}}</tt>
32163 *
32164 * <hr>
32165 * <label for="multipleSelect"> Multiple select: </label><br>
32166 * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
32167 * <option value="option-1">Option 1</option>
32168 * <option value="option-2">Option 2</option>
32169 * <option value="option-3">Option 3</option>
32170 * </select><br>
32171 * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
32172 * </form>
32173 * </div>
32174 * </file>
32175 * <file name="app.js">
32176 * angular.module('staticSelect', [])
32177 * .controller('ExampleController', ['$scope', function($scope) {
32178 * $scope.data = {
32179 * singleSelect: null,
32180 * multipleSelect: [],
32181 * option1: 'option-1'
32182 * };
32183 *
32184 * $scope.forceUnknownOption = function() {
32185 * $scope.data.singleSelect = 'nonsense';
32186 * };
32187 * }]);
32188 * </file>
32189 *</example>
32190 *
32191 * ### Using `ngRepeat` to generate `select` options
32192 * <example name="select-ngrepeat" module="ngrepeatSelect">
32193 * <file name="index.html">
32194 * <div ng-controller="ExampleController">
32195 * <form name="myForm">
32196 * <label for="repeatSelect"> Repeat select: </label>
32197 * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
32198 * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
32199 * </select>
32200 * </form>
32201 * <hr>
32202 * <tt>model = {{data.model}}</tt><br/>
32203 * </div>
32204 * </file>
32205 * <file name="app.js">
32206 * angular.module('ngrepeatSelect', [])
32207 * .controller('ExampleController', ['$scope', function($scope) {
32208 * $scope.data = {
32209 * model: null,
32210 * availableOptions: [
32211 * {id: '1', name: 'Option A'},
32212 * {id: '2', name: 'Option B'},
32213 * {id: '3', name: 'Option C'}
32214 * ]
32215 * };
32216 * }]);
32217 * </file>
32218 *</example>
32219 *
32220 * ### Using `ngValue` to bind the model to an array of objects
32221 * <example name="select-ngvalue" module="ngvalueSelect">
32222 * <file name="index.html">
32223 * <div ng-controller="ExampleController">
32224 * <form name="myForm">
32225 * <label for="ngvalueselect"> ngvalue select: </label>
32226 * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
32227 * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
32228 * </select>
32229 * </form>
32230 * <hr>
32231 * <pre>model = {{data.model | json}}</pre><br/>
32232 * </div>
32233 * </file>
32234 * <file name="app.js">
32235 * angular.module('ngvalueSelect', [])
32236 * .controller('ExampleController', ['$scope', function($scope) {
32237 * $scope.data = {
32238 * model: null,
32239 * availableOptions: [
32240 {value: 'myString', name: 'string'},
32241 {value: 1, name: 'integer'},
32242 {value: true, name: 'boolean'},
32243 {value: null, name: 'null'},
32244 {value: {prop: 'value'}, name: 'object'},
32245 {value: ['a'], name: 'array'}
32246 * ]
32247 * };
32248 * }]);
32249 * </file>
32250 *</example>
32251 *
32252 * ### Using `select` with `ngOptions` and setting a default value
32253 * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
32254 *
32255 * <example name="select-with-default-values" module="defaultValueSelect">
32256 * <file name="index.html">
32257 * <div ng-controller="ExampleController">
32258 * <form name="myForm">
32259 * <label for="mySelect">Make a choice:</label>
32260 * <select name="mySelect" id="mySelect"
32261 * ng-options="option.name for option in data.availableOptions track by option.id"
32262 * ng-model="data.selectedOption"></select>
32263 * </form>
32264 * <hr>
32265 * <tt>option = {{data.selectedOption}}</tt><br/>
32266 * </div>
32267 * </file>
32268 * <file name="app.js">
32269 * angular.module('defaultValueSelect', [])
32270 * .controller('ExampleController', ['$scope', function($scope) {
32271 * $scope.data = {
32272 * availableOptions: [
32273 * {id: '1', name: 'Option A'},
32274 * {id: '2', name: 'Option B'},
32275 * {id: '3', name: 'Option C'}
32276 * ],
32277 * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
32278 * };
32279 * }]);
32280 * </file>
32281 *</example>
32282 *
32283 *
32284 * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
32285 *
32286 * <example name="select-with-non-string-options" module="nonStringSelect">
32287 * <file name="index.html">
32288 * <select ng-model="model.id" convert-to-number>
32289 * <option value="0">Zero</option>
32290 * <option value="1">One</option>
32291 * <option value="2">Two</option>
32292 * </select>
32293 * {{ model }}
32294 * </file>
32295 * <file name="app.js">
32296 * angular.module('nonStringSelect', [])
32297 * .run(function($rootScope) {
32298 * $rootScope.model = { id: 2 };
32299 * })
32300 * .directive('convertToNumber', function() {
32301 * return {
32302 * require: 'ngModel',
32303 * link: function(scope, element, attrs, ngModel) {
32304 * ngModel.$parsers.push(function(val) {
32305 * return parseInt(val, 10);
32306 * });
32307 * ngModel.$formatters.push(function(val) {
32308 * return '' + val;
32309 * });
32310 * }
32311 * };
32312 * });
32313 * </file>
32314 * <file name="protractor.js" type="protractor">
32315 * it('should initialize to model', function() {
32316 * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
32317 * });
32318 * </file>
32319 * </example>
32320 *
32321 */
32322var selectDirective = function() {
32323
32324 return {
32325 restrict: 'E',
32326 require: ['select', '?ngModel'],
32327 controller: SelectController,
32328 priority: 1,
32329 link: {
32330 pre: selectPreLink,
32331 post: selectPostLink
32332 }
32333 };
32334
32335 function selectPreLink(scope, element, attr, ctrls) {
32336
32337 var selectCtrl = ctrls[0];
32338 var ngModelCtrl = ctrls[1];
32339
32340 // if ngModel is not defined, we don't need to do anything but set the registerOption
32341 // function to noop, so options don't get added internally
32342 if (!ngModelCtrl) {
32343 selectCtrl.registerOption = noop;
32344 return;
32345 }
32346
32347
32348 selectCtrl.ngModelCtrl = ngModelCtrl;
32349
32350 // When the selected item(s) changes we delegate getting the value of the select control
32351 // to the `readValue` method, which can be changed if the select can have multiple
32352 // selected values or if the options are being generated by `ngOptions`
32353 element.on('change', function() {
32354 selectCtrl.removeUnknownOption();
32355 scope.$apply(function() {
32356 ngModelCtrl.$setViewValue(selectCtrl.readValue());
32357 });
32358 });
32359
32360 // If the select allows multiple values then we need to modify how we read and write
32361 // values from and to the control; also what it means for the value to be empty and
32362 // we have to add an extra watch since ngModel doesn't work well with arrays - it
32363 // doesn't trigger rendering if only an item in the array changes.
32364 if (attr.multiple) {
32365 selectCtrl.multiple = true;
32366
32367 // Read value now needs to check each option to see if it is selected
32368 selectCtrl.readValue = function readMultipleValue() {
32369 var array = [];
32370 forEach(element.find('option'), function(option) {
32371 if (option.selected && !option.disabled) {
32372 var val = option.value;
32373 array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
32374 }
32375 });
32376 return array;
32377 };
32378
32379 // Write value now needs to set the selected property of each matching option
32380 selectCtrl.writeValue = function writeMultipleValue(value) {
32381 var items = new HashMap(value);
32382 forEach(element.find('option'), function(option) {
32383 option.selected = isDefined(items.get(option.value)) || isDefined(items.get(selectCtrl.selectValueMap[option.value]));
32384 });
32385 };
32386
32387 // we have to do it on each watch since ngModel watches reference, but
32388 // we need to work of an array, so we need to see if anything was inserted/removed
32389 var lastView, lastViewRef = NaN;
32390 scope.$watch(function selectMultipleWatch() {
32391 if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
32392 lastView = shallowCopy(ngModelCtrl.$viewValue);
32393 ngModelCtrl.$render();
32394 }
32395 lastViewRef = ngModelCtrl.$viewValue;
32396 });
32397
32398 // If we are a multiple select then value is now a collection
32399 // so the meaning of $isEmpty changes
32400 ngModelCtrl.$isEmpty = function(value) {
32401 return !value || value.length === 0;
32402 };
32403
32404 }
32405 }
32406
32407 function selectPostLink(scope, element, attrs, ctrls) {
32408 // if ngModel is not defined, we don't need to do anything
32409 var ngModelCtrl = ctrls[1];
32410 if (!ngModelCtrl) return;
32411
32412 var selectCtrl = ctrls[0];
32413
32414 // We delegate rendering to the `writeValue` method, which can be changed
32415 // if the select can have multiple selected values or if the options are being
32416 // generated by `ngOptions`.
32417 // This must be done in the postLink fn to prevent $render to be called before
32418 // all nodes have been linked correctly.
32419 ngModelCtrl.$render = function() {
32420 selectCtrl.writeValue(ngModelCtrl.$viewValue);
32421 };
32422 }
32423};
32424
32425
32426// The option directive is purely designed to communicate the existence (or lack of)
32427// of dynamically created (and destroyed) option elements to their containing select
32428// directive via its controller.
32429var optionDirective = ['$interpolate', function($interpolate) {
32430 return {
32431 restrict: 'E',
32432 priority: 100,
32433 compile: function(element, attr) {
32434 var interpolateValueFn, interpolateTextFn;
32435
32436 if (isDefined(attr.ngValue)) {
32437 // Will be handled by registerOption
32438 } else if (isDefined(attr.value)) {
32439 // If the value attribute is defined, check if it contains an interpolation
32440 interpolateValueFn = $interpolate(attr.value, true);
32441 } else {
32442 // If the value attribute is not defined then we fall back to the
32443 // text content of the option element, which may be interpolated
32444 interpolateTextFn = $interpolate(element.text(), true);
32445 if (!interpolateTextFn) {
32446 attr.$set('value', element.text());
32447 }
32448 }
32449
32450 return function(scope, element, attr) {
32451 // This is an optimization over using ^^ since we don't want to have to search
32452 // all the way to the root of the DOM for every single option element
32453 var selectCtrlName = '$selectController',
32454 parent = element.parent(),
32455 selectCtrl = parent.data(selectCtrlName) ||
32456 parent.parent().data(selectCtrlName); // in case we are in optgroup
32457
32458 if (selectCtrl) {
32459 selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
32460 }
32461 };
32462 }
32463 };
32464}];
32465
32466/**
32467 * @ngdoc directive
32468 * @name ngRequired
32469 * @restrict A
32470 *
32471 * @description
32472 *
32473 * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
32474 * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
32475 * applied to custom controls.
32476 *
32477 * The directive sets the `required` attribute on the element if the Angular expression inside
32478 * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
32479 * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
32480 * for more info.
32481 *
32482 * The validator will set the `required` error key to true if the `required` attribute is set and
32483 * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
32484 * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
32485 * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
32486 * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
32487 *
32488 * @example
32489 * <example name="ngRequiredDirective" module="ngRequiredExample">
32490 * <file name="index.html">
32491 * <script>
32492 * angular.module('ngRequiredExample', [])
32493 * .controller('ExampleController', ['$scope', function($scope) {
32494 * $scope.required = true;
32495 * }]);
32496 * </script>
32497 * <div ng-controller="ExampleController">
32498 * <form name="form">
32499 * <label for="required">Toggle required: </label>
32500 * <input type="checkbox" ng-model="required" id="required" />
32501 * <br>
32502 * <label for="input">This input must be filled if `required` is true: </label>
32503 * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
32504 * <hr>
32505 * required error set? = <code>{{form.input.$error.required}}</code><br>
32506 * model = <code>{{model}}</code>
32507 * </form>
32508 * </div>
32509 * </file>
32510 * <file name="protractor.js" type="protractor">
32511 var required = element(by.binding('form.input.$error.required'));
32512 var model = element(by.binding('model'));
32513 var input = element(by.id('input'));
32514
32515 it('should set the required error', function() {
32516 expect(required.getText()).toContain('true');
32517
32518 input.sendKeys('123');
32519 expect(required.getText()).not.toContain('true');
32520 expect(model.getText()).toContain('123');
32521 });
32522 * </file>
32523 * </example>
32524 */
32525var requiredDirective = function() {
32526 return {
32527 restrict: 'A',
32528 require: '?ngModel',
32529 link: function(scope, elm, attr, ctrl) {
32530 if (!ctrl) return;
32531 attr.required = true; // force truthy in case we are on non input element
32532
32533 ctrl.$validators.required = function(modelValue, viewValue) {
32534 return !attr.required || !ctrl.$isEmpty(viewValue);
32535 };
32536
32537 attr.$observe('required', function() {
32538 ctrl.$validate();
32539 });
32540 }
32541 };
32542};
32543
32544/**
32545 * @ngdoc directive
32546 * @name ngPattern
32547 *
32548 * @description
32549 *
32550 * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
32551 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
32552 *
32553 * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
32554 * does not match a RegExp which is obtained by evaluating the Angular expression given in the
32555 * `ngPattern` attribute value:
32556 * * If the expression evaluates to a RegExp object, then this is used directly.
32557 * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
32558 * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
32559 *
32560 * <div class="alert alert-info">
32561 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
32562 * start at the index of the last search's match, thus not taking the whole input value into
32563 * account.
32564 * </div>
32565 *
32566 * <div class="alert alert-info">
32567 * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
32568 * differences:
32569 * <ol>
32570 * <li>
32571 * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
32572 * not available.
32573 * </li>
32574 * <li>
32575 * The `ngPattern` attribute must be an expression, while the `pattern` value must be
32576 * interpolated.
32577 * </li>
32578 * </ol>
32579 * </div>
32580 *
32581 * @example
32582 * <example name="ngPatternDirective" module="ngPatternExample">
32583 * <file name="index.html">
32584 * <script>
32585 * angular.module('ngPatternExample', [])
32586 * .controller('ExampleController', ['$scope', function($scope) {
32587 * $scope.regex = '\\d+';
32588 * }]);
32589 * </script>
32590 * <div ng-controller="ExampleController">
32591 * <form name="form">
32592 * <label for="regex">Set a pattern (regex string): </label>
32593 * <input type="text" ng-model="regex" id="regex" />
32594 * <br>
32595 * <label for="input">This input is restricted by the current pattern: </label>
32596 * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
32597 * <hr>
32598 * input valid? = <code>{{form.input.$valid}}</code><br>
32599 * model = <code>{{model}}</code>
32600 * </form>
32601 * </div>
32602 * </file>
32603 * <file name="protractor.js" type="protractor">
32604 var model = element(by.binding('model'));
32605 var input = element(by.id('input'));
32606
32607 it('should validate the input with the default pattern', function() {
32608 input.sendKeys('aaa');
32609 expect(model.getText()).not.toContain('aaa');
32610
32611 input.clear().then(function() {
32612 input.sendKeys('123');
32613 expect(model.getText()).toContain('123');
32614 });
32615 });
32616 * </file>
32617 * </example>
32618 */
32619var patternDirective = function() {
32620 return {
32621 restrict: 'A',
32622 require: '?ngModel',
32623 link: function(scope, elm, attr, ctrl) {
32624 if (!ctrl) return;
32625
32626 var regexp, patternExp = attr.ngPattern || attr.pattern;
32627 attr.$observe('pattern', function(regex) {
32628 if (isString(regex) && regex.length > 0) {
32629 regex = new RegExp('^' + regex + '$');
32630 }
32631
32632 if (regex && !regex.test) {
32633 throw minErr('ngPattern')('noregexp',
32634 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
32635 regex, startingTag(elm));
32636 }
32637
32638 regexp = regex || undefined;
32639 ctrl.$validate();
32640 });
32641
32642 ctrl.$validators.pattern = function(modelValue, viewValue) {
32643 // HTML5 pattern constraint validates the input value, so we validate the viewValue
32644 return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
32645 };
32646 }
32647 };
32648};
32649
32650/**
32651 * @ngdoc directive
32652 * @name ngMaxlength
32653 *
32654 * @description
32655 *
32656 * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
32657 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
32658 *
32659 * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
32660 * is longer than the integer obtained by evaluating the Angular expression given in the
32661 * `ngMaxlength` attribute value.
32662 *
32663 * <div class="alert alert-info">
32664 * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
32665 * differences:
32666 * <ol>
32667 * <li>
32668 * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
32669 * validation is not available.
32670 * </li>
32671 * <li>
32672 * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
32673 * interpolated.
32674 * </li>
32675 * </ol>
32676 * </div>
32677 *
32678 * @example
32679 * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
32680 * <file name="index.html">
32681 * <script>
32682 * angular.module('ngMaxlengthExample', [])
32683 * .controller('ExampleController', ['$scope', function($scope) {
32684 * $scope.maxlength = 5;
32685 * }]);
32686 * </script>
32687 * <div ng-controller="ExampleController">
32688 * <form name="form">
32689 * <label for="maxlength">Set a maxlength: </label>
32690 * <input type="number" ng-model="maxlength" id="maxlength" />
32691 * <br>
32692 * <label for="input">This input is restricted by the current maxlength: </label>
32693 * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
32694 * <hr>
32695 * input valid? = <code>{{form.input.$valid}}</code><br>
32696 * model = <code>{{model}}</code>
32697 * </form>
32698 * </div>
32699 * </file>
32700 * <file name="protractor.js" type="protractor">
32701 var model = element(by.binding('model'));
32702 var input = element(by.id('input'));
32703
32704 it('should validate the input with the default maxlength', function() {
32705 input.sendKeys('abcdef');
32706 expect(model.getText()).not.toContain('abcdef');
32707
32708 input.clear().then(function() {
32709 input.sendKeys('abcde');
32710 expect(model.getText()).toContain('abcde');
32711 });
32712 });
32713 * </file>
32714 * </example>
32715 */
32716var maxlengthDirective = function() {
32717 return {
32718 restrict: 'A',
32719 require: '?ngModel',
32720 link: function(scope, elm, attr, ctrl) {
32721 if (!ctrl) return;
32722
32723 var maxlength = -1;
32724 attr.$observe('maxlength', function(value) {
32725 var intVal = toInt(value);
32726 maxlength = isNumberNaN(intVal) ? -1 : intVal;
32727 ctrl.$validate();
32728 });
32729 ctrl.$validators.maxlength = function(modelValue, viewValue) {
32730 return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
32731 };
32732 }
32733 };
32734};
32735
32736/**
32737 * @ngdoc directive
32738 * @name ngMinlength
32739 *
32740 * @description
32741 *
32742 * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
32743 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
32744 *
32745 * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
32746 * is shorter than the integer obtained by evaluating the Angular expression given in the
32747 * `ngMinlength` attribute value.
32748 *
32749 * <div class="alert alert-info">
32750 * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
32751 * differences:
32752 * <ol>
32753 * <li>
32754 * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
32755 * validation is not available.
32756 * </li>
32757 * <li>
32758 * The `ngMinlength` value must be an expression, while the `minlength` value must be
32759 * interpolated.
32760 * </li>
32761 * </ol>
32762 * </div>
32763 *
32764 * @example
32765 * <example name="ngMinlengthDirective" module="ngMinlengthExample">
32766 * <file name="index.html">
32767 * <script>
32768 * angular.module('ngMinlengthExample', [])
32769 * .controller('ExampleController', ['$scope', function($scope) {
32770 * $scope.minlength = 3;
32771 * }]);
32772 * </script>
32773 * <div ng-controller="ExampleController">
32774 * <form name="form">
32775 * <label for="minlength">Set a minlength: </label>
32776 * <input type="number" ng-model="minlength" id="minlength" />
32777 * <br>
32778 * <label for="input">This input is restricted by the current minlength: </label>
32779 * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
32780 * <hr>
32781 * input valid? = <code>{{form.input.$valid}}</code><br>
32782 * model = <code>{{model}}</code>
32783 * </form>
32784 * </div>
32785 * </file>
32786 * <file name="protractor.js" type="protractor">
32787 var model = element(by.binding('model'));
32788 var input = element(by.id('input'));
32789
32790 it('should validate the input with the default minlength', function() {
32791 input.sendKeys('ab');
32792 expect(model.getText()).not.toContain('ab');
32793
32794 input.sendKeys('abc');
32795 expect(model.getText()).toContain('abc');
32796 });
32797 * </file>
32798 * </example>
32799 */
32800var minlengthDirective = function() {
32801 return {
32802 restrict: 'A',
32803 require: '?ngModel',
32804 link: function(scope, elm, attr, ctrl) {
32805 if (!ctrl) return;
32806
32807 var minlength = 0;
32808 attr.$observe('minlength', function(value) {
32809 minlength = toInt(value) || 0;
32810 ctrl.$validate();
32811 });
32812 ctrl.$validators.minlength = function(modelValue, viewValue) {
32813 return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
32814 };
32815 }
32816 };
32817};
32818
32819if (window.angular.bootstrap) {
32820 // AngularJS is already loaded, so we can return here...
32821 if (window.console) {
32822 console.log('WARNING: Tried to load angular more than once.');
32823 }
32824 return;
32825}
32826
32827// try to bind to jquery now so that one can write jqLite(fn)
32828// but we will rebind on bootstrap again.
32829bindJQuery();
32830
32831publishExternalAPI(angular);
32832
32833angular.module("ngLocale", [], ["$provide", function($provide) {
32834var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
32835function getDecimals(n) {
32836 n = n + '';
32837 var i = n.indexOf('.');
32838 return (i == -1) ? 0 : n.length - i - 1;
32839}
32840
32841function getVF(n, opt_precision) {
32842 var v = opt_precision;
32843
32844 if (undefined === v) {
32845 v = Math.min(getDecimals(n), 3);
32846 }
32847
32848 var base = Math.pow(10, v);
32849 var f = ((n * base) | 0) % base;
32850 return {v: v, f: f};
32851}
32852
32853$provide.value("$locale", {
32854 "DATETIME_FORMATS": {
32855 "AMPMS": [
32856 "AM",
32857 "PM"
32858 ],
32859 "DAY": [
32860 "Sunday",
32861 "Monday",
32862 "Tuesday",
32863 "Wednesday",
32864 "Thursday",
32865 "Friday",
32866 "Saturday"
32867 ],
32868 "ERANAMES": [
32869 "Before Christ",
32870 "Anno Domini"
32871 ],
32872 "ERAS": [
32873 "BC",
32874 "AD"
32875 ],
32876 "FIRSTDAYOFWEEK": 6,
32877 "MONTH": [
32878 "January",
32879 "February",
32880 "March",
32881 "April",
32882 "May",
32883 "June",
32884 "July",
32885 "August",
32886 "September",
32887 "October",
32888 "November",
32889 "December"
32890 ],
32891 "SHORTDAY": [
32892 "Sun",
32893 "Mon",
32894 "Tue",
32895 "Wed",
32896 "Thu",
32897 "Fri",
32898 "Sat"
32899 ],
32900 "SHORTMONTH": [
32901 "Jan",
32902 "Feb",
32903 "Mar",
32904 "Apr",
32905 "May",
32906 "Jun",
32907 "Jul",
32908 "Aug",
32909 "Sep",
32910 "Oct",
32911 "Nov",
32912 "Dec"
32913 ],
32914 "STANDALONEMONTH": [
32915 "January",
32916 "February",
32917 "March",
32918 "April",
32919 "May",
32920 "June",
32921 "July",
32922 "August",
32923 "September",
32924 "October",
32925 "November",
32926 "December"
32927 ],
32928 "WEEKENDRANGE": [
32929 5,
32930 6
32931 ],
32932 "fullDate": "EEEE, MMMM d, y",
32933 "longDate": "MMMM d, y",
32934 "medium": "MMM d, y h:mm:ss a",
32935 "mediumDate": "MMM d, y",
32936 "mediumTime": "h:mm:ss a",
32937 "short": "M/d/yy h:mm a",
32938 "shortDate": "M/d/yy",
32939 "shortTime": "h:mm a"
32940 },
32941 "NUMBER_FORMATS": {
32942 "CURRENCY_SYM": "$",
32943 "DECIMAL_SEP": ".",
32944 "GROUP_SEP": ",",
32945 "PATTERNS": [
32946 {
32947 "gSize": 3,
32948 "lgSize": 3,
32949 "maxFrac": 3,
32950 "minFrac": 0,
32951 "minInt": 1,
32952 "negPre": "-",
32953 "negSuf": "",
32954 "posPre": "",
32955 "posSuf": ""
32956 },
32957 {
32958 "gSize": 3,
32959 "lgSize": 3,
32960 "maxFrac": 2,
32961 "minFrac": 2,
32962 "minInt": 1,
32963 "negPre": "-\u00a4",
32964 "negSuf": "",
32965 "posPre": "\u00a4",
32966 "posSuf": ""
32967 }
32968 ]
32969 },
32970 "id": "en-us",
32971 "localeID": "en_US",
32972 "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;}
32973});
32974}]);
32975
32976 jqLite(function() {
32977 angularInit(window.document, bootstrap);
32978 });
32979
32980})(window);
32981
32982!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>');