2 * @license AngularJS v1.5.0
3 * (c) 2010-2016 Google, Inc. http://angularjs.org
6 (function(window, document, undefined) {'use strict';
11 * This object provides a utility for producing rich Error messages within
12 * Angular. It can be called as follows:
14 * var exampleMinErr = minErr('example');
15 * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
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
23 * If fewer arguments are specified than necessary for interpolation, the extra
24 * interpolation markers will be preserved in the final string.
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.
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
38 function minErr(module, ErrorConstructor) {
39 ErrorConstructor = ErrorConstructor || Error;
43 var templateArgs = arguments,
44 code = templateArgs[0],
45 message = '[' + (module ? module + ':' : '') + code + '] ',
46 template = templateArgs[1],
49 message += template.replace(/\{\d+\}/g, function(match) {
50 var index = +match.slice(1, -1),
51 shiftedIndex = index + SKIP_INDEXES;
53 if (shiftedIndex < templateArgs.length) {
54 return toDebugString(templateArgs[shiftedIndex]);
60 message += '\nhttp://errors.angularjs.org/1.5.0/' +
61 (module ? module + '/' : '') + code;
63 for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
64 message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
65 encodeURIComponent(toDebugString(templateArgs[i]));
68 return new ErrorConstructor(message);
72 /* We need to tell jshint what variables are being exported */
73 /* global angular: true,
84 REGEX_STRING_REGEXP: true,
85 VALIDITY_STATE_PROPERTY: true,
89 manualLowercase: true,
90 manualUppercase: true,
123 escapeForRegexp: true,
136 toJsonReplacer: true,
139 convertTimezoneToLocal: true,
140 timezoneToOffset: true,
142 tryDecodeURIComponent: true,
145 encodeUriSegment: true,
146 encodeUriQuery: true,
149 getTestability: true,
154 assertNotHasOwnProperty: true,
157 hasOwnProperty: true,
160 NODE_TYPE_ELEMENT: true,
161 NODE_TYPE_ATTRIBUTE: true,
162 NODE_TYPE_TEXT: true,
163 NODE_TYPE_COMMENT: true,
164 NODE_TYPE_DOCUMENT: true,
165 NODE_TYPE_DOCUMENT_FRAGMENT: true,
168 ////////////////////////////////////
177 * The ng module is loaded by default when an AngularJS application is started. The module itself
178 * contains the essential components for an AngularJS application to function. The table below
179 * lists a high level breakdown of each of the services/factories, filters, directives and testing
180 * components available within this core module.
182 * <div doc-module-components="ng"></div>
185 var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
187 // The name of a form control's ValidityState property.
188 // This is used so that it's possible for internal tests to create mock ValidityStates.
189 var VALIDITY_STATE_PROPERTY = 'validity';
191 var hasOwnProperty = Object.prototype.hasOwnProperty;
193 var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
194 var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
197 var manualLowercase = function(s) {
198 /* jshint bitwise: false */
200 ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
203 var manualUppercase = function(s) {
204 /* jshint bitwise: false */
206 ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
211 // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
212 // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
213 // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
214 if ('i' !== 'I'.toLowerCase()) {
215 lowercase = manualLowercase;
216 uppercase = manualUppercase;
221 msie, // holds major version number for IE, or NaN if UA is not IE.
222 jqLite, // delay binding since jQuery could be loaded after us.
223 jQuery, // delay binding
227 toString = Object.prototype.toString,
228 getPrototypeOf = Object.getPrototypeOf,
229 ngMinErr = minErr('ng'),
232 angular = window.angular || (window.angular = {}),
237 * documentMode is an IE-only property
238 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
240 msie = document.documentMode;
246 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
249 function isArrayLike(obj) {
251 // `null`, `undefined` and `window` are not array-like
252 if (obj == null || isWindow(obj)) return false;
254 // arrays, strings and jQuery/jqLite objects are array like
255 // * jqLite is either the jQuery or jqLite constructor function
256 // * we have to check the existence of jqLite first as this method is called
257 // via the forEach method when constructing the jqLite object in the first place
258 if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
260 // Support: iOS 8.2 (not reproducible in simulator)
261 // "length" in obj used to prevent JIT error (gh-11508)
262 var length = "length" in Object(obj) && obj.length;
264 // NodeList objects (with `item` method) and
265 // other objects with suitable length characteristics are array-like
266 return isNumber(length) &&
267 (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item == 'function');
273 * @name angular.forEach
278 * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
279 * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
280 * is the value of an object property or an array element, `key` is the object property key or
281 * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
283 * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
284 * using the `hasOwnProperty` method.
287 * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
288 * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
289 * return the value provided.
292 var values = {name: 'misko', gender: 'male'};
294 angular.forEach(values, function(value, key) {
295 this.push(key + ': ' + value);
297 expect(log).toEqual(['name: misko', 'gender: male']);
300 * @param {Object|Array} obj Object to iterate over.
301 * @param {Function} iterator Iterator function.
302 * @param {Object=} context Object to become context (`this`) for the iterator function.
303 * @returns {Object|Array} Reference to `obj`.
306 function forEach(obj, iterator, context) {
309 if (isFunction(obj)) {
311 // Need to check if hasOwnProperty exists,
312 // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
313 if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
314 iterator.call(context, obj[key], key, obj);
317 } else if (isArray(obj) || isArrayLike(obj)) {
318 var isPrimitive = typeof obj !== 'object';
319 for (key = 0, length = obj.length; key < length; key++) {
320 if (isPrimitive || key in obj) {
321 iterator.call(context, obj[key], key, obj);
324 } else if (obj.forEach && obj.forEach !== forEach) {
325 obj.forEach(iterator, context, obj);
326 } else if (isBlankObject(obj)) {
327 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
329 iterator.call(context, obj[key], key, obj);
331 } else if (typeof obj.hasOwnProperty === 'function') {
332 // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
334 if (obj.hasOwnProperty(key)) {
335 iterator.call(context, obj[key], key, obj);
339 // Slow path for objects which do not have a method `hasOwnProperty`
341 if (hasOwnProperty.call(obj, key)) {
342 iterator.call(context, obj[key], key, obj);
350 function forEachSorted(obj, iterator, context) {
351 var keys = Object.keys(obj).sort();
352 for (var i = 0; i < keys.length; i++) {
353 iterator.call(context, obj[keys[i]], keys[i]);
360 * when using forEach the params are value, key, but it is often useful to have key, value.
361 * @param {function(string, *)} iteratorFn
362 * @returns {function(*, string)}
364 function reverseParams(iteratorFn) {
365 return function(value, key) {iteratorFn(key, value);};
369 * A consistent way of creating unique IDs in angular.
371 * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
372 * we hit number precision issues in JavaScript.
374 * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
376 * @returns {number} an unique alpha-numeric string
384 * Set or clear the hashkey for an object.
386 * @param h the hashkey (!truthy to delete the hashkey)
388 function setHashKey(obj, h) {
392 delete obj.$$hashKey;
397 function baseExtend(dst, objs, deep) {
398 var h = dst.$$hashKey;
400 for (var i = 0, ii = objs.length; i < ii; ++i) {
402 if (!isObject(obj) && !isFunction(obj)) continue;
403 var keys = Object.keys(obj);
404 for (var j = 0, jj = keys.length; j < jj; j++) {
408 if (deep && isObject(src)) {
410 dst[key] = new Date(src.valueOf());
411 } else if (isRegExp(src)) {
412 dst[key] = new RegExp(src);
413 } else if (src.nodeName) {
414 dst[key] = src.cloneNode(true);
415 } else if (isElement(src)) {
416 dst[key] = src.clone();
418 if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
419 baseExtend(dst[key], [src], true);
433 * @name angular.extend
438 * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
439 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
440 * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
442 * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
443 * {@link angular.merge} for this.
445 * @param {Object} dst Destination object.
446 * @param {...Object} src Source object(s).
447 * @returns {Object} Reference to `dst`.
449 function extend(dst) {
450 return baseExtend(dst, slice.call(arguments, 1), false);
456 * @name angular.merge
461 * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
462 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
463 * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
465 * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
466 * objects, performing a deep copy.
468 * @param {Object} dst Destination object.
469 * @param {...Object} src Source object(s).
470 * @returns {Object} Reference to `dst`.
472 function merge(dst) {
473 return baseExtend(dst, slice.call(arguments, 1), true);
478 function toInt(str) {
479 return parseInt(str, 10);
483 function inherit(parent, extra) {
484 return extend(Object.create(parent), extra);
494 * A function that performs no operations. This function can be useful when writing code in the
497 function foo(callback) {
498 var result = calculateResult();
499 (callback || angular.noop)(result);
509 * @name angular.identity
514 * A function that returns its first argument. This function is useful when writing code in the
518 function transformer(transformationFn, value) {
519 return (transformationFn || angular.identity)(value);
522 * @param {*} value to be returned.
523 * @returns {*} the value passed in.
525 function identity($) {return $;}
526 identity.$inject = [];
529 function valueFn(value) {return function() {return value;};}
531 function hasCustomToString(obj) {
532 return isFunction(obj.toString) && obj.toString !== toString;
538 * @name angular.isUndefined
543 * Determines if a reference is undefined.
545 * @param {*} value Reference to check.
546 * @returns {boolean} True if `value` is undefined.
548 function isUndefined(value) {return typeof value === 'undefined';}
553 * @name angular.isDefined
558 * Determines if a reference is defined.
560 * @param {*} value Reference to check.
561 * @returns {boolean} True if `value` is defined.
563 function isDefined(value) {return typeof value !== 'undefined';}
568 * @name angular.isObject
573 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
574 * considered to be objects. Note that JavaScript arrays are objects.
576 * @param {*} value Reference to check.
577 * @returns {boolean} True if `value` is an `Object` but not `null`.
579 function isObject(value) {
580 // http://jsperf.com/isobject4
581 return value !== null && typeof value === 'object';
586 * Determine if a value is an object with a null prototype
588 * @returns {boolean} True if `value` is an `Object` with a null prototype
590 function isBlankObject(value) {
591 return value !== null && typeof value === 'object' && !getPrototypeOf(value);
597 * @name angular.isString
602 * Determines if a reference is a `String`.
604 * @param {*} value Reference to check.
605 * @returns {boolean} True if `value` is a `String`.
607 function isString(value) {return typeof value === 'string';}
612 * @name angular.isNumber
617 * Determines if a reference is a `Number`.
619 * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
621 * If you wish to exclude these then you can use the native
622 * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
625 * @param {*} value Reference to check.
626 * @returns {boolean} True if `value` is a `Number`.
628 function isNumber(value) {return typeof value === 'number';}
633 * @name angular.isDate
638 * Determines if a value is a date.
640 * @param {*} value Reference to check.
641 * @returns {boolean} True if `value` is a `Date`.
643 function isDate(value) {
644 return toString.call(value) === '[object Date]';
650 * @name angular.isArray
655 * Determines if a reference is an `Array`.
657 * @param {*} value Reference to check.
658 * @returns {boolean} True if `value` is an `Array`.
660 var isArray = Array.isArray;
664 * @name angular.isFunction
669 * Determines if a reference is a `Function`.
671 * @param {*} value Reference to check.
672 * @returns {boolean} True if `value` is a `Function`.
674 function isFunction(value) {return typeof value === 'function';}
678 * Determines if a value is a regular expression object.
681 * @param {*} value Reference to check.
682 * @returns {boolean} True if `value` is a `RegExp`.
684 function isRegExp(value) {
685 return toString.call(value) === '[object RegExp]';
690 * Checks if `obj` is a window object.
693 * @param {*} obj Object to check
694 * @returns {boolean} True if `obj` is a window obj.
696 function isWindow(obj) {
697 return obj && obj.window === obj;
701 function isScope(obj) {
702 return obj && obj.$evalAsync && obj.$watch;
706 function isFile(obj) {
707 return toString.call(obj) === '[object File]';
711 function isFormData(obj) {
712 return toString.call(obj) === '[object FormData]';
716 function isBlob(obj) {
717 return toString.call(obj) === '[object Blob]';
721 function isBoolean(value) {
722 return typeof value === 'boolean';
726 function isPromiseLike(obj) {
727 return obj && isFunction(obj.then);
731 var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
732 function isTypedArray(value) {
733 return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
736 function isArrayBuffer(obj) {
737 return toString.call(obj) === '[object ArrayBuffer]';
741 var trim = function(value) {
742 return isString(value) ? value.trim() : value;
746 // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
747 // Prereq: s is a string.
748 var escapeForRegexp = function(s) {
749 return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
750 replace(/\x08/g, '\\x08');
756 * @name angular.isElement
761 * Determines if a reference is a DOM element (or wrapped jQuery element).
763 * @param {*} value Reference to check.
764 * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
766 function isElement(node) {
768 (node.nodeName // we are a direct element
769 || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
773 * @param str 'key1,key2,...'
774 * @returns {object} in the form of {key1:true, key2:true, ...}
776 function makeMap(str) {
777 var obj = {}, items = str.split(','), i;
778 for (i = 0; i < items.length; i++) {
779 obj[items[i]] = true;
785 function nodeName_(element) {
786 return lowercase(element.nodeName || (element[0] && element[0].nodeName));
789 function includes(array, obj) {
790 return Array.prototype.indexOf.call(array, obj) != -1;
793 function arrayRemove(array, value) {
794 var index = array.indexOf(value);
796 array.splice(index, 1);
808 * Creates a deep copy of `source`, which should be an object or an array.
810 * * If no destination is supplied, a copy of the object or array is created.
811 * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
812 * are deleted and then all elements/properties from the source are copied to it.
813 * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
814 * * If `source` is identical to 'destination' an exception will be thrown.
816 * @param {*} source The source that will be used to make a copy.
817 * Can be any type, including primitives, `null`, and `undefined`.
818 * @param {(Object|Array)=} destination Destination into which the source is copied. If
819 * provided, must be of the same type as `source`.
820 * @returns {*} The copy or updated `destination`, if `destination` was specified.
823 <example module="copyExample">
824 <file name="index.html">
825 <div ng-controller="ExampleController">
826 <form novalidate class="simple-form">
827 Name: <input type="text" ng-model="user.name" /><br />
828 E-mail: <input type="email" ng-model="user.email" /><br />
829 Gender: <input type="radio" ng-model="user.gender" value="male" />male
830 <input type="radio" ng-model="user.gender" value="female" />female<br />
831 <button ng-click="reset()">RESET</button>
832 <button ng-click="update(user)">SAVE</button>
834 <pre>form = {{user | json}}</pre>
835 <pre>master = {{master | json}}</pre>
839 angular.module('copyExample', [])
840 .controller('ExampleController', ['$scope', function($scope) {
843 $scope.update = function(user) {
844 // Example with 1 argument
845 $scope.master= angular.copy(user);
848 $scope.reset = function() {
849 // Example with 2 arguments
850 angular.copy($scope.master, $scope.user);
859 function copy(source, destination) {
860 var stackSource = [];
864 if (isTypedArray(destination) || isArrayBuffer(destination)) {
865 throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
867 if (source === destination) {
868 throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
871 // Empty the destination object
872 if (isArray(destination)) {
873 destination.length = 0;
875 forEach(destination, function(value, key) {
876 if (key !== '$$hashKey') {
877 delete destination[key];
882 stackSource.push(source);
883 stackDest.push(destination);
884 return copyRecurse(source, destination);
887 return copyElement(source);
889 function copyRecurse(source, destination) {
890 var h = destination.$$hashKey;
892 if (isArray(source)) {
893 for (var i = 0, ii = source.length; i < ii; i++) {
894 destination.push(copyElement(source[i]));
896 } else if (isBlankObject(source)) {
897 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
898 for (key in source) {
899 destination[key] = copyElement(source[key]);
901 } else if (source && typeof source.hasOwnProperty === 'function') {
902 // Slow path, which must rely on hasOwnProperty
903 for (key in source) {
904 if (source.hasOwnProperty(key)) {
905 destination[key] = copyElement(source[key]);
909 // Slowest path --- hasOwnProperty can't be called as a method
910 for (key in source) {
911 if (hasOwnProperty.call(source, key)) {
912 destination[key] = copyElement(source[key]);
916 setHashKey(destination, h);
920 function copyElement(source) {
922 if (!isObject(source)) {
926 // Already copied values
927 var index = stackSource.indexOf(source);
929 return stackDest[index];
932 if (isWindow(source) || isScope(source)) {
933 throw ngMinErr('cpws',
934 "Can't copy! Making copies of Window or Scope instances is not supported.");
937 var needsRecurse = false;
938 var destination = copyType(source);
940 if (destination === undefined) {
941 destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
945 stackSource.push(source);
946 stackDest.push(destination);
949 ? copyRecurse(source, destination)
953 function copyType(source) {
954 switch (toString.call(source)) {
955 case '[object Int8Array]':
956 case '[object Int16Array]':
957 case '[object Int32Array]':
958 case '[object Float32Array]':
959 case '[object Float64Array]':
960 case '[object Uint8Array]':
961 case '[object Uint8ClampedArray]':
962 case '[object Uint16Array]':
963 case '[object Uint32Array]':
964 return new source.constructor(copyElement(source.buffer));
966 case '[object ArrayBuffer]':
969 var copied = new ArrayBuffer(source.byteLength);
970 new Uint8Array(copied).set(new Uint8Array(source));
973 return source.slice(0);
975 case '[object Boolean]':
976 case '[object Number]':
977 case '[object String]':
978 case '[object Date]':
979 return new source.constructor(source.valueOf());
981 case '[object RegExp]':
982 var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
983 re.lastIndex = source.lastIndex;
987 if (isFunction(source.cloneNode)) {
988 return source.cloneNode(true);
994 * Creates a shallow copy of an object, an array or a primitive.
996 * Assumes that there are no proto properties for objects.
998 function shallowCopy(src, dst) {
1002 for (var i = 0, ii = src.length; i < ii; i++) {
1005 } else if (isObject(src)) {
1008 for (var key in src) {
1009 if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
1010 dst[key] = src[key];
1021 * @name angular.equals
1026 * Determines if two objects or two values are equivalent. Supports value types, regular
1027 * expressions, arrays and objects.
1029 * Two objects or values are considered equivalent if at least one of the following is true:
1031 * * Both objects or values pass `===` comparison.
1032 * * Both objects or values are of the same type and all of their properties are equal by
1033 * comparing them with `angular.equals`.
1034 * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
1035 * * Both values represent the same regular expression (In JavaScript,
1036 * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
1037 * representation matches).
1039 * During a property comparison, properties of `function` type and properties with names
1040 * that begin with `$` are ignored.
1042 * Scope and DOMWindow objects are being compared only by identify (`===`).
1044 * @param {*} o1 Object or value to compare.
1045 * @param {*} o2 Object or value to compare.
1046 * @returns {boolean} True if arguments are equal.
1048 function equals(o1, o2) {
1049 if (o1 === o2) return true;
1050 if (o1 === null || o2 === null) return false;
1051 if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
1052 var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
1053 if (t1 == t2 && t1 == 'object') {
1055 if (!isArray(o2)) return false;
1056 if ((length = o1.length) == o2.length) {
1057 for (key = 0; key < length; key++) {
1058 if (!equals(o1[key], o2[key])) return false;
1062 } else if (isDate(o1)) {
1063 if (!isDate(o2)) return false;
1064 return equals(o1.getTime(), o2.getTime());
1065 } else if (isRegExp(o1)) {
1066 if (!isRegExp(o2)) return false;
1067 return o1.toString() == o2.toString();
1069 if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
1070 isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
1071 keySet = createMap();
1073 if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
1074 if (!equals(o1[key], o2[key])) return false;
1078 if (!(key in keySet) &&
1079 key.charAt(0) !== '$' &&
1080 isDefined(o2[key]) &&
1081 !isFunction(o2[key])) return false;
1089 var csp = function() {
1090 if (!isDefined(csp.rules)) {
1093 var ngCspElement = (document.querySelector('[ng-csp]') ||
1094 document.querySelector('[data-ng-csp]'));
1097 var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
1098 ngCspElement.getAttribute('data-ng-csp');
1100 noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
1101 noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
1105 noUnsafeEval: noUnsafeEval(),
1106 noInlineStyle: false
1113 function noUnsafeEval() {
1115 /* jshint -W031, -W054 */
1117 /* jshint +W031, +W054 */
1131 * @param {string=} ngJq the name of the library available under `window`
1132 * to be used for angular.element
1134 * Use this directive to force the angular.element library. This should be
1135 * used to force either jqLite by leaving ng-jq blank or setting the name of
1136 * the jquery variable under window (eg. jQuery).
1138 * Since angular looks for this directive when it is loaded (doesn't wait for the
1139 * DOMContentLoaded event), it must be placed on an element that comes before the script
1140 * which loads angular. Also, only the first instance of `ng-jq` will be used and all
1144 * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
1153 * This example shows how to use a jQuery based library of a different name.
1154 * The library name must be available at the top most 'window'.
1157 <html ng-app ng-jq="jQueryLib">
1163 var jq = function() {
1164 if (isDefined(jq.name_)) return jq.name_;
1166 var i, ii = ngAttrPrefixes.length, prefix, name;
1167 for (i = 0; i < ii; ++i) {
1168 prefix = ngAttrPrefixes[i];
1169 if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
1170 name = el.getAttribute(prefix + 'jq');
1175 return (jq.name_ = name);
1178 function concat(array1, array2, index) {
1179 return array1.concat(slice.call(array2, index));
1182 function sliceArgs(args, startIndex) {
1183 return slice.call(args, startIndex || 0);
1190 * @name angular.bind
1195 * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
1196 * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
1197 * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
1198 * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
1200 * @param {Object} self Context which `fn` should be evaluated in.
1201 * @param {function()} fn Function to be bound.
1202 * @param {...*} args Optional arguments to be prebound to the `fn` function call.
1203 * @returns {function()} Function that wraps the `fn` with all the specified bindings.
1206 function bind(self, fn) {
1207 var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
1208 if (isFunction(fn) && !(fn instanceof RegExp)) {
1209 return curryArgs.length
1211 return arguments.length
1212 ? fn.apply(self, concat(curryArgs, arguments, 0))
1213 : fn.apply(self, curryArgs);
1216 return arguments.length
1217 ? fn.apply(self, arguments)
1221 // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
1227 function toJsonReplacer(key, value) {
1230 if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
1232 } else if (isWindow(value)) {
1234 } else if (value && document === value) {
1236 } else if (isScope(value)) {
1246 * @name angular.toJson
1251 * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
1252 * stripped since angular uses this notation internally.
1254 * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
1255 * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
1256 * If set to an integer, the JSON output will contain that many spaces per indentation.
1257 * @returns {string|undefined} JSON-ified string representing `obj`.
1259 function toJson(obj, pretty) {
1260 if (isUndefined(obj)) return undefined;
1261 if (!isNumber(pretty)) {
1262 pretty = pretty ? 2 : null;
1264 return JSON.stringify(obj, toJsonReplacer, pretty);
1270 * @name angular.fromJson
1275 * Deserializes a JSON string.
1277 * @param {string} json JSON string to deserialize.
1278 * @returns {Object|Array|string|number} Deserialized JSON string.
1280 function fromJson(json) {
1281 return isString(json)
1287 var ALL_COLONS = /:/g;
1288 function timezoneToOffset(timezone, fallback) {
1289 // IE/Edge do not "understand" colon (`:`) in timezone
1290 timezone = timezone.replace(ALL_COLONS, '');
1291 var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
1292 return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
1296 function addDateMinutes(date, minutes) {
1297 date = new Date(date.getTime());
1298 date.setMinutes(date.getMinutes() + minutes);
1303 function convertTimezoneToLocal(date, timezone, reverse) {
1304 reverse = reverse ? -1 : 1;
1305 var dateTimezoneOffset = date.getTimezoneOffset();
1306 var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
1307 return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
1312 * @returns {string} Returns the string representation of the element.
1314 function startingTag(element) {
1315 element = jqLite(element).clone();
1317 // turns out IE does not let you set .html() on elements which
1318 // are not allowed to have children. So we just ignore it.
1321 var elemHtml = jqLite('<div>').append(element).html();
1323 return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
1325 match(/^(<[^>]+>)/)[1].
1326 replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
1328 return lowercase(elemHtml);
1334 /////////////////////////////////////////////////
1337 * Tries to decode the URI component without throwing an exception.
1340 * @param str value potential URI component to check.
1341 * @returns {boolean} True if `value` can be decoded
1342 * with the decodeURIComponent function.
1344 function tryDecodeURIComponent(value) {
1346 return decodeURIComponent(value);
1348 // Ignore any invalid uri component
1354 * Parses an escaped url query string into key-value pairs.
1355 * @returns {Object.<string,boolean|Array>}
1357 function parseKeyValue(/**string*/keyValue) {
1359 forEach((keyValue || "").split('&'), function(keyValue) {
1360 var splitPoint, key, val;
1362 key = keyValue = keyValue.replace(/\+/g,'%20');
1363 splitPoint = keyValue.indexOf('=');
1364 if (splitPoint !== -1) {
1365 key = keyValue.substring(0, splitPoint);
1366 val = keyValue.substring(splitPoint + 1);
1368 key = tryDecodeURIComponent(key);
1369 if (isDefined(key)) {
1370 val = isDefined(val) ? tryDecodeURIComponent(val) : true;
1371 if (!hasOwnProperty.call(obj, key)) {
1373 } else if (isArray(obj[key])) {
1376 obj[key] = [obj[key],val];
1384 function toKeyValue(obj) {
1386 forEach(obj, function(value, key) {
1387 if (isArray(value)) {
1388 forEach(value, function(arrayValue) {
1389 parts.push(encodeUriQuery(key, true) +
1390 (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
1393 parts.push(encodeUriQuery(key, true) +
1394 (value === true ? '' : '=' + encodeUriQuery(value, true)));
1397 return parts.length ? parts.join('&') : '';
1402 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
1403 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
1406 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
1407 * pct-encoded = "%" HEXDIG HEXDIG
1408 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
1409 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
1410 * / "*" / "+" / "," / ";" / "="
1412 function encodeUriSegment(val) {
1413 return encodeUriQuery(val, true).
1414 replace(/%26/gi, '&').
1415 replace(/%3D/gi, '=').
1416 replace(/%2B/gi, '+');
1421 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
1422 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
1423 * encoded per http://tools.ietf.org/html/rfc3986:
1424 * query = *( pchar / "/" / "?" )
1425 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
1426 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
1427 * pct-encoded = "%" HEXDIG HEXDIG
1428 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
1429 * / "*" / "+" / "," / ";" / "="
1431 function encodeUriQuery(val, pctEncodeSpaces) {
1432 return encodeURIComponent(val).
1433 replace(/%40/gi, '@').
1434 replace(/%3A/gi, ':').
1435 replace(/%24/g, '$').
1436 replace(/%2C/gi, ',').
1437 replace(/%3B/gi, ';').
1438 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
1441 var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
1443 function getNgAttribute(element, ngAttr) {
1444 var attr, i, ii = ngAttrPrefixes.length;
1445 for (i = 0; i < ii; ++i) {
1446 attr = ngAttrPrefixes[i] + ngAttr;
1447 if (isString(attr = element.getAttribute(attr))) {
1460 * @param {angular.Module} ngApp an optional application
1461 * {@link angular.module module} name to load.
1462 * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
1463 * created in "strict-di" mode. This means that the application will fail to invoke functions which
1464 * do not use explicit function annotation (and are thus unsuitable for minification), as described
1465 * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
1466 * tracking down the root of these bugs.
1470 * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
1471 * designates the **root element** of the application and is typically placed near the root element
1472 * of the page - e.g. on the `<body>` or `<html>` tags.
1474 * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
1475 * found in the document will be used to define the root element to auto-bootstrap as an
1476 * application. To run multiple applications in an HTML document you must manually bootstrap them using
1477 * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
1479 * You can specify an **AngularJS module** to be used as the root module for the application. This
1480 * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
1481 * should contain the application code needed or have dependencies on other modules that will
1482 * contain the code. See {@link angular.module} for more information.
1484 * In the example below if the `ngApp` directive were not placed on the `html` element then the
1485 * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
1486 * would not be resolved to `3`.
1488 * `ngApp` is the easiest, and most common way to bootstrap an application.
1490 <example module="ngAppDemo">
1491 <file name="index.html">
1492 <div ng-controller="ngAppDemoController">
1493 I can add: {{a}} + {{b}} = {{ a+b }}
1496 <file name="script.js">
1497 angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
1504 * Using `ngStrictDi`, you would see something like this:
1506 <example ng-app-included="true">
1507 <file name="index.html">
1508 <div ng-app="ngAppStrictDemo" ng-strict-di>
1509 <div ng-controller="GoodController1">
1510 I can add: {{a}} + {{b}} = {{ a+b }}
1512 <p>This renders because the controller does not fail to
1513 instantiate, by using explicit annotation style (see
1514 script.js for details)
1518 <div ng-controller="GoodController2">
1519 Name: <input ng-model="name"><br />
1522 <p>This renders because the controller does not fail to
1523 instantiate, by using explicit annotation style
1524 (see script.js for details)
1528 <div ng-controller="BadController">
1529 I can add: {{a}} + {{b}} = {{ a+b }}
1531 <p>The controller could not be instantiated, due to relying
1532 on automatic function annotations (which are disabled in
1533 strict mode). As such, the content of this section is not
1534 interpolated, and there should be an error in your web console.
1539 <file name="script.js">
1540 angular.module('ngAppStrictDemo', [])
1541 // BadController will fail to instantiate, due to relying on automatic function annotation,
1542 // rather than an explicit annotation
1543 .controller('BadController', function($scope) {
1547 // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
1548 // due to using explicit annotations using the array style and $inject property, respectively.
1549 .controller('GoodController1', ['$scope', function($scope) {
1553 .controller('GoodController2', GoodController2);
1554 function GoodController2($scope) {
1555 $scope.name = "World";
1557 GoodController2.$inject = ['$scope'];
1559 <file name="style.css">
1560 div[ng-controller] {
1562 -webkit-border-radius: 4px;
1567 div[ng-controller^=Good] {
1568 border-color: #d6e9c6;
1569 background-color: #dff0d8;
1572 div[ng-controller^=Bad] {
1573 border-color: #ebccd1;
1574 background-color: #f2dede;
1581 function angularInit(element, bootstrap) {
1586 // The element `element` has priority over any other element
1587 forEach(ngAttrPrefixes, function(prefix) {
1588 var name = prefix + 'app';
1590 if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
1591 appElement = element;
1592 module = element.getAttribute(name);
1595 forEach(ngAttrPrefixes, function(prefix) {
1596 var name = prefix + 'app';
1599 if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
1600 appElement = candidate;
1601 module = candidate.getAttribute(name);
1605 config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
1606 bootstrap(appElement, module ? [module] : [], config);
1612 * @name angular.bootstrap
1615 * Use this function to manually start up angular application.
1617 * See: {@link guide/bootstrap Bootstrap}
1619 * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
1620 * They must use {@link ng.directive:ngApp ngApp}.
1622 * Angular will detect if it has been loaded into the browser more than once and only allow the
1623 * first loaded script to be bootstrapped and will report a warning to the browser console for
1624 * each of the subsequent scripts. This prevents strange results in applications, where otherwise
1625 * multiple instances of Angular try to work on the DOM.
1631 * <div ng-controller="WelcomeController">
1635 * <script src="angular.js"></script>
1637 * var app = angular.module('demo', [])
1638 * .controller('WelcomeController', function($scope) {
1639 * $scope.greeting = 'Welcome!';
1641 * angular.bootstrap(document, ['demo']);
1647 * @param {DOMElement} element DOM element which is the root of angular application.
1648 * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
1649 * Each item in the array should be the name of a predefined module or a (DI annotated)
1650 * function that will be invoked by the injector as a `config` block.
1651 * See: {@link angular.module modules}
1652 * @param {Object=} config an object for defining configuration options for the application. The
1653 * following keys are supported:
1655 * * `strictDi` - disable automatic function annotation for the application. This is meant to
1656 * assist in finding bugs which break minified code. Defaults to `false`.
1658 * @returns {auto.$injector} Returns the newly created injector for this app.
1660 function bootstrap(element, modules, config) {
1661 if (!isObject(config)) config = {};
1662 var defaultConfig = {
1665 config = extend(defaultConfig, config);
1666 var doBootstrap = function() {
1667 element = jqLite(element);
1669 if (element.injector()) {
1670 var tag = (element[0] === document) ? 'document' : startingTag(element);
1671 //Encode angle brackets to prevent input from being sanitized to empty string #8683
1674 "App Already Bootstrapped with this Element '{0}'",
1675 tag.replace(/</,'<').replace(/>/,'>'));
1678 modules = modules || [];
1679 modules.unshift(['$provide', function($provide) {
1680 $provide.value('$rootElement', element);
1683 if (config.debugInfoEnabled) {
1684 // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
1685 modules.push(['$compileProvider', function($compileProvider) {
1686 $compileProvider.debugInfoEnabled(true);
1690 modules.unshift('ng');
1691 var injector = createInjector(modules, config.strictDi);
1692 injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
1693 function bootstrapApply(scope, element, compile, injector) {
1694 scope.$apply(function() {
1695 element.data('$injector', injector);
1696 compile(element)(scope);
1703 var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
1704 var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
1706 if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
1707 config.debugInfoEnabled = true;
1708 window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
1711 if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
1712 return doBootstrap();
1715 window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
1716 angular.resumeBootstrap = function(extraModules) {
1717 forEach(extraModules, function(module) {
1718 modules.push(module);
1720 return doBootstrap();
1723 if (isFunction(angular.resumeDeferredBootstrap)) {
1724 angular.resumeDeferredBootstrap();
1730 * @name angular.reloadWithDebugInfo
1733 * Use this function to reload the current application with debug information turned on.
1734 * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
1736 * See {@link ng.$compileProvider#debugInfoEnabled} for more.
1738 function reloadWithDebugInfo() {
1739 window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
1740 window.location.reload();
1744 * @name angular.getTestability
1747 * Get the testability service for the instance of Angular on the given
1749 * @param {DOMElement} element DOM element which is the root of angular application.
1751 function getTestability(rootElement) {
1752 var injector = angular.element(rootElement).injector();
1754 throw ngMinErr('test',
1755 'no injector found for element argument to getTestability');
1757 return injector.get('$$testability');
1760 var SNAKE_CASE_REGEXP = /[A-Z]/g;
1761 function snake_case(name, separator) {
1762 separator = separator || '_';
1763 return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
1764 return (pos ? separator : '') + letter.toLowerCase();
1768 var bindJQueryFired = false;
1769 function bindJQuery() {
1770 var originalCleanData;
1772 if (bindJQueryFired) {
1776 // bind to jQuery if present;
1778 jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
1779 !jqName ? undefined : // use jqLite
1780 window[jqName]; // use jQuery specified by `ngJq`
1782 // Use jQuery if it exists with proper functionality, otherwise default to us.
1783 // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
1784 // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
1785 // versions. It will not work for sure with jQuery <1.7, though.
1786 if (jQuery && jQuery.fn.on) {
1789 scope: JQLitePrototype.scope,
1790 isolateScope: JQLitePrototype.isolateScope,
1791 controller: JQLitePrototype.controller,
1792 injector: JQLitePrototype.injector,
1793 inheritedData: JQLitePrototype.inheritedData
1796 // All nodes removed from the DOM via various jQuery APIs like .remove()
1797 // are passed through jQuery.cleanData. Monkey-patch this method to fire
1798 // the $destroy event on all removed nodes.
1799 originalCleanData = jQuery.cleanData;
1800 jQuery.cleanData = function(elems) {
1802 for (var i = 0, elem; (elem = elems[i]) != null; i++) {
1803 events = jQuery._data(elem, "events");
1804 if (events && events.$destroy) {
1805 jQuery(elem).triggerHandler('$destroy');
1808 originalCleanData(elems);
1814 angular.element = jqLite;
1816 // Prevent double-proxying.
1817 bindJQueryFired = true;
1821 * throw error if the argument is falsy.
1823 function assertArg(arg, name, reason) {
1825 throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
1830 function assertArgFn(arg, name, acceptArrayAnnotation) {
1831 if (acceptArrayAnnotation && isArray(arg)) {
1832 arg = arg[arg.length - 1];
1835 assertArg(isFunction(arg), name, 'not a function, got ' +
1836 (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
1841 * throw error if the name given is hasOwnProperty
1842 * @param {String} name the name to test
1843 * @param {String} context the context in which the name is used, such as module or directive
1845 function assertNotHasOwnProperty(name, context) {
1846 if (name === 'hasOwnProperty') {
1847 throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
1852 * Return the value accessible from the object by path. Any undefined traversals are ignored
1853 * @param {Object} obj starting object
1854 * @param {String} path path to traverse
1855 * @param {boolean} [bindFnToScope=true]
1856 * @returns {Object} value as accessible by path
1858 //TODO(misko): this function needs to be removed
1859 function getter(obj, path, bindFnToScope) {
1860 if (!path) return obj;
1861 var keys = path.split('.');
1863 var lastInstance = obj;
1864 var len = keys.length;
1866 for (var i = 0; i < len; i++) {
1869 obj = (lastInstance = obj)[key];
1872 if (!bindFnToScope && isFunction(obj)) {
1873 return bind(lastInstance, obj);
1879 * Return the DOM siblings between the first and last node in the given array.
1880 * @param {Array} array like object
1881 * @returns {Array} the inputted object or a jqLite collection containing the nodes
1883 function getBlockNodes(nodes) {
1884 // TODO(perf): update `nodes` instead of creating a new object?
1885 var node = nodes[0];
1886 var endNode = nodes[nodes.length - 1];
1889 for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
1890 if (blockNodes || nodes[i] !== node) {
1892 blockNodes = jqLite(slice.call(nodes, 0, i));
1894 blockNodes.push(node);
1898 return blockNodes || nodes;
1903 * Creates a new object without a prototype. This object is useful for lookup without having to
1904 * guard against prototypically inherited properties via hasOwnProperty.
1906 * Related micro-benchmarks:
1907 * - http://jsperf.com/object-create2
1908 * - http://jsperf.com/proto-map-lookup/2
1909 * - http://jsperf.com/for-in-vs-object-keys2
1913 function createMap() {
1914 return Object.create(null);
1917 var NODE_TYPE_ELEMENT = 1;
1918 var NODE_TYPE_ATTRIBUTE = 2;
1919 var NODE_TYPE_TEXT = 3;
1920 var NODE_TYPE_COMMENT = 8;
1921 var NODE_TYPE_DOCUMENT = 9;
1922 var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
1926 * @name angular.Module
1930 * Interface for configuring angular {@link angular.module modules}.
1933 function setupModuleLoader(window) {
1935 var $injectorMinErr = minErr('$injector');
1936 var ngMinErr = minErr('ng');
1938 function ensure(obj, name, factory) {
1939 return obj[name] || (obj[name] = factory());
1942 var angular = ensure(window, 'angular', Object);
1944 // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
1945 angular.$$minErr = angular.$$minErr || minErr;
1947 return ensure(angular, 'module', function() {
1948 /** @type {Object.<string, angular.Module>} */
1953 * @name angular.module
1957 * The `angular.module` is a global place for creating, registering and retrieving Angular
1959 * All modules (angular core or 3rd party) that should be available to an application must be
1960 * registered using this mechanism.
1962 * Passing one argument retrieves an existing {@link angular.Module},
1963 * whereas passing more than one argument creates a new {@link angular.Module}
1968 * A module is a collection of services, directives, controllers, filters, and configuration information.
1969 * `angular.module` is used to configure the {@link auto.$injector $injector}.
1972 * // Create a new module
1973 * var myModule = angular.module('myModule', []);
1975 * // register a new service
1976 * myModule.value('appName', 'MyCoolApp');
1978 * // configure existing services inside initialization blocks.
1979 * myModule.config(['$locationProvider', function($locationProvider) {
1980 * // Configure existing providers
1981 * $locationProvider.hashPrefix('!');
1985 * Then you can create an injector and load your modules like this:
1988 * var injector = angular.injector(['ng', 'myModule'])
1991 * However it's more likely that you'll just use
1992 * {@link ng.directive:ngApp ngApp} or
1993 * {@link angular.bootstrap} to simplify this process for you.
1995 * @param {!string} name The name of the module to create or retrieve.
1996 * @param {!Array.<string>=} requires If specified then new module is being created. If
1997 * unspecified then the module is being retrieved for further configuration.
1998 * @param {Function=} configFn Optional configuration function for the module. Same as
1999 * {@link angular.Module#config Module#config()}.
2000 * @returns {angular.Module} new module with the {@link angular.Module} api.
2002 return function module(name, requires, configFn) {
2003 var assertNotHasOwnProperty = function(name, context) {
2004 if (name === 'hasOwnProperty') {
2005 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
2009 assertNotHasOwnProperty(name, 'module');
2010 if (requires && modules.hasOwnProperty(name)) {
2011 modules[name] = null;
2013 return ensure(modules, name, function() {
2015 throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
2016 "the module name or forgot to load it. If registering a module ensure that you " +
2017 "specify the dependencies as the second argument.", name);
2020 /** @type {!Array.<Array.<*>>} */
2021 var invokeQueue = [];
2023 /** @type {!Array.<Function>} */
2024 var configBlocks = [];
2026 /** @type {!Array.<Function>} */
2029 var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
2031 /** @type {angular.Module} */
2032 var moduleInstance = {
2034 _invokeQueue: invokeQueue,
2035 _configBlocks: configBlocks,
2036 _runBlocks: runBlocks,
2040 * @name angular.Module#requires
2044 * Holds the list of modules which the injector will load before the current module is
2051 * @name angular.Module#name
2055 * Name of the module.
2062 * @name angular.Module#provider
2064 * @param {string} name service name
2065 * @param {Function} providerType Construction function for creating new instance of the
2068 * See {@link auto.$provide#provider $provide.provider()}.
2070 provider: invokeLaterAndSetModuleName('$provide', 'provider'),
2074 * @name angular.Module#factory
2076 * @param {string} name service name
2077 * @param {Function} providerFunction Function for creating new instance of the service.
2079 * See {@link auto.$provide#factory $provide.factory()}.
2081 factory: invokeLaterAndSetModuleName('$provide', 'factory'),
2085 * @name angular.Module#service
2087 * @param {string} name service name
2088 * @param {Function} constructor A constructor function that will be instantiated.
2090 * See {@link auto.$provide#service $provide.service()}.
2092 service: invokeLaterAndSetModuleName('$provide', 'service'),
2096 * @name angular.Module#value
2098 * @param {string} name service name
2099 * @param {*} object Service instance object.
2101 * See {@link auto.$provide#value $provide.value()}.
2103 value: invokeLater('$provide', 'value'),
2107 * @name angular.Module#constant
2109 * @param {string} name constant name
2110 * @param {*} object Constant value.
2112 * Because the constants are fixed, they get applied before other provide methods.
2113 * See {@link auto.$provide#constant $provide.constant()}.
2115 constant: invokeLater('$provide', 'constant', 'unshift'),
2119 * @name angular.Module#decorator
2121 * @param {string} The name of the service to decorate.
2122 * @param {Function} This function will be invoked when the service needs to be
2123 * instantiated and should return the decorated service instance.
2125 * See {@link auto.$provide#decorator $provide.decorator()}.
2127 decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
2131 * @name angular.Module#animation
2133 * @param {string} name animation name
2134 * @param {Function} animationFactory Factory function for creating new instance of an
2138 * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
2141 * Defines an animation hook that can be later used with
2142 * {@link $animate $animate} service and directives that use this service.
2145 * module.animation('.animation-name', function($inject1, $inject2) {
2147 * eventName : function(element, done) {
2148 * //code to run the animation
2149 * //once complete, then run done()
2150 * return function cancellationFunction(element) {
2151 * //code to cancel the animation
2158 * See {@link ng.$animateProvider#register $animateProvider.register()} and
2159 * {@link ngAnimate ngAnimate module} for more information.
2161 animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
2165 * @name angular.Module#filter
2167 * @param {string} name Filter name - this must be a valid angular expression identifier
2168 * @param {Function} filterFactory Factory function for creating new instance of filter.
2170 * See {@link ng.$filterProvider#register $filterProvider.register()}.
2172 * <div class="alert alert-warning">
2173 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
2174 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
2175 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
2176 * (`myapp_subsection_filterx`).
2179 filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
2183 * @name angular.Module#controller
2185 * @param {string|Object} name Controller name, or an object map of controllers where the
2186 * keys are the names and the values are the constructors.
2187 * @param {Function} constructor Controller constructor function.
2189 * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
2191 controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
2195 * @name angular.Module#directive
2197 * @param {string|Object} name Directive name, or an object map of directives where the
2198 * keys are the names and the values are the factories.
2199 * @param {Function} directiveFactory Factory function for creating new instance of
2202 * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
2204 directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
2208 * @name angular.Module#component
2210 * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
2211 * @param {Object} options Component definition object (a simplified
2212 * {@link ng.$compile#directive-definition-object directive definition object})
2215 * See {@link ng.$compileProvider#component $compileProvider.component()}.
2217 component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
2221 * @name angular.Module#config
2223 * @param {Function} configFn Execute this function on module load. Useful for service
2226 * Use this method to register work which needs to be performed on module loading.
2227 * For more about how to configure services, see
2228 * {@link providers#provider-recipe Provider Recipe}.
2234 * @name angular.Module#run
2236 * @param {Function} initializationFn Execute this function after injector creation.
2237 * Useful for application initialization.
2239 * Use this method to register work which should be performed when the injector is done
2240 * loading all modules.
2242 run: function(block) {
2243 runBlocks.push(block);
2252 return moduleInstance;
2255 * @param {string} provider
2256 * @param {string} method
2257 * @param {String=} insertMethod
2258 * @returns {angular.Module}
2260 function invokeLater(provider, method, insertMethod, queue) {
2261 if (!queue) queue = invokeQueue;
2263 queue[insertMethod || 'push']([provider, method, arguments]);
2264 return moduleInstance;
2269 * @param {string} provider
2270 * @param {string} method
2271 * @returns {angular.Module}
2273 function invokeLaterAndSetModuleName(provider, method) {
2274 return function(recipeName, factoryFunction) {
2275 if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
2276 invokeQueue.push([provider, method, arguments]);
2277 return moduleInstance;
2286 /* global: toDebugString: true */
2288 function serializeObject(obj) {
2291 return JSON.stringify(obj, function(key, val) {
2292 val = toJsonReplacer(key, val);
2293 if (isObject(val)) {
2295 if (seen.indexOf(val) >= 0) return '...';
2303 function toDebugString(obj) {
2304 if (typeof obj === 'function') {
2305 return obj.toString().replace(/ \{[\s\S]*$/, '');
2306 } else if (isUndefined(obj)) {
2308 } else if (typeof obj !== 'string') {
2309 return serializeObject(obj);
2314 /* global angularModule: true,
2319 htmlAnchorDirective,
2328 ngBindHtmlDirective,
2329 ngBindTemplateDirective,
2331 ngClassEvenDirective,
2332 ngClassOddDirective,
2334 ngControllerDirective,
2339 ngIncludeFillContentDirective,
2341 ngNonBindableDirective,
2342 ngPluralizeDirective,
2347 ngSwitchWhenDirective,
2348 ngSwitchDefaultDirective,
2350 ngTranscludeDirective,
2363 ngModelOptionsDirective,
2364 ngAttributeAliasDirectives,
2367 $AnchorScrollProvider,
2369 $CoreAnimateCssProvider,
2370 $$CoreAnimateJsProvider,
2371 $$CoreAnimateQueueProvider,
2372 $$AnimateRunnerFactoryProvider,
2373 $$AnimateAsyncRunFactoryProvider,
2375 $CacheFactoryProvider,
2376 $ControllerProvider,
2379 $ExceptionHandlerProvider,
2381 $$ForceReflowProvider,
2382 $InterpolateProvider,
2386 $HttpParamSerializerProvider,
2387 $HttpParamSerializerJQLikeProvider,
2388 $HttpBackendProvider,
2389 $xhrFactoryProvider,
2396 $$SanitizeUriProvider,
2398 $SceDelegateProvider,
2400 $TemplateCacheProvider,
2401 $TemplateRequestProvider,
2402 $$TestabilityProvider,
2407 $$CookieReaderProvider
2413 * @name angular.version
2416 * An object that contains information about the current AngularJS version.
2418 * This object has the following properties:
2420 * - `full` – `{string}` – Full version string, such as "0.9.18".
2421 * - `major` – `{number}` – Major version number, such as "0".
2422 * - `minor` – `{number}` – Minor version number, such as "9".
2423 * - `dot` – `{number}` – Dot version number, such as "18".
2424 * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
2427 full: '1.5.0', // all of these placeholder strings will be replaced by grunt's
2428 major: 1, // package task
2431 codeName: 'ennoblement-facilitation'
2435 function publishExternalAPI(angular) {
2437 'bootstrap': bootstrap,
2444 'injector': createInjector,
2448 'fromJson': fromJson,
2449 'identity': identity,
2450 'isUndefined': isUndefined,
2451 'isDefined': isDefined,
2452 'isString': isString,
2453 'isFunction': isFunction,
2454 'isObject': isObject,
2455 'isNumber': isNumber,
2456 'isElement': isElement,
2460 'lowercase': lowercase,
2461 'uppercase': uppercase,
2462 'callbacks': {counter: 0},
2463 'getTestability': getTestability,
2466 'reloadWithDebugInfo': reloadWithDebugInfo
2469 angularModule = setupModuleLoader(window);
2471 angularModule('ng', ['ngLocale'], ['$provide',
2472 function ngModule($provide) {
2473 // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
2475 $$sanitizeUri: $$SanitizeUriProvider
2477 $provide.provider('$compile', $CompileProvider).
2479 a: htmlAnchorDirective,
2480 input: inputDirective,
2481 textarea: inputDirective,
2482 form: formDirective,
2483 script: scriptDirective,
2484 select: selectDirective,
2485 style: styleDirective,
2486 option: optionDirective,
2487 ngBind: ngBindDirective,
2488 ngBindHtml: ngBindHtmlDirective,
2489 ngBindTemplate: ngBindTemplateDirective,
2490 ngClass: ngClassDirective,
2491 ngClassEven: ngClassEvenDirective,
2492 ngClassOdd: ngClassOddDirective,
2493 ngCloak: ngCloakDirective,
2494 ngController: ngControllerDirective,
2495 ngForm: ngFormDirective,
2496 ngHide: ngHideDirective,
2497 ngIf: ngIfDirective,
2498 ngInclude: ngIncludeDirective,
2499 ngInit: ngInitDirective,
2500 ngNonBindable: ngNonBindableDirective,
2501 ngPluralize: ngPluralizeDirective,
2502 ngRepeat: ngRepeatDirective,
2503 ngShow: ngShowDirective,
2504 ngStyle: ngStyleDirective,
2505 ngSwitch: ngSwitchDirective,
2506 ngSwitchWhen: ngSwitchWhenDirective,
2507 ngSwitchDefault: ngSwitchDefaultDirective,
2508 ngOptions: ngOptionsDirective,
2509 ngTransclude: ngTranscludeDirective,
2510 ngModel: ngModelDirective,
2511 ngList: ngListDirective,
2512 ngChange: ngChangeDirective,
2513 pattern: patternDirective,
2514 ngPattern: patternDirective,
2515 required: requiredDirective,
2516 ngRequired: requiredDirective,
2517 minlength: minlengthDirective,
2518 ngMinlength: minlengthDirective,
2519 maxlength: maxlengthDirective,
2520 ngMaxlength: maxlengthDirective,
2521 ngValue: ngValueDirective,
2522 ngModelOptions: ngModelOptionsDirective
2525 ngInclude: ngIncludeFillContentDirective
2527 directive(ngAttributeAliasDirectives).
2528 directive(ngEventDirectives);
2530 $anchorScroll: $AnchorScrollProvider,
2531 $animate: $AnimateProvider,
2532 $animateCss: $CoreAnimateCssProvider,
2533 $$animateJs: $$CoreAnimateJsProvider,
2534 $$animateQueue: $$CoreAnimateQueueProvider,
2535 $$AnimateRunner: $$AnimateRunnerFactoryProvider,
2536 $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
2537 $browser: $BrowserProvider,
2538 $cacheFactory: $CacheFactoryProvider,
2539 $controller: $ControllerProvider,
2540 $document: $DocumentProvider,
2541 $exceptionHandler: $ExceptionHandlerProvider,
2542 $filter: $FilterProvider,
2543 $$forceReflow: $$ForceReflowProvider,
2544 $interpolate: $InterpolateProvider,
2545 $interval: $IntervalProvider,
2546 $http: $HttpProvider,
2547 $httpParamSerializer: $HttpParamSerializerProvider,
2548 $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
2549 $httpBackend: $HttpBackendProvider,
2550 $xhrFactory: $xhrFactoryProvider,
2551 $location: $LocationProvider,
2553 $parse: $ParseProvider,
2554 $rootScope: $RootScopeProvider,
2558 $sceDelegate: $SceDelegateProvider,
2559 $sniffer: $SnifferProvider,
2560 $templateCache: $TemplateCacheProvider,
2561 $templateRequest: $TemplateRequestProvider,
2562 $$testability: $$TestabilityProvider,
2563 $timeout: $TimeoutProvider,
2564 $window: $WindowProvider,
2565 $$rAF: $$RAFProvider,
2566 $$jqLite: $$jqLiteProvider,
2567 $$HashMap: $$HashMapProvider,
2568 $$cookieReader: $$CookieReaderProvider
2574 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2575 * Any commits to this file should be reviewed with security in mind. *
2576 * Changes to this file can potentially create security vulnerabilities. *
2577 * An approval from 2 Core members with history of modifying *
2578 * this file is required. *
2580 * Does the change somehow allow for arbitrary javascript to be executed? *
2581 * Or allows for someone to change the prototype of built-in objects? *
2582 * Or gives undesired access to variables likes document or window? *
2583 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2585 /* global JQLitePrototype: true,
2586 addEventListenerFn: true,
2587 removeEventListenerFn: true,
2592 //////////////////////////////////
2594 //////////////////////////////////
2598 * @name angular.element
2603 * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
2605 * If jQuery is available, `angular.element` is an alias for the
2606 * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
2607 * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
2609 * jqLite is a tiny, API-compatible subset of jQuery that allows
2610 * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
2611 * commonly needed functionality with the goal of having a very small footprint.
2613 * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
2614 * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
2615 * specific version of jQuery if multiple versions exist on the page.
2617 * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
2618 * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
2620 * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
2621 * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
2622 * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
2624 * ## Angular's jqLite
2625 * jqLite provides only the following jQuery methods:
2627 * - [`addClass()`](http://api.jquery.com/addClass/)
2628 * - [`after()`](http://api.jquery.com/after/)
2629 * - [`append()`](http://api.jquery.com/append/)
2630 * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
2631 * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
2632 * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
2633 * - [`clone()`](http://api.jquery.com/clone/)
2634 * - [`contents()`](http://api.jquery.com/contents/)
2635 * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
2636 * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
2637 * - [`data()`](http://api.jquery.com/data/)
2638 * - [`detach()`](http://api.jquery.com/detach/)
2639 * - [`empty()`](http://api.jquery.com/empty/)
2640 * - [`eq()`](http://api.jquery.com/eq/)
2641 * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
2642 * - [`hasClass()`](http://api.jquery.com/hasClass/)
2643 * - [`html()`](http://api.jquery.com/html/)
2644 * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
2645 * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
2646 * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
2647 * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
2648 * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
2649 * - [`prepend()`](http://api.jquery.com/prepend/)
2650 * - [`prop()`](http://api.jquery.com/prop/)
2651 * - [`ready()`](http://api.jquery.com/ready/)
2652 * - [`remove()`](http://api.jquery.com/remove/)
2653 * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
2654 * - [`removeClass()`](http://api.jquery.com/removeClass/)
2655 * - [`removeData()`](http://api.jquery.com/removeData/)
2656 * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
2657 * - [`text()`](http://api.jquery.com/text/)
2658 * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
2659 * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
2660 * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
2661 * - [`val()`](http://api.jquery.com/val/)
2662 * - [`wrap()`](http://api.jquery.com/wrap/)
2664 * ## jQuery/jqLite Extras
2665 * Angular also provides the following additional methods and events to both jQuery and jqLite:
2668 * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
2669 * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
2670 * element before it is removed.
2673 * - `controller(name)` - retrieves the controller of the current element or its parent. By default
2674 * retrieves controller associated with the `ngController` directive. If `name` is provided as
2675 * camelCase directive name, then the controller for this directive will be retrieved (e.g.
2677 * - `injector()` - retrieves the injector of the current element or its parent.
2678 * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
2679 * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
2681 * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
2682 * current element. This getter should be used only on elements that contain a directive which starts a new isolate
2683 * scope. Calling `scope()` on this element always returns the original non-isolate scope.
2684 * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
2685 * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
2686 * parent element is reached.
2688 * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
2689 * @returns {Object} jQuery object.
2692 JQLite.expando = 'ng339';
2694 var jqCache = JQLite.cache = {},
2696 addEventListenerFn = function(element, type, fn) {
2697 element.addEventListener(type, fn, false);
2699 removeEventListenerFn = function(element, type, fn) {
2700 element.removeEventListener(type, fn, false);
2704 * !!! This is an undocumented "private" function !!!
2706 JQLite._data = function(node) {
2707 //jQuery always returns an object on cache miss
2708 return this.cache[node[this.expando]] || {};
2711 function jqNextId() { return ++jqId; }
2714 var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
2715 var MOZ_HACK_REGEXP = /^moz([A-Z])/;
2716 var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
2717 var jqLiteMinErr = minErr('jqLite');
2720 * Converts snake_case to camelCase.
2721 * Also there is special case for Moz prefix starting with upper case letter.
2722 * @param name Name to normalize
2724 function camelCase(name) {
2726 replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
2727 return offset ? letter.toUpperCase() : letter;
2729 replace(MOZ_HACK_REGEXP, 'Moz$1');
2732 var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
2733 var HTML_REGEXP = /<|&#?\w+;/;
2734 var TAG_NAME_REGEXP = /<([\w:-]+)/;
2735 var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
2738 'option': [1, '<select multiple="multiple">', '</select>'],
2740 'thead': [1, '<table>', '</table>'],
2741 'col': [2, '<table><colgroup>', '</colgroup></table>'],
2742 'tr': [2, '<table><tbody>', '</tbody></table>'],
2743 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
2744 '_default': [0, "", ""]
2747 wrapMap.optgroup = wrapMap.option;
2748 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
2749 wrapMap.th = wrapMap.td;
2752 function jqLiteIsTextNode(html) {
2753 return !HTML_REGEXP.test(html);
2756 function jqLiteAcceptsData(node) {
2757 // The window object can accept data but has no nodeType
2758 // Otherwise we are only interested in elements (1) and documents (9)
2759 var nodeType = node.nodeType;
2760 return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
2763 function jqLiteHasData(node) {
2764 for (var key in jqCache[node.ng339]) {
2770 function jqLiteCleanData(nodes) {
2771 for (var i = 0, ii = nodes.length; i < ii; i++) {
2772 jqLiteRemoveData(nodes[i]);
2776 function jqLiteBuildFragment(html, context) {
2778 fragment = context.createDocumentFragment(),
2781 if (jqLiteIsTextNode(html)) {
2782 // Convert non-html into a text node
2783 nodes.push(context.createTextNode(html));
2785 // Convert html into DOM nodes
2786 tmp = tmp || fragment.appendChild(context.createElement("div"));
2787 tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
2788 wrap = wrapMap[tag] || wrapMap._default;
2789 tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
2791 // Descend through wrappers to the right content
2794 tmp = tmp.lastChild;
2797 nodes = concat(nodes, tmp.childNodes);
2799 tmp = fragment.firstChild;
2800 tmp.textContent = "";
2803 // Remove wrapper from fragment
2804 fragment.textContent = "";
2805 fragment.innerHTML = ""; // Clear inner HTML
2806 forEach(nodes, function(node) {
2807 fragment.appendChild(node);
2813 function jqLiteParseHTML(html, context) {
2814 context = context || document;
2817 if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
2818 return [context.createElement(parsed[1])];
2821 if ((parsed = jqLiteBuildFragment(html, context))) {
2822 return parsed.childNodes;
2828 function jqLiteWrapNode(node, wrapper) {
2829 var parent = node.parentNode;
2832 parent.replaceChild(wrapper, node);
2835 wrapper.appendChild(node);
2839 // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
2840 var jqLiteContains = Node.prototype.contains || function(arg) {
2841 // jshint bitwise: false
2842 return !!(this.compareDocumentPosition(arg) & 16);
2843 // jshint bitwise: true
2846 /////////////////////////////////////////////
2847 function JQLite(element) {
2848 if (element instanceof JQLite) {
2854 if (isString(element)) {
2855 element = trim(element);
2858 if (!(this instanceof JQLite)) {
2859 if (argIsString && element.charAt(0) != '<') {
2860 throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
2862 return new JQLite(element);
2866 jqLiteAddNodes(this, jqLiteParseHTML(element));
2868 jqLiteAddNodes(this, element);
2872 function jqLiteClone(element) {
2873 return element.cloneNode(true);
2876 function jqLiteDealoc(element, onlyDescendants) {
2877 if (!onlyDescendants) jqLiteRemoveData(element);
2879 if (element.querySelectorAll) {
2880 var descendants = element.querySelectorAll('*');
2881 for (var i = 0, l = descendants.length; i < l; i++) {
2882 jqLiteRemoveData(descendants[i]);
2887 function jqLiteOff(element, type, fn, unsupported) {
2888 if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
2890 var expandoStore = jqLiteExpandoStore(element);
2891 var events = expandoStore && expandoStore.events;
2892 var handle = expandoStore && expandoStore.handle;
2894 if (!handle) return; //no listeners registered
2897 for (type in events) {
2898 if (type !== '$destroy') {
2899 removeEventListenerFn(element, type, handle);
2901 delete events[type];
2905 var removeHandler = function(type) {
2906 var listenerFns = events[type];
2907 if (isDefined(fn)) {
2908 arrayRemove(listenerFns || [], fn);
2910 if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
2911 removeEventListenerFn(element, type, handle);
2912 delete events[type];
2916 forEach(type.split(' '), function(type) {
2917 removeHandler(type);
2918 if (MOUSE_EVENT_MAP[type]) {
2919 removeHandler(MOUSE_EVENT_MAP[type]);
2925 function jqLiteRemoveData(element, name) {
2926 var expandoId = element.ng339;
2927 var expandoStore = expandoId && jqCache[expandoId];
2931 delete expandoStore.data[name];
2935 if (expandoStore.handle) {
2936 if (expandoStore.events.$destroy) {
2937 expandoStore.handle({}, '$destroy');
2941 delete jqCache[expandoId];
2942 element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
2947 function jqLiteExpandoStore(element, createIfNecessary) {
2948 var expandoId = element.ng339,
2949 expandoStore = expandoId && jqCache[expandoId];
2951 if (createIfNecessary && !expandoStore) {
2952 element.ng339 = expandoId = jqNextId();
2953 expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
2956 return expandoStore;
2960 function jqLiteData(element, key, value) {
2961 if (jqLiteAcceptsData(element)) {
2963 var isSimpleSetter = isDefined(value);
2964 var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
2965 var massGetter = !key;
2966 var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
2967 var data = expandoStore && expandoStore.data;
2969 if (isSimpleSetter) { // data('key', value)
2972 if (massGetter) { // data()
2975 if (isSimpleGetter) { // data('key')
2976 // don't force creation of expandoStore if it doesn't exist yet
2977 return data && data[key];
2978 } else { // mass-setter: data({key1: val1, key2: val2})
2986 function jqLiteHasClass(element, selector) {
2987 if (!element.getAttribute) return false;
2988 return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
2989 indexOf(" " + selector + " ") > -1);
2992 function jqLiteRemoveClass(element, cssClasses) {
2993 if (cssClasses && element.setAttribute) {
2994 forEach(cssClasses.split(' '), function(cssClass) {
2995 element.setAttribute('class', trim(
2996 (" " + (element.getAttribute('class') || '') + " ")
2997 .replace(/[\n\t]/g, " ")
2998 .replace(" " + trim(cssClass) + " ", " "))
3004 function jqLiteAddClass(element, cssClasses) {
3005 if (cssClasses && element.setAttribute) {
3006 var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
3007 .replace(/[\n\t]/g, " ");
3009 forEach(cssClasses.split(' '), function(cssClass) {
3010 cssClass = trim(cssClass);
3011 if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
3012 existingClasses += cssClass + ' ';
3016 element.setAttribute('class', trim(existingClasses));
3021 function jqLiteAddNodes(root, elements) {
3022 // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
3026 // if a Node (the most common case)
3027 if (elements.nodeType) {
3028 root[root.length++] = elements;
3030 var length = elements.length;
3032 // if an Array or NodeList and not a Window
3033 if (typeof length === 'number' && elements.window !== elements) {
3035 for (var i = 0; i < length; i++) {
3036 root[root.length++] = elements[i];
3040 root[root.length++] = elements;
3047 function jqLiteController(element, name) {
3048 return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
3051 function jqLiteInheritedData(element, name, value) {
3052 // if element is the document object work with the html element instead
3053 // this makes $(document).scope() possible
3054 if (element.nodeType == NODE_TYPE_DOCUMENT) {
3055 element = element.documentElement;
3057 var names = isArray(name) ? name : [name];
3060 for (var i = 0, ii = names.length; i < ii; i++) {
3061 if (isDefined(value = jqLite.data(element, names[i]))) return value;
3064 // If dealing with a document fragment node with a host element, and no parent, use the host
3065 // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
3066 // to lookup parent controllers.
3067 element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
3071 function jqLiteEmpty(element) {
3072 jqLiteDealoc(element, true);
3073 while (element.firstChild) {
3074 element.removeChild(element.firstChild);
3078 function jqLiteRemove(element, keepData) {
3079 if (!keepData) jqLiteDealoc(element);
3080 var parent = element.parentNode;
3081 if (parent) parent.removeChild(element);
3085 function jqLiteDocumentLoaded(action, win) {
3086 win = win || window;
3087 if (win.document.readyState === 'complete') {
3088 // Force the action to be run async for consistent behavior
3089 // from the action's point of view
3090 // i.e. it will definitely not be in a $apply
3091 win.setTimeout(action);
3093 // No need to unbind this handler as load is only ever called once
3094 jqLite(win).on('load', action);
3098 //////////////////////////////////////////
3099 // Functions which are declared directly.
3100 //////////////////////////////////////////
3101 var JQLitePrototype = JQLite.prototype = {
3102 ready: function(fn) {
3105 function trigger() {
3111 // check if document is already loaded
3112 if (document.readyState === 'complete') {
3113 setTimeout(trigger);
3115 this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
3116 // we can not use jqLite since we are not done loading and jQuery could be loaded later.
3118 JQLite(window).on('load', trigger); // fallback to window.onload for others
3122 toString: function() {
3124 forEach(this, function(e) { value.push('' + e);});
3125 return '[' + value.join(', ') + ']';
3128 eq: function(index) {
3129 return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
3138 //////////////////////////////////////////
3139 // Functions iterating getter/setters.
3140 // these functions return self on setter and
3142 //////////////////////////////////////////
3143 var BOOLEAN_ATTR = {};
3144 forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
3145 BOOLEAN_ATTR[lowercase(value)] = value;
3147 var BOOLEAN_ELEMENTS = {};
3148 forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
3149 BOOLEAN_ELEMENTS[value] = true;
3151 var ALIASED_ATTR = {
3152 'ngMinlength': 'minlength',
3153 'ngMaxlength': 'maxlength',
3156 'ngPattern': 'pattern'
3159 function getBooleanAttrName(element, name) {
3160 // check dom last since we will most likely fail on name
3161 var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
3163 // booleanAttr is here twice to minimize DOM access
3164 return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
3167 function getAliasedAttrName(name) {
3168 return ALIASED_ATTR[name];
3173 removeData: jqLiteRemoveData,
3174 hasData: jqLiteHasData,
3175 cleanData: jqLiteCleanData
3176 }, function(fn, name) {
3182 inheritedData: jqLiteInheritedData,
3184 scope: function(element) {
3185 // Can't use jqLiteData here directly so we stay compatible with jQuery!
3186 return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
3189 isolateScope: function(element) {
3190 // Can't use jqLiteData here directly so we stay compatible with jQuery!
3191 return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
3194 controller: jqLiteController,
3196 injector: function(element) {
3197 return jqLiteInheritedData(element, '$injector');
3200 removeAttr: function(element, name) {
3201 element.removeAttribute(name);
3204 hasClass: jqLiteHasClass,
3206 css: function(element, name, value) {
3207 name = camelCase(name);
3209 if (isDefined(value)) {
3210 element.style[name] = value;
3212 return element.style[name];
3216 attr: function(element, name, value) {
3217 var nodeType = element.nodeType;
3218 if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
3221 var lowercasedName = lowercase(name);
3222 if (BOOLEAN_ATTR[lowercasedName]) {
3223 if (isDefined(value)) {
3225 element[name] = true;
3226 element.setAttribute(name, lowercasedName);
3228 element[name] = false;
3229 element.removeAttribute(lowercasedName);
3232 return (element[name] ||
3233 (element.attributes.getNamedItem(name) || noop).specified)
3237 } else if (isDefined(value)) {
3238 element.setAttribute(name, value);
3239 } else if (element.getAttribute) {
3240 // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
3241 // some elements (e.g. Document) don't have get attribute, so return undefined
3242 var ret = element.getAttribute(name, 2);
3243 // normalize non-existing attributes to undefined (as jQuery)
3244 return ret === null ? undefined : ret;
3248 prop: function(element, name, value) {
3249 if (isDefined(value)) {
3250 element[name] = value;
3252 return element[name];
3260 function getText(element, value) {
3261 if (isUndefined(value)) {
3262 var nodeType = element.nodeType;
3263 return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
3265 element.textContent = value;
3269 val: function(element, value) {
3270 if (isUndefined(value)) {
3271 if (element.multiple && nodeName_(element) === 'select') {
3273 forEach(element.options, function(option) {
3274 if (option.selected) {
3275 result.push(option.value || option.text);
3278 return result.length === 0 ? null : result;
3280 return element.value;
3282 element.value = value;
3285 html: function(element, value) {
3286 if (isUndefined(value)) {
3287 return element.innerHTML;
3289 jqLiteDealoc(element, true);
3290 element.innerHTML = value;
3294 }, function(fn, name) {
3296 * Properties: writes return selection, reads return first value
3298 JQLite.prototype[name] = function(arg1, arg2) {
3300 var nodeCount = this.length;
3302 // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
3303 // in a way that survives minification.
3304 // jqLiteEmpty takes no arguments but is a setter.
3305 if (fn !== jqLiteEmpty &&
3306 (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
3307 if (isObject(arg1)) {
3309 // we are a write, but the object properties are the key/values
3310 for (i = 0; i < nodeCount; i++) {
3311 if (fn === jqLiteData) {
3312 // data() takes the whole object in jQuery
3316 fn(this[i], key, arg1[key]);
3320 // return self for chaining
3323 // we are a read, so read the first child.
3324 // TODO: do we still need this?
3326 // Only if we have $dv do we iterate over all, otherwise it is just the first element.
3327 var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
3328 for (var j = 0; j < jj; j++) {
3329 var nodeValue = fn(this[j], arg1, arg2);
3330 value = value ? value + nodeValue : nodeValue;
3335 // we are a write, so apply to all children
3336 for (i = 0; i < nodeCount; i++) {
3337 fn(this[i], arg1, arg2);
3339 // return self for chaining
3345 function createEventHandler(element, events) {
3346 var eventHandler = function(event, type) {
3347 // jQuery specific api
3348 event.isDefaultPrevented = function() {
3349 return event.defaultPrevented;
3352 var eventFns = events[type || event.type];
3353 var eventFnsLength = eventFns ? eventFns.length : 0;
3355 if (!eventFnsLength) return;
3357 if (isUndefined(event.immediatePropagationStopped)) {
3358 var originalStopImmediatePropagation = event.stopImmediatePropagation;
3359 event.stopImmediatePropagation = function() {
3360 event.immediatePropagationStopped = true;
3362 if (event.stopPropagation) {
3363 event.stopPropagation();
3366 if (originalStopImmediatePropagation) {
3367 originalStopImmediatePropagation.call(event);
3372 event.isImmediatePropagationStopped = function() {
3373 return event.immediatePropagationStopped === true;
3376 // Some events have special handlers that wrap the real handler
3377 var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
3379 // Copy event handlers in case event handlers array is modified during execution.
3380 if ((eventFnsLength > 1)) {
3381 eventFns = shallowCopy(eventFns);
3384 for (var i = 0; i < eventFnsLength; i++) {
3385 if (!event.isImmediatePropagationStopped()) {
3386 handlerWrapper(element, event, eventFns[i]);
3391 // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
3392 // events on `element`
3393 eventHandler.elem = element;
3394 return eventHandler;
3397 function defaultHandlerWrapper(element, event, handler) {
3398 handler.call(element, event);
3401 function specialMouseHandlerWrapper(target, event, handler) {
3402 // Refer to jQuery's implementation of mouseenter & mouseleave
3403 // Read about mouseenter and mouseleave:
3404 // http://www.quirksmode.org/js/events_mouse.html#link8
3405 var related = event.relatedTarget;
3406 // For mousenter/leave call the handler if related is outside the target.
3407 // NB: No relatedTarget if the mouse left/entered the browser window
3408 if (!related || (related !== target && !jqLiteContains.call(target, related))) {
3409 handler.call(target, event);
3413 //////////////////////////////////////////
3414 // Functions iterating traversal.
3415 // These functions chain results into a single
3417 //////////////////////////////////////////
3419 removeData: jqLiteRemoveData,
3421 on: function jqLiteOn(element, type, fn, unsupported) {
3422 if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
3424 // Do not add event handlers to non-elements because they will not be cleaned up.
3425 if (!jqLiteAcceptsData(element)) {
3429 var expandoStore = jqLiteExpandoStore(element, true);
3430 var events = expandoStore.events;
3431 var handle = expandoStore.handle;
3434 handle = expandoStore.handle = createEventHandler(element, events);
3437 // http://jsperf.com/string-indexof-vs-split
3438 var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
3439 var i = types.length;
3441 var addHandler = function(type, specialHandlerWrapper, noEventListener) {
3442 var eventFns = events[type];
3445 eventFns = events[type] = [];
3446 eventFns.specialHandlerWrapper = specialHandlerWrapper;
3447 if (type !== '$destroy' && !noEventListener) {
3448 addEventListenerFn(element, type, handle);
3457 if (MOUSE_EVENT_MAP[type]) {
3458 addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
3459 addHandler(type, undefined, true);
3468 one: function(element, type, fn) {
3469 element = jqLite(element);
3471 //add the listener twice so that when it is called
3472 //you can remove the original function and still be
3473 //able to call element.off(ev, fn) normally
3474 element.on(type, function onFn() {
3475 element.off(type, fn);
3476 element.off(type, onFn);
3478 element.on(type, fn);
3481 replaceWith: function(element, replaceNode) {
3482 var index, parent = element.parentNode;
3483 jqLiteDealoc(element);
3484 forEach(new JQLite(replaceNode), function(node) {
3486 parent.insertBefore(node, index.nextSibling);
3488 parent.replaceChild(node, element);
3494 children: function(element) {
3496 forEach(element.childNodes, function(element) {
3497 if (element.nodeType === NODE_TYPE_ELEMENT) {
3498 children.push(element);
3504 contents: function(element) {
3505 return element.contentDocument || element.childNodes || [];
3508 append: function(element, node) {
3509 var nodeType = element.nodeType;
3510 if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
3512 node = new JQLite(node);
3514 for (var i = 0, ii = node.length; i < ii; i++) {
3515 var child = node[i];
3516 element.appendChild(child);
3520 prepend: function(element, node) {
3521 if (element.nodeType === NODE_TYPE_ELEMENT) {
3522 var index = element.firstChild;
3523 forEach(new JQLite(node), function(child) {
3524 element.insertBefore(child, index);
3529 wrap: function(element, wrapNode) {
3530 jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
3533 remove: jqLiteRemove,
3535 detach: function(element) {
3536 jqLiteRemove(element, true);
3539 after: function(element, newElement) {
3540 var index = element, parent = element.parentNode;
3541 newElement = new JQLite(newElement);
3543 for (var i = 0, ii = newElement.length; i < ii; i++) {
3544 var node = newElement[i];
3545 parent.insertBefore(node, index.nextSibling);
3550 addClass: jqLiteAddClass,
3551 removeClass: jqLiteRemoveClass,
3553 toggleClass: function(element, selector, condition) {
3555 forEach(selector.split(' '), function(className) {
3556 var classCondition = condition;
3557 if (isUndefined(classCondition)) {
3558 classCondition = !jqLiteHasClass(element, className);
3560 (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
3565 parent: function(element) {
3566 var parent = element.parentNode;
3567 return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
3570 next: function(element) {
3571 return element.nextElementSibling;
3574 find: function(element, selector) {
3575 if (element.getElementsByTagName) {
3576 return element.getElementsByTagName(selector);
3584 triggerHandler: function(element, event, extraParameters) {
3586 var dummyEvent, eventFnsCopy, handlerArgs;
3587 var eventName = event.type || event;
3588 var expandoStore = jqLiteExpandoStore(element);
3589 var events = expandoStore && expandoStore.events;
3590 var eventFns = events && events[eventName];
3593 // Create a dummy event to pass to the handlers
3595 preventDefault: function() { this.defaultPrevented = true; },
3596 isDefaultPrevented: function() { return this.defaultPrevented === true; },
3597 stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
3598 isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
3599 stopPropagation: noop,
3604 // If a custom event was provided then extend our dummy event with it
3606 dummyEvent = extend(dummyEvent, event);
3609 // Copy event handlers in case event handlers array is modified during execution.
3610 eventFnsCopy = shallowCopy(eventFns);
3611 handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
3613 forEach(eventFnsCopy, function(fn) {
3614 if (!dummyEvent.isImmediatePropagationStopped()) {
3615 fn.apply(element, handlerArgs);
3620 }, function(fn, name) {
3622 * chaining functions
3624 JQLite.prototype[name] = function(arg1, arg2, arg3) {
3627 for (var i = 0, ii = this.length; i < ii; i++) {
3628 if (isUndefined(value)) {
3629 value = fn(this[i], arg1, arg2, arg3);
3630 if (isDefined(value)) {
3631 // any function which returns a value needs to be wrapped
3632 value = jqLite(value);
3635 jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
3638 return isDefined(value) ? value : this;
3641 // bind legacy bind/unbind to on/off
3642 JQLite.prototype.bind = JQLite.prototype.on;
3643 JQLite.prototype.unbind = JQLite.prototype.off;
3647 // Provider for private $$jqLite service
3648 function $$jqLiteProvider() {
3649 this.$get = function $$jqLite() {
3650 return extend(JQLite, {
3651 hasClass: function(node, classes) {
3652 if (node.attr) node = node[0];
3653 return jqLiteHasClass(node, classes);
3655 addClass: function(node, classes) {
3656 if (node.attr) node = node[0];
3657 return jqLiteAddClass(node, classes);
3659 removeClass: function(node, classes) {
3660 if (node.attr) node = node[0];
3661 return jqLiteRemoveClass(node, classes);
3668 * Computes a hash of an 'obj'.
3671 * number is number as string
3672 * object is either result of calling $$hashKey function on the object or uniquely generated id,
3673 * that is also assigned to the $$hashKey property of the object.
3676 * @returns {string} hash string such that the same input will have the same hash string.
3677 * The resulting string key is in 'type:hashKey' format.
3679 function hashKey(obj, nextUidFn) {
3680 var key = obj && obj.$$hashKey;
3683 if (typeof key === 'function') {
3684 key = obj.$$hashKey();
3689 var objType = typeof obj;
3690 if (objType == 'function' || (objType == 'object' && obj !== null)) {
3691 key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
3693 key = objType + ':' + obj;
3700 * HashMap which can use objects as keys
3702 function HashMap(array, isolatedUid) {
3705 this.nextUid = function() {
3709 forEach(array, this.put, this);
3711 HashMap.prototype = {
3713 * Store key value pair
3714 * @param key key to store can be any type
3715 * @param value value to store can be any type
3717 put: function(key, value) {
3718 this[hashKey(key, this.nextUid)] = value;
3723 * @returns {Object} the value for the key
3725 get: function(key) {
3726 return this[hashKey(key, this.nextUid)];
3730 * Remove the key/value pair
3733 remove: function(key) {
3734 var value = this[key = hashKey(key, this.nextUid)];
3740 var $$HashMapProvider = [function() {
3741 this.$get = [function() {
3749 * @name angular.injector
3753 * Creates an injector object that can be used for retrieving services as well as for
3754 * dependency injection (see {@link guide/di dependency injection}).
3756 * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
3757 * {@link angular.module}. The `ng` module must be explicitly added.
3758 * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
3759 * disallows argument name annotation inference.
3760 * @returns {injector} Injector object. See {@link auto.$injector $injector}.
3765 * // create an injector
3766 * var $injector = angular.injector(['ng']);
3768 * // use the injector to kick off your application
3769 * // use the type inference to auto inject arguments, or use implicit injection
3770 * $injector.invoke(function($rootScope, $compile, $document) {
3771 * $compile($document)($rootScope);
3772 * $rootScope.$digest();
3776 * Sometimes you want to get access to the injector of a currently running Angular app
3777 * from outside Angular. Perhaps, you want to inject and compile some markup after the
3778 * application has been bootstrapped. You can do this using the extra `injector()` added
3779 * to JQuery/jqLite elements. See {@link angular.element}.
3781 * *This is fairly rare but could be the case if a third party library is injecting the
3784 * In the following example a new block of HTML containing a `ng-controller`
3785 * directive is added to the end of the document body by JQuery. We then compile and link
3786 * it into the current AngularJS scope.
3789 * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
3790 * $(document.body).append($div);
3792 * angular.element(document).injector().invoke(function($compile) {
3793 * var scope = angular.element($div).scope();
3794 * $compile($div)(scope);
3805 * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
3808 var ARROW_ARG = /^([^\(]+?)=>/;
3809 var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
3810 var FN_ARG_SPLIT = /,/;
3811 var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
3812 var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
3813 var $injectorMinErr = minErr('$injector');
3815 function extractArgs(fn) {
3816 var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
3817 args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
3821 function anonFn(fn) {
3822 // For anonymous functions, showing at the very least the function signature can help in
3824 var args = extractArgs(fn);
3826 return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
3831 function annotate(fn, strictDi, name) {
3836 if (typeof fn === 'function') {
3837 if (!($inject = fn.$inject)) {
3841 if (!isString(name) || !name) {
3842 name = fn.name || anonFn(fn);
3844 throw $injectorMinErr('strictdi',
3845 '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
3847 argDecl = extractArgs(fn);
3848 forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
3849 arg.replace(FN_ARG, function(all, underscore, name) {
3854 fn.$inject = $inject;
3856 } else if (isArray(fn)) {
3857 last = fn.length - 1;
3858 assertArgFn(fn[last], 'fn');
3859 $inject = fn.slice(0, last);
3861 assertArgFn(fn, 'fn', true);
3866 ///////////////////////////////////////
3874 * `$injector` is used to retrieve object instances as defined by
3875 * {@link auto.$provide provider}, instantiate types, invoke methods,
3878 * The following always holds true:
3881 * var $injector = angular.injector();
3882 * expect($injector.get('$injector')).toBe($injector);
3883 * expect($injector.invoke(function($injector) {
3885 * })).toBe($injector);
3888 * # Injection Function Annotation
3890 * JavaScript does not have annotations, and annotations are needed for dependency injection. The
3891 * following are all valid ways of annotating function with injection arguments and are equivalent.
3894 * // inferred (only works if code not minified/obfuscated)
3895 * $injector.invoke(function(serviceA){});
3898 * function explicit(serviceA) {};
3899 * explicit.$inject = ['serviceA'];
3900 * $injector.invoke(explicit);
3903 * $injector.invoke(['serviceA', function(serviceA){}]);
3908 * In JavaScript calling `toString()` on a function returns the function definition. The definition
3909 * can then be parsed and the function arguments can be extracted. This method of discovering
3910 * annotations is disallowed when the injector is in strict mode.
3911 * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
3914 * ## `$inject` Annotation
3915 * By adding an `$inject` property onto a function the injection parameters can be specified.
3918 * As an array of injection names, where the last item in the array is the function to call.
3923 * @name $injector#get
3926 * Return an instance of the service.
3928 * @param {string} name The name of the instance to retrieve.
3929 * @param {string=} caller An optional string to provide the origin of the function call for error messages.
3930 * @return {*} The instance.
3935 * @name $injector#invoke
3938 * Invoke the method and supply the method arguments from the `$injector`.
3940 * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
3941 * injected according to the {@link guide/di $inject Annotation} rules.
3942 * @param {Object=} self The `this` for the invoked method.
3943 * @param {Object=} locals Optional object. If preset then any argument names are read from this
3944 * object first, before the `$injector` is consulted.
3945 * @returns {*} the value returned by the invoked `fn` function.
3950 * @name $injector#has
3953 * Allows the user to query if the particular service exists.
3955 * @param {string} name Name of the service to query.
3956 * @returns {boolean} `true` if injector has given service.
3961 * @name $injector#instantiate
3963 * Create a new instance of JS type. The method takes a constructor function, invokes the new
3964 * operator, and supplies all of the arguments to the constructor function as specified by the
3965 * constructor annotation.
3967 * @param {Function} Type Annotated constructor function.
3968 * @param {Object=} locals Optional object. If preset then any argument names are read from this
3969 * object first, before the `$injector` is consulted.
3970 * @returns {Object} new instance of `Type`.
3975 * @name $injector#annotate
3978 * Returns an array of service names which the function is requesting for injection. This API is
3979 * used by the injector to determine which services need to be injected into the function when the
3980 * function is invoked. There are three ways in which the function can be annotated with the needed
3985 * The simplest form is to extract the dependencies from the arguments of the function. This is done
3986 * by converting the function into a string using `toString()` method and extracting the argument
3990 * function MyController($scope, $route) {
3995 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
3998 * You can disallow this method by using strict injection mode.
4000 * This method does not work with code minification / obfuscation. For this reason the following
4001 * annotation strategies are supported.
4003 * # The `$inject` property
4005 * If a function has an `$inject` property and its value is an array of strings, then the strings
4006 * represent names of services to be injected into the function.
4009 * var MyController = function(obfuscatedScope, obfuscatedRoute) {
4012 * // Define function dependencies
4013 * MyController['$inject'] = ['$scope', '$route'];
4016 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
4019 * # The array notation
4021 * It is often desirable to inline Injected functions and that's when setting the `$inject` property
4022 * is very inconvenient. In these situations using the array notation to specify the dependencies in
4023 * a way that survives minification is a better choice:
4026 * // We wish to write this (not minification / obfuscation safe)
4027 * injector.invoke(function($compile, $rootScope) {
4031 * // We are forced to write break inlining
4032 * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
4035 * tmpFn.$inject = ['$compile', '$rootScope'];
4036 * injector.invoke(tmpFn);
4038 * // To better support inline function the inline annotation is supported
4039 * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
4044 * expect(injector.annotate(
4045 * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
4046 * ).toEqual(['$compile', '$rootScope']);
4049 * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
4050 * be retrieved as described above.
4052 * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
4054 * @returns {Array.<string>} The names of the services which the function requires.
4066 * The {@link auto.$provide $provide} service has a number of methods for registering components
4067 * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
4068 * {@link angular.Module}.
4070 * An Angular **service** is a singleton object created by a **service factory**. These **service
4071 * factories** are functions which, in turn, are created by a **service provider**.
4072 * The **service providers** are constructor functions. When instantiated they must contain a
4073 * property called `$get`, which holds the **service factory** function.
4075 * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
4076 * correct **service provider**, instantiating it and then calling its `$get` **service factory**
4077 * function to get the instance of the **service**.
4079 * Often services have no configuration options and there is no need to add methods to the service
4080 * provider. The provider will be no more than a constructor function with a `$get` property. For
4081 * these cases the {@link auto.$provide $provide} service has additional helper methods to register
4082 * services without specifying a provider.
4084 * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
4085 * {@link auto.$injector $injector}
4086 * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
4087 * providers and services.
4088 * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
4089 * services, not providers.
4090 * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
4091 * that will be wrapped in a **service provider** object, whose `$get` property will contain the
4092 * given factory function.
4093 * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
4094 * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
4095 * a new object using the given constructor function.
4097 * See the individual methods for more information and examples.
4102 * @name $provide#provider
4105 * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
4106 * are constructor functions, whose instances are responsible for "providing" a factory for a
4109 * Service provider names start with the name of the service they provide followed by `Provider`.
4110 * For example, the {@link ng.$log $log} service has a provider called
4111 * {@link ng.$logProvider $logProvider}.
4113 * Service provider objects can have additional methods which allow configuration of the provider
4114 * and its service. Importantly, you can configure what kind of service is created by the `$get`
4115 * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
4116 * method {@link ng.$logProvider#debugEnabled debugEnabled}
4117 * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
4120 * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
4122 * @param {(Object|function())} provider If the provider is:
4124 * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
4125 * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
4126 * - `Constructor`: a new instance of the provider will be created using
4127 * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
4129 * @returns {Object} registered provider instance
4133 * The following example shows how to create a simple event tracking service and register it using
4134 * {@link auto.$provide#provider $provide.provider()}.
4137 * // Define the eventTracker provider
4138 * function EventTrackerProvider() {
4139 * var trackingUrl = '/track';
4141 * // A provider method for configuring where the tracked events should been saved
4142 * this.setTrackingUrl = function(url) {
4143 * trackingUrl = url;
4146 * // The service factory function
4147 * this.$get = ['$http', function($http) {
4148 * var trackedEvents = {};
4150 * // Call this to track an event
4151 * event: function(event) {
4152 * var count = trackedEvents[event] || 0;
4154 * trackedEvents[event] = count;
4157 * // Call this to save the tracked events to the trackingUrl
4158 * save: function() {
4159 * $http.post(trackingUrl, trackedEvents);
4165 * describe('eventTracker', function() {
4168 * beforeEach(module(function($provide) {
4169 * // Register the eventTracker provider
4170 * $provide.provider('eventTracker', EventTrackerProvider);
4173 * beforeEach(module(function(eventTrackerProvider) {
4174 * // Configure eventTracker provider
4175 * eventTrackerProvider.setTrackingUrl('/custom-track');
4178 * it('tracks events', inject(function(eventTracker) {
4179 * expect(eventTracker.event('login')).toEqual(1);
4180 * expect(eventTracker.event('login')).toEqual(2);
4183 * it('saves to the tracking url', inject(function(eventTracker, $http) {
4184 * postSpy = spyOn($http, 'post');
4185 * eventTracker.event('login');
4186 * eventTracker.save();
4187 * expect(postSpy).toHaveBeenCalled();
4188 * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
4189 * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
4190 * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
4198 * @name $provide#factory
4201 * Register a **service factory**, which will be called to return the service instance.
4202 * This is short for registering a service where its provider consists of only a `$get` property,
4203 * which is the given service factory function.
4204 * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
4205 * configure your service in a provider.
4207 * @param {string} name The name of the instance.
4208 * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
4209 * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
4210 * @returns {Object} registered provider instance
4213 * Here is an example of registering a service
4215 * $provide.factory('ping', ['$http', function($http) {
4216 * return function ping() {
4217 * return $http.send('/ping');
4221 * You would then inject and use this service like this:
4223 * someModule.controller('Ctrl', ['ping', function(ping) {
4232 * @name $provide#service
4235 * Register a **service constructor**, which will be invoked with `new` to create the service
4237 * This is short for registering a service where its provider's `$get` property is a factory
4238 * function that returns an instance instantiated by the injector from the service constructor
4241 * Internally it looks a bit like this:
4245 * $get: function() {
4246 * return $injector.instantiate(constructor);
4252 * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
4255 * @param {string} name The name of the instance.
4256 * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
4257 * that will be instantiated.
4258 * @returns {Object} registered provider instance
4261 * Here is an example of registering a service using
4262 * {@link auto.$provide#service $provide.service(class)}.
4264 * var Ping = function($http) {
4265 * this.$http = $http;
4268 * Ping.$inject = ['$http'];
4270 * Ping.prototype.send = function() {
4271 * return this.$http.get('/ping');
4273 * $provide.service('ping', Ping);
4275 * You would then inject and use this service like this:
4277 * someModule.controller('Ctrl', ['ping', function(ping) {
4286 * @name $provide#value
4289 * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
4290 * number, an array, an object or a function. This is short for registering a service where its
4291 * provider's `$get` property is a factory function that takes no arguments and returns the **value
4294 * Value services are similar to constant services, except that they cannot be injected into a
4295 * module configuration function (see {@link angular.Module#config}) but they can be overridden by
4297 * {@link auto.$provide#decorator decorator}.
4299 * @param {string} name The name of the instance.
4300 * @param {*} value The value.
4301 * @returns {Object} registered provider instance
4304 * Here are some examples of creating value services.
4306 * $provide.value('ADMIN_USER', 'admin');
4308 * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
4310 * $provide.value('halfOf', function(value) {
4319 * @name $provide#constant
4322 * Register a **constant service**, such as a string, a number, an array, an object or a function,
4323 * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
4324 * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
4325 * be overridden by an Angular {@link auto.$provide#decorator decorator}.
4327 * @param {string} name The name of the constant.
4328 * @param {*} value The constant value.
4329 * @returns {Object} registered instance
4332 * Here a some examples of creating constants:
4334 * $provide.constant('SHARD_HEIGHT', 306);
4336 * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
4338 * $provide.constant('double', function(value) {
4347 * @name $provide#decorator
4350 * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
4351 * intercepts the creation of a service, allowing it to override or modify the behavior of the
4352 * service. The object returned by the decorator may be the original service, or a new service
4353 * object which replaces or wraps and delegates to the original service.
4355 * @param {string} name The name of the service to decorate.
4356 * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
4357 * instantiated and should return the decorated service instance. The function is called using
4358 * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
4359 * Local injection arguments:
4361 * * `$delegate` - The original service instance, which can be monkey patched, configured,
4362 * decorated or delegated to.
4365 * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
4366 * calls to {@link ng.$log#error $log.warn()}.
4368 * $provide.decorator('$log', ['$delegate', function($delegate) {
4369 * $delegate.warn = $delegate.error;
4376 function createInjector(modulesToLoad, strictDi) {
4377 strictDi = (strictDi === true);
4378 var INSTANTIATING = {},
4379 providerSuffix = 'Provider',
4381 loadedModules = new HashMap([], true),
4384 provider: supportObject(provider),
4385 factory: supportObject(factory),
4386 service: supportObject(service),
4387 value: supportObject(value),
4388 constant: supportObject(constant),
4389 decorator: decorator
4392 providerInjector = (providerCache.$injector =
4393 createInternalInjector(providerCache, function(serviceName, caller) {
4394 if (angular.isString(caller)) {
4397 throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
4400 protoInstanceInjector =
4401 createInternalInjector(instanceCache, function(serviceName, caller) {
4402 var provider = providerInjector.get(serviceName + providerSuffix, caller);
4403 return instanceInjector.invoke(
4404 provider.$get, provider, undefined, serviceName);
4406 instanceInjector = protoInstanceInjector;
4408 providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
4409 var runBlocks = loadModules(modulesToLoad);
4410 instanceInjector = protoInstanceInjector.get('$injector');
4411 instanceInjector.strictDi = strictDi;
4412 forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
4414 return instanceInjector;
4416 ////////////////////////////////////
4418 ////////////////////////////////////
4420 function supportObject(delegate) {
4421 return function(key, value) {
4422 if (isObject(key)) {
4423 forEach(key, reverseParams(delegate));
4425 return delegate(key, value);
4430 function provider(name, provider_) {
4431 assertNotHasOwnProperty(name, 'service');
4432 if (isFunction(provider_) || isArray(provider_)) {
4433 provider_ = providerInjector.instantiate(provider_);
4435 if (!provider_.$get) {
4436 throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
4438 return providerCache[name + providerSuffix] = provider_;
4441 function enforceReturnValue(name, factory) {
4442 return function enforcedReturnValue() {
4443 var result = instanceInjector.invoke(factory, this);
4444 if (isUndefined(result)) {
4445 throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
4451 function factory(name, factoryFn, enforce) {
4452 return provider(name, {
4453 $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
4457 function service(name, constructor) {
4458 return factory(name, ['$injector', function($injector) {
4459 return $injector.instantiate(constructor);
4463 function value(name, val) { return factory(name, valueFn(val), false); }
4465 function constant(name, value) {
4466 assertNotHasOwnProperty(name, 'constant');
4467 providerCache[name] = value;
4468 instanceCache[name] = value;
4471 function decorator(serviceName, decorFn) {
4472 var origProvider = providerInjector.get(serviceName + providerSuffix),
4473 orig$get = origProvider.$get;
4475 origProvider.$get = function() {
4476 var origInstance = instanceInjector.invoke(orig$get, origProvider);
4477 return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
4481 ////////////////////////////////////
4483 ////////////////////////////////////
4484 function loadModules(modulesToLoad) {
4485 assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
4486 var runBlocks = [], moduleFn;
4487 forEach(modulesToLoad, function(module) {
4488 if (loadedModules.get(module)) return;
4489 loadedModules.put(module, true);
4491 function runInvokeQueue(queue) {
4493 for (i = 0, ii = queue.length; i < ii; i++) {
4494 var invokeArgs = queue[i],
4495 provider = providerInjector.get(invokeArgs[0]);
4497 provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
4502 if (isString(module)) {
4503 moduleFn = angularModule(module);
4504 runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
4505 runInvokeQueue(moduleFn._invokeQueue);
4506 runInvokeQueue(moduleFn._configBlocks);
4507 } else if (isFunction(module)) {
4508 runBlocks.push(providerInjector.invoke(module));
4509 } else if (isArray(module)) {
4510 runBlocks.push(providerInjector.invoke(module));
4512 assertArgFn(module, 'module');
4515 if (isArray(module)) {
4516 module = module[module.length - 1];
4518 if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
4519 // Safari & FF's stack traces don't contain error.message content
4520 // unlike those of Chrome and IE
4521 // So if stack doesn't contain message, we create a new string that contains both.
4522 // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
4524 e = e.message + '\n' + e.stack;
4526 throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
4527 module, e.stack || e.message || e);
4533 ////////////////////////////////////
4534 // internal Injector
4535 ////////////////////////////////////
4537 function createInternalInjector(cache, factory) {
4539 function getService(serviceName, caller) {
4540 if (cache.hasOwnProperty(serviceName)) {
4541 if (cache[serviceName] === INSTANTIATING) {
4542 throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
4543 serviceName + ' <- ' + path.join(' <- '));
4545 return cache[serviceName];
4548 path.unshift(serviceName);
4549 cache[serviceName] = INSTANTIATING;
4550 return cache[serviceName] = factory(serviceName, caller);
4552 if (cache[serviceName] === INSTANTIATING) {
4553 delete cache[serviceName];
4563 function injectionArgs(fn, locals, serviceName) {
4565 $inject = createInjector.$$annotate(fn, strictDi, serviceName);
4567 for (var i = 0, length = $inject.length; i < length; i++) {
4568 var key = $inject[i];
4569 if (typeof key !== 'string') {
4570 throw $injectorMinErr('itkn',
4571 'Incorrect injection token! Expected service name as string, got {0}', key);
4573 args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
4574 getService(key, serviceName));
4579 function isClass(func) {
4580 // IE 9-11 do not support classes and IE9 leaks with the code below.
4584 // Workaround for MS Edge.
4585 // Check https://connect.microsoft.com/IE/Feedback/Details/2211653
4586 return typeof func === 'function'
4587 && /^(?:class\s|constructor\()/.test(Function.prototype.toString.call(func));
4590 function invoke(fn, self, locals, serviceName) {
4591 if (typeof locals === 'string') {
4592 serviceName = locals;
4596 var args = injectionArgs(fn, locals, serviceName);
4598 fn = fn[fn.length - 1];
4602 // http://jsperf.com/angularjs-invoke-apply-vs-switch
4604 return fn.apply(self, args);
4607 return new (Function.prototype.bind.apply(fn, args))();
4612 function instantiate(Type, locals, serviceName) {
4613 // Check if Type is annotated and use just the given function at n-1 as parameter
4614 // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
4615 var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
4616 var args = injectionArgs(Type, locals, serviceName);
4617 // Empty object at position 0 is ignored for invocation with `new`, but required.
4619 return new (Function.prototype.bind.apply(ctor, args))();
4625 instantiate: instantiate,
4627 annotate: createInjector.$$annotate,
4628 has: function(name) {
4629 return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
4635 createInjector.$$annotate = annotate;
4639 * @name $anchorScrollProvider
4642 * Use `$anchorScrollProvider` to disable automatic scrolling whenever
4643 * {@link ng.$location#hash $location.hash()} changes.
4645 function $AnchorScrollProvider() {
4647 var autoScrollingEnabled = true;
4651 * @name $anchorScrollProvider#disableAutoScrolling
4654 * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
4655 * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
4656 * Use this method to disable automatic scrolling.
4658 * If automatic scrolling is disabled, one must explicitly call
4659 * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
4662 this.disableAutoScrolling = function() {
4663 autoScrollingEnabled = false;
4668 * @name $anchorScroll
4671 * @requires $location
4672 * @requires $rootScope
4675 * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
4676 * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
4678 * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
4680 * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
4681 * match any anchor whenever it changes. This can be disabled by calling
4682 * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
4684 * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
4685 * vertical scroll-offset (either fixed or dynamic).
4687 * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
4688 * {@link ng.$location#hash $location.hash()} will be used.
4690 * @property {(number|function|jqLite)} yOffset
4691 * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
4692 * positioned elements at the top of the page, such as navbars, headers etc.
4694 * `yOffset` can be specified in various ways:
4695 * - **number**: A fixed number of pixels to be used as offset.<br /><br />
4696 * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
4697 * a number representing the offset (in pixels).<br /><br />
4698 * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
4699 * the top of the page to the element's bottom will be used as offset.<br />
4700 * **Note**: The element will be taken into account only as long as its `position` is set to
4701 * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
4702 * their height and/or positioning according to the viewport's size.
4705 * <div class="alert alert-warning">
4706 * In order for `yOffset` to work properly, scrolling should take place on the document's root and
4707 * not some child element.
4711 <example module="anchorScrollExample">
4712 <file name="index.html">
4713 <div id="scrollArea" ng-controller="ScrollController">
4714 <a ng-click="gotoBottom()">Go to bottom</a>
4715 <a id="bottom"></a> You're at the bottom!
4718 <file name="script.js">
4719 angular.module('anchorScrollExample', [])
4720 .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
4721 function ($scope, $location, $anchorScroll) {
4722 $scope.gotoBottom = function() {
4723 // set the location.hash to the id of
4724 // the element you wish to scroll to.
4725 $location.hash('bottom');
4727 // call $anchorScroll()
4732 <file name="style.css">
4746 * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
4747 * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
4750 <example module="anchorScrollOffsetExample">
4751 <file name="index.html">
4752 <div class="fixed-header" ng-controller="headerCtrl">
4753 <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
4757 <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
4761 <file name="script.js">
4762 angular.module('anchorScrollOffsetExample', [])
4763 .run(['$anchorScroll', function($anchorScroll) {
4764 $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
4766 .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
4767 function ($anchorScroll, $location, $scope) {
4768 $scope.gotoAnchor = function(x) {
4769 var newHash = 'anchor' + x;
4770 if ($location.hash() !== newHash) {
4771 // set the $location.hash to `newHash` and
4772 // $anchorScroll will automatically scroll to it
4773 $location.hash('anchor' + x);
4775 // call $anchorScroll() explicitly,
4776 // since $location.hash hasn't changed
4783 <file name="style.css">
4789 border: 2px dashed DarkOrchid;
4790 padding: 10px 10px 200px 10px;
4794 background-color: rgba(0, 0, 0, 0.2);
4797 top: 0; left: 0; right: 0;
4801 display: inline-block;
4807 this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
4808 var document = $window.document;
4810 // Helper function to get first anchor from a NodeList
4811 // (using `Array#some()` instead of `angular#forEach()` since it's more performant
4812 // and working in all supported browsers.)
4813 function getFirstAnchor(list) {
4815 Array.prototype.some.call(list, function(element) {
4816 if (nodeName_(element) === 'a') {
4824 function getYOffset() {
4826 var offset = scroll.yOffset;
4828 if (isFunction(offset)) {
4830 } else if (isElement(offset)) {
4831 var elem = offset[0];
4832 var style = $window.getComputedStyle(elem);
4833 if (style.position !== 'fixed') {
4836 offset = elem.getBoundingClientRect().bottom;
4838 } else if (!isNumber(offset)) {
4845 function scrollTo(elem) {
4847 elem.scrollIntoView();
4849 var offset = getYOffset();
4852 // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
4853 // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
4854 // top of the viewport.
4856 // IF the number of pixels from the top of `elem` to the end of the page's content is less
4857 // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
4858 // way down the page.
4860 // This is often the case for elements near the bottom of the page.
4862 // In such cases we do not need to scroll the whole `offset` up, just the difference between
4863 // the top of the element and the offset, which is enough to align the top of `elem` at the
4864 // desired position.
4865 var elemTop = elem.getBoundingClientRect().top;
4866 $window.scrollBy(0, elemTop - offset);
4869 $window.scrollTo(0, 0);
4873 function scroll(hash) {
4874 hash = isString(hash) ? hash : $location.hash();
4877 // empty hash, scroll to the top of the page
4878 if (!hash) scrollTo(null);
4880 // element with given id
4881 else if ((elm = document.getElementById(hash))) scrollTo(elm);
4883 // first anchor with given name :-D
4884 else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
4886 // no element and hash == 'top', scroll to the top of the page
4887 else if (hash === 'top') scrollTo(null);
4890 // does not scroll when user clicks on anchor link that is currently on
4891 // (no url change, no $location.hash() change), browser native does scroll
4892 if (autoScrollingEnabled) {
4893 $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
4894 function autoScrollWatchAction(newVal, oldVal) {
4895 // skip the initial scroll if $location.hash is empty
4896 if (newVal === oldVal && newVal === '') return;
4898 jqLiteDocumentLoaded(function() {
4899 $rootScope.$evalAsync(scroll);
4908 var $animateMinErr = minErr('$animate');
4909 var ELEMENT_NODE = 1;
4910 var NG_ANIMATE_CLASSNAME = 'ng-animate';
4912 function mergeClasses(a,b) {
4913 if (!a && !b) return '';
4916 if (isArray(a)) a = a.join(' ');
4917 if (isArray(b)) b = b.join(' ');
4921 function extractElementNode(element) {
4922 for (var i = 0; i < element.length; i++) {
4923 var elm = element[i];
4924 if (elm.nodeType === ELEMENT_NODE) {
4930 function splitClasses(classes) {
4931 if (isString(classes)) {
4932 classes = classes.split(' ');
4935 // Use createMap() to prevent class assumptions involving property names in
4937 var obj = createMap();
4938 forEach(classes, function(klass) {
4939 // sometimes the split leaves empty string values
4940 // incase extra spaces were applied to the options
4948 // if any other type of options value besides an Object value is
4949 // passed into the $animate.method() animation then this helper code
4950 // will be run which will ignore it. While this patch is not the
4951 // greatest solution to this, a lot of existing plugins depend on
4952 // $animate to either call the callback (< 1.2) or return a promise
4953 // that can be changed. This helper function ensures that the options
4954 // are wiped clean incase a callback function is provided.
4955 function prepareAnimateOptions(options) {
4956 return isObject(options)
4961 var $$CoreAnimateJsProvider = function() {
4962 this.$get = function() {};
4965 // this is prefixed with Core since it conflicts with
4966 // the animateQueueProvider defined in ngAnimate/animateQueue.js
4967 var $$CoreAnimateQueueProvider = function() {
4968 var postDigestQueue = new HashMap();
4969 var postDigestElements = [];
4971 this.$get = ['$$AnimateRunner', '$rootScope',
4972 function($$AnimateRunner, $rootScope) {
4979 push: function(element, event, options, domOperation) {
4980 domOperation && domOperation();
4982 options = options || {};
4983 options.from && element.css(options.from);
4984 options.to && element.css(options.to);
4986 if (options.addClass || options.removeClass) {
4987 addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
4990 var runner = new $$AnimateRunner(); // jshint ignore:line
4992 // since there are no animations to run the runner needs to be
4993 // notified that the animation call is complete.
5000 function updateData(data, classes, value) {
5001 var changed = false;
5003 classes = isString(classes) ? classes.split(' ') :
5004 isArray(classes) ? classes : [];
5005 forEach(classes, function(className) {
5008 data[className] = value;
5015 function handleCSSClassChanges() {
5016 forEach(postDigestElements, function(element) {
5017 var data = postDigestQueue.get(element);
5019 var existing = splitClasses(element.attr('class'));
5022 forEach(data, function(status, className) {
5023 var hasClass = !!existing[className];
5024 if (status !== hasClass) {
5026 toAdd += (toAdd.length ? ' ' : '') + className;
5028 toRemove += (toRemove.length ? ' ' : '') + className;
5033 forEach(element, function(elm) {
5034 toAdd && jqLiteAddClass(elm, toAdd);
5035 toRemove && jqLiteRemoveClass(elm, toRemove);
5037 postDigestQueue.remove(element);
5040 postDigestElements.length = 0;
5044 function addRemoveClassesPostDigest(element, add, remove) {
5045 var data = postDigestQueue.get(element) || {};
5047 var classesAdded = updateData(data, add, true);
5048 var classesRemoved = updateData(data, remove, false);
5050 if (classesAdded || classesRemoved) {
5052 postDigestQueue.put(element, data);
5053 postDigestElements.push(element);
5055 if (postDigestElements.length === 1) {
5056 $rootScope.$$postDigest(handleCSSClassChanges);
5065 * @name $animateProvider
5068 * Default implementation of $animate that doesn't perform any animations, instead just
5069 * synchronously performs DOM updates and resolves the returned runner promise.
5071 * In order to enable animations the `ngAnimate` module has to be loaded.
5073 * To see the functional implementation check out `src/ngAnimate/animate.js`.
5075 var $AnimateProvider = ['$provide', function($provide) {
5076 var provider = this;
5078 this.$$registeredAnimations = Object.create(null);
5082 * @name $animateProvider#register
5085 * Registers a new injectable animation factory function. The factory function produces the
5086 * animation object which contains callback functions for each event that is expected to be
5089 * * `eventFn`: `function(element, ... , doneFunction, options)`
5090 * The element to animate, the `doneFunction` and the options fed into the animation. Depending
5091 * on the type of animation additional arguments will be injected into the animation function. The
5092 * list below explains the function signatures for the different animation methods:
5094 * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
5095 * - addClass: function(element, addedClasses, doneFunction, options)
5096 * - removeClass: function(element, removedClasses, doneFunction, options)
5097 * - enter, leave, move: function(element, doneFunction, options)
5098 * - animate: function(element, fromStyles, toStyles, doneFunction, options)
5100 * Make sure to trigger the `doneFunction` once the animation is fully complete.
5104 * //enter, leave, move signature
5105 * eventFn : function(element, done, options) {
5106 * //code to run the animation
5107 * //once complete, then run done()
5108 * return function endFunction(wasCancelled) {
5109 * //code to cancel the animation
5115 * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
5116 * @param {Function} factory The factory function that will be executed to return the animation
5119 this.register = function(name, factory) {
5120 if (name && name.charAt(0) !== '.') {
5121 throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
5124 var key = name + '-animation';
5125 provider.$$registeredAnimations[name.substr(1)] = key;
5126 $provide.factory(key, factory);
5131 * @name $animateProvider#classNameFilter
5134 * Sets and/or returns the CSS class regular expression that is checked when performing
5135 * an animation. Upon bootstrap the classNameFilter value is not set at all and will
5136 * therefore enable $animate to attempt to perform an animation on any element that is triggered.
5137 * When setting the `classNameFilter` value, animations will only be performed on elements
5138 * that successfully match the filter expression. This in turn can boost performance
5139 * for low-powered devices as well as applications containing a lot of structural operations.
5140 * @param {RegExp=} expression The className expression which will be checked against all animations
5141 * @return {RegExp} The current CSS className expression value. If null then there is no expression value
5143 this.classNameFilter = function(expression) {
5144 if (arguments.length === 1) {
5145 this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
5146 if (this.$$classNameFilter) {
5147 var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
5148 if (reservedRegex.test(this.$$classNameFilter.toString())) {
5149 throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
5154 return this.$$classNameFilter;
5157 this.$get = ['$$animateQueue', function($$animateQueue) {
5158 function domInsert(element, parentElement, afterElement) {
5159 // if for some reason the previous element was removed
5160 // from the dom sometime before this code runs then let's
5161 // just stick to using the parent element as the anchor
5163 var afterNode = extractElementNode(afterElement);
5164 if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
5165 afterElement = null;
5168 afterElement ? afterElement.after(element) : parentElement.prepend(element);
5174 * @description The $animate service exposes a series of DOM utility methods that provide support
5175 * for animation hooks. The default behavior is the application of DOM operations, however,
5176 * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
5177 * to ensure that animation runs with the triggered DOM operation.
5179 * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
5180 * included and only when it is active then the animation hooks that `$animate` triggers will be
5181 * functional. Once active then all structural `ng-` directives will trigger animations as they perform
5182 * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
5183 * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
5185 * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
5187 * To learn more about enabling animation support, click here to visit the
5188 * {@link ngAnimate ngAnimate module page}.
5191 // we don't call it directly since non-existant arguments may
5192 // be interpreted as null within the sub enabled function
5199 * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
5200 * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
5201 * is fired with the following params:
5204 * $animate.on('enter', container,
5205 * function callback(element, phase) {
5206 * // cool we detected an enter animation within the container
5211 * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
5212 * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
5213 * as well as among its children
5214 * @param {Function} callback the callback function that will be fired when the listener is triggered
5216 * The arguments present in the callback function are:
5217 * * `element` - The captured DOM element that the animation was fired on.
5218 * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
5220 on: $$animateQueue.on,
5225 * @name $animate#off
5227 * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
5228 * can be used in three different ways depending on the arguments:
5231 * // remove all the animation event listeners listening for `enter`
5232 * $animate.off('enter');
5234 * // remove all the animation event listeners listening for `enter` on the given element and its children
5235 * $animate.off('enter', container);
5237 * // remove the event listener function provided by `callback` that is set
5238 * // to listen for `enter` on the given `container` as well as its children
5239 * $animate.off('enter', container, callback);
5242 * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
5243 * @param {DOMElement=} container the container element the event listener was placed on
5244 * @param {Function=} callback the callback function that was registered as the listener
5246 off: $$animateQueue.off,
5250 * @name $animate#pin
5252 * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
5253 * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
5254 * element despite being outside the realm of the application or within another application. Say for example if the application
5255 * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
5256 * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
5257 * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
5259 * Note that this feature is only active when the `ngAnimate` module is used.
5261 * @param {DOMElement} element the external element that will be pinned
5262 * @param {DOMElement} parentElement the host parent element that will be associated with the external element
5264 pin: $$animateQueue.pin,
5269 * @name $animate#enabled
5271 * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
5272 * function can be called in four ways:
5275 * // returns true or false
5276 * $animate.enabled();
5278 * // changes the enabled state for all animations
5279 * $animate.enabled(false);
5280 * $animate.enabled(true);
5282 * // returns true or false if animations are enabled for an element
5283 * $animate.enabled(element);
5285 * // changes the enabled state for an element and its children
5286 * $animate.enabled(element, true);
5287 * $animate.enabled(element, false);
5290 * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
5291 * @param {boolean=} enabled whether or not the animations will be enabled for the element
5293 * @return {boolean} whether or not animations are enabled
5295 enabled: $$animateQueue.enabled,
5299 * @name $animate#cancel
5301 * @description Cancels the provided animation.
5303 * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
5305 cancel: function(runner) {
5306 runner.end && runner.end();
5312 * @name $animate#enter
5314 * @description Inserts the element into the DOM either after the `after` element (if provided) or
5315 * as the first child within the `parent` element and then triggers an animation.
5316 * A promise is returned that will be resolved during the next digest once the animation
5319 * @param {DOMElement} element the element which will be inserted into the DOM
5320 * @param {DOMElement} parent the parent element which will append the element as
5321 * a child (so long as the after element is not present)
5322 * @param {DOMElement=} after the sibling element after which the element will be appended
5323 * @param {object=} options an optional collection of options/styles that will be applied to the element
5325 * @return {Promise} the animation callback promise
5327 enter: function(element, parent, after, options) {
5328 parent = parent && jqLite(parent);
5329 after = after && jqLite(after);
5330 parent = parent || after.parent();
5331 domInsert(element, parent, after);
5332 return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
5338 * @name $animate#move
5340 * @description Inserts (moves) the element into its new position in the DOM either after
5341 * the `after` element (if provided) or as the first child within the `parent` element
5342 * and then triggers an animation. A promise is returned that will be resolved
5343 * during the next digest once the animation has completed.
5345 * @param {DOMElement} element the element which will be moved into the new DOM position
5346 * @param {DOMElement} parent the parent element which will append the element as
5347 * a child (so long as the after element is not present)
5348 * @param {DOMElement=} after the sibling element after which the element will be appended
5349 * @param {object=} options an optional collection of options/styles that will be applied to the element
5351 * @return {Promise} the animation callback promise
5353 move: function(element, parent, after, options) {
5354 parent = parent && jqLite(parent);
5355 after = after && jqLite(after);
5356 parent = parent || after.parent();
5357 domInsert(element, parent, after);
5358 return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
5363 * @name $animate#leave
5365 * @description Triggers an animation and then removes the element from the DOM.
5366 * When the function is called a promise is returned that will be resolved during the next
5367 * digest once the animation has completed.
5369 * @param {DOMElement} element the element which will be removed from the DOM
5370 * @param {object=} options an optional collection of options/styles that will be applied to the element
5372 * @return {Promise} the animation callback promise
5374 leave: function(element, options) {
5375 return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
5382 * @name $animate#addClass
5385 * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
5386 * execution, the addClass operation will only be handled after the next digest and it will not trigger an
5387 * animation if element already contains the CSS class or if the class is removed at a later step.
5388 * Note that class-based animations are treated differently compared to structural animations
5389 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5390 * depending if CSS or JavaScript animations are used.
5392 * @param {DOMElement} element the element which the CSS classes will be applied to
5393 * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
5394 * @param {object=} options an optional collection of options/styles that will be applied to the element
5396 * @return {Promise} the animation callback promise
5398 addClass: function(element, className, options) {
5399 options = prepareAnimateOptions(options);
5400 options.addClass = mergeClasses(options.addclass, className);
5401 return $$animateQueue.push(element, 'addClass', options);
5406 * @name $animate#removeClass
5409 * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
5410 * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
5411 * animation if element does not contain the CSS class or if the class is added at a later step.
5412 * Note that class-based animations are treated differently compared to structural animations
5413 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5414 * depending if CSS or JavaScript animations are used.
5416 * @param {DOMElement} element the element which the CSS classes will be applied to
5417 * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
5418 * @param {object=} options an optional collection of options/styles that will be applied to the element
5420 * @return {Promise} the animation callback promise
5422 removeClass: function(element, className, options) {
5423 options = prepareAnimateOptions(options);
5424 options.removeClass = mergeClasses(options.removeClass, className);
5425 return $$animateQueue.push(element, 'removeClass', options);
5430 * @name $animate#setClass
5433 * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
5434 * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
5435 * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
5436 * passed. Note that class-based animations are treated differently compared to structural animations
5437 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5438 * depending if CSS or JavaScript animations are used.
5440 * @param {DOMElement} element the element which the CSS classes will be applied to
5441 * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
5442 * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
5443 * @param {object=} options an optional collection of options/styles that will be applied to the element
5445 * @return {Promise} the animation callback promise
5447 setClass: function(element, add, remove, options) {
5448 options = prepareAnimateOptions(options);
5449 options.addClass = mergeClasses(options.addClass, add);
5450 options.removeClass = mergeClasses(options.removeClass, remove);
5451 return $$animateQueue.push(element, 'setClass', options);
5456 * @name $animate#animate
5459 * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
5460 * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
5461 * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
5462 * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
5463 * style in `to`, the style in `from` is applied immediately, and no animation is run.
5464 * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
5465 * method (or as part of the `options` parameter):
5468 * ngModule.animation('.my-inline-animation', function() {
5470 * animate : function(element, from, to, done, options) {
5478 * @param {DOMElement} element the element which the CSS styles will be applied to
5479 * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
5480 * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
5481 * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
5482 * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
5483 * (Note that if no animation is detected then this value will not be applied to the element.)
5484 * @param {object=} options an optional collection of options/styles that will be applied to the element
5486 * @return {Promise} the animation callback promise
5488 animate: function(element, from, to, className, options) {
5489 options = prepareAnimateOptions(options);
5490 options.from = options.from ? extend(options.from, from) : from;
5491 options.to = options.to ? extend(options.to, to) : to;
5493 className = className || 'ng-inline-animate';
5494 options.tempClasses = mergeClasses(options.tempClasses, className);
5495 return $$animateQueue.push(element, 'animate', options);
5501 var $$AnimateAsyncRunFactoryProvider = function() {
5502 this.$get = ['$$rAF', function($$rAF) {
5505 function waitForTick(fn) {
5507 if (waitQueue.length > 1) return;
5509 for (var i = 0; i < waitQueue.length; i++) {
5518 waitForTick(function() {
5521 return function(callback) {
5522 passed ? callback() : waitForTick(callback);
5528 var $$AnimateRunnerFactoryProvider = function() {
5529 this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
5530 function($q, $sniffer, $$animateAsyncRun, $document, $timeout) {
5532 var INITIAL_STATE = 0;
5533 var DONE_PENDING_STATE = 1;
5534 var DONE_COMPLETE_STATE = 2;
5536 AnimateRunner.chain = function(chain, callback) {
5541 if (index === chain.length) {
5546 chain[index](function(response) {
5547 if (response === false) {
5557 AnimateRunner.all = function(runners, callback) {
5560 forEach(runners, function(runner) {
5561 runner.done(onProgress);
5564 function onProgress(response) {
5565 status = status && response;
5566 if (++count === runners.length) {
5572 function AnimateRunner(host) {
5575 var rafTick = $$animateAsyncRun();
5576 var timeoutTick = function(fn) {
5577 $timeout(fn, 0, false);
5580 this._doneCallbacks = [];
5581 this._tick = function(fn) {
5582 var doc = $document[0];
5584 // the document may not be ready or attached
5585 // to the module for some internal tests
5586 if (doc && doc.hidden) {
5595 AnimateRunner.prototype = {
5596 setHost: function(host) {
5597 this.host = host || {};
5600 done: function(fn) {
5601 if (this._state === DONE_COMPLETE_STATE) {
5604 this._doneCallbacks.push(fn);
5610 getPromise: function() {
5611 if (!this.promise) {
5613 this.promise = $q(function(resolve, reject) {
5614 self.done(function(status) {
5615 status === false ? reject() : resolve();
5619 return this.promise;
5622 then: function(resolveHandler, rejectHandler) {
5623 return this.getPromise().then(resolveHandler, rejectHandler);
5626 'catch': function(handler) {
5627 return this.getPromise()['catch'](handler);
5630 'finally': function(handler) {
5631 return this.getPromise()['finally'](handler);
5635 if (this.host.pause) {
5640 resume: function() {
5641 if (this.host.resume) {
5647 if (this.host.end) {
5650 this._resolve(true);
5653 cancel: function() {
5654 if (this.host.cancel) {
5657 this._resolve(false);
5660 complete: function(response) {
5662 if (self._state === INITIAL_STATE) {
5663 self._state = DONE_PENDING_STATE;
5664 self._tick(function() {
5665 self._resolve(response);
5670 _resolve: function(response) {
5671 if (this._state !== DONE_COMPLETE_STATE) {
5672 forEach(this._doneCallbacks, function(fn) {
5675 this._doneCallbacks.length = 0;
5676 this._state = DONE_COMPLETE_STATE;
5681 return AnimateRunner;
5691 * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
5692 * then the `$animateCss` service will actually perform animations.
5694 * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
5696 var $CoreAnimateCssProvider = function() {
5697 this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
5699 return function(element, initialOptions) {
5700 // all of the animation functions should create
5701 // a copy of the options data, however, if a
5702 // parent service has already created a copy then
5703 // we should stick to using that
5704 var options = initialOptions || {};
5705 if (!options.$$prepared) {
5706 options = copy(options);
5709 // there is no point in applying the styles since
5710 // there is no animation that goes on at all in
5711 // this version of $animateCss.
5712 if (options.cleanupStyles) {
5713 options.from = options.to = null;
5717 element.css(options.from);
5718 options.from = null;
5721 /* jshint newcap: false */
5722 var closed, runner = new $$AnimateRunner();
5730 applyAnimationContents();
5739 function applyAnimationContents() {
5740 if (options.addClass) {
5741 element.addClass(options.addClass);
5742 options.addClass = null;
5744 if (options.removeClass) {
5745 element.removeClass(options.removeClass);
5746 options.removeClass = null;
5749 element.css(options.to);
5757 /* global stripHash: true */
5760 * ! This is a private undocumented service !
5765 * This object has two goals:
5767 * - hide all the global state in the browser caused by the window object
5768 * - abstract away all the browser specific features and inconsistencies
5770 * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
5771 * service, which can be used for convenient testing of the application without the interaction with
5772 * the real browser apis.
5775 * @param {object} window The global window object.
5776 * @param {object} document jQuery wrapped document.
5777 * @param {object} $log window.console or an object with the same interface.
5778 * @param {object} $sniffer $sniffer service
5780 function Browser(window, document, $log, $sniffer) {
5782 rawDocument = document[0],
5783 location = window.location,
5784 history = window.history,
5785 setTimeout = window.setTimeout,
5786 clearTimeout = window.clearTimeout,
5787 pendingDeferIds = {};
5789 self.isMock = false;
5791 var outstandingRequestCount = 0;
5792 var outstandingRequestCallbacks = [];
5794 // TODO(vojta): remove this temporary api
5795 self.$$completeOutstandingRequest = completeOutstandingRequest;
5796 self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
5799 * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
5800 * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
5802 function completeOutstandingRequest(fn) {
5804 fn.apply(null, sliceArgs(arguments, 1));
5806 outstandingRequestCount--;
5807 if (outstandingRequestCount === 0) {
5808 while (outstandingRequestCallbacks.length) {
5810 outstandingRequestCallbacks.pop()();
5819 function getHash(url) {
5820 var index = url.indexOf('#');
5821 return index === -1 ? '' : url.substr(index);
5826 * Note: this method is used only by scenario runner
5827 * TODO(vojta): prefix this method with $$ ?
5828 * @param {function()} callback Function that will be called when no outstanding request
5830 self.notifyWhenNoOutstandingRequests = function(callback) {
5831 if (outstandingRequestCount === 0) {
5834 outstandingRequestCallbacks.push(callback);
5838 //////////////////////////////////////////////////////////////
5840 //////////////////////////////////////////////////////////////
5842 var cachedState, lastHistoryState,
5843 lastBrowserUrl = location.href,
5844 baseElement = document.find('base'),
5845 pendingLocation = null;
5848 lastHistoryState = cachedState;
5851 * @name $browser#url
5855 * Without any argument, this method just returns current value of location.href.
5858 * With at least one argument, this method sets url to new value.
5859 * If html5 history api supported, pushState/replaceState is used, otherwise
5860 * location.href/location.replace is used.
5861 * Returns its own instance to allow chaining
5863 * NOTE: this api is intended for use only by the $location service. Please use the
5864 * {@link ng.$location $location service} to change url.
5866 * @param {string} url New url (when used as setter)
5867 * @param {boolean=} replace Should new url replace current history record?
5868 * @param {object=} state object to use with pushState/replaceState
5870 self.url = function(url, replace, state) {
5871 // In modern browsers `history.state` is `null` by default; treating it separately
5872 // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
5873 // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
5874 if (isUndefined(state)) {
5878 // Android Browser BFCache causes location, history reference to become stale.
5879 if (location !== window.location) location = window.location;
5880 if (history !== window.history) history = window.history;
5884 var sameState = lastHistoryState === state;
5886 // Don't change anything if previous and current URLs and states match. This also prevents
5887 // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
5888 // See https://github.com/angular/angular.js/commit/ffb2701
5889 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
5892 var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
5893 lastBrowserUrl = url;
5894 lastHistoryState = state;
5895 // Don't use history API if only the hash changed
5896 // due to a bug in IE10/IE11 which leads
5897 // to not firing a `hashchange` nor `popstate` event
5898 // in some cases (see #9143).
5899 if ($sniffer.history && (!sameBase || !sameState)) {
5900 history[replace ? 'replaceState' : 'pushState'](state, '', url);
5902 // Do the assignment again so that those two variables are referentially identical.
5903 lastHistoryState = cachedState;
5905 if (!sameBase || pendingLocation) {
5906 pendingLocation = url;
5909 location.replace(url);
5910 } else if (!sameBase) {
5911 location.href = url;
5913 location.hash = getHash(url);
5915 if (location.href !== url) {
5916 pendingLocation = url;
5922 // - pendingLocation is needed as browsers don't allow to read out
5923 // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
5924 // https://openradar.appspot.com/22186109).
5925 // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
5926 return pendingLocation || location.href.replace(/%27/g,"'");
5931 * @name $browser#state
5934 * This method is a getter.
5936 * Return history.state or null if history.state is undefined.
5938 * @returns {object} state
5940 self.state = function() {
5944 var urlChangeListeners = [],
5945 urlChangeInit = false;
5947 function cacheStateAndFireUrlChange() {
5948 pendingLocation = null;
5953 function getCurrentState() {
5955 return history.state;
5957 // MSIE can reportedly throw when there is no state (UNCONFIRMED).
5961 // This variable should be used *only* inside the cacheState function.
5962 var lastCachedState = null;
5963 function cacheState() {
5964 // This should be the only place in $browser where `history.state` is read.
5965 cachedState = getCurrentState();
5966 cachedState = isUndefined(cachedState) ? null : cachedState;
5968 // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
5969 if (equals(cachedState, lastCachedState)) {
5970 cachedState = lastCachedState;
5972 lastCachedState = cachedState;
5975 function fireUrlChange() {
5976 if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
5980 lastBrowserUrl = self.url();
5981 lastHistoryState = cachedState;
5982 forEach(urlChangeListeners, function(listener) {
5983 listener(self.url(), cachedState);
5988 * @name $browser#onUrlChange
5991 * Register callback function that will be called, when url changes.
5993 * It's only called when the url is changed from outside of angular:
5994 * - user types different url into address bar
5995 * - user clicks on history (forward/back) button
5996 * - user clicks on a link
5998 * It's not called when url is changed by $browser.url() method
6000 * The listener gets called with new url as parameter.
6002 * NOTE: this api is intended for use only by the $location service. Please use the
6003 * {@link ng.$location $location service} to monitor url changes in angular apps.
6005 * @param {function(string)} listener Listener function to be called when url changes.
6006 * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
6008 self.onUrlChange = function(callback) {
6009 // TODO(vojta): refactor to use node's syntax for events
6010 if (!urlChangeInit) {
6011 // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
6012 // don't fire popstate when user change the address bar and don't fire hashchange when url
6013 // changed by push/replaceState
6015 // html5 history api - popstate event
6016 if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
6018 jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
6020 urlChangeInit = true;
6023 urlChangeListeners.push(callback);
6029 * Remove popstate and hashchange handler from window.
6031 * NOTE: this api is intended for use only by $rootScope.
6033 self.$$applicationDestroyed = function() {
6034 jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
6038 * Checks whether the url has changed outside of Angular.
6039 * Needs to be exported to be able to check for changes that have been done in sync,
6040 * as hashchange/popstate events fire in async.
6042 self.$$checkUrlChange = fireUrlChange;
6044 //////////////////////////////////////////////////////////////
6046 //////////////////////////////////////////////////////////////
6049 * @name $browser#baseHref
6052 * Returns current <base href>
6053 * (always relative - without domain)
6055 * @returns {string} The current base href
6057 self.baseHref = function() {
6058 var href = baseElement.attr('href');
6059 return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
6063 * @name $browser#defer
6064 * @param {function()} fn A function, who's execution should be deferred.
6065 * @param {number=} [delay=0] of milliseconds to defer the function execution.
6066 * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
6069 * Executes a fn asynchronously via `setTimeout(fn, delay)`.
6071 * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
6072 * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
6073 * via `$browser.defer.flush()`.
6076 self.defer = function(fn, delay) {
6078 outstandingRequestCount++;
6079 timeoutId = setTimeout(function() {
6080 delete pendingDeferIds[timeoutId];
6081 completeOutstandingRequest(fn);
6083 pendingDeferIds[timeoutId] = true;
6089 * @name $browser#defer.cancel
6092 * Cancels a deferred task identified with `deferId`.
6094 * @param {*} deferId Token returned by the `$browser.defer` function.
6095 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
6098 self.defer.cancel = function(deferId) {
6099 if (pendingDeferIds[deferId]) {
6100 delete pendingDeferIds[deferId];
6101 clearTimeout(deferId);
6102 completeOutstandingRequest(noop);
6110 function $BrowserProvider() {
6111 this.$get = ['$window', '$log', '$sniffer', '$document',
6112 function($window, $log, $sniffer, $document) {
6113 return new Browser($window, $document, $log, $sniffer);
6119 * @name $cacheFactory
6122 * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
6127 * var cache = $cacheFactory('cacheId');
6128 * expect($cacheFactory.get('cacheId')).toBe(cache);
6129 * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
6131 * cache.put("key", "value");
6132 * cache.put("another key", "another value");
6134 * // We've specified no options on creation
6135 * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
6140 * @param {string} cacheId Name or id of the newly created cache.
6141 * @param {object=} options Options object that specifies the cache behavior. Properties:
6143 * - `{number=}` `capacity` — turns the cache into LRU cache.
6145 * @returns {object} Newly created cache object with the following set of methods:
6147 * - `{object}` `info()` — Returns id, size, and options of cache.
6148 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
6150 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
6151 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
6152 * - `{void}` `removeAll()` — Removes all cached values.
6153 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
6156 <example module="cacheExampleApp">
6157 <file name="index.html">
6158 <div ng-controller="CacheController">
6159 <input ng-model="newCacheKey" placeholder="Key">
6160 <input ng-model="newCacheValue" placeholder="Value">
6161 <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
6163 <p ng-if="keys.length">Cached Values</p>
6164 <div ng-repeat="key in keys">
6165 <span ng-bind="key"></span>
6167 <b ng-bind="cache.get(key)"></b>
6171 <div ng-repeat="(key, value) in cache.info()">
6172 <span ng-bind="key"></span>
6174 <b ng-bind="value"></b>
6178 <file name="script.js">
6179 angular.module('cacheExampleApp', []).
6180 controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
6182 $scope.cache = $cacheFactory('cacheId');
6183 $scope.put = function(key, value) {
6184 if (angular.isUndefined($scope.cache.get(key))) {
6185 $scope.keys.push(key);
6187 $scope.cache.put(key, angular.isUndefined(value) ? null : value);
6191 <file name="style.css">
6198 function $CacheFactoryProvider() {
6200 this.$get = function() {
6203 function cacheFactory(cacheId, options) {
6204 if (cacheId in caches) {
6205 throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
6209 stats = extend({}, options, {id: cacheId}),
6211 capacity = (options && options.capacity) || Number.MAX_VALUE,
6212 lruHash = createMap(),
6218 * @name $cacheFactory.Cache
6221 * A cache object used to store and retrieve data, primarily used by
6222 * {@link $http $http} and the {@link ng.directive:script script} directive to cache
6223 * templates and other data.
6226 * angular.module('superCache')
6227 * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
6228 * return $cacheFactory('super-cache');
6235 * it('should behave like a cache', inject(function(superCache) {
6236 * superCache.put('key', 'value');
6237 * superCache.put('another key', 'another value');
6239 * expect(superCache.info()).toEqual({
6240 * id: 'super-cache',
6244 * superCache.remove('another key');
6245 * expect(superCache.get('another key')).toBeUndefined();
6247 * superCache.removeAll();
6248 * expect(superCache.info()).toEqual({
6249 * id: 'super-cache',
6255 return caches[cacheId] = {
6259 * @name $cacheFactory.Cache#put
6263 * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
6264 * retrieved later, and incrementing the size of the cache if the key was not already
6265 * present in the cache. If behaving like an LRU cache, it will also remove stale
6266 * entries from the set.
6268 * It will not insert undefined values into the cache.
6270 * @param {string} key the key under which the cached data is stored.
6271 * @param {*} value the value to store alongside the key. If it is undefined, the key
6272 * will not be stored.
6273 * @returns {*} the value stored.
6275 put: function(key, value) {
6276 if (isUndefined(value)) return;
6277 if (capacity < Number.MAX_VALUE) {
6278 var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
6283 if (!(key in data)) size++;
6286 if (size > capacity) {
6287 this.remove(staleEnd.key);
6295 * @name $cacheFactory.Cache#get
6299 * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
6301 * @param {string} key the key of the data to be retrieved
6302 * @returns {*} the value stored.
6304 get: function(key) {
6305 if (capacity < Number.MAX_VALUE) {
6306 var lruEntry = lruHash[key];
6308 if (!lruEntry) return;
6319 * @name $cacheFactory.Cache#remove
6323 * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
6325 * @param {string} key the key of the entry to be removed
6327 remove: function(key) {
6328 if (capacity < Number.MAX_VALUE) {
6329 var lruEntry = lruHash[key];
6331 if (!lruEntry) return;
6333 if (lruEntry == freshEnd) freshEnd = lruEntry.p;
6334 if (lruEntry == staleEnd) staleEnd = lruEntry.n;
6335 link(lruEntry.n,lruEntry.p);
6337 delete lruHash[key];
6340 if (!(key in data)) return;
6349 * @name $cacheFactory.Cache#removeAll
6353 * Clears the cache object of any entries.
6355 removeAll: function() {
6358 lruHash = createMap();
6359 freshEnd = staleEnd = null;
6365 * @name $cacheFactory.Cache#destroy
6369 * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
6370 * removing it from the {@link $cacheFactory $cacheFactory} set.
6372 destroy: function() {
6376 delete caches[cacheId];
6382 * @name $cacheFactory.Cache#info
6386 * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
6388 * @returns {object} an object with the following properties:
6390 * <li>**id**: the id of the cache instance</li>
6391 * <li>**size**: the number of entries kept in the cache instance</li>
6392 * <li>**...**: any additional properties from the options object when creating the
6397 return extend({}, stats, {size: size});
6403 * makes the `entry` the freshEnd of the LRU linked list
6405 function refresh(entry) {
6406 if (entry != freshEnd) {
6409 } else if (staleEnd == entry) {
6413 link(entry.n, entry.p);
6414 link(entry, freshEnd);
6422 * bidirectionally links two entries of the LRU linked list
6424 function link(nextEntry, prevEntry) {
6425 if (nextEntry != prevEntry) {
6426 if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
6427 if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
6435 * @name $cacheFactory#info
6438 * Get information about all the caches that have been created
6440 * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
6442 cacheFactory.info = function() {
6444 forEach(caches, function(cache, cacheId) {
6445 info[cacheId] = cache.info();
6453 * @name $cacheFactory#get
6456 * Get access to a cache object by the `cacheId` used when it was created.
6458 * @param {string} cacheId Name or id of a cache to access.
6459 * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
6461 cacheFactory.get = function(cacheId) {
6462 return caches[cacheId];
6466 return cacheFactory;
6472 * @name $templateCache
6475 * The first time a template is used, it is loaded in the template cache for quick retrieval. You
6476 * can load templates directly into the cache in a `script` tag, or by consuming the
6477 * `$templateCache` service directly.
6479 * Adding via the `script` tag:
6482 * <script type="text/ng-template" id="templateId.html">
6483 * <p>This is the content of the template</p>
6487 * **Note:** the `script` tag containing the template does not need to be included in the `head` of
6488 * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
6489 * element with ng-app attribute), otherwise the template will be ignored.
6491 * Adding via the `$templateCache` service:
6494 * var myApp = angular.module('myApp', []);
6495 * myApp.run(function($templateCache) {
6496 * $templateCache.put('templateId.html', 'This is the content of the template');
6500 * To retrieve the template later, simply use it in your HTML:
6502 * <div ng-include=" 'templateId.html' "></div>
6505 * or get it via Javascript:
6507 * $templateCache.get('templateId.html')
6510 * See {@link ng.$cacheFactory $cacheFactory}.
6513 function $TemplateCacheProvider() {
6514 this.$get = ['$cacheFactory', function($cacheFactory) {
6515 return $cacheFactory('templates');
6519 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
6520 * Any commits to this file should be reviewed with security in mind. *
6521 * Changes to this file can potentially create security vulnerabilities. *
6522 * An approval from 2 Core members with history of modifying *
6523 * this file is required. *
6525 * Does the change somehow allow for arbitrary javascript to be executed? *
6526 * Or allows for someone to change the prototype of built-in objects? *
6527 * Or gives undesired access to variables likes document or window? *
6528 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
6530 /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
6532 * DOM-related variables:
6534 * - "node" - DOM Node
6535 * - "element" - DOM Element or Node
6536 * - "$node" or "$element" - jqLite-wrapped node or element
6539 * Compiler related stuff:
6541 * - "linkFn" - linking fn of a single directive
6542 * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
6543 * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
6544 * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
6554 * Compiles an HTML string or DOM into a template and produces a template function, which
6555 * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
6557 * The compilation is a process of walking the DOM tree and matching DOM elements to
6558 * {@link ng.$compileProvider#directive directives}.
6560 * <div class="alert alert-warning">
6561 * **Note:** This document is an in-depth reference of all directive options.
6562 * For a gentle introduction to directives with examples of common use cases,
6563 * see the {@link guide/directive directive guide}.
6566 * ## Comprehensive Directive API
6568 * There are many different options for a directive.
6570 * The difference resides in the return value of the factory function.
6571 * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
6572 * or just the `postLink` function (all other properties will have the default values).
6574 * <div class="alert alert-success">
6575 * **Best Practice:** It's recommended to use the "directive definition object" form.
6578 * Here's an example directive declared with a Directive Definition Object:
6581 * var myModule = angular.module(...);
6583 * myModule.directive('directiveName', function factory(injectables) {
6584 * var directiveDefinitionObject = {
6586 * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
6588 * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
6589 * transclude: false,
6591 * templateNamespace: 'html',
6593 * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
6594 * controllerAs: 'stringIdentifier',
6595 * bindToController: false,
6596 * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
6597 * compile: function compile(tElement, tAttrs, transclude) {
6599 * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
6600 * post: function postLink(scope, iElement, iAttrs, controller) { ... }
6603 * // return function postLink( ... ) { ... }
6607 * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
6608 * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
6611 * // link: function postLink( ... ) { ... }
6613 * return directiveDefinitionObject;
6617 * <div class="alert alert-warning">
6618 * **Note:** Any unspecified options will use the default value. You can see the default values below.
6621 * Therefore the above can be simplified as:
6624 * var myModule = angular.module(...);
6626 * myModule.directive('directiveName', function factory(injectables) {
6627 * var directiveDefinitionObject = {
6628 * link: function postLink(scope, iElement, iAttrs) { ... }
6630 * return directiveDefinitionObject;
6632 * // return function postLink(scope, iElement, iAttrs) { ... }
6638 * ### Directive Definition Object
6640 * The directive definition object provides instructions to the {@link ng.$compile
6641 * compiler}. The attributes are:
6643 * #### `multiElement`
6644 * When this property is set to true, the HTML compiler will collect DOM nodes between
6645 * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
6646 * together as the directive elements. It is recommended that this feature be used on directives
6647 * which are not strictly behavioral (such as {@link ngClick}), and which
6648 * do not manipulate or replace child nodes (such as {@link ngInclude}).
6651 * When there are multiple directives defined on a single DOM element, sometimes it
6652 * is necessary to specify the order in which the directives are applied. The `priority` is used
6653 * to sort the directives before their `compile` functions get called. Priority is defined as a
6654 * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
6655 * are also run in priority order, but post-link functions are run in reverse order. The order
6656 * of directives with the same priority is undefined. The default priority is `0`.
6659 * If set to true then the current `priority` will be the last set of directives
6660 * which will execute (any directives at the current priority will still execute
6661 * as the order of execution on same `priority` is undefined). Note that expressions
6662 * and other directives used in the directive's template will also be excluded from execution.
6665 * The scope property can be `true`, an object or a falsy value:
6667 * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
6669 * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
6670 * the directive's element. If multiple directives on the same element request a new scope,
6671 * only one new scope is created. The new scope rule does not apply for the root of the template
6672 * since the root of the template always gets a new scope.
6674 * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
6675 * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
6676 * scope. This is useful when creating reusable components, which should not accidentally read or modify
6677 * data in the parent scope.
6679 * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
6680 * directive's element. These local properties are useful for aliasing values for templates. The keys in
6681 * the object hash map to the name of the property on the isolate scope; the values define how the property
6682 * is bound to the parent scope, via matching attributes on the directive's element:
6684 * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
6685 * always a string since DOM attributes are strings. If no `attr` name is specified then the
6686 * attribute name is assumed to be the same as the local name. Given `<my-component
6687 * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
6688 * the directive's scope property `localName` will reflect the interpolated value of `hello
6689 * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
6690 * scope. The `name` is read from the parent scope (not the directive's scope).
6692 * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
6693 * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
6694 * If no `attr` name is specified then the attribute name is assumed to be the same as the local
6695 * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
6696 * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
6697 * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
6698 * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
6699 * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
6700 * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
6701 * will be thrown upon discovering changes to the local value, since it will be impossible to sync
6702 * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
6703 * method is used for tracking changes, and the equality check is based on object identity.
6704 * However, if an object literal or an array literal is passed as the binding expression, the
6705 * equality check is done by value (using the {@link angular.equals} function). It's also possible
6706 * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
6707 * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
6709 * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
6710 * expression passed via the attribute `attr`. The expression is evaluated in the context of the
6711 * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
6712 * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
6714 * For example, given `<my-component my-attr="parentModel">` and directive definition of
6715 * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
6716 * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
6717 * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
6719 * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
6720 * sets the same value. That means if your bound value is an object, changes to its properties
6721 * in the isolated scope will be reflected in the parent scope (because both reference the same object).
6722 * 2. one-way binding watches changes to the **identity** of the parent value. That means the
6723 * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
6724 * to the value has changed. In most cases, this should not be of concern, but can be important
6725 * to know if you one-way bind to an object, and then replace that object in the isolated scope.
6726 * If you now change a property of the object in your parent scope, the change will not be
6727 * propagated to the isolated scope, because the identity of the object on the parent scope
6728 * has not changed. Instead you must assign a new object.
6730 * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
6731 * back to the parent. However, it does not make this completely impossible.
6733 * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
6734 * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
6735 * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
6736 * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
6737 * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
6738 * via an expression to the parent scope. This can be done by passing a map of local variable names
6739 * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
6740 * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
6742 * In general it's possible to apply more than one directive to one element, but there might be limitations
6743 * depending on the type of scope required by the directives. The following points will help explain these limitations.
6744 * For simplicity only two directives are taken into account, but it is also applicable for several directives:
6746 * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
6747 * * **child scope** + **no scope** => Both directives will share one single child scope
6748 * * **child scope** + **child scope** => Both directives will share one single child scope
6749 * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
6750 * its parent's scope
6751 * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
6752 * be applied to the same element.
6753 * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
6754 * cannot be applied to the same element.
6757 * #### `bindToController`
6758 * This property is used to bind scope properties directly to the controller. It can be either
6759 * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
6760 * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
6761 * definition: `controller: 'myCtrl as myAlias'`.
6763 * When an isolate scope is used for a directive (see above), `bindToController: true` will
6764 * allow a component to have its properties bound to the controller, rather than to scope.
6766 * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
6767 * properties. You can access these bindings once they have been initialized by providing a controller method called
6768 * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
6771 * <div class="alert alert-warning">
6772 * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
6773 * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
6774 * code that relies upon bindings inside a `$onInit` method on the controller, instead.
6777 * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
6778 * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
6779 * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
6780 * scope (useful for component directives).
6782 * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
6786 * Controller constructor function. The controller is instantiated before the
6787 * pre-linking phase and can be accessed by other directives (see
6788 * `require` attribute). This allows the directives to communicate with each other and augment
6789 * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
6791 * * `$scope` - Current scope associated with the element
6792 * * `$element` - Current element
6793 * * `$attrs` - Current attributes object for the element
6794 * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
6795 * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
6796 * * `scope`: (optional) override the scope.
6797 * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
6798 * * `futureParentElement` (optional):
6799 * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
6800 * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
6801 * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
6802 * and when the `cloneLinkinFn` is passed,
6803 * as those elements need to created and cloned in a special way when they are defined outside their
6804 * usual containers (e.g. like `<svg>`).
6805 * * See also the `directive.templateNamespace` property.
6806 * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
6807 * then the default translusion is provided.
6808 * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
6809 * `true` if the specified slot contains content (i.e. one or more DOM nodes).
6811 * The controller can provide the following methods that act as life-cycle hooks:
6812 * * `$onInit` - Called on each controller after all the controllers on an element have been constructed and
6813 * had their bindings initialized (and before the pre & post linking functions for the directives on
6814 * this element). This is a good place to put initialization code for your controller.
6817 * Require another directive and inject its controller as the fourth argument to the linking function. The
6818 * `require` property can be a string, an array or an object:
6819 * * a **string** containing the name of the directive to pass to the linking function
6820 * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
6821 * linking function will be an array of controllers in the same order as the names in the `require` property
6822 * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
6823 * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
6826 * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
6827 * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
6828 * have been constructed but before `$onInit` is called.
6829 * See the {@link $compileProvider#component} helper for an example of how this can be used.
6831 * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
6832 * raised (unless no link function is specified and the required controllers are not being bound to the directive
6833 * controller, in which case error checking is skipped). The name can be prefixed with:
6835 * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
6836 * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
6837 * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
6838 * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
6839 * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
6840 * `null` to the `link` fn if not found.
6841 * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
6842 * `null` to the `link` fn if not found.
6845 * #### `controllerAs`
6846 * Identifier name for a reference to the controller in the directive's scope.
6847 * This allows the controller to be referenced from the directive template. This is especially
6848 * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
6849 * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
6850 * `controllerAs` reference might overwrite a property that already exists on the parent scope.
6854 * String of subset of `EACM` which restricts the directive to a specific directive
6855 * declaration style. If omitted, the defaults (elements and attributes) are used.
6857 * * `E` - Element name (default): `<my-directive></my-directive>`
6858 * * `A` - Attribute (default): `<div my-directive="exp"></div>`
6859 * * `C` - Class: `<div class="my-directive: exp;"></div>`
6860 * * `M` - Comment: `<!-- directive: my-directive exp -->`
6863 * #### `templateNamespace`
6864 * String representing the document type used by the markup in the template.
6865 * AngularJS needs this information as those elements need to be created and cloned
6866 * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
6868 * * `html` - All root nodes in the template are HTML. Root nodes may also be
6869 * top-level elements such as `<svg>` or `<math>`.
6870 * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
6871 * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
6873 * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
6876 * HTML markup that may:
6877 * * Replace the contents of the directive's element (default).
6878 * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
6879 * * Wrap the contents of the directive's element (if `transclude` is true).
6883 * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
6884 * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
6885 * function api below) and returns a string value.
6888 * #### `templateUrl`
6889 * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
6891 * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
6892 * for later when the template has been resolved. In the meantime it will continue to compile and link
6893 * sibling and parent elements as though this element had not contained any directives.
6895 * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
6896 * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
6897 * case when only one deeply nested directive has `templateUrl`.
6899 * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
6901 * You can specify `templateUrl` as a string representing the URL or as a function which takes two
6902 * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
6903 * a string value representing the url. In either case, the template URL is passed through {@link
6904 * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
6907 * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
6908 * specify what the template should replace. Defaults to `false`.
6910 * * `true` - the template will replace the directive's element.
6911 * * `false` - the template will replace the contents of the directive's element.
6913 * The replacement process migrates all of the attributes / classes from the old element to the new
6914 * one. See the {@link guide/directive#template-expanding-directive
6915 * Directives Guide} for an example.
6917 * There are very few scenarios where element replacement is required for the application function,
6918 * the main one being reusable custom components that are used within SVG contexts
6919 * (because SVG doesn't work with custom elements in the DOM tree).
6922 * Extract the contents of the element where the directive appears and make it available to the directive.
6923 * The contents are compiled and provided to the directive as a **transclusion function**. See the
6924 * {@link $compile#transclusion Transclusion} section below.
6930 * function compile(tElement, tAttrs, transclude) { ... }
6933 * The compile function deals with transforming the template DOM. Since most directives do not do
6934 * template transformation, it is not used often. The compile function takes the following arguments:
6936 * * `tElement` - template element - The element where the directive has been declared. It is
6937 * safe to do template transformation on the element and child elements only.
6939 * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
6940 * between all directive compile functions.
6942 * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
6944 * <div class="alert alert-warning">
6945 * **Note:** The template instance and the link instance may be different objects if the template has
6946 * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
6947 * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
6948 * should be done in a linking function rather than in a compile function.
6951 * <div class="alert alert-warning">
6952 * **Note:** The compile function cannot handle directives that recursively use themselves in their
6953 * own templates or compile functions. Compiling these directives results in an infinite loop and
6954 * stack overflow errors.
6956 * This can be avoided by manually using $compile in the postLink function to imperatively compile
6957 * a directive's template instead of relying on automatic template compilation via `template` or
6958 * `templateUrl` declaration or manual compilation inside the compile function.
6961 * <div class="alert alert-danger">
6962 * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
6963 * e.g. does not know about the right outer scope. Please use the transclude function that is passed
6964 * to the link function instead.
6967 * A compile function can have a return value which can be either a function or an object.
6969 * * returning a (post-link) function - is equivalent to registering the linking function via the
6970 * `link` property of the config object when the compile function is empty.
6972 * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
6973 * control when a linking function should be called during the linking phase. See info about
6974 * pre-linking and post-linking functions below.
6978 * This property is used only if the `compile` property is not defined.
6981 * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
6984 * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
6985 * executed after the template has been cloned. This is where most of the directive logic will be
6988 * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
6989 * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
6991 * * `iElement` - instance element - The element where the directive is to be used. It is safe to
6992 * manipulate the children of the element only in `postLink` function since the children have
6993 * already been linked.
6995 * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
6996 * between all directive linking functions.
6998 * * `controller` - the directive's required controller instance(s) - Instances are shared
6999 * among all directives, which allows the directives to use the controllers as a communication
7000 * channel. The exact value depends on the directive's `require` property:
7001 * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
7002 * * `string`: the controller instance
7003 * * `array`: array of controller instances
7005 * If a required controller cannot be found, and it is optional, the instance is `null`,
7006 * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
7008 * Note that you can also require the directive's own controller - it will be made available like
7009 * any other controller.
7011 * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
7012 * This is the same as the `$transclude`
7013 * parameter of directive controllers, see there for details.
7014 * `function([scope], cloneLinkingFn, futureParentElement)`.
7016 * #### Pre-linking function
7018 * Executed before the child elements are linked. Not safe to do DOM transformation since the
7019 * compiler linking function will fail to locate the correct elements for linking.
7021 * #### Post-linking function
7023 * Executed after the child elements are linked.
7025 * Note that child elements that contain `templateUrl` directives will not have been compiled
7026 * and linked since they are waiting for their template to load asynchronously and their own
7027 * compilation and linking has been suspended until that occurs.
7029 * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
7030 * for their async templates to be resolved.
7035 * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
7036 * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
7037 * scope from where they were taken.
7039 * Transclusion is used (often with {@link ngTransclude}) to insert the
7040 * original contents of a directive's element into a specified place in the template of the directive.
7041 * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
7042 * content has access to the properties on the scope from which it was taken, even if the directive
7043 * has isolated scope.
7044 * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
7046 * This makes it possible for the widget to have private state for its template, while the transcluded
7047 * content has access to its originating scope.
7049 * <div class="alert alert-warning">
7050 * **Note:** When testing an element transclude directive you must not place the directive at the root of the
7051 * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
7052 * Testing Transclusion Directives}.
7055 * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
7056 * directive's element, the entire element or multiple parts of the element contents:
7058 * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
7059 * * `'element'` - transclude the whole of the directive's element including any directives on this
7060 * element that defined at a lower priority than this directive. When used, the `template`
7061 * property is ignored.
7062 * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
7064 * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
7066 * This object is a map where the keys are the name of the slot to fill and the value is an element selector
7067 * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
7068 * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
7070 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
7072 * If the element selector is prefixed with a `?` then that slot is optional.
7074 * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
7075 * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
7077 * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
7078 * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
7079 * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
7080 * injectable into the directive's controller.
7083 * #### Transclusion Functions
7085 * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
7086 * function** to the directive's `link` function and `controller`. This transclusion function is a special
7087 * **linking function** that will return the compiled contents linked to a new transclusion scope.
7089 * <div class="alert alert-info">
7090 * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
7091 * ngTransclude will deal with it for us.
7094 * If you want to manually control the insertion and removal of the transcluded content in your directive
7095 * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
7096 * object that contains the compiled DOM, which is linked to the correct transclusion scope.
7098 * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
7099 * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
7100 * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
7102 * <div class="alert alert-info">
7103 * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
7104 * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
7107 * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
7108 * attach function**:
7111 * var transcludedContent, transclusionScope;
7113 * $transclude(function(clone, scope) {
7114 * element.append(clone);
7115 * transcludedContent = clone;
7116 * transclusionScope = scope;
7120 * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
7121 * associated transclusion scope:
7124 * transcludedContent.remove();
7125 * transclusionScope.$destroy();
7128 * <div class="alert alert-info">
7129 * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
7130 * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
7131 * then you are also responsible for calling `$destroy` on the transclusion scope.
7134 * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
7135 * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
7136 * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
7139 * #### Transclusion Scopes
7141 * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
7142 * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
7143 * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
7146 * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
7152 * <div transclusion>
7158 * The `$parent` scope hierarchy will look like this:
7166 * but the scopes will inherit prototypically from different scopes to their `$parent`.
7177 * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
7178 * `link()` or `compile()` functions. It has a variety of uses.
7180 * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
7181 * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
7182 * to the attributes.
7184 * * *Directive inter-communication:* All directives share the same instance of the attributes
7185 * object which allows the directives to use the attributes object as inter directive
7188 * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
7189 * allowing other directives to read the interpolated value.
7191 * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
7192 * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
7193 * the only way to easily get the actual value because during the linking phase the interpolation
7194 * hasn't been evaluated yet and so the value is at this time set to `undefined`.
7197 * function linkingFn(scope, elm, attrs, ctrl) {
7198 * // get the attribute value
7199 * console.log(attrs.ngModel);
7201 * // change the attribute
7202 * attrs.$set('ngModel', 'new value');
7204 * // observe changes to interpolated attribute
7205 * attrs.$observe('ngModel', function(value) {
7206 * console.log('ngModel has changed value to ' + value);
7213 * <div class="alert alert-warning">
7214 * **Note**: Typically directives are registered with `module.directive`. The example below is
7215 * to illustrate how `$compile` works.
7218 <example module="compileExample">
7219 <file name="index.html">
7221 angular.module('compileExample', [], function($compileProvider) {
7222 // configure new 'compile' directive by passing a directive
7223 // factory function. The factory function injects the '$compile'
7224 $compileProvider.directive('compile', function($compile) {
7225 // directive factory creates a link function
7226 return function(scope, element, attrs) {
7229 // watch the 'compile' expression for changes
7230 return scope.$eval(attrs.compile);
7233 // when the 'compile' expression changes
7234 // assign it into the current DOM
7235 element.html(value);
7237 // compile the new DOM and link it to the current
7239 // NOTE: we only compile .childNodes so that
7240 // we don't get into infinite loop compiling ourselves
7241 $compile(element.contents())(scope);
7247 .controller('GreeterController', ['$scope', function($scope) {
7248 $scope.name = 'Angular';
7249 $scope.html = 'Hello {{name}}';
7252 <div ng-controller="GreeterController">
7253 <input ng-model="name"> <br/>
7254 <textarea ng-model="html"></textarea> <br/>
7255 <div compile="html"></div>
7258 <file name="protractor.js" type="protractor">
7259 it('should auto compile', function() {
7260 var textarea = $('textarea');
7261 var output = $('div[compile]');
7262 // The initial state reads 'Hello Angular'.
7263 expect(output.getText()).toBe('Hello Angular');
7265 textarea.sendKeys('{{name}}!');
7266 expect(output.getText()).toBe('Angular!');
7273 * @param {string|DOMElement} element Element or HTML string to compile into a template function.
7274 * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
7276 * <div class="alert alert-danger">
7277 * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
7278 * e.g. will not use the right outer scope. Please pass the transclude function as a
7279 * `parentBoundTranscludeFn` to the link function instead.
7282 * @param {number} maxPriority only apply directives lower than given priority (Only effects the
7283 * root element(s), not their children)
7284 * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
7285 * (a DOM element/tree) to a scope. Where:
7287 * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
7288 * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
7289 * `template` and call the `cloneAttachFn` function allowing the caller to attach the
7290 * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
7291 * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
7293 * * `clonedElement` - is a clone of the original `element` passed into the compiler.
7294 * * `scope` - is the current scope with which the linking function is working with.
7296 * * `options` - An optional object hash with linking options. If `options` is provided, then the following
7297 * keys may be used to control linking behavior:
7299 * * `parentBoundTranscludeFn` - the transclude function made available to
7300 * directives; if given, it will be passed through to the link functions of
7301 * directives found in `element` during compilation.
7302 * * `transcludeControllers` - an object hash with keys that map controller names
7303 * to a hash with the key `instance`, which maps to the controller instance;
7304 * if given, it will make the controllers available to directives on the compileNode:
7308 * instance: parentControllerInstance
7312 * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
7313 * the cloned elements; only needed for transcludes that are allowed to contain non html
7314 * elements (e.g. SVG elements). See also the directive.controller property.
7316 * Calling the linking function returns the element of the template. It is either the original
7317 * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
7319 * After linking the view is not updated until after a call to $digest which typically is done by
7320 * Angular automatically.
7322 * If you need access to the bound view, there are two ways to do it:
7324 * - If you are not asking the linking function to clone the template, create the DOM element(s)
7325 * before you send them to the compiler and keep this reference around.
7327 * var element = $compile('<p>{{total}}</p>')(scope);
7330 * - if on the other hand, you need the element to be cloned, the view reference from the original
7331 * example would not point to the clone, but rather to the original template that was cloned. In
7332 * this case, you can access the clone via the cloneAttachFn:
7334 * var templateElement = angular.element('<p>{{total}}</p>'),
7337 * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
7338 * //attach the clone to DOM document at the right place
7341 * //now we have reference to the cloned DOM via `clonedElement`
7345 * For information on how the compiler works, see the
7346 * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
7349 var $compileMinErr = minErr('$compile');
7353 * @name $compileProvider
7357 $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
7358 function $CompileProvider($provide, $$sanitizeUriProvider) {
7359 var hasDirectives = {},
7360 Suffix = 'Directive',
7361 COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
7362 CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
7363 ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
7364 REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
7366 // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
7367 // The assumption is that future DOM event attribute names will begin with
7368 // 'on' and be composed of only English letters.
7369 var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
7371 function parseIsolateBindings(scope, directiveName, isController) {
7372 var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
7376 forEach(scope, function(definition, scopeName) {
7377 var match = definition.match(LOCAL_REGEXP);
7380 throw $compileMinErr('iscp',
7381 "Invalid {3} for directive '{0}'." +
7382 " Definition: {... {1}: '{2}' ...}",
7383 directiveName, scopeName, definition,
7384 (isController ? "controller bindings definition" :
7385 "isolate scope definition"));
7388 bindings[scopeName] = {
7390 collection: match[2] === '*',
7391 optional: match[3] === '?',
7392 attrName: match[4] || scopeName
7399 function parseDirectiveBindings(directive, directiveName) {
7402 bindToController: null
7404 if (isObject(directive.scope)) {
7405 if (directive.bindToController === true) {
7406 bindings.bindToController = parseIsolateBindings(directive.scope,
7407 directiveName, true);
7408 bindings.isolateScope = {};
7410 bindings.isolateScope = parseIsolateBindings(directive.scope,
7411 directiveName, false);
7414 if (isObject(directive.bindToController)) {
7415 bindings.bindToController =
7416 parseIsolateBindings(directive.bindToController, directiveName, true);
7418 if (isObject(bindings.bindToController)) {
7419 var controller = directive.controller;
7420 var controllerAs = directive.controllerAs;
7422 // There is no controller, there may or may not be a controllerAs property
7423 throw $compileMinErr('noctrl',
7424 "Cannot bind to controller without directive '{0}'s controller.",
7426 } else if (!identifierForController(controller, controllerAs)) {
7427 // There is a controller, but no identifier or controllerAs property
7428 throw $compileMinErr('noident',
7429 "Cannot bind to controller without identifier for directive '{0}'.",
7436 function assertValidDirectiveName(name) {
7437 var letter = name.charAt(0);
7438 if (!letter || letter !== lowercase(letter)) {
7439 throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
7441 if (name !== name.trim()) {
7442 throw $compileMinErr('baddir',
7443 "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
7450 * @name $compileProvider#directive
7454 * Register a new directive with the compiler.
7456 * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
7457 * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
7458 * names and the values are the factories.
7459 * @param {Function|Array} directiveFactory An injectable directive factory function. See the
7460 * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
7461 * @returns {ng.$compileProvider} Self for chaining.
7463 this.directive = function registerDirective(name, directiveFactory) {
7464 assertNotHasOwnProperty(name, 'directive');
7465 if (isString(name)) {
7466 assertValidDirectiveName(name);
7467 assertArg(directiveFactory, 'directiveFactory');
7468 if (!hasDirectives.hasOwnProperty(name)) {
7469 hasDirectives[name] = [];
7470 $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
7471 function($injector, $exceptionHandler) {
7472 var directives = [];
7473 forEach(hasDirectives[name], function(directiveFactory, index) {
7475 var directive = $injector.invoke(directiveFactory);
7476 if (isFunction(directive)) {
7477 directive = { compile: valueFn(directive) };
7478 } else if (!directive.compile && directive.link) {
7479 directive.compile = valueFn(directive.link);
7481 directive.priority = directive.priority || 0;
7482 directive.index = index;
7483 directive.name = directive.name || name;
7484 directive.require = directive.require || (directive.controller && directive.name);
7485 directive.restrict = directive.restrict || 'EA';
7486 var bindings = directive.$$bindings =
7487 parseDirectiveBindings(directive, directive.name);
7488 if (isObject(bindings.isolateScope)) {
7489 directive.$$isolateBindings = bindings.isolateScope;
7491 directive.$$moduleName = directiveFactory.$$moduleName;
7492 directives.push(directive);
7494 $exceptionHandler(e);
7500 hasDirectives[name].push(directiveFactory);
7502 forEach(name, reverseParams(registerDirective));
7509 * @name $compileProvider#component
7511 * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
7512 * @param {Object} options Component definition object (a simplified
7513 * {@link ng.$compile#directive-definition-object directive definition object}),
7514 * with the following properties (all optional):
7516 * - `controller` – `{(string|function()=}` – controller constructor function that should be
7517 * associated with newly created scope or the name of a {@link ng.$compile#-controller-
7518 * registered controller} if passed as a string. An empty `noop` function by default.
7519 * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
7520 * If present, the controller will be published to scope under the `controllerAs` name.
7521 * If not present, this will default to be `$ctrl`.
7522 * - `template` – `{string=|function()=}` – html template as a string or a function that
7523 * returns an html template as a string which should be used as the contents of this component.
7524 * Empty string by default.
7526 * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
7527 * the following locals:
7529 * - `$element` - Current element
7530 * - `$attrs` - Current attributes object for the element
7532 * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
7533 * template that should be used as the contents of this component.
7535 * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
7536 * the following locals:
7538 * - `$element` - Current element
7539 * - `$attrs` - Current attributes object for the element
7541 * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
7542 * Component properties are always bound to the component controller and not to the scope.
7543 * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
7544 * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
7545 * Disabled by default.
7546 * - `$...` – `{function()=}` – additional annotations to provide to the directive factory function.
7548 * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
7550 * Register a **component definition** with the compiler. This is a shorthand for registering a special
7551 * type of directive, which represents a self-contained UI component in your application. Such components
7552 * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
7554 * Component definitions are very simple and do not require as much configuration as defining general
7555 * directives. Component definitions usually consist only of a template and a controller backing it.
7557 * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
7558 * `bindToController`. They always have **isolate scope** and are restricted to elements.
7560 * Here are a few examples of how you would usually define components:
7563 * var myMod = angular.module(...);
7564 * myMod.component('myComp', {
7565 * template: '<div>My name is {{$ctrl.name}}</div>',
7566 * controller: function() {
7567 * this.name = 'shahar';
7571 * myMod.component('myComp', {
7572 * template: '<div>My name is {{$ctrl.name}}</div>',
7573 * bindings: {name: '@'}
7576 * myMod.component('myComp', {
7577 * templateUrl: 'views/my-comp.html',
7578 * controller: 'MyCtrl as ctrl',
7579 * bindings: {name: '@'}
7583 * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
7586 * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
7588 this.component = function registerComponent(name, options) {
7589 var controller = options.controller || function() {};
7591 function factory($injector) {
7592 function makeInjectable(fn) {
7593 if (isFunction(fn) || isArray(fn)) {
7594 return function(tElement, tAttrs) {
7595 return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
7602 var template = (!options.template && !options.templateUrl ? '' : options.template);
7604 controller: controller,
7605 controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
7606 template: makeInjectable(template),
7607 templateUrl: makeInjectable(options.templateUrl),
7608 transclude: options.transclude,
7610 bindToController: options.bindings || {},
7612 require: options.require
7616 // Copy any annotation properties (starting with $) over to the factory function
7617 // These could be used by libraries such as the new component router
7618 forEach(options, function(val, key) {
7619 if (key.charAt(0) === '$') {
7624 factory.$inject = ['$injector'];
7626 return this.directive(name, factory);
7632 * @name $compileProvider#aHrefSanitizationWhitelist
7636 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
7637 * urls during a[href] sanitization.
7639 * The sanitization is a security measure aimed at preventing XSS attacks via html links.
7641 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
7642 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
7643 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
7644 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
7646 * @param {RegExp=} regexp New regexp to whitelist urls with.
7647 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
7648 * chaining otherwise.
7650 this.aHrefSanitizationWhitelist = function(regexp) {
7651 if (isDefined(regexp)) {
7652 $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
7655 return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
7662 * @name $compileProvider#imgSrcSanitizationWhitelist
7666 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
7667 * urls during img[src] sanitization.
7669 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
7671 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
7672 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
7673 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
7674 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
7676 * @param {RegExp=} regexp New regexp to whitelist urls with.
7677 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
7678 * chaining otherwise.
7680 this.imgSrcSanitizationWhitelist = function(regexp) {
7681 if (isDefined(regexp)) {
7682 $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
7685 return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
7691 * @name $compileProvider#debugInfoEnabled
7693 * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
7694 * current debugInfoEnabled state
7695 * @returns {*} current value if used as getter or itself (chaining) if used as setter
7700 * Call this method to enable/disable various debug runtime information in the compiler such as adding
7701 * binding information and a reference to the current scope on to DOM elements.
7702 * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
7703 * * `ng-binding` CSS class
7704 * * `$binding` data property containing an array of the binding expressions
7706 * You may want to disable this in production for a significant performance boost. See
7707 * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
7709 * The default value is true.
7711 var debugInfoEnabled = true;
7712 this.debugInfoEnabled = function(enabled) {
7713 if (isDefined(enabled)) {
7714 debugInfoEnabled = enabled;
7717 return debugInfoEnabled;
7721 '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
7722 '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
7723 function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
7724 $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
7726 var SIMPLE_ATTR_NAME = /^\w/;
7727 var specialAttrHolder = document.createElement('div');
7728 var Attributes = function(element, attributesToCopy) {
7729 if (attributesToCopy) {
7730 var keys = Object.keys(attributesToCopy);
7733 for (i = 0, l = keys.length; i < l; i++) {
7735 this[key] = attributesToCopy[key];
7741 this.$$element = element;
7744 Attributes.prototype = {
7747 * @name $compile.directive.Attributes#$normalize
7751 * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
7752 * `data-`) to its normalized, camelCase form.
7754 * Also there is special case for Moz prefix starting with upper case letter.
7756 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
7758 * @param {string} name Name to normalize
7760 $normalize: directiveNormalize,
7765 * @name $compile.directive.Attributes#$addClass
7769 * Adds the CSS class value specified by the classVal parameter to the element. If animations
7770 * are enabled then an animation will be triggered for the class addition.
7772 * @param {string} classVal The className value that will be added to the element
7774 $addClass: function(classVal) {
7775 if (classVal && classVal.length > 0) {
7776 $animate.addClass(this.$$element, classVal);
7782 * @name $compile.directive.Attributes#$removeClass
7786 * Removes the CSS class value specified by the classVal parameter from the element. If
7787 * animations are enabled then an animation will be triggered for the class removal.
7789 * @param {string} classVal The className value that will be removed from the element
7791 $removeClass: function(classVal) {
7792 if (classVal && classVal.length > 0) {
7793 $animate.removeClass(this.$$element, classVal);
7799 * @name $compile.directive.Attributes#$updateClass
7803 * Adds and removes the appropriate CSS class values to the element based on the difference
7804 * between the new and old CSS class values (specified as newClasses and oldClasses).
7806 * @param {string} newClasses The current CSS className value
7807 * @param {string} oldClasses The former CSS className value
7809 $updateClass: function(newClasses, oldClasses) {
7810 var toAdd = tokenDifference(newClasses, oldClasses);
7811 if (toAdd && toAdd.length) {
7812 $animate.addClass(this.$$element, toAdd);
7815 var toRemove = tokenDifference(oldClasses, newClasses);
7816 if (toRemove && toRemove.length) {
7817 $animate.removeClass(this.$$element, toRemove);
7822 * Set a normalized attribute on the element in a way such that all directives
7823 * can share the attribute. This function properly handles boolean attributes.
7824 * @param {string} key Normalized key. (ie ngAttribute)
7825 * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
7826 * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
7828 * @param {string=} attrName Optional none normalized name. Defaults to key.
7830 $set: function(key, value, writeAttr, attrName) {
7831 // TODO: decide whether or not to throw an error if "class"
7832 //is set through this function since it may cause $updateClass to
7835 var node = this.$$element[0],
7836 booleanKey = getBooleanAttrName(node, key),
7837 aliasedKey = getAliasedAttrName(key),
7842 this.$$element.prop(key, value);
7843 attrName = booleanKey;
7844 } else if (aliasedKey) {
7845 this[aliasedKey] = value;
7846 observer = aliasedKey;
7851 // translate normalized key to actual key
7853 this.$attr[key] = attrName;
7855 attrName = this.$attr[key];
7857 this.$attr[key] = attrName = snake_case(key, '-');
7861 nodeName = nodeName_(this.$$element);
7863 if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
7864 (nodeName === 'img' && key === 'src')) {
7865 // sanitize a[href] and img[src] values
7866 this[key] = value = $$sanitizeUri(value, key === 'src');
7867 } else if (nodeName === 'img' && key === 'srcset') {
7868 // sanitize img[srcset] values
7871 // first check if there are spaces because it's not the same pattern
7872 var trimmedSrcset = trim(value);
7873 // ( 999x ,| 999w ,| ,|, )
7874 var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
7875 var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
7877 // split srcset into tuple of uri and descriptor except for the last item
7878 var rawUris = trimmedSrcset.split(pattern);
7881 var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
7882 for (var i = 0; i < nbrUrisWith2parts; i++) {
7883 var innerIdx = i * 2;
7885 result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
7886 // add the descriptor
7887 result += (" " + trim(rawUris[innerIdx + 1]));
7890 // split the last item into uri and descriptor
7891 var lastTuple = trim(rawUris[i * 2]).split(/\s/);
7893 // sanitize the last uri
7894 result += $$sanitizeUri(trim(lastTuple[0]), true);
7896 // and add the last descriptor if any
7897 if (lastTuple.length === 2) {
7898 result += (" " + trim(lastTuple[1]));
7900 this[key] = value = result;
7903 if (writeAttr !== false) {
7904 if (value === null || isUndefined(value)) {
7905 this.$$element.removeAttr(attrName);
7907 if (SIMPLE_ATTR_NAME.test(attrName)) {
7908 this.$$element.attr(attrName, value);
7910 setSpecialAttr(this.$$element[0], attrName, value);
7916 var $$observers = this.$$observers;
7917 $$observers && forEach($$observers[observer], function(fn) {
7921 $exceptionHandler(e);
7929 * @name $compile.directive.Attributes#$observe
7933 * Observes an interpolated attribute.
7935 * The observer function will be invoked once during the next `$digest` following
7936 * compilation. The observer is then invoked whenever the interpolated value
7939 * @param {string} key Normalized key. (ie ngAttribute) .
7940 * @param {function(interpolatedValue)} fn Function that will be called whenever
7941 the interpolated value of the attribute changes.
7942 * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
7943 * guide} for more info.
7944 * @returns {function()} Returns a deregistration function for this observer.
7946 $observe: function(key, fn) {
7948 $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
7949 listeners = ($$observers[key] || ($$observers[key] = []));
7952 $rootScope.$evalAsync(function() {
7953 if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
7954 // no one registered attribute interpolation function, so lets call it manually
7960 arrayRemove(listeners, fn);
7965 function setSpecialAttr(element, attrName, value) {
7966 // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
7967 // so we have to jump through some hoops to get such an attribute
7968 // https://github.com/angular/angular.js/pull/13318
7969 specialAttrHolder.innerHTML = "<span " + attrName + ">";
7970 var attributes = specialAttrHolder.firstChild.attributes;
7971 var attribute = attributes[0];
7972 // We have to remove the attribute from its container element before we can add it to the destination element
7973 attributes.removeNamedItem(attribute.name);
7974 attribute.value = value;
7975 element.attributes.setNamedItem(attribute);
7978 function safeAddClass($element, className) {
7980 $element.addClass(className);
7982 // ignore, since it means that we are trying to set class on
7983 // SVG element, where class name is read-only.
7988 var startSymbol = $interpolate.startSymbol(),
7989 endSymbol = $interpolate.endSymbol(),
7990 denormalizeTemplate = (startSymbol == '{{' && endSymbol == '}}')
7992 : function denormalizeTemplate(template) {
7993 return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
7995 NG_ATTR_BINDING = /^ngAttr[A-Z]/;
7996 var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
7998 compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
7999 var bindings = $element.data('$binding') || [];
8001 if (isArray(binding)) {
8002 bindings = bindings.concat(binding);
8004 bindings.push(binding);
8007 $element.data('$binding', bindings);
8010 compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
8011 safeAddClass($element, 'ng-binding');
8014 compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
8015 var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
8016 $element.data(dataName, scope);
8019 compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
8020 safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
8025 //================================
8027 function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
8028 previousCompileContext) {
8029 if (!($compileNodes instanceof jqLite)) {
8030 // jquery always rewraps, whereas we need to preserve the original selector so that we can
8032 $compileNodes = jqLite($compileNodes);
8035 var NOT_EMPTY = /\S+/;
8037 // We can not compile top level text elements since text nodes can be merged and we will
8038 // not be able to attach scope data to them, so we will wrap them in <span>
8039 for (var i = 0, len = $compileNodes.length; i < len; i++) {
8040 var domNode = $compileNodes[i];
8042 if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
8043 jqLiteWrapNode(domNode, $compileNodes[i] = document.createElement('span'));
8047 var compositeLinkFn =
8048 compileNodes($compileNodes, transcludeFn, $compileNodes,
8049 maxPriority, ignoreDirective, previousCompileContext);
8050 compile.$$addScopeClass($compileNodes);
8051 var namespace = null;
8052 return function publicLinkFn(scope, cloneConnectFn, options) {
8053 assertArg(scope, 'scope');
8055 if (previousCompileContext && previousCompileContext.needsNewScope) {
8056 // A parent directive did a replace and a directive on this element asked
8057 // for transclusion, which caused us to lose a layer of element on which
8058 // we could hold the new transclusion scope, so we will create it manually
8060 scope = scope.$parent.$new();
8063 options = options || {};
8064 var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
8065 transcludeControllers = options.transcludeControllers,
8066 futureParentElement = options.futureParentElement;
8068 // When `parentBoundTranscludeFn` is passed, it is a
8069 // `controllersBoundTransclude` function (it was previously passed
8070 // as `transclude` to directive.link) so we must unwrap it to get
8071 // its `boundTranscludeFn`
8072 if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
8073 parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
8077 namespace = detectNamespaceForChildElements(futureParentElement);
8080 if (namespace !== 'html') {
8081 // When using a directive with replace:true and templateUrl the $compileNodes
8082 // (or a child element inside of them)
8083 // might change, so we need to recreate the namespace adapted compileNodes
8084 // for call to the link function.
8085 // Note: This will already clone the nodes...
8087 wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
8089 } else if (cloneConnectFn) {
8090 // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
8091 // and sometimes changes the structure of the DOM.
8092 $linkNode = JQLitePrototype.clone.call($compileNodes);
8094 $linkNode = $compileNodes;
8097 if (transcludeControllers) {
8098 for (var controllerName in transcludeControllers) {
8099 $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
8103 compile.$$addScopeInfo($linkNode, scope);
8105 if (cloneConnectFn) cloneConnectFn($linkNode, scope);
8106 if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
8111 function detectNamespaceForChildElements(parentElement) {
8112 // TODO: Make this detect MathML as well...
8113 var node = parentElement && parentElement[0];
8117 return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
8122 * Compile function matches each node in nodeList against the directives. Once all directives
8123 * for a particular node are collected their compile functions are executed. The compile
8124 * functions return values - the linking functions - are combined into a composite linking
8125 * function, which is the a linking function for the node.
8127 * @param {NodeList} nodeList an array of nodes or NodeList to compile
8128 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
8129 * scope argument is auto-generated to the new child of the transcluded parent scope.
8130 * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
8131 * the rootElement must be set the jqLite collection of the compile root. This is
8132 * needed so that the jqLite collection items can be replaced with widgets.
8133 * @param {number=} maxPriority Max directive priority.
8134 * @returns {Function} A composite linking function of all of the matched directives or null.
8136 function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
8137 previousCompileContext) {
8139 attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
8141 for (var i = 0; i < nodeList.length; i++) {
8142 attrs = new Attributes();
8144 // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
8145 directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
8148 nodeLinkFn = (directives.length)
8149 ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
8150 null, [], [], previousCompileContext)
8153 if (nodeLinkFn && nodeLinkFn.scope) {
8154 compile.$$addScopeClass(attrs.$$element);
8157 childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
8158 !(childNodes = nodeList[i].childNodes) ||
8161 : compileNodes(childNodes,
8163 (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
8164 && nodeLinkFn.transclude) : transcludeFn);
8166 if (nodeLinkFn || childLinkFn) {
8167 linkFns.push(i, nodeLinkFn, childLinkFn);
8169 nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
8172 //use the previous context only for the first element in the virtual group
8173 previousCompileContext = null;
8176 // return a linking function if we have found anything, null otherwise
8177 return linkFnFound ? compositeLinkFn : null;
8179 function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
8180 var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
8184 if (nodeLinkFnFound) {
8185 // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
8186 // offsets don't get screwed up
8187 var nodeListLength = nodeList.length;
8188 stableNodeList = new Array(nodeListLength);
8190 // create a sparse array by only copying the elements which have a linkFn
8191 for (i = 0; i < linkFns.length; i+=3) {
8193 stableNodeList[idx] = nodeList[idx];
8196 stableNodeList = nodeList;
8199 for (i = 0, ii = linkFns.length; i < ii;) {
8200 node = stableNodeList[linkFns[i++]];
8201 nodeLinkFn = linkFns[i++];
8202 childLinkFn = linkFns[i++];
8205 if (nodeLinkFn.scope) {
8206 childScope = scope.$new();
8207 compile.$$addScopeInfo(jqLite(node), childScope);
8212 if (nodeLinkFn.transcludeOnThisElement) {
8213 childBoundTranscludeFn = createBoundTranscludeFn(
8214 scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
8216 } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
8217 childBoundTranscludeFn = parentBoundTranscludeFn;
8219 } else if (!parentBoundTranscludeFn && transcludeFn) {
8220 childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
8223 childBoundTranscludeFn = null;
8226 nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
8228 } else if (childLinkFn) {
8229 childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
8235 function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
8237 var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
8239 if (!transcludedScope) {
8240 transcludedScope = scope.$new(false, containingScope);
8241 transcludedScope.$$transcluded = true;
8244 return transcludeFn(transcludedScope, cloneFn, {
8245 parentBoundTranscludeFn: previousBoundTranscludeFn,
8246 transcludeControllers: controllers,
8247 futureParentElement: futureParentElement
8251 // We need to attach the transclusion slots onto the `boundTranscludeFn`
8252 // so that they are available inside the `controllersBoundTransclude` function
8253 var boundSlots = boundTranscludeFn.$$slots = createMap();
8254 for (var slotName in transcludeFn.$$slots) {
8255 if (transcludeFn.$$slots[slotName]) {
8256 boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
8258 boundSlots[slotName] = null;
8262 return boundTranscludeFn;
8266 * Looks for directives on the given node and adds them to the directive collection which is
8269 * @param node Node to search.
8270 * @param directives An array to which the directives are added to. This array is sorted before
8271 * the function returns.
8272 * @param attrs The shared attrs object which is used to populate the normalized attributes.
8273 * @param {number=} maxPriority Max directive priority.
8275 function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
8276 var nodeType = node.nodeType,
8277 attrsMap = attrs.$attr,
8282 case NODE_TYPE_ELEMENT: /* Element */
8283 // use the node name: <directive>
8284 addDirective(directives,
8285 directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
8287 // iterate over the attributes
8288 for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
8289 j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
8290 var attrStartName = false;
8291 var attrEndName = false;
8295 value = trim(attr.value);
8297 // support ngAttr attribute binding
8298 ngAttrName = directiveNormalize(name);
8299 if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
8300 name = name.replace(PREFIX_REGEXP, '')
8301 .substr(8).replace(/_(.)/g, function(match, letter) {
8302 return letter.toUpperCase();
8306 var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
8307 if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
8308 attrStartName = name;
8309 attrEndName = name.substr(0, name.length - 5) + 'end';
8310 name = name.substr(0, name.length - 6);
8313 nName = directiveNormalize(name.toLowerCase());
8314 attrsMap[nName] = name;
8315 if (isNgAttr || !attrs.hasOwnProperty(nName)) {
8316 attrs[nName] = value;
8317 if (getBooleanAttrName(node, nName)) {
8318 attrs[nName] = true; // presence means true
8321 addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
8322 addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
8326 // use class as directive
8327 className = node.className;
8328 if (isObject(className)) {
8329 // Maybe SVGAnimatedString
8330 className = className.animVal;
8332 if (isString(className) && className !== '') {
8333 while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
8334 nName = directiveNormalize(match[2]);
8335 if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
8336 attrs[nName] = trim(match[3]);
8338 className = className.substr(match.index + match[0].length);
8342 case NODE_TYPE_TEXT: /* Text Node */
8344 // Workaround for #11781
8345 while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
8346 node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
8347 node.parentNode.removeChild(node.nextSibling);
8350 addTextInterpolateDirective(directives, node.nodeValue);
8352 case NODE_TYPE_COMMENT: /* Comment */
8354 match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
8356 nName = directiveNormalize(match[1]);
8357 if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
8358 attrs[nName] = trim(match[2]);
8362 // turns out that under some circumstances IE9 throws errors when one attempts to read
8363 // comment's node value.
8364 // Just ignore it and continue. (Can't seem to reproduce in test case.)
8369 directives.sort(byPriority);
8374 * Given a node with an directive-start it collects all of the siblings until it finds
8381 function groupScan(node, attrStart, attrEnd) {
8384 if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
8387 throw $compileMinErr('uterdir',
8388 "Unterminated attribute, found '{0}' but no matching '{1}' found.",
8389 attrStart, attrEnd);
8391 if (node.nodeType == NODE_TYPE_ELEMENT) {
8392 if (node.hasAttribute(attrStart)) depth++;
8393 if (node.hasAttribute(attrEnd)) depth--;
8396 node = node.nextSibling;
8397 } while (depth > 0);
8402 return jqLite(nodes);
8406 * Wrapper for linking function which converts normal linking function into a grouped
8411 * @returns {Function}
8413 function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
8414 return function(scope, element, attrs, controllers, transcludeFn) {
8415 element = groupScan(element[0], attrStart, attrEnd);
8416 return linkFn(scope, element, attrs, controllers, transcludeFn);
8421 * A function generator that is used to support both eager and lazy compilation
8424 * @param $compileNodes
8425 * @param transcludeFn
8426 * @param maxPriority
8427 * @param ignoreDirective
8428 * @param previousCompileContext
8429 * @returns {Function}
8431 function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
8433 return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
8440 compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
8442 // Null out all of these references in order to make them eligible for garbage collection
8443 // since this is a potentially long lived closure
8444 $compileNodes = transcludeFn = previousCompileContext = null;
8447 return compiled.apply(this, arguments);
8452 * Once the directives have been collected, their compile functions are executed. This method
8453 * is responsible for inlining directive templates as well as terminating the application
8454 * of the directives if the terminal directive has been reached.
8456 * @param {Array} directives Array of collected directives to execute their compile function.
8457 * this needs to be pre-sorted by priority order.
8458 * @param {Node} compileNode The raw DOM node to apply the compile functions to
8459 * @param {Object} templateAttrs The shared attribute function
8460 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
8461 * scope argument is auto-generated to the new
8462 * child of the transcluded parent scope.
8463 * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
8464 * argument has the root jqLite array so that we can replace nodes
8466 * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
8467 * compiling the transclusion.
8468 * @param {Array.<Function>} preLinkFns
8469 * @param {Array.<Function>} postLinkFns
8470 * @param {Object} previousCompileContext Context used for previous compilation of the current
8472 * @returns {Function} linkFn
8474 function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
8475 jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
8476 previousCompileContext) {
8477 previousCompileContext = previousCompileContext || {};
8479 var terminalPriority = -Number.MAX_VALUE,
8480 newScopeDirective = previousCompileContext.newScopeDirective,
8481 controllerDirectives = previousCompileContext.controllerDirectives,
8482 newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
8483 templateDirective = previousCompileContext.templateDirective,
8484 nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
8485 hasTranscludeDirective = false,
8486 hasTemplate = false,
8487 hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
8488 $compileNode = templateAttrs.$$element = jqLite(compileNode),
8492 replaceDirective = originalReplaceDirective,
8493 childTranscludeFn = transcludeFn,
8495 didScanForMultipleTransclusion = false,
8496 mightHaveMultipleTransclusionError = false,
8499 // executes all directives on the current element
8500 for (var i = 0, ii = directives.length; i < ii; i++) {
8501 directive = directives[i];
8502 var attrStart = directive.$$start;
8503 var attrEnd = directive.$$end;
8505 // collect multiblock sections
8507 $compileNode = groupScan(compileNode, attrStart, attrEnd);
8509 $template = undefined;
8511 if (terminalPriority > directive.priority) {
8512 break; // prevent further processing of directives
8515 if (directiveValue = directive.scope) {
8517 // skip the check for directives with async templates, we'll check the derived sync
8518 // directive when the template arrives
8519 if (!directive.templateUrl) {
8520 if (isObject(directiveValue)) {
8521 // This directive is trying to add an isolated scope.
8522 // Check that there is no scope of any kind already
8523 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
8524 directive, $compileNode);
8525 newIsolateScopeDirective = directive;
8527 // This directive is trying to add a child scope.
8528 // Check that there is no isolated scope already
8529 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
8534 newScopeDirective = newScopeDirective || directive;
8537 directiveName = directive.name;
8539 // If we encounter a condition that can result in transclusion on the directive,
8540 // then scan ahead in the remaining directives for others that may cause a multiple
8541 // transclusion error to be thrown during the compilation process. If a matching directive
8542 // is found, then we know that when we encounter a transcluded directive, we need to eagerly
8543 // compile the `transclude` function rather than doing it lazily in order to throw
8544 // exceptions at the correct time
8545 if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
8546 || (directive.transclude && !directive.$$tlb))) {
8547 var candidateDirective;
8549 for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
8550 if ((candidateDirective.transclude && !candidateDirective.$$tlb)
8551 || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
8552 mightHaveMultipleTransclusionError = true;
8557 didScanForMultipleTransclusion = true;
8560 if (!directive.templateUrl && directive.controller) {
8561 directiveValue = directive.controller;
8562 controllerDirectives = controllerDirectives || createMap();
8563 assertNoDuplicate("'" + directiveName + "' controller",
8564 controllerDirectives[directiveName], directive, $compileNode);
8565 controllerDirectives[directiveName] = directive;
8568 if (directiveValue = directive.transclude) {
8569 hasTranscludeDirective = true;
8571 // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
8572 // This option should only be used by directives that know how to safely handle element transclusion,
8573 // where the transcluded nodes are added or replaced after linking.
8574 if (!directive.$$tlb) {
8575 assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
8576 nonTlbTranscludeDirective = directive;
8579 if (directiveValue == 'element') {
8580 hasElementTranscludeDirective = true;
8581 terminalPriority = directive.priority;
8582 $template = $compileNode;
8583 $compileNode = templateAttrs.$$element =
8584 jqLite(document.createComment(' ' + directiveName + ': ' +
8585 templateAttrs[directiveName] + ' '));
8586 compileNode = $compileNode[0];
8587 replaceWith(jqCollection, sliceArgs($template), compileNode);
8589 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
8590 replaceDirective && replaceDirective.name, {
8592 // - controllerDirectives - otherwise we'll create duplicates controllers
8593 // - newIsolateScopeDirective or templateDirective - combining templates with
8594 // element transclusion doesn't make sense.
8596 // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
8597 // on the same element more than once.
8598 nonTlbTranscludeDirective: nonTlbTranscludeDirective
8602 var slots = createMap();
8604 $template = jqLite(jqLiteClone(compileNode)).contents();
8606 if (isObject(directiveValue)) {
8608 // We have transclusion slots,
8609 // collect them up, compile them and store their transclusion functions
8612 var slotMap = createMap();
8613 var filledSlots = createMap();
8615 // Parse the element selectors
8616 forEach(directiveValue, function(elementSelector, slotName) {
8617 // If an element selector starts with a ? then it is optional
8618 var optional = (elementSelector.charAt(0) === '?');
8619 elementSelector = optional ? elementSelector.substring(1) : elementSelector;
8621 slotMap[elementSelector] = slotName;
8623 // We explicitly assign `null` since this implies that a slot was defined but not filled.
8624 // Later when calling boundTransclusion functions with a slot name we only error if the
8625 // slot is `undefined`
8626 slots[slotName] = null;
8628 // filledSlots contains `true` for all slots that are either optional or have been
8629 // filled. This is used to check that we have not missed any required slots
8630 filledSlots[slotName] = optional;
8633 // Add the matching elements into their slot
8634 forEach($compileNode.contents(), function(node) {
8635 var slotName = slotMap[directiveNormalize(nodeName_(node))];
8637 filledSlots[slotName] = true;
8638 slots[slotName] = slots[slotName] || [];
8639 slots[slotName].push(node);
8641 $template.push(node);
8645 // Check for required slots that were not filled
8646 forEach(filledSlots, function(filled, slotName) {
8648 throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
8652 for (var slotName in slots) {
8653 if (slots[slotName]) {
8654 // Only define a transclusion function if the slot was filled
8655 slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
8660 $compileNode.empty(); // clear contents
8661 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
8662 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
8663 childTranscludeFn.$$slots = slots;
8667 if (directive.template) {
8669 assertNoDuplicate('template', templateDirective, directive, $compileNode);
8670 templateDirective = directive;
8672 directiveValue = (isFunction(directive.template))
8673 ? directive.template($compileNode, templateAttrs)
8674 : directive.template;
8676 directiveValue = denormalizeTemplate(directiveValue);
8678 if (directive.replace) {
8679 replaceDirective = directive;
8680 if (jqLiteIsTextNode(directiveValue)) {
8683 $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
8685 compileNode = $template[0];
8687 if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
8688 throw $compileMinErr('tplrt',
8689 "Template for directive '{0}' must have exactly one root element. {1}",
8693 replaceWith(jqCollection, $compileNode, compileNode);
8695 var newTemplateAttrs = {$attr: {}};
8697 // combine directives from the original node and from the template:
8698 // - take the array of directives for this element
8699 // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
8700 // - collect directives from the template and sort them by priority
8701 // - combine directives as: processed + template + unprocessed
8702 var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
8703 var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
8705 if (newIsolateScopeDirective || newScopeDirective) {
8706 // The original directive caused the current element to be replaced but this element
8707 // also needs to have a new scope, so we need to tell the template directives
8708 // that they would need to get their scope from further up, if they require transclusion
8709 markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
8711 directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
8712 mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
8714 ii = directives.length;
8716 $compileNode.html(directiveValue);
8720 if (directive.templateUrl) {
8722 assertNoDuplicate('template', templateDirective, directive, $compileNode);
8723 templateDirective = directive;
8725 if (directive.replace) {
8726 replaceDirective = directive;
8729 nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
8730 templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
8731 controllerDirectives: controllerDirectives,
8732 newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
8733 newIsolateScopeDirective: newIsolateScopeDirective,
8734 templateDirective: templateDirective,
8735 nonTlbTranscludeDirective: nonTlbTranscludeDirective
8737 ii = directives.length;
8738 } else if (directive.compile) {
8740 linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
8741 if (isFunction(linkFn)) {
8742 addLinkFns(null, linkFn, attrStart, attrEnd);
8743 } else if (linkFn) {
8744 addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
8747 $exceptionHandler(e, startingTag($compileNode));
8751 if (directive.terminal) {
8752 nodeLinkFn.terminal = true;
8753 terminalPriority = Math.max(terminalPriority, directive.priority);
8758 nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
8759 nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
8760 nodeLinkFn.templateOnThisElement = hasTemplate;
8761 nodeLinkFn.transclude = childTranscludeFn;
8763 previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
8765 // might be normal or delayed nodeLinkFn depending on if templateUrl is present
8768 ////////////////////
8770 function addLinkFns(pre, post, attrStart, attrEnd) {
8772 if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
8773 pre.require = directive.require;
8774 pre.directiveName = directiveName;
8775 if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
8776 pre = cloneAndAnnotateFn(pre, {isolateScope: true});
8778 preLinkFns.push(pre);
8781 if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
8782 post.require = directive.require;
8783 post.directiveName = directiveName;
8784 if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
8785 post = cloneAndAnnotateFn(post, {isolateScope: true});
8787 postLinkFns.push(post);
8792 function getControllers(directiveName, require, $element, elementControllers) {
8795 if (isString(require)) {
8796 var match = require.match(REQUIRE_PREFIX_REGEXP);
8797 var name = require.substring(match[0].length);
8798 var inheritType = match[1] || match[3];
8799 var optional = match[2] === '?';
8801 //If only parents then start at the parent element
8802 if (inheritType === '^^') {
8803 $element = $element.parent();
8804 //Otherwise attempt getting the controller from elementControllers in case
8805 //the element is transcluded (and has no data) and to avoid .data if possible
8807 value = elementControllers && elementControllers[name];
8808 value = value && value.instance;
8812 var dataName = '$' + name + 'Controller';
8813 value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
8816 if (!value && !optional) {
8817 throw $compileMinErr('ctreq',
8818 "Controller '{0}', required by directive '{1}', can't be found!",
8819 name, directiveName);
8821 } else if (isArray(require)) {
8823 for (var i = 0, ii = require.length; i < ii; i++) {
8824 value[i] = getControllers(directiveName, require[i], $element, elementControllers);
8826 } else if (isObject(require)) {
8828 forEach(require, function(controller, property) {
8829 value[property] = getControllers(directiveName, controller, $element, elementControllers);
8833 return value || null;
8836 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
8837 var elementControllers = createMap();
8838 for (var controllerKey in controllerDirectives) {
8839 var directive = controllerDirectives[controllerKey];
8841 $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
8844 $transclude: transcludeFn
8847 var controller = directive.controller;
8848 if (controller == '@') {
8849 controller = attrs[directive.name];
8852 var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
8854 // For directives with element transclusion the element is a comment,
8855 // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
8856 // clean up (http://bugs.jquery.com/ticket/8335).
8857 // Instead, we save the controllers for the element in a local hash and attach to .data
8858 // later, once we have the actual element.
8859 elementControllers[directive.name] = controllerInstance;
8860 if (!hasElementTranscludeDirective) {
8861 $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
8864 return elementControllers;
8867 function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
8868 var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
8869 attrs, removeScopeBindingWatches, removeControllerBindingWatches;
8871 if (compileNode === linkNode) {
8872 attrs = templateAttrs;
8873 $element = templateAttrs.$$element;
8875 $element = jqLite(linkNode);
8876 attrs = new Attributes($element, templateAttrs);
8879 controllerScope = scope;
8880 if (newIsolateScopeDirective) {
8881 isolateScope = scope.$new(true);
8882 } else if (newScopeDirective) {
8883 controllerScope = scope.$parent;
8886 if (boundTranscludeFn) {
8887 // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
8888 // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
8889 transcludeFn = controllersBoundTransclude;
8890 transcludeFn.$$boundTransclude = boundTranscludeFn;
8891 // expose the slots on the `$transclude` function
8892 transcludeFn.isSlotFilled = function(slotName) {
8893 return !!boundTranscludeFn.$$slots[slotName];
8897 if (controllerDirectives) {
8898 elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
8901 if (newIsolateScopeDirective) {
8902 // Initialize isolate scope bindings for new isolate scope directive.
8903 compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
8904 templateDirective === newIsolateScopeDirective.$$originalDirective)));
8905 compile.$$addScopeClass($element, true);
8906 isolateScope.$$isolateBindings =
8907 newIsolateScopeDirective.$$isolateBindings;
8908 removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
8909 isolateScope.$$isolateBindings,
8910 newIsolateScopeDirective);
8911 if (removeScopeBindingWatches) {
8912 isolateScope.$on('$destroy', removeScopeBindingWatches);
8916 // Initialize bindToController bindings
8917 for (var name in elementControllers) {
8918 var controllerDirective = controllerDirectives[name];
8919 var controller = elementControllers[name];
8920 var bindings = controllerDirective.$$bindings.bindToController;
8922 if (controller.identifier && bindings) {
8923 removeControllerBindingWatches =
8924 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
8927 var controllerResult = controller();
8928 if (controllerResult !== controller.instance) {
8929 // If the controller constructor has a return value, overwrite the instance
8930 // from setupControllers
8931 controller.instance = controllerResult;
8932 $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
8933 removeControllerBindingWatches && removeControllerBindingWatches();
8934 removeControllerBindingWatches =
8935 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
8939 // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
8940 forEach(controllerDirectives, function(controllerDirective, name) {
8941 var require = controllerDirective.require;
8942 if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
8943 extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
8947 // Trigger the `$onInit` method on all controllers that have one
8948 forEach(elementControllers, function(controller) {
8949 if (isFunction(controller.instance.$onInit)) {
8950 controller.instance.$onInit();
8955 for (i = 0, ii = preLinkFns.length; i < ii; i++) {
8956 linkFn = preLinkFns[i];
8957 invokeLinkFn(linkFn,
8958 linkFn.isolateScope ? isolateScope : scope,
8961 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
8967 // We only pass the isolate scope, if the isolate directive has a template,
8968 // otherwise the child elements do not belong to the isolate directive.
8969 var scopeToChild = scope;
8970 if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
8971 scopeToChild = isolateScope;
8973 childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
8976 for (i = postLinkFns.length - 1; i >= 0; i--) {
8977 linkFn = postLinkFns[i];
8978 invokeLinkFn(linkFn,
8979 linkFn.isolateScope ? isolateScope : scope,
8982 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
8987 // This is the function that is injected as `$transclude`.
8988 // Note: all arguments are optional!
8989 function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
8990 var transcludeControllers;
8991 // No scope passed in:
8992 if (!isScope(scope)) {
8993 slotName = futureParentElement;
8994 futureParentElement = cloneAttachFn;
8995 cloneAttachFn = scope;
8999 if (hasElementTranscludeDirective) {
9000 transcludeControllers = elementControllers;
9002 if (!futureParentElement) {
9003 futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
9006 // slotTranscludeFn can be one of three things:
9007 // * a transclude function - a filled slot
9008 // * `null` - an optional slot that was not filled
9009 // * `undefined` - a slot that was not declared (i.e. invalid)
9010 var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
9011 if (slotTranscludeFn) {
9012 return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
9013 } else if (isUndefined(slotTranscludeFn)) {
9014 throw $compileMinErr('noslot',
9015 'No parent directive that requires a transclusion with slot name "{0}". ' +
9017 slotName, startingTag($element));
9020 return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
9026 // Depending upon the context in which a directive finds itself it might need to have a new isolated
9027 // or child scope created. For instance:
9028 // * if the directive has been pulled into a template because another directive with a higher priority
9029 // asked for element transclusion
9030 // * if the directive itself asks for transclusion but it is at the root of a template and the original
9031 // element was replaced. See https://github.com/angular/angular.js/issues/12936
9032 function markDirectiveScope(directives, isolateScope, newScope) {
9033 for (var j = 0, jj = directives.length; j < jj; j++) {
9034 directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
9039 * looks up the directive and decorates it with exception handling and proper parameters. We
9040 * call this the boundDirective.
9042 * @param {string} name name of the directive to look up.
9043 * @param {string} location The directive must be found in specific format.
9044 * String containing any of theses characters:
9046 * * `E`: element name
9050 * @returns {boolean} true if directive was added.
9052 function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
9054 if (name === ignoreDirective) return null;
9056 if (hasDirectives.hasOwnProperty(name)) {
9057 for (var directive, directives = $injector.get(name + Suffix),
9058 i = 0, ii = directives.length; i < ii; i++) {
9060 directive = directives[i];
9061 if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
9062 directive.restrict.indexOf(location) != -1) {
9063 if (startAttrName) {
9064 directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
9066 tDirectives.push(directive);
9069 } catch (e) { $exceptionHandler(e); }
9077 * looks up the directive and returns true if it is a multi-element directive,
9078 * and therefore requires DOM nodes between -start and -end markers to be grouped
9081 * @param {string} name name of the directive to look up.
9082 * @returns true if directive was registered as multi-element.
9084 function directiveIsMultiElement(name) {
9085 if (hasDirectives.hasOwnProperty(name)) {
9086 for (var directive, directives = $injector.get(name + Suffix),
9087 i = 0, ii = directives.length; i < ii; i++) {
9088 directive = directives[i];
9089 if (directive.multiElement) {
9098 * When the element is replaced with HTML template then the new attributes
9099 * on the template need to be merged with the existing attributes in the DOM.
9100 * The desired effect is to have both of the attributes present.
9102 * @param {object} dst destination attributes (original DOM)
9103 * @param {object} src source attributes (from the directive template)
9105 function mergeTemplateAttributes(dst, src) {
9106 var srcAttr = src.$attr,
9107 dstAttr = dst.$attr,
9108 $element = dst.$$element;
9110 // reapply the old attributes to the new element
9111 forEach(dst, function(value, key) {
9112 if (key.charAt(0) != '$') {
9113 if (src[key] && src[key] !== value) {
9114 value += (key === 'style' ? ';' : ' ') + src[key];
9116 dst.$set(key, value, true, srcAttr[key]);
9120 // copy the new attributes on the old attrs object
9121 forEach(src, function(value, key) {
9122 if (key == 'class') {
9123 safeAddClass($element, value);
9124 dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
9125 } else if (key == 'style') {
9126 $element.attr('style', $element.attr('style') + ';' + value);
9127 dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
9128 // `dst` will never contain hasOwnProperty as DOM parser won't let it.
9129 // You will get an "InvalidCharacterError: DOM Exception 5" error if you
9130 // have an attribute like "has-own-property" or "data-has-own-property", etc.
9131 } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
9133 dstAttr[key] = srcAttr[key];
9139 function compileTemplateUrl(directives, $compileNode, tAttrs,
9140 $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
9142 afterTemplateNodeLinkFn,
9143 afterTemplateChildLinkFn,
9144 beforeTemplateCompileNode = $compileNode[0],
9145 origAsyncDirective = directives.shift(),
9146 derivedSyncDirective = inherit(origAsyncDirective, {
9147 templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
9149 templateUrl = (isFunction(origAsyncDirective.templateUrl))
9150 ? origAsyncDirective.templateUrl($compileNode, tAttrs)
9151 : origAsyncDirective.templateUrl,
9152 templateNamespace = origAsyncDirective.templateNamespace;
9154 $compileNode.empty();
9156 $templateRequest(templateUrl)
9157 .then(function(content) {
9158 var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
9160 content = denormalizeTemplate(content);
9162 if (origAsyncDirective.replace) {
9163 if (jqLiteIsTextNode(content)) {
9166 $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
9168 compileNode = $template[0];
9170 if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
9171 throw $compileMinErr('tplrt',
9172 "Template for directive '{0}' must have exactly one root element. {1}",
9173 origAsyncDirective.name, templateUrl);
9176 tempTemplateAttrs = {$attr: {}};
9177 replaceWith($rootElement, $compileNode, compileNode);
9178 var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
9180 if (isObject(origAsyncDirective.scope)) {
9181 // the original directive that caused the template to be loaded async required
9183 markDirectiveScope(templateDirectives, true);
9185 directives = templateDirectives.concat(directives);
9186 mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
9188 compileNode = beforeTemplateCompileNode;
9189 $compileNode.html(content);
9192 directives.unshift(derivedSyncDirective);
9194 afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
9195 childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
9196 previousCompileContext);
9197 forEach($rootElement, function(node, i) {
9198 if (node == compileNode) {
9199 $rootElement[i] = $compileNode[0];
9202 afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
9204 while (linkQueue.length) {
9205 var scope = linkQueue.shift(),
9206 beforeTemplateLinkNode = linkQueue.shift(),
9207 linkRootElement = linkQueue.shift(),
9208 boundTranscludeFn = linkQueue.shift(),
9209 linkNode = $compileNode[0];
9211 if (scope.$$destroyed) continue;
9213 if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
9214 var oldClasses = beforeTemplateLinkNode.className;
9216 if (!(previousCompileContext.hasElementTranscludeDirective &&
9217 origAsyncDirective.replace)) {
9218 // it was cloned therefore we have to clone as well.
9219 linkNode = jqLiteClone(compileNode);
9221 replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
9223 // Copy in CSS classes from original node
9224 safeAddClass(jqLite(linkNode), oldClasses);
9226 if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
9227 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
9229 childBoundTranscludeFn = boundTranscludeFn;
9231 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
9232 childBoundTranscludeFn);
9237 return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
9238 var childBoundTranscludeFn = boundTranscludeFn;
9239 if (scope.$$destroyed) return;
9241 linkQueue.push(scope,
9244 childBoundTranscludeFn);
9246 if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
9247 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
9249 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
9256 * Sorting function for bound directives.
9258 function byPriority(a, b) {
9259 var diff = b.priority - a.priority;
9260 if (diff !== 0) return diff;
9261 if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
9262 return a.index - b.index;
9265 function assertNoDuplicate(what, previousDirective, directive, element) {
9267 function wrapModuleNameIfDefined(moduleName) {
9269 (' (module: ' + moduleName + ')') :
9273 if (previousDirective) {
9274 throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
9275 previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
9276 directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
9281 function addTextInterpolateDirective(directives, text) {
9282 var interpolateFn = $interpolate(text, true);
9283 if (interpolateFn) {
9286 compile: function textInterpolateCompileFn(templateNode) {
9287 var templateNodeParent = templateNode.parent(),
9288 hasCompileParent = !!templateNodeParent.length;
9290 // When transcluding a template that has bindings in the root
9291 // we don't have a parent and thus need to add the class during linking fn.
9292 if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
9294 return function textInterpolateLinkFn(scope, node) {
9295 var parent = node.parent();
9296 if (!hasCompileParent) compile.$$addBindingClass(parent);
9297 compile.$$addBindingInfo(parent, interpolateFn.expressions);
9298 scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
9299 node[0].nodeValue = value;
9308 function wrapTemplate(type, template) {
9309 type = lowercase(type || 'html');
9313 var wrapper = document.createElement('div');
9314 wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
9315 return wrapper.childNodes[0].childNodes;
9322 function getTrustedContext(node, attrNormalizedName) {
9323 if (attrNormalizedName == "srcdoc") {
9326 var tag = nodeName_(node);
9327 // maction[xlink:href] can source SVG. It's not limited to <maction>.
9328 if (attrNormalizedName == "xlinkHref" ||
9329 (tag == "form" && attrNormalizedName == "action") ||
9330 (tag != "img" && (attrNormalizedName == "src" ||
9331 attrNormalizedName == "ngSrc"))) {
9332 return $sce.RESOURCE_URL;
9337 function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
9338 var trustedContext = getTrustedContext(node, name);
9339 allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
9341 var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
9343 // no interpolation found -> ignore
9344 if (!interpolateFn) return;
9347 if (name === "multiple" && nodeName_(node) === "select") {
9348 throw $compileMinErr("selmulti",
9349 "Binding to the 'multiple' attribute is not supported. Element: {0}",
9355 compile: function() {
9357 pre: function attrInterpolatePreLinkFn(scope, element, attr) {
9358 var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
9360 if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
9361 throw $compileMinErr('nodomevents',
9362 "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
9363 "ng- versions (such as ng-click instead of onclick) instead.");
9366 // If the attribute has changed since last $interpolate()ed
9367 var newValue = attr[name];
9368 if (newValue !== value) {
9369 // we need to interpolate again since the attribute value has been updated
9370 // (e.g. by another directive's compile function)
9371 // ensure unset/empty values make interpolateFn falsy
9372 interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
9376 // if attribute was updated so that there is no interpolation going on we don't want to
9377 // register any observers
9378 if (!interpolateFn) return;
9380 // initialize attr object so that it's ready in case we need the value for isolate
9381 // scope initialization, otherwise the value would not be available from isolate
9382 // directive's linking fn during linking phase
9383 attr[name] = interpolateFn(scope);
9385 ($$observers[name] || ($$observers[name] = [])).$$inter = true;
9386 (attr.$$observers && attr.$$observers[name].$$scope || scope).
9387 $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
9388 //special case for class attribute addition + removal
9389 //so that class changes can tap into the animation
9390 //hooks provided by the $animate service. Be sure to
9391 //skip animations when the first digest occurs (when
9392 //both the new and the old values are the same) since
9393 //the CSS classes are the non-interpolated values
9394 if (name === 'class' && newValue != oldValue) {
9395 attr.$updateClass(newValue, oldValue);
9397 attr.$set(name, newValue);
9408 * This is a special jqLite.replaceWith, which can replace items which
9409 * have no parents, provided that the containing jqLite collection is provided.
9411 * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
9412 * in the root of the tree.
9413 * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
9414 * the shell, but replace its DOM node reference.
9415 * @param {Node} newNode The new DOM node.
9417 function replaceWith($rootElement, elementsToRemove, newNode) {
9418 var firstElementToRemove = elementsToRemove[0],
9419 removeCount = elementsToRemove.length,
9420 parent = firstElementToRemove.parentNode,
9424 for (i = 0, ii = $rootElement.length; i < ii; i++) {
9425 if ($rootElement[i] == firstElementToRemove) {
9426 $rootElement[i++] = newNode;
9427 for (var j = i, j2 = j + removeCount - 1,
9428 jj = $rootElement.length;
9429 j < jj; j++, j2++) {
9431 $rootElement[j] = $rootElement[j2];
9433 delete $rootElement[j];
9436 $rootElement.length -= removeCount - 1;
9438 // If the replaced element is also the jQuery .context then replace it
9439 // .context is a deprecated jQuery api, so we should set it only when jQuery set it
9440 // http://api.jquery.com/context/
9441 if ($rootElement.context === firstElementToRemove) {
9442 $rootElement.context = newNode;
9450 parent.replaceChild(newNode, firstElementToRemove);
9453 // Append all the `elementsToRemove` to a fragment. This will...
9454 // - remove them from the DOM
9455 // - allow them to still be traversed with .nextSibling
9456 // - allow a single fragment.qSA to fetch all elements being removed
9457 var fragment = document.createDocumentFragment();
9458 for (i = 0; i < removeCount; i++) {
9459 fragment.appendChild(elementsToRemove[i]);
9462 if (jqLite.hasData(firstElementToRemove)) {
9463 // Copy over user data (that includes Angular's $scope etc.). Don't copy private
9464 // data here because there's no public interface in jQuery to do that and copying over
9465 // event listeners (which is the main use of private data) wouldn't work anyway.
9466 jqLite.data(newNode, jqLite.data(firstElementToRemove));
9468 // Remove $destroy event listeners from `firstElementToRemove`
9469 jqLite(firstElementToRemove).off('$destroy');
9472 // Cleanup any data/listeners on the elements and children.
9473 // This includes invoking the $destroy event on any elements with listeners.
9474 jqLite.cleanData(fragment.querySelectorAll('*'));
9476 // Update the jqLite collection to only contain the `newNode`
9477 for (i = 1; i < removeCount; i++) {
9478 delete elementsToRemove[i];
9480 elementsToRemove[0] = newNode;
9481 elementsToRemove.length = 1;
9485 function cloneAndAnnotateFn(fn, annotation) {
9486 return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
9490 function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
9492 linkFn(scope, $element, attrs, controllers, transcludeFn);
9494 $exceptionHandler(e, startingTag($element));
9499 // Set up $watches for isolate scope and controller bindings. This process
9500 // only occurs for isolate scopes and new scopes with controllerAs.
9501 function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
9502 var removeWatchCollection = [];
9503 forEach(bindings, function(definition, scopeName) {
9504 var attrName = definition.attrName,
9505 optional = definition.optional,
9506 mode = definition.mode, // @, =, or &
9508 parentGet, parentSet, compare, removeWatch;
9513 if (!optional && !hasOwnProperty.call(attrs, attrName)) {
9514 destination[scopeName] = attrs[attrName] = void 0;
9516 attrs.$observe(attrName, function(value) {
9517 if (isString(value)) {
9518 destination[scopeName] = value;
9521 attrs.$$observers[attrName].$$scope = scope;
9522 lastValue = attrs[attrName];
9523 if (isString(lastValue)) {
9524 // If the attribute has been provided then we trigger an interpolation to ensure
9525 // the value is there for use in the link fn
9526 destination[scopeName] = $interpolate(lastValue)(scope);
9527 } else if (isBoolean(lastValue)) {
9528 // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
9529 // the value to boolean rather than a string, so we special case this situation
9530 destination[scopeName] = lastValue;
9535 if (!hasOwnProperty.call(attrs, attrName)) {
9536 if (optional) break;
9537 attrs[attrName] = void 0;
9539 if (optional && !attrs[attrName]) break;
9541 parentGet = $parse(attrs[attrName]);
9542 if (parentGet.literal) {
9545 compare = function(a, b) { return a === b || (a !== a && b !== b); };
9547 parentSet = parentGet.assign || function() {
9548 // reset the change, or we will throw this exception on every $digest
9549 lastValue = destination[scopeName] = parentGet(scope);
9550 throw $compileMinErr('nonassign',
9551 "Expression '{0}' in attribute '{1}' used with directive '{2}' is non-assignable!",
9552 attrs[attrName], attrName, directive.name);
9554 lastValue = destination[scopeName] = parentGet(scope);
9555 var parentValueWatch = function parentValueWatch(parentValue) {
9556 if (!compare(parentValue, destination[scopeName])) {
9557 // we are out of sync and need to copy
9558 if (!compare(parentValue, lastValue)) {
9559 // parent changed and it has precedence
9560 destination[scopeName] = parentValue;
9562 // if the parent can be assigned then do so
9563 parentSet(scope, parentValue = destination[scopeName]);
9566 return lastValue = parentValue;
9568 parentValueWatch.$stateful = true;
9569 if (definition.collection) {
9570 removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
9572 removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
9574 removeWatchCollection.push(removeWatch);
9578 if (!hasOwnProperty.call(attrs, attrName)) {
9579 if (optional) break;
9580 attrs[attrName] = void 0;
9582 if (optional && !attrs[attrName]) break;
9584 parentGet = $parse(attrs[attrName]);
9586 destination[scopeName] = parentGet(scope);
9588 removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
9589 destination[scopeName] = newParentValue;
9590 }, parentGet.literal);
9592 removeWatchCollection.push(removeWatch);
9596 // Don't assign Object.prototype method to scope
9597 parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
9599 // Don't assign noop to destination if expression is not valid
9600 if (parentGet === noop && optional) break;
9602 destination[scopeName] = function(locals) {
9603 return parentGet(scope, locals);
9609 return removeWatchCollection.length && function removeWatches() {
9610 for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
9611 removeWatchCollection[i]();
9618 var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
9620 * Converts all accepted directives format into proper directive name.
9621 * @param name Name to normalize
9623 function directiveNormalize(name) {
9624 return camelCase(name.replace(PREFIX_REGEXP, ''));
9629 * @name $compile.directive.Attributes
9632 * A shared object between directive compile / linking functions which contains normalized DOM
9633 * element attributes. The values reflect current binding state `{{ }}`. The normalization is
9634 * needed since all of these are treated as equivalent in Angular:
9637 * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
9643 * @name $compile.directive.Attributes#$attr
9646 * A map of DOM element attribute names to the normalized name. This is
9647 * needed to do reverse lookup from normalized name back to actual name.
9653 * @name $compile.directive.Attributes#$set
9657 * Set DOM element attribute value.
9660 * @param {string} name Normalized element attribute name of the property to modify. The name is
9661 * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
9662 * property to the original name.
9663 * @param {string} value Value to set the attribute to. The value can be an interpolated string.
9669 * Closure compiler type information
9672 function nodesetLinkingFn(
9673 /* angular.Scope */ scope,
9674 /* NodeList */ nodeList,
9675 /* Element */ rootElement,
9676 /* function(Function) */ boundTranscludeFn
9679 function directiveLinkingFn(
9680 /* nodesetLinkingFn */ nodesetLinkingFn,
9681 /* angular.Scope */ scope,
9683 /* Element */ rootElement,
9684 /* function(Function) */ boundTranscludeFn
9687 function tokenDifference(str1, str2) {
9689 tokens1 = str1.split(/\s+/),
9690 tokens2 = str2.split(/\s+/);
9693 for (var i = 0; i < tokens1.length; i++) {
9694 var token = tokens1[i];
9695 for (var j = 0; j < tokens2.length; j++) {
9696 if (token == tokens2[j]) continue outer;
9698 values += (values.length > 0 ? ' ' : '') + token;
9703 function removeComments(jqNodes) {
9704 jqNodes = jqLite(jqNodes);
9705 var i = jqNodes.length;
9712 var node = jqNodes[i];
9713 if (node.nodeType === NODE_TYPE_COMMENT) {
9714 splice.call(jqNodes, i, 1);
9720 var $controllerMinErr = minErr('$controller');
9723 var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
9724 function identifierForController(controller, ident) {
9725 if (ident && isString(ident)) return ident;
9726 if (isString(controller)) {
9727 var match = CNTRL_REG.exec(controller);
9728 if (match) return match[3];
9735 * @name $controllerProvider
9737 * The {@link ng.$controller $controller service} is used by Angular to create new
9740 * This provider allows controller registration via the
9741 * {@link ng.$controllerProvider#register register} method.
9743 function $ControllerProvider() {
9744 var controllers = {},
9749 * @name $controllerProvider#register
9750 * @param {string|Object} name Controller name, or an object map of controllers where the keys are
9751 * the names and the values are the constructors.
9752 * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
9753 * annotations in the array notation).
9755 this.register = function(name, constructor) {
9756 assertNotHasOwnProperty(name, 'controller');
9757 if (isObject(name)) {
9758 extend(controllers, name);
9760 controllers[name] = constructor;
9766 * @name $controllerProvider#allowGlobals
9767 * @description If called, allows `$controller` to find controller constructors on `window`
9769 this.allowGlobals = function() {
9774 this.$get = ['$injector', '$window', function($injector, $window) {
9779 * @requires $injector
9781 * @param {Function|string} constructor If called with a function then it's considered to be the
9782 * controller constructor function. Otherwise it's considered to be a string which is used
9783 * to retrieve the controller constructor using the following steps:
9785 * * check if a controller with given name is registered via `$controllerProvider`
9786 * * check if evaluating the string on the current scope returns a constructor
9787 * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
9788 * `window` object (not recommended)
9790 * The string can use the `controller as property` syntax, where the controller instance is published
9791 * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
9792 * to work correctly.
9794 * @param {Object} locals Injection locals for Controller.
9795 * @return {Object} Instance of given controller.
9798 * `$controller` service is responsible for instantiating controllers.
9800 * It's just a simple call to {@link auto.$injector $injector}, but extracted into
9801 * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
9803 return function(expression, locals, later, ident) {
9805 // param `later` --- indicates that the controller's constructor is invoked at a later time.
9806 // If true, $controller will allocate the object with the correct
9807 // prototype chain, but will not invoke the controller until a returned
9808 // callback is invoked.
9809 // param `ident` --- An optional label which overrides the label parsed from the controller
9810 // expression, if any.
9811 var instance, match, constructor, identifier;
9812 later = later === true;
9813 if (ident && isString(ident)) {
9817 if (isString(expression)) {
9818 match = expression.match(CNTRL_REG);
9820 throw $controllerMinErr('ctrlfmt',
9821 "Badly formed controller string '{0}'. " +
9822 "Must match `__name__ as __id__` or `__name__`.", expression);
9824 constructor = match[1],
9825 identifier = identifier || match[3];
9826 expression = controllers.hasOwnProperty(constructor)
9827 ? controllers[constructor]
9828 : getter(locals.$scope, constructor, true) ||
9829 (globals ? getter($window, constructor, true) : undefined);
9831 assertArgFn(expression, constructor, true);
9835 // Instantiate controller later:
9836 // This machinery is used to create an instance of the object before calling the
9837 // controller's constructor itself.
9839 // This allows properties to be added to the controller before the constructor is
9840 // invoked. Primarily, this is used for isolate scope bindings in $compile.
9842 // This feature is not intended for use by applications, and is thus not documented
9844 // Object creation: http://jsperf.com/create-constructor/2
9845 var controllerPrototype = (isArray(expression) ?
9846 expression[expression.length - 1] : expression).prototype;
9847 instance = Object.create(controllerPrototype || null);
9850 addIdentifier(locals, identifier, instance, constructor || expression.name);
9854 return instantiate = extend(function() {
9855 var result = $injector.invoke(expression, instance, locals, constructor);
9856 if (result !== instance && (isObject(result) || isFunction(result))) {
9859 // If result changed, re-assign controllerAs value to scope.
9860 addIdentifier(locals, identifier, instance, constructor || expression.name);
9866 identifier: identifier
9870 instance = $injector.instantiate(expression, locals, constructor);
9873 addIdentifier(locals, identifier, instance, constructor || expression.name);
9879 function addIdentifier(locals, identifier, instance, name) {
9880 if (!(locals && isObject(locals.$scope))) {
9881 throw minErr('$controller')('noscp',
9882 "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
9886 locals.$scope[identifier] = instance;
9897 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
9900 <example module="documentExample">
9901 <file name="index.html">
9902 <div ng-controller="ExampleController">
9903 <p>$document title: <b ng-bind="title"></b></p>
9904 <p>window.document title: <b ng-bind="windowTitle"></b></p>
9907 <file name="script.js">
9908 angular.module('documentExample', [])
9909 .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
9910 $scope.title = $document[0].title;
9911 $scope.windowTitle = angular.element(window.document)[0].title;
9916 function $DocumentProvider() {
9917 this.$get = ['$window', function(window) {
9918 return jqLite(window.document);
9924 * @name $exceptionHandler
9928 * Any uncaught exception in angular expressions is delegated to this service.
9929 * The default implementation simply delegates to `$log.error` which logs it into
9930 * the browser console.
9932 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
9933 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
9938 * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
9939 * return function(exception, cause) {
9940 * exception.message += ' (caused by "' + cause + '")';
9946 * This example will override the normal action of `$exceptionHandler`, to make angular
9947 * exceptions fail hard when they happen, instead of just logging to the console.
9950 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
9951 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
9952 * (unless executed during a digest).
9954 * If you wish, you can manually delegate exceptions, e.g.
9955 * `try { ... } catch(e) { $exceptionHandler(e); }`
9957 * @param {Error} exception Exception associated with the error.
9958 * @param {string=} cause optional information about the context in which
9959 * the error was thrown.
9962 function $ExceptionHandlerProvider() {
9963 this.$get = ['$log', function($log) {
9964 return function(exception, cause) {
9965 $log.error.apply($log, arguments);
9970 var $$ForceReflowProvider = function() {
9971 this.$get = ['$document', function($document) {
9972 return function(domNode) {
9973 //the line below will force the browser to perform a repaint so
9974 //that all the animated elements within the animation frame will
9975 //be properly updated and drawn on screen. This is required to
9976 //ensure that the preparation animation is properly flushed so that
9977 //the active state picks up from there. DO NOT REMOVE THIS LINE.
9978 //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
9979 //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
9980 //WILL TAKE YEARS AWAY FROM YOUR LIFE.
9982 if (!domNode.nodeType && domNode instanceof jqLite) {
9983 domNode = domNode[0];
9986 domNode = $document[0].body;
9988 return domNode.offsetWidth + 1;
9993 var APPLICATION_JSON = 'application/json';
9994 var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
9995 var JSON_START = /^\[|^\{(?!\{)/;
10000 var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
10001 var $httpMinErr = minErr('$http');
10002 var $httpMinErrLegacyFn = function(method) {
10003 return function() {
10004 throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
10008 function serializeValue(v) {
10010 return isDate(v) ? v.toISOString() : toJson(v);
10016 function $HttpParamSerializerProvider() {
10019 * @name $httpParamSerializer
10022 * Default {@link $http `$http`} params serializer that converts objects to strings
10023 * according to the following rules:
10025 * * `{'foo': 'bar'}` results in `foo=bar`
10026 * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
10027 * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
10028 * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
10030 * Note that serializer will sort the request parameters alphabetically.
10033 this.$get = function() {
10034 return function ngParamSerializer(params) {
10035 if (!params) return '';
10037 forEachSorted(params, function(value, key) {
10038 if (value === null || isUndefined(value)) return;
10039 if (isArray(value)) {
10040 forEach(value, function(v, k) {
10041 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
10044 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
10048 return parts.join('&');
10053 function $HttpParamSerializerJQLikeProvider() {
10056 * @name $httpParamSerializerJQLike
10059 * Alternative {@link $http `$http`} params serializer that follows
10060 * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
10061 * The serializer will also sort the params alphabetically.
10063 * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
10069 * params: myParams,
10070 * paramSerializer: '$httpParamSerializerJQLike'
10074 * It is also possible to set it as the default `paramSerializer` in the
10075 * {@link $httpProvider#defaults `$httpProvider`}.
10077 * Additionally, you can inject the serializer and use it explicitly, for example to serialize
10078 * form data for submission:
10081 * .controller(function($http, $httpParamSerializerJQLike) {
10087 * data: $httpParamSerializerJQLike(myData),
10089 * 'Content-Type': 'application/x-www-form-urlencoded'
10097 this.$get = function() {
10098 return function jQueryLikeParamSerializer(params) {
10099 if (!params) return '';
10101 serialize(params, '', true);
10102 return parts.join('&');
10104 function serialize(toSerialize, prefix, topLevel) {
10105 if (toSerialize === null || isUndefined(toSerialize)) return;
10106 if (isArray(toSerialize)) {
10107 forEach(toSerialize, function(value, index) {
10108 serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
10110 } else if (isObject(toSerialize) && !isDate(toSerialize)) {
10111 forEachSorted(toSerialize, function(value, key) {
10112 serialize(value, prefix +
10113 (topLevel ? '' : '[') +
10115 (topLevel ? '' : ']'));
10118 parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
10125 function defaultHttpResponseTransform(data, headers) {
10126 if (isString(data)) {
10127 // Strip json vulnerability protection prefix and trim whitespace
10128 var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
10131 var contentType = headers('Content-Type');
10132 if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
10133 data = fromJson(tempData);
10141 function isJsonLike(str) {
10142 var jsonStart = str.match(JSON_START);
10143 return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
10147 * Parse headers into key value object
10149 * @param {string} headers Raw headers as a string
10150 * @returns {Object} Parsed headers as key value object
10152 function parseHeaders(headers) {
10153 var parsed = createMap(), i;
10155 function fillInParsed(key, val) {
10157 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
10161 if (isString(headers)) {
10162 forEach(headers.split('\n'), function(line) {
10163 i = line.indexOf(':');
10164 fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
10166 } else if (isObject(headers)) {
10167 forEach(headers, function(headerVal, headerKey) {
10168 fillInParsed(lowercase(headerKey), trim(headerVal));
10177 * Returns a function that provides access to parsed headers.
10179 * Headers are lazy parsed when first requested.
10180 * @see parseHeaders
10182 * @param {(string|Object)} headers Headers to provide access to.
10183 * @returns {function(string=)} Returns a getter function which if called with:
10185 * - if called with single an argument returns a single header value or null
10186 * - if called with no arguments returns an object containing all headers.
10188 function headersGetter(headers) {
10191 return function(name) {
10192 if (!headersObj) headersObj = parseHeaders(headers);
10195 var value = headersObj[lowercase(name)];
10196 if (value === void 0) {
10208 * Chain all given functions
10210 * This function is used for both request and response transforming
10212 * @param {*} data Data to transform.
10213 * @param {function(string=)} headers HTTP headers getter fn.
10214 * @param {number} status HTTP status code of the response.
10215 * @param {(Function|Array.<Function>)} fns Function or an array of functions.
10216 * @returns {*} Transformed data.
10218 function transformData(data, headers, status, fns) {
10219 if (isFunction(fns)) {
10220 return fns(data, headers, status);
10223 forEach(fns, function(fn) {
10224 data = fn(data, headers, status);
10231 function isSuccess(status) {
10232 return 200 <= status && status < 300;
10238 * @name $httpProvider
10240 * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
10242 function $HttpProvider() {
10245 * @name $httpProvider#defaults
10248 * Object containing default values for all {@link ng.$http $http} requests.
10250 * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
10251 * that will provide the cache for all requests who set their `cache` property to `true`.
10252 * If you set the `defaults.cache = false` then only requests that specify their own custom
10253 * cache object will be cached. See {@link $http#caching $http Caching} for more information.
10255 * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
10256 * Defaults value is `'XSRF-TOKEN'`.
10258 * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
10259 * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
10261 * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
10262 * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
10263 * setting default headers.
10264 * - **`defaults.headers.common`**
10265 * - **`defaults.headers.post`**
10266 * - **`defaults.headers.put`**
10267 * - **`defaults.headers.patch`**
10270 * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
10271 * used to the prepare string representation of request parameters (specified as an object).
10272 * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
10273 * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
10276 var defaults = this.defaults = {
10277 // transform incoming response data
10278 transformResponse: [defaultHttpResponseTransform],
10280 // transform outgoing request data
10281 transformRequest: [function(d) {
10282 return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
10288 'Accept': 'application/json, text/plain, */*'
10290 post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
10291 put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
10292 patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
10295 xsrfCookieName: 'XSRF-TOKEN',
10296 xsrfHeaderName: 'X-XSRF-TOKEN',
10298 paramSerializer: '$httpParamSerializer'
10301 var useApplyAsync = false;
10304 * @name $httpProvider#useApplyAsync
10307 * Configure $http service to combine processing of multiple http responses received at around
10308 * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
10309 * significant performance improvement for bigger applications that make many HTTP requests
10310 * concurrently (common during application bootstrap).
10312 * Defaults to false. If no value is specified, returns the current configured value.
10314 * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
10315 * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
10316 * to load and share the same digest cycle.
10318 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
10319 * otherwise, returns the current configured value.
10321 this.useApplyAsync = function(value) {
10322 if (isDefined(value)) {
10323 useApplyAsync = !!value;
10326 return useApplyAsync;
10329 var useLegacyPromise = true;
10332 * @name $httpProvider#useLegacyPromiseExtensions
10335 * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
10336 * This should be used to make sure that applications work without these methods.
10338 * Defaults to true. If no value is specified, returns the current configured value.
10340 * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
10342 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
10343 * otherwise, returns the current configured value.
10345 this.useLegacyPromiseExtensions = function(value) {
10346 if (isDefined(value)) {
10347 useLegacyPromise = !!value;
10350 return useLegacyPromise;
10355 * @name $httpProvider#interceptors
10358 * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
10359 * pre-processing of request or postprocessing of responses.
10361 * These service factories are ordered by request, i.e. they are applied in the same order as the
10362 * array, on request, but reverse order, on response.
10364 * {@link ng.$http#interceptors Interceptors detailed info}
10366 var interceptorFactories = this.interceptors = [];
10368 this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
10369 function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
10371 var defaultCache = $cacheFactory('$http');
10374 * Make sure that default param serializer is exposed as a function
10376 defaults.paramSerializer = isString(defaults.paramSerializer) ?
10377 $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
10380 * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
10381 * The reversal is needed so that we can build up the interception chain around the
10384 var reversedInterceptors = [];
10386 forEach(interceptorFactories, function(interceptorFactory) {
10387 reversedInterceptors.unshift(isString(interceptorFactory)
10388 ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
10395 * @requires ng.$httpBackend
10396 * @requires $cacheFactory
10397 * @requires $rootScope
10399 * @requires $injector
10402 * The `$http` service is a core Angular service that facilitates communication with the remote
10403 * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
10404 * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
10406 * For unit testing applications that use `$http` service, see
10407 * {@link ngMock.$httpBackend $httpBackend mock}.
10409 * For a higher level of abstraction, please check out the {@link ngResource.$resource
10410 * $resource} service.
10412 * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
10413 * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
10414 * it is important to familiarize yourself with these APIs and the guarantees they provide.
10418 * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
10419 * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
10422 * // Simple GET request example:
10426 * }).then(function successCallback(response) {
10427 * // this callback will be called asynchronously
10428 * // when the response is available
10429 * }, function errorCallback(response) {
10430 * // called asynchronously if an error occurs
10431 * // or server returns response with an error status.
10435 * The response object has these properties:
10437 * - **data** – `{string|Object}` – The response body transformed with the transform
10439 * - **status** – `{number}` – HTTP status code of the response.
10440 * - **headers** – `{function([headerName])}` – Header getter function.
10441 * - **config** – `{Object}` – The configuration object that was used to generate the request.
10442 * - **statusText** – `{string}` – HTTP status text of the response.
10444 * A response status code between 200 and 299 is considered a success status and
10445 * will result in the success callback being called. Note that if the response is a redirect,
10446 * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
10447 * called for such responses.
10450 * ## Shortcut methods
10452 * Shortcut methods are also available. All shortcut methods require passing in the URL, and
10453 * request data must be passed in for POST/PUT requests. An optional config can be passed as the
10457 * $http.get('/someUrl', config).then(successCallback, errorCallback);
10458 * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
10461 * Complete list of shortcut methods:
10463 * - {@link ng.$http#get $http.get}
10464 * - {@link ng.$http#head $http.head}
10465 * - {@link ng.$http#post $http.post}
10466 * - {@link ng.$http#put $http.put}
10467 * - {@link ng.$http#delete $http.delete}
10468 * - {@link ng.$http#jsonp $http.jsonp}
10469 * - {@link ng.$http#patch $http.patch}
10472 * ## Writing Unit Tests that use $http
10473 * When unit testing (using {@link ngMock ngMock}), it is necessary to call
10474 * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
10475 * request using trained responses.
10478 * $httpBackend.expectGET(...);
10480 * $httpBackend.flush();
10483 * ## Deprecation Notice
10484 * <div class="alert alert-danger">
10485 * The `$http` legacy promise methods `success` and `error` have been deprecated.
10486 * Use the standard `then` method instead.
10487 * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
10488 * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
10491 * ## Setting HTTP Headers
10493 * The $http service will automatically add certain HTTP headers to all requests. These defaults
10494 * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
10495 * object, which currently contains this default configuration:
10497 * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
10498 * - `Accept: application/json, text/plain, * / *`
10499 * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
10500 * - `Content-Type: application/json`
10501 * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
10502 * - `Content-Type: application/json`
10504 * To add or overwrite these defaults, simply add or remove a property from these configuration
10505 * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
10506 * with the lowercased HTTP method name as the key, e.g.
10507 * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
10509 * The defaults can also be set at runtime via the `$http.defaults` object in the same
10510 * fashion. For example:
10513 * module.run(function($http) {
10514 * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
10518 * In addition, you can supply a `headers` property in the config object passed when
10519 * calling `$http(config)`, which overrides the defaults without changing them globally.
10521 * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
10522 * Use the `headers` property, setting the desired header to `undefined`. For example:
10527 * url: 'http://example.com',
10529 * 'Content-Type': undefined
10531 * data: { test: 'test' }
10534 * $http(req).then(function(){...}, function(){...});
10537 * ## Transforming Requests and Responses
10539 * Both requests and responses can be transformed using transformation functions: `transformRequest`
10540 * and `transformResponse`. These properties can be a single function that returns
10541 * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
10542 * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
10544 * ### Default Transformations
10546 * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
10547 * `defaults.transformResponse` properties. If a request does not provide its own transformations
10548 * then these will be applied.
10550 * You can augment or replace the default transformations by modifying these properties by adding to or
10551 * replacing the array.
10553 * Angular provides the following default transformations:
10555 * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
10557 * - If the `data` property of the request configuration object contains an object, serialize it
10558 * into JSON format.
10560 * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
10562 * - If XSRF prefix is detected, strip it (see Security Considerations section below).
10563 * - If JSON response is detected, deserialize it using a JSON parser.
10566 * ### Overriding the Default Transformations Per Request
10568 * If you wish override the request/response transformations only for a single request then provide
10569 * `transformRequest` and/or `transformResponse` properties on the configuration object passed
10572 * Note that if you provide these properties on the config object the default transformations will be
10573 * overwritten. If you wish to augment the default transformations then you must include them in your
10574 * local transformation array.
10576 * The following code demonstrates adding a new response transformation to be run after the default response
10577 * transformations have been run.
10580 * function appendTransform(defaults, transform) {
10582 * // We can't guarantee that the default transformation is an array
10583 * defaults = angular.isArray(defaults) ? defaults : [defaults];
10585 * // Append the new transformation to the defaults
10586 * return defaults.concat(transform);
10592 * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
10593 * return doTransform(value);
10601 * To enable caching, set the request configuration `cache` property to `true` (to use default
10602 * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
10603 * When the cache is enabled, `$http` stores the response from the server in the specified
10604 * cache. The next time the same request is made, the response is served from the cache without
10605 * sending a request to the server.
10607 * Note that even if the response is served from cache, delivery of the data is asynchronous in
10608 * the same way that real requests are.
10610 * If there are multiple GET requests for the same URL that should be cached using the same
10611 * cache, but the cache is not populated yet, only one request to the server will be made and
10612 * the remaining requests will be fulfilled using the response from the first request.
10614 * You can change the default cache to a new object (built with
10615 * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
10616 * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
10617 * their `cache` property to `true` will now use this cache object.
10619 * If you set the default cache to `false` then only requests that specify their own custom
10620 * cache object will be cached.
10624 * Before you start creating interceptors, be sure to understand the
10625 * {@link ng.$q $q and deferred/promise APIs}.
10627 * For purposes of global error handling, authentication, or any kind of synchronous or
10628 * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
10629 * able to intercept requests before they are handed to the server and
10630 * responses before they are handed over to the application code that
10631 * initiated these requests. The interceptors leverage the {@link ng.$q
10632 * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
10634 * The interceptors are service factories that are registered with the `$httpProvider` by
10635 * adding them to the `$httpProvider.interceptors` array. The factory is called and
10636 * injected with dependencies (if specified) and returns the interceptor.
10638 * There are two kinds of interceptors (and two kinds of rejection interceptors):
10640 * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
10641 * modify the `config` object or create a new one. The function needs to return the `config`
10642 * object directly, or a promise containing the `config` or a new `config` object.
10643 * * `requestError`: interceptor gets called when a previous interceptor threw an error or
10644 * resolved with a rejection.
10645 * * `response`: interceptors get called with http `response` object. The function is free to
10646 * modify the `response` object or create a new one. The function needs to return the `response`
10647 * object directly, or as a promise containing the `response` or a new `response` object.
10648 * * `responseError`: interceptor gets called when a previous interceptor threw an error or
10649 * resolved with a rejection.
10653 * // register the interceptor as a service
10654 * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
10656 * // optional method
10657 * 'request': function(config) {
10658 * // do something on success
10662 * // optional method
10663 * 'requestError': function(rejection) {
10664 * // do something on error
10665 * if (canRecover(rejection)) {
10666 * return responseOrNewPromise
10668 * return $q.reject(rejection);
10673 * // optional method
10674 * 'response': function(response) {
10675 * // do something on success
10679 * // optional method
10680 * 'responseError': function(rejection) {
10681 * // do something on error
10682 * if (canRecover(rejection)) {
10683 * return responseOrNewPromise
10685 * return $q.reject(rejection);
10690 * $httpProvider.interceptors.push('myHttpInterceptor');
10693 * // alternatively, register the interceptor via an anonymous factory
10694 * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
10696 * 'request': function(config) {
10700 * 'response': function(response) {
10707 * ## Security Considerations
10709 * When designing web applications, consider security threats from:
10711 * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
10712 * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
10714 * Both server and the client must cooperate in order to eliminate these threats. Angular comes
10715 * pre-configured with strategies that address these issues, but for this to work backend server
10716 * cooperation is required.
10718 * ### JSON Vulnerability Protection
10720 * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
10721 * allows third party website to turn your JSON resource URL into
10722 * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
10723 * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
10724 * Angular will automatically strip the prefix before processing it as JSON.
10726 * For example if your server needs to return:
10731 * which is vulnerable to attack, your server can return:
10737 * Angular will strip the prefix, before processing the JSON.
10740 * ### Cross Site Request Forgery (XSRF) Protection
10742 * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
10743 * which the attacker can trick an authenticated user into unknowingly executing actions on your
10744 * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
10745 * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
10746 * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
10747 * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
10748 * The header will not be set for cross-domain requests.
10750 * To take advantage of this, your server needs to set a token in a JavaScript readable session
10751 * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
10752 * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
10753 * that only JavaScript running on your domain could have sent the request. The token must be
10754 * unique for each user and must be verifiable by the server (to prevent the JavaScript from
10755 * making up its own tokens). We recommend that the token is a digest of your site's
10756 * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
10757 * for added security.
10759 * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
10760 * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
10761 * or the per-request config object.
10763 * In order to prevent collisions in environments where multiple Angular apps share the
10764 * same domain or subdomain, we recommend that each application uses unique cookie name.
10766 * @param {object} config Object describing the request to be made and how it should be
10767 * processed. The object has following properties:
10769 * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
10770 * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
10771 * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
10772 * with the `paramSerializer` and appended as GET parameters.
10773 * - **data** – `{string|Object}` – Data to be sent as the request message data.
10774 * - **headers** – `{Object}` – Map of strings or functions which return strings representing
10775 * HTTP headers to send to the server. If the return value of a function is null, the
10776 * header will not be sent. Functions accept a config object as an argument.
10777 * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
10778 * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
10779 * - **transformRequest** –
10780 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
10781 * transform function or an array of such functions. The transform function takes the http
10782 * request body and headers and returns its transformed (typically serialized) version.
10783 * See {@link ng.$http#overriding-the-default-transformations-per-request
10784 * Overriding the Default Transformations}
10785 * - **transformResponse** –
10786 * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
10787 * transform function or an array of such functions. The transform function takes the http
10788 * response body, headers and status and returns its transformed (typically deserialized) version.
10789 * See {@link ng.$http#overriding-the-default-transformations-per-request
10790 * Overriding the Default TransformationjqLiks}
10791 * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
10792 * prepare the string representation of request parameters (specified as an object).
10793 * If specified as string, it is interpreted as function registered with the
10794 * {@link $injector $injector}, which means you can create your own serializer
10795 * by registering it as a {@link auto.$provide#service service}.
10796 * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
10797 * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
10798 * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
10799 * GET request, otherwise if a cache instance built with
10800 * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
10802 * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
10803 * that should abort the request when resolved.
10804 * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
10805 * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
10806 * for more information.
10807 * - **responseType** - `{string}` - see
10808 * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
10810 * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
10811 * when the request succeeds or fails.
10814 * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
10815 * requests. This is primarily meant to be used for debugging purposes.
10819 <example module="httpExample">
10820 <file name="index.html">
10821 <div ng-controller="FetchController">
10822 <select ng-model="method" aria-label="Request method">
10823 <option>GET</option>
10824 <option>JSONP</option>
10826 <input type="text" ng-model="url" size="80" aria-label="URL" />
10827 <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
10828 <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
10829 <button id="samplejsonpbtn"
10830 ng-click="updateModel('JSONP',
10831 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
10834 <button id="invalidjsonpbtn"
10835 ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
10838 <pre>http status code: {{status}}</pre>
10839 <pre>http response data: {{data}}</pre>
10842 <file name="script.js">
10843 angular.module('httpExample', [])
10844 .controller('FetchController', ['$scope', '$http', '$templateCache',
10845 function($scope, $http, $templateCache) {
10846 $scope.method = 'GET';
10847 $scope.url = 'http-hello.html';
10849 $scope.fetch = function() {
10850 $scope.code = null;
10851 $scope.response = null;
10853 $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
10854 then(function(response) {
10855 $scope.status = response.status;
10856 $scope.data = response.data;
10857 }, function(response) {
10858 $scope.data = response.data || "Request failed";
10859 $scope.status = response.status;
10863 $scope.updateModel = function(method, url) {
10864 $scope.method = method;
10869 <file name="http-hello.html">
10872 <file name="protractor.js" type="protractor">
10873 var status = element(by.binding('status'));
10874 var data = element(by.binding('data'));
10875 var fetchBtn = element(by.id('fetchbtn'));
10876 var sampleGetBtn = element(by.id('samplegetbtn'));
10877 var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
10878 var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
10880 it('should make an xhr GET request', function() {
10881 sampleGetBtn.click();
10883 expect(status.getText()).toMatch('200');
10884 expect(data.getText()).toMatch(/Hello, \$http!/);
10887 // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
10888 // it('should make a JSONP request to angularjs.org', function() {
10889 // sampleJsonpBtn.click();
10890 // fetchBtn.click();
10891 // expect(status.getText()).toMatch('200');
10892 // expect(data.getText()).toMatch(/Super Hero!/);
10895 it('should make JSONP request to invalid URL and invoke the error handler',
10897 invalidJsonpBtn.click();
10899 expect(status.getText()).toMatch('0');
10900 expect(data.getText()).toMatch('Request failed');
10905 function $http(requestConfig) {
10907 if (!isObject(requestConfig)) {
10908 throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
10911 if (!isString(requestConfig.url)) {
10912 throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
10915 var config = extend({
10917 transformRequest: defaults.transformRequest,
10918 transformResponse: defaults.transformResponse,
10919 paramSerializer: defaults.paramSerializer
10922 config.headers = mergeHeaders(requestConfig);
10923 config.method = uppercase(config.method);
10924 config.paramSerializer = isString(config.paramSerializer) ?
10925 $injector.get(config.paramSerializer) : config.paramSerializer;
10927 var serverRequest = function(config) {
10928 var headers = config.headers;
10929 var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
10931 // strip content-type if data is undefined
10932 if (isUndefined(reqData)) {
10933 forEach(headers, function(value, header) {
10934 if (lowercase(header) === 'content-type') {
10935 delete headers[header];
10940 if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
10941 config.withCredentials = defaults.withCredentials;
10945 return sendReq(config, reqData).then(transformResponse, transformResponse);
10948 var chain = [serverRequest, undefined];
10949 var promise = $q.when(config);
10951 // apply interceptors
10952 forEach(reversedInterceptors, function(interceptor) {
10953 if (interceptor.request || interceptor.requestError) {
10954 chain.unshift(interceptor.request, interceptor.requestError);
10956 if (interceptor.response || interceptor.responseError) {
10957 chain.push(interceptor.response, interceptor.responseError);
10961 while (chain.length) {
10962 var thenFn = chain.shift();
10963 var rejectFn = chain.shift();
10965 promise = promise.then(thenFn, rejectFn);
10968 if (useLegacyPromise) {
10969 promise.success = function(fn) {
10970 assertArgFn(fn, 'fn');
10972 promise.then(function(response) {
10973 fn(response.data, response.status, response.headers, config);
10978 promise.error = function(fn) {
10979 assertArgFn(fn, 'fn');
10981 promise.then(null, function(response) {
10982 fn(response.data, response.status, response.headers, config);
10987 promise.success = $httpMinErrLegacyFn('success');
10988 promise.error = $httpMinErrLegacyFn('error');
10993 function transformResponse(response) {
10994 // make a copy since the response must be cacheable
10995 var resp = extend({}, response);
10996 resp.data = transformData(response.data, response.headers, response.status,
10997 config.transformResponse);
10998 return (isSuccess(response.status))
11003 function executeHeaderFns(headers, config) {
11004 var headerContent, processedHeaders = {};
11006 forEach(headers, function(headerFn, header) {
11007 if (isFunction(headerFn)) {
11008 headerContent = headerFn(config);
11009 if (headerContent != null) {
11010 processedHeaders[header] = headerContent;
11013 processedHeaders[header] = headerFn;
11017 return processedHeaders;
11020 function mergeHeaders(config) {
11021 var defHeaders = defaults.headers,
11022 reqHeaders = extend({}, config.headers),
11023 defHeaderName, lowercaseDefHeaderName, reqHeaderName;
11025 defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
11027 // using for-in instead of forEach to avoid unnecessary iteration after header has been found
11028 defaultHeadersIteration:
11029 for (defHeaderName in defHeaders) {
11030 lowercaseDefHeaderName = lowercase(defHeaderName);
11032 for (reqHeaderName in reqHeaders) {
11033 if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
11034 continue defaultHeadersIteration;
11038 reqHeaders[defHeaderName] = defHeaders[defHeaderName];
11041 // execute if header value is a function for merged headers
11042 return executeHeaderFns(reqHeaders, shallowCopy(config));
11046 $http.pendingRequests = [];
11053 * Shortcut method to perform `GET` request.
11055 * @param {string} url Relative or absolute URL specifying the destination of the request
11056 * @param {Object=} config Optional configuration object
11057 * @returns {HttpPromise} Future object
11062 * @name $http#delete
11065 * Shortcut method to perform `DELETE` request.
11067 * @param {string} url Relative or absolute URL specifying the destination of the request
11068 * @param {Object=} config Optional configuration object
11069 * @returns {HttpPromise} Future object
11077 * Shortcut method to perform `HEAD` request.
11079 * @param {string} url Relative or absolute URL specifying the destination of the request
11080 * @param {Object=} config Optional configuration object
11081 * @returns {HttpPromise} Future object
11086 * @name $http#jsonp
11089 * Shortcut method to perform `JSONP` request.
11091 * @param {string} url Relative or absolute URL specifying the destination of the request.
11092 * The name of the callback should be the string `JSON_CALLBACK`.
11093 * @param {Object=} config Optional configuration object
11094 * @returns {HttpPromise} Future object
11096 createShortMethods('get', 'delete', 'head', 'jsonp');
11103 * Shortcut method to perform `POST` request.
11105 * @param {string} url Relative or absolute URL specifying the destination of the request
11106 * @param {*} data Request content
11107 * @param {Object=} config Optional configuration object
11108 * @returns {HttpPromise} Future object
11116 * Shortcut method to perform `PUT` request.
11118 * @param {string} url Relative or absolute URL specifying the destination of the request
11119 * @param {*} data Request content
11120 * @param {Object=} config Optional configuration object
11121 * @returns {HttpPromise} Future object
11126 * @name $http#patch
11129 * Shortcut method to perform `PATCH` request.
11131 * @param {string} url Relative or absolute URL specifying the destination of the request
11132 * @param {*} data Request content
11133 * @param {Object=} config Optional configuration object
11134 * @returns {HttpPromise} Future object
11136 createShortMethodsWithData('post', 'put', 'patch');
11140 * @name $http#defaults
11143 * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
11144 * default headers, withCredentials as well as request and response transformations.
11146 * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
11148 $http.defaults = defaults;
11154 function createShortMethods(names) {
11155 forEach(arguments, function(name) {
11156 $http[name] = function(url, config) {
11157 return $http(extend({}, config || {}, {
11166 function createShortMethodsWithData(name) {
11167 forEach(arguments, function(name) {
11168 $http[name] = function(url, data, config) {
11169 return $http(extend({}, config || {}, {
11180 * Makes the request.
11182 * !!! ACCESSES CLOSURE VARS:
11183 * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
11185 function sendReq(config, reqData) {
11186 var deferred = $q.defer(),
11187 promise = deferred.promise,
11190 reqHeaders = config.headers,
11191 url = buildUrl(config.url, config.paramSerializer(config.params));
11193 $http.pendingRequests.push(config);
11194 promise.then(removePendingReq, removePendingReq);
11197 if ((config.cache || defaults.cache) && config.cache !== false &&
11198 (config.method === 'GET' || config.method === 'JSONP')) {
11199 cache = isObject(config.cache) ? config.cache
11200 : isObject(defaults.cache) ? defaults.cache
11205 cachedResp = cache.get(url);
11206 if (isDefined(cachedResp)) {
11207 if (isPromiseLike(cachedResp)) {
11208 // cached request has already been sent, but there is no response yet
11209 cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
11211 // serving from cache
11212 if (isArray(cachedResp)) {
11213 resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
11215 resolvePromise(cachedResp, 200, {}, 'OK');
11219 // put the promise for the non-transformed response into cache as a placeholder
11220 cache.put(url, promise);
11225 // if we won't have the response in cache, set the xsrf headers and
11226 // send the request to the backend
11227 if (isUndefined(cachedResp)) {
11228 var xsrfValue = urlIsSameOrigin(config.url)
11229 ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
11232 reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
11235 $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
11236 config.withCredentials, config.responseType);
11243 * Callback registered to $httpBackend():
11244 * - caches the response if desired
11245 * - resolves the raw $http promise
11248 function done(status, response, headersString, statusText) {
11250 if (isSuccess(status)) {
11251 cache.put(url, [status, response, parseHeaders(headersString), statusText]);
11253 // remove promise from the cache
11258 function resolveHttpPromise() {
11259 resolvePromise(response, status, headersString, statusText);
11262 if (useApplyAsync) {
11263 $rootScope.$applyAsync(resolveHttpPromise);
11265 resolveHttpPromise();
11266 if (!$rootScope.$$phase) $rootScope.$apply();
11272 * Resolves the raw $http promise.
11274 function resolvePromise(response, status, headers, statusText) {
11275 //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
11276 status = status >= -1 ? status : 0;
11278 (isSuccess(status) ? deferred.resolve : deferred.reject)({
11281 headers: headersGetter(headers),
11283 statusText: statusText
11287 function resolvePromiseWithResult(result) {
11288 resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
11291 function removePendingReq() {
11292 var idx = $http.pendingRequests.indexOf(config);
11293 if (idx !== -1) $http.pendingRequests.splice(idx, 1);
11298 function buildUrl(url, serializedParams) {
11299 if (serializedParams.length > 0) {
11300 url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
11309 * @name $xhrFactory
11312 * Factory function used to create XMLHttpRequest objects.
11314 * Replace or decorate this service to create your own custom XMLHttpRequest objects.
11317 * angular.module('myApp', [])
11318 * .factory('$xhrFactory', function() {
11319 * return function createXhr(method, url) {
11320 * return new window.XMLHttpRequest({mozSystem: true});
11325 * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
11326 * @param {string} url URL of the request.
11328 function $xhrFactoryProvider() {
11329 this.$get = function() {
11330 return function createXhr() {
11331 return new window.XMLHttpRequest();
11338 * @name $httpBackend
11339 * @requires $window
11340 * @requires $document
11341 * @requires $xhrFactory
11344 * HTTP backend used by the {@link ng.$http service} that delegates to
11345 * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
11347 * You should never need to use this service directly, instead use the higher-level abstractions:
11348 * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
11350 * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
11351 * $httpBackend} which can be trained with responses.
11353 function $HttpBackendProvider() {
11354 this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
11355 return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
11359 function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
11360 // TODO(vojta): fix the signature
11361 return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
11362 $browser.$$incOutstandingRequestCount();
11363 url = url || $browser.url();
11365 if (lowercase(method) == 'jsonp') {
11366 var callbackId = '_' + (callbacks.counter++).toString(36);
11367 callbacks[callbackId] = function(data) {
11368 callbacks[callbackId].data = data;
11369 callbacks[callbackId].called = true;
11372 var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
11373 callbackId, function(status, text) {
11374 completeRequest(callback, status, callbacks[callbackId].data, "", text);
11375 callbacks[callbackId] = noop;
11379 var xhr = createXhr(method, url);
11381 xhr.open(method, url, true);
11382 forEach(headers, function(value, key) {
11383 if (isDefined(value)) {
11384 xhr.setRequestHeader(key, value);
11388 xhr.onload = function requestLoaded() {
11389 var statusText = xhr.statusText || '';
11391 // responseText is the old-school way of retrieving response (supported by IE9)
11392 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
11393 var response = ('response' in xhr) ? xhr.response : xhr.responseText;
11395 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
11396 var status = xhr.status === 1223 ? 204 : xhr.status;
11398 // fix status code when it is 0 (0 status is undocumented).
11399 // Occurs when accessing file resources or on Android 4.1 stock browser
11400 // while retrieving files from application cache.
11401 if (status === 0) {
11402 status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
11405 completeRequest(callback,
11408 xhr.getAllResponseHeaders(),
11412 var requestError = function() {
11413 // The response is always empty
11414 // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
11415 completeRequest(callback, -1, null, null, '');
11418 xhr.onerror = requestError;
11419 xhr.onabort = requestError;
11421 if (withCredentials) {
11422 xhr.withCredentials = true;
11425 if (responseType) {
11427 xhr.responseType = responseType;
11429 // WebKit added support for the json responseType value on 09/03/2013
11430 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
11431 // known to throw when setting the value "json" as the response type. Other older
11432 // browsers implementing the responseType
11434 // The json response type can be ignored if not supported, because JSON payloads are
11435 // parsed on the client-side regardless.
11436 if (responseType !== 'json') {
11442 xhr.send(isUndefined(post) ? null : post);
11446 var timeoutId = $browserDefer(timeoutRequest, timeout);
11447 } else if (isPromiseLike(timeout)) {
11448 timeout.then(timeoutRequest);
11452 function timeoutRequest() {
11453 jsonpDone && jsonpDone();
11454 xhr && xhr.abort();
11457 function completeRequest(callback, status, response, headersString, statusText) {
11458 // cancel timeout and subsequent timeout promise resolution
11459 if (isDefined(timeoutId)) {
11460 $browserDefer.cancel(timeoutId);
11462 jsonpDone = xhr = null;
11464 callback(status, response, headersString, statusText);
11465 $browser.$$completeOutstandingRequest(noop);
11469 function jsonpReq(url, callbackId, done) {
11470 // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
11471 // - fetches local scripts via XHR and evals them
11472 // - adds and immediately removes script elements from the document
11473 var script = rawDocument.createElement('script'), callback = null;
11474 script.type = "text/javascript";
11476 script.async = true;
11478 callback = function(event) {
11479 removeEventListenerFn(script, "load", callback);
11480 removeEventListenerFn(script, "error", callback);
11481 rawDocument.body.removeChild(script);
11484 var text = "unknown";
11487 if (event.type === "load" && !callbacks[callbackId].called) {
11488 event = { type: "error" };
11491 status = event.type === "error" ? 404 : 200;
11495 done(status, text);
11499 addEventListenerFn(script, "load", callback);
11500 addEventListenerFn(script, "error", callback);
11501 rawDocument.body.appendChild(script);
11506 var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
11507 $interpolateMinErr.throwNoconcat = function(text) {
11508 throw $interpolateMinErr('noconcat',
11509 "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
11510 "interpolations that concatenate multiple expressions when a trusted value is " +
11511 "required. See http://docs.angularjs.org/api/ng.$sce", text);
11514 $interpolateMinErr.interr = function(text, err) {
11515 return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
11520 * @name $interpolateProvider
11524 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
11526 * <div class="alert alert-danger">
11527 * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
11528 * template within a Python Jinja template (or any other template language). Mixing templating
11529 * languages is **very dangerous**. The embedding template language will not safely escape Angular
11530 * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
11535 <example name="custom-interpolation-markup" module="customInterpolationApp">
11536 <file name="index.html">
11538 var customInterpolationApp = angular.module('customInterpolationApp', []);
11540 customInterpolationApp.config(function($interpolateProvider) {
11541 $interpolateProvider.startSymbol('//');
11542 $interpolateProvider.endSymbol('//');
11546 customInterpolationApp.controller('DemoController', function() {
11547 this.label = "This binding is brought you by // interpolation symbols.";
11550 <div ng-controller="DemoController as demo">
11554 <file name="protractor.js" type="protractor">
11555 it('should interpolate binding with custom symbols', function() {
11556 expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
11561 function $InterpolateProvider() {
11562 var startSymbol = '{{';
11563 var endSymbol = '}}';
11567 * @name $interpolateProvider#startSymbol
11569 * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
11571 * @param {string=} value new value to set the starting symbol to.
11572 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
11574 this.startSymbol = function(value) {
11576 startSymbol = value;
11579 return startSymbol;
11585 * @name $interpolateProvider#endSymbol
11587 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
11589 * @param {string=} value new value to set the ending symbol to.
11590 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
11592 this.endSymbol = function(value) {
11602 this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
11603 var startSymbolLength = startSymbol.length,
11604 endSymbolLength = endSymbol.length,
11605 escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
11606 escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
11608 function escape(ch) {
11609 return '\\\\\\' + ch;
11612 function unescapeText(text) {
11613 return text.replace(escapedStartRegexp, startSymbol).
11614 replace(escapedEndRegexp, endSymbol);
11617 function stringify(value) {
11618 if (value == null) { // null || undefined
11621 switch (typeof value) {
11625 value = '' + value;
11628 value = toJson(value);
11634 //TODO: this is the same as the constantWatchDelegate in parse.js
11635 function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
11637 return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
11639 return constantInterp(scope);
11640 }, listener, objectEquality);
11645 * @name $interpolate
11653 * Compiles a string with markup into an interpolation function. This service is used by the
11654 * HTML {@link ng.$compile $compile} service for data binding. See
11655 * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
11656 * interpolation markup.
11660 * var $interpolate = ...; // injected
11661 * var exp = $interpolate('Hello {{name | uppercase}}!');
11662 * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
11665 * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
11666 * `true`, the interpolation function will return `undefined` unless all embedded expressions
11667 * evaluate to a value other than `undefined`.
11670 * var $interpolate = ...; // injected
11671 * var context = {greeting: 'Hello', name: undefined };
11673 * // default "forgiving" mode
11674 * var exp = $interpolate('{{greeting}} {{name}}!');
11675 * expect(exp(context)).toEqual('Hello !');
11677 * // "allOrNothing" mode
11678 * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
11679 * expect(exp(context)).toBeUndefined();
11680 * context.name = 'Angular';
11681 * expect(exp(context)).toEqual('Hello Angular!');
11684 * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
11686 * ####Escaped Interpolation
11687 * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
11688 * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
11689 * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
11692 * This enables web-servers to prevent script injection attacks and defacing attacks, to some
11693 * degree, while also enabling code examples to work without relying on the
11694 * {@link ng.directive:ngNonBindable ngNonBindable} directive.
11696 * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
11697 * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all
11698 * interpolation start/end markers with their escaped counterparts.**
11700 * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
11701 * output when the $interpolate service processes the text. So, for HTML elements interpolated
11702 * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
11703 * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
11704 * this is typically useful only when user-data is used in rendering a template from the server, or
11705 * when otherwise untrusted data is used by a directive.
11708 * <file name="index.html">
11709 * <div ng-init="username='A user'">
11710 * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
11712 * <p><strong>{{username}}</strong> attempts to inject code which will deface the
11713 * application, but fails to accomplish their task, because the server has correctly
11714 * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
11716 * <p>Instead, the result of the attempted script injection is visible, and can be removed
11717 * from the database by an administrator.</p>
11722 * @param {string} text The text with markup to interpolate.
11723 * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
11724 * embedded expression in order to return an interpolation function. Strings with no
11725 * embedded expression will return null for the interpolation function.
11726 * @param {string=} trustedContext when provided, the returned function passes the interpolated
11727 * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
11728 * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
11729 * provides Strict Contextual Escaping for details.
11730 * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
11731 * unless all embedded expressions evaluate to a value other than `undefined`.
11732 * @returns {function(context)} an interpolation function which is used to compute the
11733 * interpolated string. The function has these parameters:
11735 * - `context`: evaluation context for all expressions embedded in the interpolated text
11737 function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
11738 // Provide a quick exit and simplified result function for text with no interpolation
11739 if (!text.length || text.indexOf(startSymbol) === -1) {
11740 var constantInterp;
11741 if (!mustHaveExpression) {
11742 var unescapedText = unescapeText(text);
11743 constantInterp = valueFn(unescapedText);
11744 constantInterp.exp = text;
11745 constantInterp.expressions = [];
11746 constantInterp.$$watchDelegate = constantWatchDelegate;
11748 return constantInterp;
11751 allOrNothing = !!allOrNothing;
11757 textLength = text.length,
11760 expressionPositions = [];
11762 while (index < textLength) {
11763 if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
11764 ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
11765 if (index !== startIndex) {
11766 concat.push(unescapeText(text.substring(index, startIndex)));
11768 exp = text.substring(startIndex + startSymbolLength, endIndex);
11769 expressions.push(exp);
11770 parseFns.push($parse(exp, parseStringifyInterceptor));
11771 index = endIndex + endSymbolLength;
11772 expressionPositions.push(concat.length);
11775 // we did not find an interpolation, so we have to add the remainder to the separators array
11776 if (index !== textLength) {
11777 concat.push(unescapeText(text.substring(index)));
11783 // Concatenating expressions makes it hard to reason about whether some combination of
11784 // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
11785 // single expression be used for iframe[src], object[src], etc., we ensure that the value
11786 // that's used is assigned or constructed by some JS code somewhere that is more testable or
11787 // make it obvious that you bound the value to some user controlled value. This helps reduce
11788 // the load when auditing for XSS issues.
11789 if (trustedContext && concat.length > 1) {
11790 $interpolateMinErr.throwNoconcat(text);
11793 if (!mustHaveExpression || expressions.length) {
11794 var compute = function(values) {
11795 for (var i = 0, ii = expressions.length; i < ii; i++) {
11796 if (allOrNothing && isUndefined(values[i])) return;
11797 concat[expressionPositions[i]] = values[i];
11799 return concat.join('');
11802 var getValue = function(value) {
11803 return trustedContext ?
11804 $sce.getTrusted(trustedContext, value) :
11805 $sce.valueOf(value);
11808 return extend(function interpolationFn(context) {
11810 var ii = expressions.length;
11811 var values = new Array(ii);
11814 for (; i < ii; i++) {
11815 values[i] = parseFns[i](context);
11818 return compute(values);
11820 $exceptionHandler($interpolateMinErr.interr(text, err));
11824 // all of these properties are undocumented for now
11825 exp: text, //just for compatibility with regular watchers created via $watch
11826 expressions: expressions,
11827 $$watchDelegate: function(scope, listener) {
11829 return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
11830 var currValue = compute(values);
11831 if (isFunction(listener)) {
11832 listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
11834 lastValue = currValue;
11840 function parseStringifyInterceptor(value) {
11842 value = getValue(value);
11843 return allOrNothing && !isDefined(value) ? value : stringify(value);
11845 $exceptionHandler($interpolateMinErr.interr(text, err));
11853 * @name $interpolate#startSymbol
11855 * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
11857 * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
11860 * @returns {string} start symbol.
11862 $interpolate.startSymbol = function() {
11863 return startSymbol;
11869 * @name $interpolate#endSymbol
11871 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
11873 * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
11876 * @returns {string} end symbol.
11878 $interpolate.endSymbol = function() {
11882 return $interpolate;
11886 function $IntervalProvider() {
11887 this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
11888 function($rootScope, $window, $q, $$q, $browser) {
11889 var intervals = {};
11897 * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
11900 * The return value of registering an interval function is a promise. This promise will be
11901 * notified upon each tick of the interval, and will be resolved after `count` iterations, or
11902 * run indefinitely if `count` is not defined. The value of the notification will be the
11903 * number of iterations that have run.
11904 * To cancel an interval, call `$interval.cancel(promise)`.
11906 * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
11907 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
11910 * <div class="alert alert-warning">
11911 * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
11912 * with them. In particular they are not automatically destroyed when a controller's scope or a
11913 * directive's element are destroyed.
11914 * You should take this into consideration and make sure to always cancel the interval at the
11915 * appropriate moment. See the example below for more details on how and when to do this.
11918 * @param {function()} fn A function that should be called repeatedly.
11919 * @param {number} delay Number of milliseconds between each function call.
11920 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
11922 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
11923 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
11924 * @param {...*=} Pass additional parameters to the executed function.
11925 * @returns {promise} A promise which will be notified on each iteration.
11928 * <example module="intervalExample">
11929 * <file name="index.html">
11931 * angular.module('intervalExample', [])
11932 * .controller('ExampleController', ['$scope', '$interval',
11933 * function($scope, $interval) {
11934 * $scope.format = 'M/d/yy h:mm:ss a';
11935 * $scope.blood_1 = 100;
11936 * $scope.blood_2 = 120;
11939 * $scope.fight = function() {
11940 * // Don't start a new fight if we are already fighting
11941 * if ( angular.isDefined(stop) ) return;
11943 * stop = $interval(function() {
11944 * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
11945 * $scope.blood_1 = $scope.blood_1 - 3;
11946 * $scope.blood_2 = $scope.blood_2 - 4;
11948 * $scope.stopFight();
11953 * $scope.stopFight = function() {
11954 * if (angular.isDefined(stop)) {
11955 * $interval.cancel(stop);
11956 * stop = undefined;
11960 * $scope.resetFight = function() {
11961 * $scope.blood_1 = 100;
11962 * $scope.blood_2 = 120;
11965 * $scope.$on('$destroy', function() {
11966 * // Make sure that the interval is destroyed too
11967 * $scope.stopFight();
11970 * // Register the 'myCurrentTime' directive factory method.
11971 * // We inject $interval and dateFilter service since the factory method is DI.
11972 * .directive('myCurrentTime', ['$interval', 'dateFilter',
11973 * function($interval, dateFilter) {
11974 * // return the directive link function. (compile function not needed)
11975 * return function(scope, element, attrs) {
11976 * var format, // date format
11977 * stopTime; // so that we can cancel the time updates
11979 * // used to update the UI
11980 * function updateTime() {
11981 * element.text(dateFilter(new Date(), format));
11984 * // watch the expression, and update the UI on change.
11985 * scope.$watch(attrs.myCurrentTime, function(value) {
11990 * stopTime = $interval(updateTime, 1000);
11992 * // listen on DOM destroy (removal) event, and cancel the next UI update
11993 * // to prevent updating time after the DOM element was removed.
11994 * element.on('$destroy', function() {
11995 * $interval.cancel(stopTime);
12002 * <div ng-controller="ExampleController">
12003 * <label>Date format: <input ng-model="format"></label> <hr/>
12004 * Current time is: <span my-current-time="format"></span>
12006 * Blood 1 : <font color='red'>{{blood_1}}</font>
12007 * Blood 2 : <font color='red'>{{blood_2}}</font>
12008 * <button type="button" data-ng-click="fight()">Fight</button>
12009 * <button type="button" data-ng-click="stopFight()">StopFight</button>
12010 * <button type="button" data-ng-click="resetFight()">resetFight</button>
12017 function interval(fn, delay, count, invokeApply) {
12018 var hasParams = arguments.length > 4,
12019 args = hasParams ? sliceArgs(arguments, 4) : [],
12020 setInterval = $window.setInterval,
12021 clearInterval = $window.clearInterval,
12023 skipApply = (isDefined(invokeApply) && !invokeApply),
12024 deferred = (skipApply ? $$q : $q).defer(),
12025 promise = deferred.promise;
12027 count = isDefined(count) ? count : 0;
12029 promise.$$intervalId = setInterval(function tick() {
12031 $browser.defer(callback);
12033 $rootScope.$evalAsync(callback);
12035 deferred.notify(iteration++);
12037 if (count > 0 && iteration >= count) {
12038 deferred.resolve(iteration);
12039 clearInterval(promise.$$intervalId);
12040 delete intervals[promise.$$intervalId];
12043 if (!skipApply) $rootScope.$apply();
12047 intervals[promise.$$intervalId] = deferred;
12051 function callback() {
12055 fn.apply(null, args);
12063 * @name $interval#cancel
12066 * Cancels a task associated with the `promise`.
12068 * @param {Promise=} promise returned by the `$interval` function.
12069 * @returns {boolean} Returns `true` if the task was successfully canceled.
12071 interval.cancel = function(promise) {
12072 if (promise && promise.$$intervalId in intervals) {
12073 intervals[promise.$$intervalId].reject('canceled');
12074 $window.clearInterval(promise.$$intervalId);
12075 delete intervals[promise.$$intervalId];
12090 * $locale service provides localization rules for various Angular components. As of right now the
12091 * only public api is:
12093 * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
12096 var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
12097 DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
12098 var $locationMinErr = minErr('$location');
12102 * Encode path using encodeUriSegment, ignoring forward slashes
12104 * @param {string} path Path to encode
12105 * @returns {string}
12107 function encodePath(path) {
12108 var segments = path.split('/'),
12109 i = segments.length;
12112 segments[i] = encodeUriSegment(segments[i]);
12115 return segments.join('/');
12118 function parseAbsoluteUrl(absoluteUrl, locationObj) {
12119 var parsedUrl = urlResolve(absoluteUrl);
12121 locationObj.$$protocol = parsedUrl.protocol;
12122 locationObj.$$host = parsedUrl.hostname;
12123 locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
12127 function parseAppUrl(relativeUrl, locationObj) {
12128 var prefixed = (relativeUrl.charAt(0) !== '/');
12130 relativeUrl = '/' + relativeUrl;
12132 var match = urlResolve(relativeUrl);
12133 locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
12134 match.pathname.substring(1) : match.pathname);
12135 locationObj.$$search = parseKeyValue(match.search);
12136 locationObj.$$hash = decodeURIComponent(match.hash);
12138 // make sure path starts with '/';
12139 if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
12140 locationObj.$$path = '/' + locationObj.$$path;
12147 * @param {string} begin
12148 * @param {string} whole
12149 * @returns {string} returns text from whole after begin or undefined if it does not begin with
12152 function beginsWith(begin, whole) {
12153 if (whole.indexOf(begin) === 0) {
12154 return whole.substr(begin.length);
12159 function stripHash(url) {
12160 var index = url.indexOf('#');
12161 return index == -1 ? url : url.substr(0, index);
12164 function trimEmptyHash(url) {
12165 return url.replace(/(#.+)|#$/, '$1');
12169 function stripFile(url) {
12170 return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
12173 /* return the server only (scheme://host:port) */
12174 function serverBase(url) {
12175 return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
12180 * LocationHtml5Url represents an url
12181 * This object is exposed as $location service when HTML5 mode is enabled and supported
12184 * @param {string} appBase application base URL
12185 * @param {string} appBaseNoFile application base URL stripped of any filename
12186 * @param {string} basePrefix url path prefix
12188 function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
12189 this.$$html5 = true;
12190 basePrefix = basePrefix || '';
12191 parseAbsoluteUrl(appBase, this);
12195 * Parse given html5 (regular) url string into properties
12196 * @param {string} url HTML5 url
12199 this.$$parse = function(url) {
12200 var pathUrl = beginsWith(appBaseNoFile, url);
12201 if (!isString(pathUrl)) {
12202 throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
12206 parseAppUrl(pathUrl, this);
12208 if (!this.$$path) {
12216 * Compose url and update `absUrl` property
12219 this.$$compose = function() {
12220 var search = toKeyValue(this.$$search),
12221 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
12223 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
12224 this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
12227 this.$$parseLinkUrl = function(url, relHref) {
12228 if (relHref && relHref[0] === '#') {
12229 // special case for links to hash fragments:
12230 // keep the old url and only replace the hash fragment
12231 this.hash(relHref.slice(1));
12234 var appUrl, prevAppUrl;
12237 if (isDefined(appUrl = beginsWith(appBase, url))) {
12238 prevAppUrl = appUrl;
12239 if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
12240 rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
12242 rewrittenUrl = appBase + prevAppUrl;
12244 } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
12245 rewrittenUrl = appBaseNoFile + appUrl;
12246 } else if (appBaseNoFile == url + '/') {
12247 rewrittenUrl = appBaseNoFile;
12249 if (rewrittenUrl) {
12250 this.$$parse(rewrittenUrl);
12252 return !!rewrittenUrl;
12258 * LocationHashbangUrl represents url
12259 * This object is exposed as $location service when developer doesn't opt into html5 mode.
12260 * It also serves as the base class for html5 mode fallback on legacy browsers.
12263 * @param {string} appBase application base URL
12264 * @param {string} appBaseNoFile application base URL stripped of any filename
12265 * @param {string} hashPrefix hashbang prefix
12267 function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
12269 parseAbsoluteUrl(appBase, this);
12273 * Parse given hashbang url into properties
12274 * @param {string} url Hashbang url
12277 this.$$parse = function(url) {
12278 var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
12279 var withoutHashUrl;
12281 if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
12283 // The rest of the url starts with a hash so we have
12284 // got either a hashbang path or a plain hash fragment
12285 withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
12286 if (isUndefined(withoutHashUrl)) {
12287 // There was no hashbang prefix so we just have a hash fragment
12288 withoutHashUrl = withoutBaseUrl;
12292 // There was no hashbang path nor hash fragment:
12293 // If we are in HTML5 mode we use what is left as the path;
12294 // Otherwise we ignore what is left
12295 if (this.$$html5) {
12296 withoutHashUrl = withoutBaseUrl;
12298 withoutHashUrl = '';
12299 if (isUndefined(withoutBaseUrl)) {
12306 parseAppUrl(withoutHashUrl, this);
12308 this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
12313 * In Windows, on an anchor node on documents loaded from
12314 * the filesystem, the browser will return a pathname
12315 * prefixed with the drive name ('/C:/path') when a
12316 * pathname without a drive is set:
12317 * * a.setAttribute('href', '/foo')
12318 * * a.pathname === '/C:/foo' //true
12320 * Inside of Angular, we're always using pathnames that
12321 * do not include drive names for routing.
12323 function removeWindowsDriveName(path, url, base) {
12325 Matches paths for file protocol on windows,
12326 such as /C:/foo/bar, and captures only /foo/bar.
12328 var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
12330 var firstPathSegmentMatch;
12332 //Get the relative path from the input URL.
12333 if (url.indexOf(base) === 0) {
12334 url = url.replace(base, '');
12337 // The input URL intentionally contains a first path segment that ends with a colon.
12338 if (windowsFilePathExp.exec(url)) {
12342 firstPathSegmentMatch = windowsFilePathExp.exec(path);
12343 return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
12348 * Compose hashbang url and update `absUrl` property
12351 this.$$compose = function() {
12352 var search = toKeyValue(this.$$search),
12353 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
12355 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
12356 this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
12359 this.$$parseLinkUrl = function(url, relHref) {
12360 if (stripHash(appBase) == stripHash(url)) {
12370 * LocationHashbangUrl represents url
12371 * This object is exposed as $location service when html5 history api is enabled but the browser
12372 * does not support it.
12375 * @param {string} appBase application base URL
12376 * @param {string} appBaseNoFile application base URL stripped of any filename
12377 * @param {string} hashPrefix hashbang prefix
12379 function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
12380 this.$$html5 = true;
12381 LocationHashbangUrl.apply(this, arguments);
12383 this.$$parseLinkUrl = function(url, relHref) {
12384 if (relHref && relHref[0] === '#') {
12385 // special case for links to hash fragments:
12386 // keep the old url and only replace the hash fragment
12387 this.hash(relHref.slice(1));
12394 if (appBase == stripHash(url)) {
12395 rewrittenUrl = url;
12396 } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
12397 rewrittenUrl = appBase + hashPrefix + appUrl;
12398 } else if (appBaseNoFile === url + '/') {
12399 rewrittenUrl = appBaseNoFile;
12401 if (rewrittenUrl) {
12402 this.$$parse(rewrittenUrl);
12404 return !!rewrittenUrl;
12407 this.$$compose = function() {
12408 var search = toKeyValue(this.$$search),
12409 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
12411 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
12412 // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
12413 this.$$absUrl = appBase + hashPrefix + this.$$url;
12419 var locationPrototype = {
12422 * Are we in html5 mode?
12428 * Has any change been replacing?
12435 * @name $location#absUrl
12438 * This method is getter only.
12440 * Return full url representation with all segments encoded according to rules specified in
12441 * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
12445 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12446 * var absUrl = $location.absUrl();
12447 * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
12450 * @return {string} full url
12452 absUrl: locationGetter('$$absUrl'),
12456 * @name $location#url
12459 * This method is getter / setter.
12461 * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
12463 * Change path, search and hash, when called with parameter and return `$location`.
12467 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12468 * var url = $location.url();
12469 * // => "/some/path?foo=bar&baz=xoxo"
12472 * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
12473 * @return {string} url
12475 url: function(url) {
12476 if (isUndefined(url)) {
12480 var match = PATH_MATCH.exec(url);
12481 if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
12482 if (match[2] || match[1] || url === '') this.search(match[3] || '');
12483 this.hash(match[5] || '');
12490 * @name $location#protocol
12493 * This method is getter only.
12495 * Return protocol of current url.
12499 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12500 * var protocol = $location.protocol();
12504 * @return {string} protocol of current url
12506 protocol: locationGetter('$$protocol'),
12510 * @name $location#host
12513 * This method is getter only.
12515 * Return host of current url.
12517 * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
12521 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12522 * var host = $location.host();
12523 * // => "example.com"
12525 * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
12526 * host = $location.host();
12527 * // => "example.com"
12528 * host = location.host;
12529 * // => "example.com:8080"
12532 * @return {string} host of current url.
12534 host: locationGetter('$$host'),
12538 * @name $location#port
12541 * This method is getter only.
12543 * Return port of current url.
12547 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12548 * var port = $location.port();
12552 * @return {Number} port
12554 port: locationGetter('$$port'),
12558 * @name $location#path
12561 * This method is getter / setter.
12563 * Return path of current url when called without any parameter.
12565 * Change path when called with parameter and return `$location`.
12567 * Note: Path should always begin with forward slash (/), this method will add the forward slash
12568 * if it is missing.
12572 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12573 * var path = $location.path();
12574 * // => "/some/path"
12577 * @param {(string|number)=} path New path
12578 * @return {string} path
12580 path: locationGetterSetter('$$path', function(path) {
12581 path = path !== null ? path.toString() : '';
12582 return path.charAt(0) == '/' ? path : '/' + path;
12587 * @name $location#search
12590 * This method is getter / setter.
12592 * Return search part (as object) of current url when called without any parameter.
12594 * Change search part when called with parameter and return `$location`.
12598 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12599 * var searchObject = $location.search();
12600 * // => {foo: 'bar', baz: 'xoxo'}
12602 * // set foo to 'yipee'
12603 * $location.search('foo', 'yipee');
12604 * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
12607 * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
12610 * When called with a single argument the method acts as a setter, setting the `search` component
12611 * of `$location` to the specified value.
12613 * If the argument is a hash object containing an array of values, these values will be encoded
12614 * as duplicate search parameters in the url.
12616 * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
12617 * will override only a single search property.
12619 * If `paramValue` is an array, it will override the property of the `search` component of
12620 * `$location` specified via the first argument.
12622 * If `paramValue` is `null`, the property specified via the first argument will be deleted.
12624 * If `paramValue` is `true`, the property specified via the first argument will be added with no
12625 * value nor trailing equal sign.
12627 * @return {Object} If called with no arguments returns the parsed `search` object. If called with
12628 * one or more arguments returns `$location` object itself.
12630 search: function(search, paramValue) {
12631 switch (arguments.length) {
12633 return this.$$search;
12635 if (isString(search) || isNumber(search)) {
12636 search = search.toString();
12637 this.$$search = parseKeyValue(search);
12638 } else if (isObject(search)) {
12639 search = copy(search, {});
12640 // remove object undefined or null properties
12641 forEach(search, function(value, key) {
12642 if (value == null) delete search[key];
12645 this.$$search = search;
12647 throw $locationMinErr('isrcharg',
12648 'The first argument of the `$location#search()` call must be a string or an object.');
12652 if (isUndefined(paramValue) || paramValue === null) {
12653 delete this.$$search[search];
12655 this.$$search[search] = paramValue;
12665 * @name $location#hash
12668 * This method is getter / setter.
12670 * Returns the hash fragment when called without any parameters.
12672 * Changes the hash fragment when called with a parameter and returns `$location`.
12676 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
12677 * var hash = $location.hash();
12678 * // => "hashValue"
12681 * @param {(string|number)=} hash New hash fragment
12682 * @return {string} hash
12684 hash: locationGetterSetter('$$hash', function(hash) {
12685 return hash !== null ? hash.toString() : '';
12690 * @name $location#replace
12693 * If called, all changes to $location during the current `$digest` will replace the current history
12694 * record, instead of adding a new one.
12696 replace: function() {
12697 this.$$replace = true;
12702 forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
12703 Location.prototype = Object.create(locationPrototype);
12707 * @name $location#state
12710 * This method is getter / setter.
12712 * Return the history state object when called without any parameter.
12714 * Change the history state object when called with one parameter and return `$location`.
12715 * The state object is later passed to `pushState` or `replaceState`.
12717 * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
12718 * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
12719 * older browsers (like IE9 or Android < 4.0), don't use this method.
12721 * @param {object=} state State object for pushState or replaceState
12722 * @return {object} state
12724 Location.prototype.state = function(state) {
12725 if (!arguments.length) {
12726 return this.$$state;
12729 if (Location !== LocationHtml5Url || !this.$$html5) {
12730 throw $locationMinErr('nostate', 'History API state support is available only ' +
12731 'in HTML5 mode and only in browsers supporting HTML5 History API');
12733 // The user might modify `stateObject` after invoking `$location.state(stateObject)`
12734 // but we're changing the $$state reference to $browser.state() during the $digest
12735 // so the modification window is narrow.
12736 this.$$state = isUndefined(state) ? null : state;
12743 function locationGetter(property) {
12744 return function() {
12745 return this[property];
12750 function locationGetterSetter(property, preprocess) {
12751 return function(value) {
12752 if (isUndefined(value)) {
12753 return this[property];
12756 this[property] = preprocess(value);
12768 * @requires $rootElement
12771 * The $location service parses the URL in the browser address bar (based on the
12772 * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
12773 * available to your application. Changes to the URL in the address bar are reflected into
12774 * $location service and changes to $location are reflected into the browser address bar.
12776 * **The $location service:**
12778 * - Exposes the current URL in the browser address bar, so you can
12779 * - Watch and observe the URL.
12780 * - Change the URL.
12781 * - Synchronizes the URL with the browser when the user
12782 * - Changes the address bar.
12783 * - Clicks the back or forward button (or clicks a History link).
12784 * - Clicks on a link.
12785 * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
12787 * For more information see {@link guide/$location Developer Guide: Using $location}
12792 * @name $locationProvider
12794 * Use the `$locationProvider` to configure how the application deep linking paths are stored.
12796 function $LocationProvider() {
12797 var hashPrefix = '',
12806 * @name $locationProvider#hashPrefix
12808 * @param {string=} prefix Prefix for hash part (containing path and search)
12809 * @returns {*} current value if used as getter or itself (chaining) if used as setter
12811 this.hashPrefix = function(prefix) {
12812 if (isDefined(prefix)) {
12813 hashPrefix = prefix;
12822 * @name $locationProvider#html5Mode
12824 * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
12825 * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
12827 * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
12828 * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
12829 * support `pushState`.
12830 * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
12831 * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
12832 * true, and a base tag is not present, an error will be thrown when `$location` is injected.
12833 * See the {@link guide/$location $location guide for more information}
12834 * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
12835 * enables/disables url rewriting for relative links.
12837 * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
12839 this.html5Mode = function(mode) {
12840 if (isBoolean(mode)) {
12841 html5Mode.enabled = mode;
12843 } else if (isObject(mode)) {
12845 if (isBoolean(mode.enabled)) {
12846 html5Mode.enabled = mode.enabled;
12849 if (isBoolean(mode.requireBase)) {
12850 html5Mode.requireBase = mode.requireBase;
12853 if (isBoolean(mode.rewriteLinks)) {
12854 html5Mode.rewriteLinks = mode.rewriteLinks;
12865 * @name $location#$locationChangeStart
12866 * @eventType broadcast on root scope
12868 * Broadcasted before a URL will change.
12870 * This change can be prevented by calling
12871 * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
12872 * details about event object. Upon successful change
12873 * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
12875 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
12876 * the browser supports the HTML5 History API.
12878 * @param {Object} angularEvent Synthetic event object.
12879 * @param {string} newUrl New URL
12880 * @param {string=} oldUrl URL that was before it was changed.
12881 * @param {string=} newState New history state object
12882 * @param {string=} oldState History state object that was before it was changed.
12887 * @name $location#$locationChangeSuccess
12888 * @eventType broadcast on root scope
12890 * Broadcasted after a URL was changed.
12892 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
12893 * the browser supports the HTML5 History API.
12895 * @param {Object} angularEvent Synthetic event object.
12896 * @param {string} newUrl New URL
12897 * @param {string=} oldUrl URL that was before it was changed.
12898 * @param {string=} newState New history state object
12899 * @param {string=} oldState History state object that was before it was changed.
12902 this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
12903 function($rootScope, $browser, $sniffer, $rootElement, $window) {
12906 baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
12907 initialUrl = $browser.url(),
12910 if (html5Mode.enabled) {
12911 if (!baseHref && html5Mode.requireBase) {
12912 throw $locationMinErr('nobase',
12913 "$location in HTML5 mode requires a <base> tag to be present!");
12915 appBase = serverBase(initialUrl) + (baseHref || '/');
12916 LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
12918 appBase = stripHash(initialUrl);
12919 LocationMode = LocationHashbangUrl;
12921 var appBaseNoFile = stripFile(appBase);
12923 $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
12924 $location.$$parseLinkUrl(initialUrl, initialUrl);
12926 $location.$$state = $browser.state();
12928 var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
12930 function setBrowserUrlWithFallback(url, replace, state) {
12931 var oldUrl = $location.url();
12932 var oldState = $location.$$state;
12934 $browser.url(url, replace, state);
12936 // Make sure $location.state() returns referentially identical (not just deeply equal)
12937 // state object; this makes possible quick checking if the state changed in the digest
12938 // loop. Checking deep equality would be too expensive.
12939 $location.$$state = $browser.state();
12941 // Restore old values if pushState fails
12942 $location.url(oldUrl);
12943 $location.$$state = oldState;
12949 $rootElement.on('click', function(event) {
12950 // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
12951 // currently we open nice url link and redirect then
12953 if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
12955 var elm = jqLite(event.target);
12957 // traverse the DOM up to find first A tag
12958 while (nodeName_(elm[0]) !== 'a') {
12959 // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
12960 if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
12963 var absHref = elm.prop('href');
12964 // get the actual href attribute - see
12965 // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
12966 var relHref = elm.attr('href') || elm.attr('xlink:href');
12968 if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
12969 // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
12971 absHref = urlResolve(absHref.animVal).href;
12974 // Ignore when url is started with javascript: or mailto:
12975 if (IGNORE_URI_REGEXP.test(absHref)) return;
12977 if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
12978 if ($location.$$parseLinkUrl(absHref, relHref)) {
12979 // We do a preventDefault for all urls that are part of the angular application,
12980 // in html5mode and also without, so that we are able to abort navigation without
12981 // getting double entries in the location history.
12982 event.preventDefault();
12983 // update location manually
12984 if ($location.absUrl() != $browser.url()) {
12985 $rootScope.$apply();
12986 // hack to work around FF6 bug 684208 when scenario runner clicks on links
12987 $window.angular['ff-684208-preventDefault'] = true;
12994 // rewrite hashbang url <> html5 url
12995 if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
12996 $browser.url($location.absUrl(), true);
12999 var initializing = true;
13001 // update $location when $browser url changes
13002 $browser.onUrlChange(function(newUrl, newState) {
13004 if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
13005 // If we are navigating outside of the app then force a reload
13006 $window.location.href = newUrl;
13010 $rootScope.$evalAsync(function() {
13011 var oldUrl = $location.absUrl();
13012 var oldState = $location.$$state;
13013 var defaultPrevented;
13014 newUrl = trimEmptyHash(newUrl);
13015 $location.$$parse(newUrl);
13016 $location.$$state = newState;
13018 defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
13019 newState, oldState).defaultPrevented;
13021 // if the location was changed by a `$locationChangeStart` handler then stop
13022 // processing this location change
13023 if ($location.absUrl() !== newUrl) return;
13025 if (defaultPrevented) {
13026 $location.$$parse(oldUrl);
13027 $location.$$state = oldState;
13028 setBrowserUrlWithFallback(oldUrl, false, oldState);
13030 initializing = false;
13031 afterLocationChange(oldUrl, oldState);
13034 if (!$rootScope.$$phase) $rootScope.$digest();
13038 $rootScope.$watch(function $locationWatch() {
13039 var oldUrl = trimEmptyHash($browser.url());
13040 var newUrl = trimEmptyHash($location.absUrl());
13041 var oldState = $browser.state();
13042 var currentReplace = $location.$$replace;
13043 var urlOrStateChanged = oldUrl !== newUrl ||
13044 ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
13046 if (initializing || urlOrStateChanged) {
13047 initializing = false;
13049 $rootScope.$evalAsync(function() {
13050 var newUrl = $location.absUrl();
13051 var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
13052 $location.$$state, oldState).defaultPrevented;
13054 // if the location was changed by a `$locationChangeStart` handler then stop
13055 // processing this location change
13056 if ($location.absUrl() !== newUrl) return;
13058 if (defaultPrevented) {
13059 $location.$$parse(oldUrl);
13060 $location.$$state = oldState;
13062 if (urlOrStateChanged) {
13063 setBrowserUrlWithFallback(newUrl, currentReplace,
13064 oldState === $location.$$state ? null : $location.$$state);
13066 afterLocationChange(oldUrl, oldState);
13071 $location.$$replace = false;
13073 // we don't need to return anything because $evalAsync will make the digest loop dirty when
13074 // there is a change
13079 function afterLocationChange(oldUrl, oldState) {
13080 $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
13081 $location.$$state, oldState);
13089 * @requires $window
13092 * Simple service for logging. Default implementation safely writes the message
13093 * into the browser's console (if present).
13095 * The main purpose of this service is to simplify debugging and troubleshooting.
13097 * The default is to log `debug` messages. You can use
13098 * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
13101 <example module="logExample">
13102 <file name="script.js">
13103 angular.module('logExample', [])
13104 .controller('LogController', ['$scope', '$log', function($scope, $log) {
13105 $scope.$log = $log;
13106 $scope.message = 'Hello World!';
13109 <file name="index.html">
13110 <div ng-controller="LogController">
13111 <p>Reload this page with open console, enter text and hit the log button...</p>
13113 <input type="text" ng-model="message" /></label>
13114 <button ng-click="$log.log(message)">log</button>
13115 <button ng-click="$log.warn(message)">warn</button>
13116 <button ng-click="$log.info(message)">info</button>
13117 <button ng-click="$log.error(message)">error</button>
13118 <button ng-click="$log.debug(message)">debug</button>
13126 * @name $logProvider
13128 * Use the `$logProvider` to configure how the application logs messages
13130 function $LogProvider() {
13136 * @name $logProvider#debugEnabled
13138 * @param {boolean=} flag enable or disable debug level messages
13139 * @returns {*} current value if used as getter or itself (chaining) if used as setter
13141 this.debugEnabled = function(flag) {
13142 if (isDefined(flag)) {
13150 this.$get = ['$window', function($window) {
13157 * Write a log message
13159 log: consoleLog('log'),
13166 * Write an information message
13168 info: consoleLog('info'),
13175 * Write a warning message
13177 warn: consoleLog('warn'),
13184 * Write an error message
13186 error: consoleLog('error'),
13193 * Write a debug message
13195 debug: (function() {
13196 var fn = consoleLog('debug');
13198 return function() {
13200 fn.apply(self, arguments);
13206 function formatError(arg) {
13207 if (arg instanceof Error) {
13209 arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
13210 ? 'Error: ' + arg.message + '\n' + arg.stack
13212 } else if (arg.sourceURL) {
13213 arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
13219 function consoleLog(type) {
13220 var console = $window.console || {},
13221 logFn = console[type] || console.log || noop,
13224 // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
13225 // The reason behind this is that console.log has type "object" in IE8...
13227 hasApply = !!logFn.apply;
13231 return function() {
13233 forEach(arguments, function(arg) {
13234 args.push(formatError(arg));
13236 return logFn.apply(console, args);
13240 // we are IE which either doesn't have window.console => this is noop and we do nothing,
13241 // or we are IE where console.log doesn't have apply so we log at least first 2 args
13242 return function(arg1, arg2) {
13243 logFn(arg1, arg2 == null ? '' : arg2);
13249 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
13250 * Any commits to this file should be reviewed with security in mind. *
13251 * Changes to this file can potentially create security vulnerabilities. *
13252 * An approval from 2 Core members with history of modifying *
13253 * this file is required. *
13255 * Does the change somehow allow for arbitrary javascript to be executed? *
13256 * Or allows for someone to change the prototype of built-in objects? *
13257 * Or gives undesired access to variables likes document or window? *
13258 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
13260 var $parseMinErr = minErr('$parse');
13262 // Sandboxing Angular Expressions
13263 // ------------------------------
13264 // Angular expressions are generally considered safe because these expressions only have direct
13265 // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
13266 // obtaining a reference to native JS functions such as the Function constructor.
13268 // As an example, consider the following Angular expression:
13270 // {}.toString.constructor('alert("evil JS code")')
13272 // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
13273 // against the expression language, but not to prevent exploits that were enabled by exposing
13274 // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
13275 // practice and therefore we are not even trying to protect against interaction with an object
13276 // explicitly exposed in this way.
13278 // In general, it is not possible to access a Window object from an angular expression unless a
13279 // window or some DOM object that has a reference to window is published onto a Scope.
13280 // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
13283 // See https://docs.angularjs.org/guide/security
13286 function ensureSafeMemberName(name, fullExpression) {
13287 if (name === "__defineGetter__" || name === "__defineSetter__"
13288 || name === "__lookupGetter__" || name === "__lookupSetter__"
13289 || name === "__proto__") {
13290 throw $parseMinErr('isecfld',
13291 'Attempting to access a disallowed field in Angular expressions! '
13292 + 'Expression: {0}', fullExpression);
13297 function getStringValue(name) {
13298 // Property names must be strings. This means that non-string objects cannot be used
13299 // as keys in an object. Any non-string object, including a number, is typecasted
13300 // into a string via the toString method.
13301 // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
13303 // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
13304 // to a string. It's not always possible. If `name` is an object and its `toString` method is
13305 // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
13307 // TypeError: Cannot convert object to primitive value
13309 // For performance reasons, we don't catch this error here and allow it to propagate up the call
13310 // stack. Note that you'll get the same error in JavaScript if you try to access a property using
13311 // such a 'broken' object as a key.
13315 function ensureSafeObject(obj, fullExpression) {
13316 // nifty check if obj is Function that is fast and works across iframes and other contexts
13318 if (obj.constructor === obj) {
13319 throw $parseMinErr('isecfn',
13320 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
13322 } else if (// isWindow(obj)
13323 obj.window === obj) {
13324 throw $parseMinErr('isecwindow',
13325 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
13327 } else if (// isElement(obj)
13328 obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
13329 throw $parseMinErr('isecdom',
13330 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
13332 } else if (// block Object so that we can't get hold of dangerous Object.* methods
13334 throw $parseMinErr('isecobj',
13335 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
13342 var CALL = Function.prototype.call;
13343 var APPLY = Function.prototype.apply;
13344 var BIND = Function.prototype.bind;
13346 function ensureSafeFunction(obj, fullExpression) {
13348 if (obj.constructor === obj) {
13349 throw $parseMinErr('isecfn',
13350 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
13352 } else if (obj === CALL || obj === APPLY || obj === BIND) {
13353 throw $parseMinErr('isecff',
13354 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
13360 function ensureSafeAssignContext(obj, fullExpression) {
13362 if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
13363 obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
13364 throw $parseMinErr('isecaf',
13365 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
13370 var OPERATORS = createMap();
13371 forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
13372 var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
13375 /////////////////////////////////////////
13381 var Lexer = function(options) {
13382 this.options = options;
13385 Lexer.prototype = {
13386 constructor: Lexer,
13388 lex: function(text) {
13393 while (this.index < this.text.length) {
13394 var ch = this.text.charAt(this.index);
13395 if (ch === '"' || ch === "'") {
13396 this.readString(ch);
13397 } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
13399 } else if (this.isIdent(ch)) {
13401 } else if (this.is(ch, '(){}[].,;:?')) {
13402 this.tokens.push({index: this.index, text: ch});
13404 } else if (this.isWhitespace(ch)) {
13407 var ch2 = ch + this.peek();
13408 var ch3 = ch2 + this.peek(2);
13409 var op1 = OPERATORS[ch];
13410 var op2 = OPERATORS[ch2];
13411 var op3 = OPERATORS[ch3];
13412 if (op1 || op2 || op3) {
13413 var token = op3 ? ch3 : (op2 ? ch2 : ch);
13414 this.tokens.push({index: this.index, text: token, operator: true});
13415 this.index += token.length;
13417 this.throwError('Unexpected next character ', this.index, this.index + 1);
13421 return this.tokens;
13424 is: function(ch, chars) {
13425 return chars.indexOf(ch) !== -1;
13428 peek: function(i) {
13430 return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
13433 isNumber: function(ch) {
13434 return ('0' <= ch && ch <= '9') && typeof ch === "string";
13437 isWhitespace: function(ch) {
13438 // IE treats non-breaking space as \u00A0
13439 return (ch === ' ' || ch === '\r' || ch === '\t' ||
13440 ch === '\n' || ch === '\v' || ch === '\u00A0');
13443 isIdent: function(ch) {
13444 return ('a' <= ch && ch <= 'z' ||
13445 'A' <= ch && ch <= 'Z' ||
13446 '_' === ch || ch === '$');
13449 isExpOperator: function(ch) {
13450 return (ch === '-' || ch === '+' || this.isNumber(ch));
13453 throwError: function(error, start, end) {
13454 end = end || this.index;
13455 var colStr = (isDefined(start)
13456 ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
13458 throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
13459 error, colStr, this.text);
13462 readNumber: function() {
13464 var start = this.index;
13465 while (this.index < this.text.length) {
13466 var ch = lowercase(this.text.charAt(this.index));
13467 if (ch == '.' || this.isNumber(ch)) {
13470 var peekCh = this.peek();
13471 if (ch == 'e' && this.isExpOperator(peekCh)) {
13473 } else if (this.isExpOperator(ch) &&
13474 peekCh && this.isNumber(peekCh) &&
13475 number.charAt(number.length - 1) == 'e') {
13477 } else if (this.isExpOperator(ch) &&
13478 (!peekCh || !this.isNumber(peekCh)) &&
13479 number.charAt(number.length - 1) == 'e') {
13480 this.throwError('Invalid exponent');
13491 value: Number(number)
13495 readIdent: function() {
13496 var start = this.index;
13497 while (this.index < this.text.length) {
13498 var ch = this.text.charAt(this.index);
13499 if (!(this.isIdent(ch) || this.isNumber(ch))) {
13506 text: this.text.slice(start, this.index),
13511 readString: function(quote) {
13512 var start = this.index;
13515 var rawString = quote;
13516 var escape = false;
13517 while (this.index < this.text.length) {
13518 var ch = this.text.charAt(this.index);
13522 var hex = this.text.substring(this.index + 1, this.index + 5);
13523 if (!hex.match(/[\da-f]{4}/i)) {
13524 this.throwError('Invalid unicode escape [\\u' + hex + ']');
13527 string += String.fromCharCode(parseInt(hex, 16));
13529 var rep = ESCAPE[ch];
13530 string = string + (rep || ch);
13533 } else if (ch === '\\') {
13535 } else if (ch === quote) {
13549 this.throwError('Unterminated quote', start);
13553 var AST = function(lexer, options) {
13554 this.lexer = lexer;
13555 this.options = options;
13558 AST.Program = 'Program';
13559 AST.ExpressionStatement = 'ExpressionStatement';
13560 AST.AssignmentExpression = 'AssignmentExpression';
13561 AST.ConditionalExpression = 'ConditionalExpression';
13562 AST.LogicalExpression = 'LogicalExpression';
13563 AST.BinaryExpression = 'BinaryExpression';
13564 AST.UnaryExpression = 'UnaryExpression';
13565 AST.CallExpression = 'CallExpression';
13566 AST.MemberExpression = 'MemberExpression';
13567 AST.Identifier = 'Identifier';
13568 AST.Literal = 'Literal';
13569 AST.ArrayExpression = 'ArrayExpression';
13570 AST.Property = 'Property';
13571 AST.ObjectExpression = 'ObjectExpression';
13572 AST.ThisExpression = 'ThisExpression';
13573 AST.LocalsExpression = 'LocalsExpression';
13575 // Internal use only
13576 AST.NGValueParameter = 'NGValueParameter';
13579 ast: function(text) {
13581 this.tokens = this.lexer.lex(text);
13583 var value = this.program();
13585 if (this.tokens.length !== 0) {
13586 this.throwError('is an unexpected token', this.tokens[0]);
13592 program: function() {
13595 if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
13596 body.push(this.expressionStatement());
13597 if (!this.expect(';')) {
13598 return { type: AST.Program, body: body};
13603 expressionStatement: function() {
13604 return { type: AST.ExpressionStatement, expression: this.filterChain() };
13607 filterChain: function() {
13608 var left = this.expression();
13610 while ((token = this.expect('|'))) {
13611 left = this.filter(left);
13616 expression: function() {
13617 return this.assignment();
13620 assignment: function() {
13621 var result = this.ternary();
13622 if (this.expect('=')) {
13623 result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
13628 ternary: function() {
13629 var test = this.logicalOR();
13632 if (this.expect('?')) {
13633 alternate = this.expression();
13634 if (this.consume(':')) {
13635 consequent = this.expression();
13636 return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
13642 logicalOR: function() {
13643 var left = this.logicalAND();
13644 while (this.expect('||')) {
13645 left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
13650 logicalAND: function() {
13651 var left = this.equality();
13652 while (this.expect('&&')) {
13653 left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
13658 equality: function() {
13659 var left = this.relational();
13661 while ((token = this.expect('==','!=','===','!=='))) {
13662 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
13667 relational: function() {
13668 var left = this.additive();
13670 while ((token = this.expect('<', '>', '<=', '>='))) {
13671 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
13676 additive: function() {
13677 var left = this.multiplicative();
13679 while ((token = this.expect('+','-'))) {
13680 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
13685 multiplicative: function() {
13686 var left = this.unary();
13688 while ((token = this.expect('*','/','%'))) {
13689 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
13694 unary: function() {
13696 if ((token = this.expect('+', '-', '!'))) {
13697 return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
13699 return this.primary();
13703 primary: function() {
13705 if (this.expect('(')) {
13706 primary = this.filterChain();
13708 } else if (this.expect('[')) {
13709 primary = this.arrayDeclaration();
13710 } else if (this.expect('{')) {
13711 primary = this.object();
13712 } else if (this.constants.hasOwnProperty(this.peek().text)) {
13713 primary = copy(this.constants[this.consume().text]);
13714 } else if (this.peek().identifier) {
13715 primary = this.identifier();
13716 } else if (this.peek().constant) {
13717 primary = this.constant();
13719 this.throwError('not a primary expression', this.peek());
13723 while ((next = this.expect('(', '[', '.'))) {
13724 if (next.text === '(') {
13725 primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
13727 } else if (next.text === '[') {
13728 primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
13730 } else if (next.text === '.') {
13731 primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
13733 this.throwError('IMPOSSIBLE');
13739 filter: function(baseExpression) {
13740 var args = [baseExpression];
13741 var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
13743 while (this.expect(':')) {
13744 args.push(this.expression());
13750 parseArguments: function() {
13752 if (this.peekToken().text !== ')') {
13754 args.push(this.expression());
13755 } while (this.expect(','));
13760 identifier: function() {
13761 var token = this.consume();
13762 if (!token.identifier) {
13763 this.throwError('is not a valid identifier', token);
13765 return { type: AST.Identifier, name: token.text };
13768 constant: function() {
13769 // TODO check that it is a constant
13770 return { type: AST.Literal, value: this.consume().value };
13773 arrayDeclaration: function() {
13775 if (this.peekToken().text !== ']') {
13777 if (this.peek(']')) {
13778 // Support trailing commas per ES5.1.
13781 elements.push(this.expression());
13782 } while (this.expect(','));
13786 return { type: AST.ArrayExpression, elements: elements };
13789 object: function() {
13790 var properties = [], property;
13791 if (this.peekToken().text !== '}') {
13793 if (this.peek('}')) {
13794 // Support trailing commas per ES5.1.
13797 property = {type: AST.Property, kind: 'init'};
13798 if (this.peek().constant) {
13799 property.key = this.constant();
13800 } else if (this.peek().identifier) {
13801 property.key = this.identifier();
13803 this.throwError("invalid key", this.peek());
13806 property.value = this.expression();
13807 properties.push(property);
13808 } while (this.expect(','));
13812 return {type: AST.ObjectExpression, properties: properties };
13815 throwError: function(msg, token) {
13816 throw $parseMinErr('syntax',
13817 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
13818 token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
13821 consume: function(e1) {
13822 if (this.tokens.length === 0) {
13823 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
13826 var token = this.expect(e1);
13828 this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
13833 peekToken: function() {
13834 if (this.tokens.length === 0) {
13835 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
13837 return this.tokens[0];
13840 peek: function(e1, e2, e3, e4) {
13841 return this.peekAhead(0, e1, e2, e3, e4);
13844 peekAhead: function(i, e1, e2, e3, e4) {
13845 if (this.tokens.length > i) {
13846 var token = this.tokens[i];
13847 var t = token.text;
13848 if (t === e1 || t === e2 || t === e3 || t === e4 ||
13849 (!e1 && !e2 && !e3 && !e4)) {
13856 expect: function(e1, e2, e3, e4) {
13857 var token = this.peek(e1, e2, e3, e4);
13859 this.tokens.shift();
13866 /* `undefined` is not a constant, it is an identifier,
13867 * but using it as an identifier is not supported
13870 'true': { type: AST.Literal, value: true },
13871 'false': { type: AST.Literal, value: false },
13872 'null': { type: AST.Literal, value: null },
13873 'undefined': {type: AST.Literal, value: undefined },
13874 'this': {type: AST.ThisExpression },
13875 '$locals': {type: AST.LocalsExpression }
13879 function ifDefined(v, d) {
13880 return typeof v !== 'undefined' ? v : d;
13883 function plusFn(l, r) {
13884 if (typeof l === 'undefined') return r;
13885 if (typeof r === 'undefined') return l;
13889 function isStateless($filter, filterName) {
13890 var fn = $filter(filterName);
13891 return !fn.$stateful;
13894 function findConstantAndWatchExpressions(ast, $filter) {
13897 switch (ast.type) {
13899 allConstants = true;
13900 forEach(ast.body, function(expr) {
13901 findConstantAndWatchExpressions(expr.expression, $filter);
13902 allConstants = allConstants && expr.expression.constant;
13904 ast.constant = allConstants;
13907 ast.constant = true;
13910 case AST.UnaryExpression:
13911 findConstantAndWatchExpressions(ast.argument, $filter);
13912 ast.constant = ast.argument.constant;
13913 ast.toWatch = ast.argument.toWatch;
13915 case AST.BinaryExpression:
13916 findConstantAndWatchExpressions(ast.left, $filter);
13917 findConstantAndWatchExpressions(ast.right, $filter);
13918 ast.constant = ast.left.constant && ast.right.constant;
13919 ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
13921 case AST.LogicalExpression:
13922 findConstantAndWatchExpressions(ast.left, $filter);
13923 findConstantAndWatchExpressions(ast.right, $filter);
13924 ast.constant = ast.left.constant && ast.right.constant;
13925 ast.toWatch = ast.constant ? [] : [ast];
13927 case AST.ConditionalExpression:
13928 findConstantAndWatchExpressions(ast.test, $filter);
13929 findConstantAndWatchExpressions(ast.alternate, $filter);
13930 findConstantAndWatchExpressions(ast.consequent, $filter);
13931 ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
13932 ast.toWatch = ast.constant ? [] : [ast];
13934 case AST.Identifier:
13935 ast.constant = false;
13936 ast.toWatch = [ast];
13938 case AST.MemberExpression:
13939 findConstantAndWatchExpressions(ast.object, $filter);
13940 if (ast.computed) {
13941 findConstantAndWatchExpressions(ast.property, $filter);
13943 ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
13944 ast.toWatch = [ast];
13946 case AST.CallExpression:
13947 allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
13949 forEach(ast.arguments, function(expr) {
13950 findConstantAndWatchExpressions(expr, $filter);
13951 allConstants = allConstants && expr.constant;
13952 if (!expr.constant) {
13953 argsToWatch.push.apply(argsToWatch, expr.toWatch);
13956 ast.constant = allConstants;
13957 ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
13959 case AST.AssignmentExpression:
13960 findConstantAndWatchExpressions(ast.left, $filter);
13961 findConstantAndWatchExpressions(ast.right, $filter);
13962 ast.constant = ast.left.constant && ast.right.constant;
13963 ast.toWatch = [ast];
13965 case AST.ArrayExpression:
13966 allConstants = true;
13968 forEach(ast.elements, function(expr) {
13969 findConstantAndWatchExpressions(expr, $filter);
13970 allConstants = allConstants && expr.constant;
13971 if (!expr.constant) {
13972 argsToWatch.push.apply(argsToWatch, expr.toWatch);
13975 ast.constant = allConstants;
13976 ast.toWatch = argsToWatch;
13978 case AST.ObjectExpression:
13979 allConstants = true;
13981 forEach(ast.properties, function(property) {
13982 findConstantAndWatchExpressions(property.value, $filter);
13983 allConstants = allConstants && property.value.constant;
13984 if (!property.value.constant) {
13985 argsToWatch.push.apply(argsToWatch, property.value.toWatch);
13988 ast.constant = allConstants;
13989 ast.toWatch = argsToWatch;
13991 case AST.ThisExpression:
13992 ast.constant = false;
13995 case AST.LocalsExpression:
13996 ast.constant = false;
14002 function getInputs(body) {
14003 if (body.length != 1) return;
14004 var lastExpression = body[0].expression;
14005 var candidate = lastExpression.toWatch;
14006 if (candidate.length !== 1) return candidate;
14007 return candidate[0] !== lastExpression ? candidate : undefined;
14010 function isAssignable(ast) {
14011 return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
14014 function assignableAST(ast) {
14015 if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
14016 return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
14020 function isLiteral(ast) {
14021 return ast.body.length === 0 ||
14022 ast.body.length === 1 && (
14023 ast.body[0].expression.type === AST.Literal ||
14024 ast.body[0].expression.type === AST.ArrayExpression ||
14025 ast.body[0].expression.type === AST.ObjectExpression);
14028 function isConstant(ast) {
14029 return ast.constant;
14032 function ASTCompiler(astBuilder, $filter) {
14033 this.astBuilder = astBuilder;
14034 this.$filter = $filter;
14037 ASTCompiler.prototype = {
14038 compile: function(expression, expensiveChecks) {
14040 var ast = this.astBuilder.ast(expression);
14044 expensiveChecks: expensiveChecks,
14045 fn: {vars: [], body: [], own: {}},
14046 assign: {vars: [], body: [], own: {}},
14049 findConstantAndWatchExpressions(ast, self.$filter);
14052 this.stage = 'assign';
14053 if ((assignable = assignableAST(ast))) {
14054 this.state.computing = 'assign';
14055 var result = this.nextId();
14056 this.recurse(assignable, result);
14057 this.return_(result);
14058 extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
14060 var toWatch = getInputs(ast.body);
14061 self.stage = 'inputs';
14062 forEach(toWatch, function(watch, key) {
14063 var fnKey = 'fn' + key;
14064 self.state[fnKey] = {vars: [], body: [], own: {}};
14065 self.state.computing = fnKey;
14066 var intoId = self.nextId();
14067 self.recurse(watch, intoId);
14068 self.return_(intoId);
14069 self.state.inputs.push(fnKey);
14070 watch.watchId = key;
14072 this.state.computing = 'fn';
14073 this.stage = 'main';
14076 // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
14077 // This is a workaround for this until we do a better job at only removing the prefix only when we should.
14078 '"' + this.USE + ' ' + this.STRICT + '";\n' +
14079 this.filterPrefix() +
14080 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
14086 var fn = (new Function('$filter',
14087 'ensureSafeMemberName',
14088 'ensureSafeObject',
14089 'ensureSafeFunction',
14091 'ensureSafeAssignContext',
14097 ensureSafeMemberName,
14099 ensureSafeFunction,
14101 ensureSafeAssignContext,
14106 this.state = this.stage = undefined;
14107 fn.literal = isLiteral(ast);
14108 fn.constant = isConstant(ast);
14116 watchFns: function() {
14118 var fns = this.state.inputs;
14120 forEach(fns, function(name) {
14121 result.push('var ' + name + '=' + self.generateFunction(name, 's'));
14124 result.push('fn.inputs=[' + fns.join(',') + '];');
14126 return result.join('');
14129 generateFunction: function(name, params) {
14130 return 'function(' + params + '){' +
14131 this.varsPrefix(name) +
14136 filterPrefix: function() {
14139 forEach(this.state.filters, function(id, filter) {
14140 parts.push(id + '=$filter(' + self.escape(filter) + ')');
14142 if (parts.length) return 'var ' + parts.join(',') + ';';
14146 varsPrefix: function(section) {
14147 return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
14150 body: function(section) {
14151 return this.state[section].body.join('');
14154 recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
14155 var left, right, self = this, args, expression;
14156 recursionFn = recursionFn || noop;
14157 if (!skipWatchIdCheck && isDefined(ast.watchId)) {
14158 intoId = intoId || this.nextId();
14160 this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
14161 this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
14165 switch (ast.type) {
14167 forEach(ast.body, function(expression, pos) {
14168 self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
14169 if (pos !== ast.body.length - 1) {
14170 self.current().body.push(right, ';');
14172 self.return_(right);
14177 expression = this.escape(ast.value);
14178 this.assign(intoId, expression);
14179 recursionFn(expression);
14181 case AST.UnaryExpression:
14182 this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
14183 expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
14184 this.assign(intoId, expression);
14185 recursionFn(expression);
14187 case AST.BinaryExpression:
14188 this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
14189 this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
14190 if (ast.operator === '+') {
14191 expression = this.plus(left, right);
14192 } else if (ast.operator === '-') {
14193 expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
14195 expression = '(' + left + ')' + ast.operator + '(' + right + ')';
14197 this.assign(intoId, expression);
14198 recursionFn(expression);
14200 case AST.LogicalExpression:
14201 intoId = intoId || this.nextId();
14202 self.recurse(ast.left, intoId);
14203 self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
14204 recursionFn(intoId);
14206 case AST.ConditionalExpression:
14207 intoId = intoId || this.nextId();
14208 self.recurse(ast.test, intoId);
14209 self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
14210 recursionFn(intoId);
14212 case AST.Identifier:
14213 intoId = intoId || this.nextId();
14215 nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
14216 nameId.computed = false;
14217 nameId.name = ast.name;
14219 ensureSafeMemberName(ast.name);
14220 self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
14222 self.if_(self.stage === 'inputs' || 's', function() {
14223 if (create && create !== 1) {
14225 self.not(self.nonComputedMember('s', ast.name)),
14226 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
14228 self.assign(intoId, self.nonComputedMember('s', ast.name));
14230 }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
14232 if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
14233 self.addEnsureSafeObject(intoId);
14235 recursionFn(intoId);
14237 case AST.MemberExpression:
14238 left = nameId && (nameId.context = this.nextId()) || this.nextId();
14239 intoId = intoId || this.nextId();
14240 self.recurse(ast.object, left, undefined, function() {
14241 self.if_(self.notNull(left), function() {
14242 if (create && create !== 1) {
14243 self.addEnsureSafeAssignContext(left);
14245 if (ast.computed) {
14246 right = self.nextId();
14247 self.recurse(ast.property, right);
14248 self.getStringValue(right);
14249 self.addEnsureSafeMemberName(right);
14250 if (create && create !== 1) {
14251 self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
14253 expression = self.ensureSafeObject(self.computedMember(left, right));
14254 self.assign(intoId, expression);
14256 nameId.computed = true;
14257 nameId.name = right;
14260 ensureSafeMemberName(ast.property.name);
14261 if (create && create !== 1) {
14262 self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
14264 expression = self.nonComputedMember(left, ast.property.name);
14265 if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
14266 expression = self.ensureSafeObject(expression);
14268 self.assign(intoId, expression);
14270 nameId.computed = false;
14271 nameId.name = ast.property.name;
14275 self.assign(intoId, 'undefined');
14277 recursionFn(intoId);
14280 case AST.CallExpression:
14281 intoId = intoId || this.nextId();
14283 right = self.filter(ast.callee.name);
14285 forEach(ast.arguments, function(expr) {
14286 var argument = self.nextId();
14287 self.recurse(expr, argument);
14288 args.push(argument);
14290 expression = right + '(' + args.join(',') + ')';
14291 self.assign(intoId, expression);
14292 recursionFn(intoId);
14294 right = self.nextId();
14297 self.recurse(ast.callee, right, left, function() {
14298 self.if_(self.notNull(right), function() {
14299 self.addEnsureSafeFunction(right);
14300 forEach(ast.arguments, function(expr) {
14301 self.recurse(expr, self.nextId(), undefined, function(argument) {
14302 args.push(self.ensureSafeObject(argument));
14306 if (!self.state.expensiveChecks) {
14307 self.addEnsureSafeObject(left.context);
14309 expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
14311 expression = right + '(' + args.join(',') + ')';
14313 expression = self.ensureSafeObject(expression);
14314 self.assign(intoId, expression);
14316 self.assign(intoId, 'undefined');
14318 recursionFn(intoId);
14322 case AST.AssignmentExpression:
14323 right = this.nextId();
14325 if (!isAssignable(ast.left)) {
14326 throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
14328 this.recurse(ast.left, undefined, left, function() {
14329 self.if_(self.notNull(left.context), function() {
14330 self.recurse(ast.right, right);
14331 self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
14332 self.addEnsureSafeAssignContext(left.context);
14333 expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
14334 self.assign(intoId, expression);
14335 recursionFn(intoId || expression);
14339 case AST.ArrayExpression:
14341 forEach(ast.elements, function(expr) {
14342 self.recurse(expr, self.nextId(), undefined, function(argument) {
14343 args.push(argument);
14346 expression = '[' + args.join(',') + ']';
14347 this.assign(intoId, expression);
14348 recursionFn(expression);
14350 case AST.ObjectExpression:
14352 forEach(ast.properties, function(property) {
14353 self.recurse(property.value, self.nextId(), undefined, function(expr) {
14354 args.push(self.escape(
14355 property.key.type === AST.Identifier ? property.key.name :
14356 ('' + property.key.value)) +
14360 expression = '{' + args.join(',') + '}';
14361 this.assign(intoId, expression);
14362 recursionFn(expression);
14364 case AST.ThisExpression:
14365 this.assign(intoId, 's');
14368 case AST.LocalsExpression:
14369 this.assign(intoId, 'l');
14372 case AST.NGValueParameter:
14373 this.assign(intoId, 'v');
14379 getHasOwnProperty: function(element, property) {
14380 var key = element + '.' + property;
14381 var own = this.current().own;
14382 if (!own.hasOwnProperty(key)) {
14383 own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
14388 assign: function(id, value) {
14390 this.current().body.push(id, '=', value, ';');
14394 filter: function(filterName) {
14395 if (!this.state.filters.hasOwnProperty(filterName)) {
14396 this.state.filters[filterName] = this.nextId(true);
14398 return this.state.filters[filterName];
14401 ifDefined: function(id, defaultValue) {
14402 return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
14405 plus: function(left, right) {
14406 return 'plus(' + left + ',' + right + ')';
14409 return_: function(id) {
14410 this.current().body.push('return ', id, ';');
14413 if_: function(test, alternate, consequent) {
14414 if (test === true) {
14417 var body = this.current().body;
14418 body.push('if(', test, '){');
14422 body.push('else{');
14429 not: function(expression) {
14430 return '!(' + expression + ')';
14433 notNull: function(expression) {
14434 return expression + '!=null';
14437 nonComputedMember: function(left, right) {
14438 return left + '.' + right;
14441 computedMember: function(left, right) {
14442 return left + '[' + right + ']';
14445 member: function(left, right, computed) {
14446 if (computed) return this.computedMember(left, right);
14447 return this.nonComputedMember(left, right);
14450 addEnsureSafeObject: function(item) {
14451 this.current().body.push(this.ensureSafeObject(item), ';');
14454 addEnsureSafeMemberName: function(item) {
14455 this.current().body.push(this.ensureSafeMemberName(item), ';');
14458 addEnsureSafeFunction: function(item) {
14459 this.current().body.push(this.ensureSafeFunction(item), ';');
14462 addEnsureSafeAssignContext: function(item) {
14463 this.current().body.push(this.ensureSafeAssignContext(item), ';');
14466 ensureSafeObject: function(item) {
14467 return 'ensureSafeObject(' + item + ',text)';
14470 ensureSafeMemberName: function(item) {
14471 return 'ensureSafeMemberName(' + item + ',text)';
14474 ensureSafeFunction: function(item) {
14475 return 'ensureSafeFunction(' + item + ',text)';
14478 getStringValue: function(item) {
14479 this.assign(item, 'getStringValue(' + item + ')');
14482 ensureSafeAssignContext: function(item) {
14483 return 'ensureSafeAssignContext(' + item + ',text)';
14486 lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
14488 return function() {
14489 self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
14493 lazyAssign: function(id, value) {
14495 return function() {
14496 self.assign(id, value);
14500 stringEscapeRegex: /[^ a-zA-Z0-9]/g,
14502 stringEscapeFn: function(c) {
14503 return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
14506 escape: function(value) {
14507 if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
14508 if (isNumber(value)) return value.toString();
14509 if (value === true) return 'true';
14510 if (value === false) return 'false';
14511 if (value === null) return 'null';
14512 if (typeof value === 'undefined') return 'undefined';
14514 throw $parseMinErr('esc', 'IMPOSSIBLE');
14517 nextId: function(skip, init) {
14518 var id = 'v' + (this.state.nextId++);
14520 this.current().vars.push(id + (init ? '=' + init : ''));
14525 current: function() {
14526 return this.state[this.state.computing];
14531 function ASTInterpreter(astBuilder, $filter) {
14532 this.astBuilder = astBuilder;
14533 this.$filter = $filter;
14536 ASTInterpreter.prototype = {
14537 compile: function(expression, expensiveChecks) {
14539 var ast = this.astBuilder.ast(expression);
14540 this.expression = expression;
14541 this.expensiveChecks = expensiveChecks;
14542 findConstantAndWatchExpressions(ast, self.$filter);
14545 if ((assignable = assignableAST(ast))) {
14546 assign = this.recurse(assignable);
14548 var toWatch = getInputs(ast.body);
14552 forEach(toWatch, function(watch, key) {
14553 var input = self.recurse(watch);
14554 watch.input = input;
14555 inputs.push(input);
14556 watch.watchId = key;
14559 var expressions = [];
14560 forEach(ast.body, function(expression) {
14561 expressions.push(self.recurse(expression.expression));
14563 var fn = ast.body.length === 0 ? function() {} :
14564 ast.body.length === 1 ? expressions[0] :
14565 function(scope, locals) {
14567 forEach(expressions, function(exp) {
14568 lastValue = exp(scope, locals);
14573 fn.assign = function(scope, value, locals) {
14574 return assign(scope, locals, value);
14578 fn.inputs = inputs;
14580 fn.literal = isLiteral(ast);
14581 fn.constant = isConstant(ast);
14585 recurse: function(ast, context, create) {
14586 var left, right, self = this, args, expression;
14588 return this.inputs(ast.input, ast.watchId);
14590 switch (ast.type) {
14592 return this.value(ast.value, context);
14593 case AST.UnaryExpression:
14594 right = this.recurse(ast.argument);
14595 return this['unary' + ast.operator](right, context);
14596 case AST.BinaryExpression:
14597 left = this.recurse(ast.left);
14598 right = this.recurse(ast.right);
14599 return this['binary' + ast.operator](left, right, context);
14600 case AST.LogicalExpression:
14601 left = this.recurse(ast.left);
14602 right = this.recurse(ast.right);
14603 return this['binary' + ast.operator](left, right, context);
14604 case AST.ConditionalExpression:
14605 return this['ternary?:'](
14606 this.recurse(ast.test),
14607 this.recurse(ast.alternate),
14608 this.recurse(ast.consequent),
14611 case AST.Identifier:
14612 ensureSafeMemberName(ast.name, self.expression);
14613 return self.identifier(ast.name,
14614 self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
14615 context, create, self.expression);
14616 case AST.MemberExpression:
14617 left = this.recurse(ast.object, false, !!create);
14618 if (!ast.computed) {
14619 ensureSafeMemberName(ast.property.name, self.expression);
14620 right = ast.property.name;
14622 if (ast.computed) right = this.recurse(ast.property);
14623 return ast.computed ?
14624 this.computedMember(left, right, context, create, self.expression) :
14625 this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
14626 case AST.CallExpression:
14628 forEach(ast.arguments, function(expr) {
14629 args.push(self.recurse(expr));
14631 if (ast.filter) right = this.$filter(ast.callee.name);
14632 if (!ast.filter) right = this.recurse(ast.callee, true);
14633 return ast.filter ?
14634 function(scope, locals, assign, inputs) {
14636 for (var i = 0; i < args.length; ++i) {
14637 values.push(args[i](scope, locals, assign, inputs));
14639 var value = right.apply(undefined, values, inputs);
14640 return context ? {context: undefined, name: undefined, value: value} : value;
14642 function(scope, locals, assign, inputs) {
14643 var rhs = right(scope, locals, assign, inputs);
14645 if (rhs.value != null) {
14646 ensureSafeObject(rhs.context, self.expression);
14647 ensureSafeFunction(rhs.value, self.expression);
14649 for (var i = 0; i < args.length; ++i) {
14650 values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
14652 value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
14654 return context ? {value: value} : value;
14656 case AST.AssignmentExpression:
14657 left = this.recurse(ast.left, true, 1);
14658 right = this.recurse(ast.right);
14659 return function(scope, locals, assign, inputs) {
14660 var lhs = left(scope, locals, assign, inputs);
14661 var rhs = right(scope, locals, assign, inputs);
14662 ensureSafeObject(lhs.value, self.expression);
14663 ensureSafeAssignContext(lhs.context);
14664 lhs.context[lhs.name] = rhs;
14665 return context ? {value: rhs} : rhs;
14667 case AST.ArrayExpression:
14669 forEach(ast.elements, function(expr) {
14670 args.push(self.recurse(expr));
14672 return function(scope, locals, assign, inputs) {
14674 for (var i = 0; i < args.length; ++i) {
14675 value.push(args[i](scope, locals, assign, inputs));
14677 return context ? {value: value} : value;
14679 case AST.ObjectExpression:
14681 forEach(ast.properties, function(property) {
14682 args.push({key: property.key.type === AST.Identifier ?
14683 property.key.name :
14684 ('' + property.key.value),
14685 value: self.recurse(property.value)
14688 return function(scope, locals, assign, inputs) {
14690 for (var i = 0; i < args.length; ++i) {
14691 value[args[i].key] = args[i].value(scope, locals, assign, inputs);
14693 return context ? {value: value} : value;
14695 case AST.ThisExpression:
14696 return function(scope) {
14697 return context ? {value: scope} : scope;
14699 case AST.LocalsExpression:
14700 return function(scope, locals) {
14701 return context ? {value: locals} : locals;
14703 case AST.NGValueParameter:
14704 return function(scope, locals, assign, inputs) {
14705 return context ? {value: assign} : assign;
14710 'unary+': function(argument, context) {
14711 return function(scope, locals, assign, inputs) {
14712 var arg = argument(scope, locals, assign, inputs);
14713 if (isDefined(arg)) {
14718 return context ? {value: arg} : arg;
14721 'unary-': function(argument, context) {
14722 return function(scope, locals, assign, inputs) {
14723 var arg = argument(scope, locals, assign, inputs);
14724 if (isDefined(arg)) {
14729 return context ? {value: arg} : arg;
14732 'unary!': function(argument, context) {
14733 return function(scope, locals, assign, inputs) {
14734 var arg = !argument(scope, locals, assign, inputs);
14735 return context ? {value: arg} : arg;
14738 'binary+': function(left, right, context) {
14739 return function(scope, locals, assign, inputs) {
14740 var lhs = left(scope, locals, assign, inputs);
14741 var rhs = right(scope, locals, assign, inputs);
14742 var arg = plusFn(lhs, rhs);
14743 return context ? {value: arg} : arg;
14746 'binary-': function(left, right, context) {
14747 return function(scope, locals, assign, inputs) {
14748 var lhs = left(scope, locals, assign, inputs);
14749 var rhs = right(scope, locals, assign, inputs);
14750 var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
14751 return context ? {value: arg} : arg;
14754 'binary*': function(left, right, context) {
14755 return function(scope, locals, assign, inputs) {
14756 var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
14757 return context ? {value: arg} : arg;
14760 'binary/': function(left, right, context) {
14761 return function(scope, locals, assign, inputs) {
14762 var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
14763 return context ? {value: arg} : arg;
14766 'binary%': function(left, right, context) {
14767 return function(scope, locals, assign, inputs) {
14768 var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
14769 return context ? {value: arg} : arg;
14772 'binary===': function(left, right, context) {
14773 return function(scope, locals, assign, inputs) {
14774 var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
14775 return context ? {value: arg} : arg;
14778 'binary!==': function(left, right, context) {
14779 return function(scope, locals, assign, inputs) {
14780 var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
14781 return context ? {value: arg} : arg;
14784 'binary==': function(left, right, context) {
14785 return function(scope, locals, assign, inputs) {
14786 var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
14787 return context ? {value: arg} : arg;
14790 'binary!=': function(left, right, context) {
14791 return function(scope, locals, assign, inputs) {
14792 var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
14793 return context ? {value: arg} : arg;
14796 'binary<': function(left, right, context) {
14797 return function(scope, locals, assign, inputs) {
14798 var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
14799 return context ? {value: arg} : arg;
14802 'binary>': function(left, right, context) {
14803 return function(scope, locals, assign, inputs) {
14804 var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
14805 return context ? {value: arg} : arg;
14808 'binary<=': function(left, right, context) {
14809 return function(scope, locals, assign, inputs) {
14810 var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
14811 return context ? {value: arg} : arg;
14814 'binary>=': function(left, right, context) {
14815 return function(scope, locals, assign, inputs) {
14816 var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
14817 return context ? {value: arg} : arg;
14820 'binary&&': function(left, right, context) {
14821 return function(scope, locals, assign, inputs) {
14822 var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
14823 return context ? {value: arg} : arg;
14826 'binary||': function(left, right, context) {
14827 return function(scope, locals, assign, inputs) {
14828 var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
14829 return context ? {value: arg} : arg;
14832 'ternary?:': function(test, alternate, consequent, context) {
14833 return function(scope, locals, assign, inputs) {
14834 var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
14835 return context ? {value: arg} : arg;
14838 value: function(value, context) {
14839 return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
14841 identifier: function(name, expensiveChecks, context, create, expression) {
14842 return function(scope, locals, assign, inputs) {
14843 var base = locals && (name in locals) ? locals : scope;
14844 if (create && create !== 1 && base && !(base[name])) {
14847 var value = base ? base[name] : undefined;
14848 if (expensiveChecks) {
14849 ensureSafeObject(value, expression);
14852 return {context: base, name: name, value: value};
14858 computedMember: function(left, right, context, create, expression) {
14859 return function(scope, locals, assign, inputs) {
14860 var lhs = left(scope, locals, assign, inputs);
14864 rhs = right(scope, locals, assign, inputs);
14865 rhs = getStringValue(rhs);
14866 ensureSafeMemberName(rhs, expression);
14867 if (create && create !== 1) {
14868 ensureSafeAssignContext(lhs);
14869 if (lhs && !(lhs[rhs])) {
14874 ensureSafeObject(value, expression);
14877 return {context: lhs, name: rhs, value: value};
14883 nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
14884 return function(scope, locals, assign, inputs) {
14885 var lhs = left(scope, locals, assign, inputs);
14886 if (create && create !== 1) {
14887 ensureSafeAssignContext(lhs);
14888 if (lhs && !(lhs[right])) {
14892 var value = lhs != null ? lhs[right] : undefined;
14893 if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
14894 ensureSafeObject(value, expression);
14897 return {context: lhs, name: right, value: value};
14903 inputs: function(input, watchId) {
14904 return function(scope, value, locals, inputs) {
14905 if (inputs) return inputs[watchId];
14906 return input(scope, value, locals);
14914 var Parser = function(lexer, $filter, options) {
14915 this.lexer = lexer;
14916 this.$filter = $filter;
14917 this.options = options;
14918 this.ast = new AST(this.lexer);
14919 this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
14920 new ASTCompiler(this.ast, $filter);
14923 Parser.prototype = {
14924 constructor: Parser,
14926 parse: function(text) {
14927 return this.astCompiler.compile(text, this.options.expensiveChecks);
14931 function isPossiblyDangerousMemberName(name) {
14932 return name == 'constructor';
14935 var objectValueOf = Object.prototype.valueOf;
14937 function getValueOf(value) {
14938 return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
14941 ///////////////////////////////////
14950 * Converts Angular {@link guide/expression expression} into a function.
14953 * var getter = $parse('user.name');
14954 * var setter = getter.assign;
14955 * var context = {user:{name:'angular'}};
14956 * var locals = {user:{name:'local'}};
14958 * expect(getter(context)).toEqual('angular');
14959 * setter(context, 'newValue');
14960 * expect(context.user.name).toEqual('newValue');
14961 * expect(getter(context, locals)).toEqual('local');
14965 * @param {string} expression String expression to compile.
14966 * @returns {function(context, locals)} a function which represents the compiled expression:
14968 * * `context` – `{object}` – an object against which any expressions embedded in the strings
14969 * are evaluated against (typically a scope object).
14970 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
14973 * The returned function also has the following properties:
14974 * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
14976 * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
14977 * constant literals.
14978 * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
14979 * set to a function to change its value on the given context.
14986 * @name $parseProvider
14989 * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
14992 function $ParseProvider() {
14993 var cacheDefault = createMap();
14994 var cacheExpensive = createMap();
14996 this.$get = ['$filter', function($filter) {
14997 var noUnsafeEval = csp().noUnsafeEval;
14998 var $parseOptions = {
15000 expensiveChecks: false
15002 $parseOptionsExpensive = {
15004 expensiveChecks: true
15006 var runningChecksEnabled = false;
15008 $parse.$$runningExpensiveChecks = function() {
15009 return runningChecksEnabled;
15014 function $parse(exp, interceptorFn, expensiveChecks) {
15015 var parsedExpression, oneTime, cacheKey;
15017 expensiveChecks = expensiveChecks || runningChecksEnabled;
15019 switch (typeof exp) {
15024 var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
15025 parsedExpression = cache[cacheKey];
15027 if (!parsedExpression) {
15028 if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
15030 exp = exp.substring(2);
15032 var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
15033 var lexer = new Lexer(parseOptions);
15034 var parser = new Parser(lexer, $filter, parseOptions);
15035 parsedExpression = parser.parse(exp);
15036 if (parsedExpression.constant) {
15037 parsedExpression.$$watchDelegate = constantWatchDelegate;
15038 } else if (oneTime) {
15039 parsedExpression.$$watchDelegate = parsedExpression.literal ?
15040 oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
15041 } else if (parsedExpression.inputs) {
15042 parsedExpression.$$watchDelegate = inputsWatchDelegate;
15044 if (expensiveChecks) {
15045 parsedExpression = expensiveChecksInterceptor(parsedExpression);
15047 cache[cacheKey] = parsedExpression;
15049 return addInterceptor(parsedExpression, interceptorFn);
15052 return addInterceptor(exp, interceptorFn);
15055 return addInterceptor(noop, interceptorFn);
15059 function expensiveChecksInterceptor(fn) {
15060 if (!fn) return fn;
15061 expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
15062 expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
15063 expensiveCheckFn.constant = fn.constant;
15064 expensiveCheckFn.literal = fn.literal;
15065 for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
15066 fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
15068 expensiveCheckFn.inputs = fn.inputs;
15070 return expensiveCheckFn;
15072 function expensiveCheckFn(scope, locals, assign, inputs) {
15073 var expensiveCheckOldValue = runningChecksEnabled;
15074 runningChecksEnabled = true;
15076 return fn(scope, locals, assign, inputs);
15078 runningChecksEnabled = expensiveCheckOldValue;
15083 function expressionInputDirtyCheck(newValue, oldValueOfValue) {
15085 if (newValue == null || oldValueOfValue == null) { // null/undefined
15086 return newValue === oldValueOfValue;
15089 if (typeof newValue === 'object') {
15091 // attempt to convert the value to a primitive type
15092 // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
15093 // be cheaply dirty-checked
15094 newValue = getValueOf(newValue);
15096 if (typeof newValue === 'object') {
15097 // objects/arrays are not supported - deep-watching them would be too expensive
15101 // fall-through to the primitive equality check
15105 return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
15108 function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
15109 var inputExpressions = parsedExpression.inputs;
15112 if (inputExpressions.length === 1) {
15113 var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
15114 inputExpressions = inputExpressions[0];
15115 return scope.$watch(function expressionInputWatch(scope) {
15116 var newInputValue = inputExpressions(scope);
15117 if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
15118 lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
15119 oldInputValueOf = newInputValue && getValueOf(newInputValue);
15122 }, listener, objectEquality, prettyPrintExpression);
15125 var oldInputValueOfValues = [];
15126 var oldInputValues = [];
15127 for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
15128 oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
15129 oldInputValues[i] = null;
15132 return scope.$watch(function expressionInputsWatch(scope) {
15133 var changed = false;
15135 for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
15136 var newInputValue = inputExpressions[i](scope);
15137 if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
15138 oldInputValues[i] = newInputValue;
15139 oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
15144 lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
15148 }, listener, objectEquality, prettyPrintExpression);
15151 function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
15152 var unwatch, lastValue;
15153 return unwatch = scope.$watch(function oneTimeWatch(scope) {
15154 return parsedExpression(scope);
15155 }, function oneTimeListener(value, old, scope) {
15157 if (isFunction(listener)) {
15158 listener.apply(this, arguments);
15160 if (isDefined(value)) {
15161 scope.$$postDigest(function() {
15162 if (isDefined(lastValue)) {
15167 }, objectEquality);
15170 function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
15171 var unwatch, lastValue;
15172 return unwatch = scope.$watch(function oneTimeWatch(scope) {
15173 return parsedExpression(scope);
15174 }, function oneTimeListener(value, old, scope) {
15176 if (isFunction(listener)) {
15177 listener.call(this, value, old, scope);
15179 if (isAllDefined(value)) {
15180 scope.$$postDigest(function() {
15181 if (isAllDefined(lastValue)) unwatch();
15184 }, objectEquality);
15186 function isAllDefined(value) {
15187 var allDefined = true;
15188 forEach(value, function(val) {
15189 if (!isDefined(val)) allDefined = false;
15195 function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
15197 return unwatch = scope.$watch(function constantWatch(scope) {
15199 return parsedExpression(scope);
15200 }, listener, objectEquality);
15203 function addInterceptor(parsedExpression, interceptorFn) {
15204 if (!interceptorFn) return parsedExpression;
15205 var watchDelegate = parsedExpression.$$watchDelegate;
15206 var useInputs = false;
15209 watchDelegate !== oneTimeLiteralWatchDelegate &&
15210 watchDelegate !== oneTimeWatchDelegate;
15212 var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
15213 var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
15214 return interceptorFn(value, scope, locals);
15215 } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
15216 var value = parsedExpression(scope, locals, assign, inputs);
15217 var result = interceptorFn(value, scope, locals);
15218 // we only return the interceptor's result if the
15219 // initial value is defined (for bind-once)
15220 return isDefined(value) ? result : value;
15223 // Propagate $$watchDelegates other then inputsWatchDelegate
15224 if (parsedExpression.$$watchDelegate &&
15225 parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
15226 fn.$$watchDelegate = parsedExpression.$$watchDelegate;
15227 } else if (!interceptorFn.$stateful) {
15228 // If there is an interceptor, but no watchDelegate then treat the interceptor like
15229 // we treat filters - it is assumed to be a pure function unless flagged with $stateful
15230 fn.$$watchDelegate = inputsWatchDelegate;
15231 useInputs = !parsedExpression.inputs;
15232 fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
15243 * @requires $rootScope
15246 * A service that helps you run functions asynchronously, and use their return values (or exceptions)
15247 * when they are done processing.
15249 * This is an implementation of promises/deferred objects inspired by
15250 * [Kris Kowal's Q](https://github.com/kriskowal/q).
15252 * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
15253 * implementations, and the other which resembles ES6 promises to some degree.
15257 * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
15258 * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
15259 * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
15261 * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
15264 * It can be used like so:
15267 * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
15268 * // are available in the current lexical scope (they could have been injected or passed in).
15270 * function asyncGreet(name) {
15271 * // perform some asynchronous operation, resolve or reject the promise when appropriate.
15272 * return $q(function(resolve, reject) {
15273 * setTimeout(function() {
15274 * if (okToGreet(name)) {
15275 * resolve('Hello, ' + name + '!');
15277 * reject('Greeting ' + name + ' is not allowed.');
15283 * var promise = asyncGreet('Robin Hood');
15284 * promise.then(function(greeting) {
15285 * alert('Success: ' + greeting);
15286 * }, function(reason) {
15287 * alert('Failed: ' + reason);
15291 * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
15293 * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
15295 * However, the more traditional CommonJS-style usage is still available, and documented below.
15297 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
15298 * interface for interacting with an object that represents the result of an action that is
15299 * performed asynchronously, and may or may not be finished at any given point in time.
15301 * From the perspective of dealing with error handling, deferred and promise APIs are to
15302 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
15305 * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
15306 * // are available in the current lexical scope (they could have been injected or passed in).
15308 * function asyncGreet(name) {
15309 * var deferred = $q.defer();
15311 * setTimeout(function() {
15312 * deferred.notify('About to greet ' + name + '.');
15314 * if (okToGreet(name)) {
15315 * deferred.resolve('Hello, ' + name + '!');
15317 * deferred.reject('Greeting ' + name + ' is not allowed.');
15321 * return deferred.promise;
15324 * var promise = asyncGreet('Robin Hood');
15325 * promise.then(function(greeting) {
15326 * alert('Success: ' + greeting);
15327 * }, function(reason) {
15328 * alert('Failed: ' + reason);
15329 * }, function(update) {
15330 * alert('Got notification: ' + update);
15334 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
15335 * comes in the way of guarantees that promise and deferred APIs make, see
15336 * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
15338 * Additionally the promise api allows for composition that is very hard to do with the
15339 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
15340 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
15341 * section on serial or parallel joining of promises.
15343 * # The Deferred API
15345 * A new instance of deferred is constructed by calling `$q.defer()`.
15347 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
15348 * that can be used for signaling the successful or unsuccessful completion, as well as the status
15353 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
15354 * constructed via `$q.reject`, the promise will be rejected instead.
15355 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
15356 * resolving it with a rejection constructed via `$q.reject`.
15357 * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
15358 * multiple times before the promise is either resolved or rejected.
15362 * - promise – `{Promise}` – promise object associated with this deferred.
15365 * # The Promise API
15367 * A new promise instance is created when a deferred instance is created and can be retrieved by
15368 * calling `deferred.promise`.
15370 * The purpose of the promise object is to allow for interested parties to get access to the result
15371 * of the deferred task when it completes.
15375 * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
15376 * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
15377 * as soon as the result is available. The callbacks are called with a single argument: the result
15378 * or rejection reason. Additionally, the notify callback may be called zero or more times to
15379 * provide a progress indication, before the promise is resolved or rejected.
15381 * This method *returns a new promise* which is resolved or rejected via the return value of the
15382 * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
15383 * with the value which is resolved in that promise using
15384 * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
15385 * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
15386 * resolved or rejected from the notifyCallback method.
15388 * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
15390 * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
15391 * but to do so without modifying the final value. This is useful to release resources or do some
15392 * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
15393 * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
15394 * more information.
15396 * # Chaining promises
15398 * Because calling the `then` method of a promise returns a new derived promise, it is easily
15399 * possible to create a chain of promises:
15402 * promiseB = promiseA.then(function(result) {
15403 * return result + 1;
15406 * // promiseB will be resolved immediately after promiseA is resolved and its value
15407 * // will be the result of promiseA incremented by 1
15410 * It is possible to create chains of any length and since a promise can be resolved with another
15411 * promise (which will defer its resolution further), it is possible to pause/defer resolution of
15412 * the promises at any point in the chain. This makes it possible to implement powerful APIs like
15413 * $http's response interceptors.
15416 * # Differences between Kris Kowal's Q and $q
15418 * There are two main differences:
15420 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
15421 * mechanism in angular, which means faster propagation of resolution or rejection into your
15422 * models and avoiding unnecessary browser repaints, which would result in flickering UI.
15423 * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
15424 * all the important functionality needed for common async tasks.
15429 * it('should simulate promise', inject(function($q, $rootScope) {
15430 * var deferred = $q.defer();
15431 * var promise = deferred.promise;
15432 * var resolvedValue;
15434 * promise.then(function(value) { resolvedValue = value; });
15435 * expect(resolvedValue).toBeUndefined();
15437 * // Simulate resolving of promise
15438 * deferred.resolve(123);
15439 * // Note that the 'then' function does not get called synchronously.
15440 * // This is because we want the promise API to always be async, whether or not
15441 * // it got called synchronously or asynchronously.
15442 * expect(resolvedValue).toBeUndefined();
15444 * // Propagate promise resolution to 'then' functions using $apply().
15445 * $rootScope.$apply();
15446 * expect(resolvedValue).toEqual(123);
15450 * @param {function(function, function)} resolver Function which is responsible for resolving or
15451 * rejecting the newly created promise. The first parameter is a function which resolves the
15452 * promise, the second parameter is a function which rejects the promise.
15454 * @returns {Promise} The newly created promise.
15456 function $QProvider() {
15458 this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
15459 return qFactory(function(callback) {
15460 $rootScope.$evalAsync(callback);
15461 }, $exceptionHandler);
15465 function $$QProvider() {
15466 this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
15467 return qFactory(function(callback) {
15468 $browser.defer(callback);
15469 }, $exceptionHandler);
15474 * Constructs a promise manager.
15476 * @param {function(function)} nextTick Function for executing functions in the next turn.
15477 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
15478 * debugging purposes.
15479 * @returns {object} Promise manager.
15481 function qFactory(nextTick, exceptionHandler) {
15482 var $qMinErr = minErr('$q', TypeError);
15486 * @name ng.$q#defer
15490 * Creates a `Deferred` object which represents a task which will finish in the future.
15492 * @returns {Deferred} Returns a new instance of deferred.
15494 var defer = function() {
15495 var d = new Deferred();
15496 //Necessary to support unbound execution :/
15497 d.resolve = simpleBind(d, d.resolve);
15498 d.reject = simpleBind(d, d.reject);
15499 d.notify = simpleBind(d, d.notify);
15503 function Promise() {
15504 this.$$state = { status: 0 };
15507 extend(Promise.prototype, {
15508 then: function(onFulfilled, onRejected, progressBack) {
15509 if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
15512 var result = new Deferred();
15514 this.$$state.pending = this.$$state.pending || [];
15515 this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
15516 if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
15518 return result.promise;
15521 "catch": function(callback) {
15522 return this.then(null, callback);
15525 "finally": function(callback, progressBack) {
15526 return this.then(function(value) {
15527 return handleCallback(value, true, callback);
15528 }, function(error) {
15529 return handleCallback(error, false, callback);
15534 //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
15535 function simpleBind(context, fn) {
15536 return function(value) {
15537 fn.call(context, value);
15541 function processQueue(state) {
15542 var fn, deferred, pending;
15544 pending = state.pending;
15545 state.processScheduled = false;
15546 state.pending = undefined;
15547 for (var i = 0, ii = pending.length; i < ii; ++i) {
15548 deferred = pending[i][0];
15549 fn = pending[i][state.status];
15551 if (isFunction(fn)) {
15552 deferred.resolve(fn(state.value));
15553 } else if (state.status === 1) {
15554 deferred.resolve(state.value);
15556 deferred.reject(state.value);
15559 deferred.reject(e);
15560 exceptionHandler(e);
15565 function scheduleProcessQueue(state) {
15566 if (state.processScheduled || !state.pending) return;
15567 state.processScheduled = true;
15568 nextTick(function() { processQueue(state); });
15571 function Deferred() {
15572 this.promise = new Promise();
15575 extend(Deferred.prototype, {
15576 resolve: function(val) {
15577 if (this.promise.$$state.status) return;
15578 if (val === this.promise) {
15579 this.$$reject($qMinErr(
15581 "Expected promise to be resolved with value other than itself '{0}'",
15584 this.$$resolve(val);
15589 $$resolve: function(val) {
15594 if ((isObject(val) || isFunction(val))) then = val && val.then;
15595 if (isFunction(then)) {
15596 this.promise.$$state.status = -1;
15597 then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
15599 this.promise.$$state.value = val;
15600 this.promise.$$state.status = 1;
15601 scheduleProcessQueue(this.promise.$$state);
15605 exceptionHandler(e);
15608 function resolvePromise(val) {
15611 that.$$resolve(val);
15613 function rejectPromise(val) {
15616 that.$$reject(val);
15620 reject: function(reason) {
15621 if (this.promise.$$state.status) return;
15622 this.$$reject(reason);
15625 $$reject: function(reason) {
15626 this.promise.$$state.value = reason;
15627 this.promise.$$state.status = 2;
15628 scheduleProcessQueue(this.promise.$$state);
15631 notify: function(progress) {
15632 var callbacks = this.promise.$$state.pending;
15634 if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
15635 nextTick(function() {
15636 var callback, result;
15637 for (var i = 0, ii = callbacks.length; i < ii; i++) {
15638 result = callbacks[i][0];
15639 callback = callbacks[i][3];
15641 result.notify(isFunction(callback) ? callback(progress) : progress);
15643 exceptionHandler(e);
15657 * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
15658 * used to forward rejection in a chain of promises. If you are dealing with the last promise in
15659 * a promise chain, you don't need to worry about it.
15661 * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
15662 * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
15663 * a promise error callback and you want to forward the error to the promise derived from the
15664 * current promise, you have to "rethrow" the error by returning a rejection constructed via
15668 * promiseB = promiseA.then(function(result) {
15669 * // success: do something and resolve promiseB
15670 * // with the old or a new result
15672 * }, function(reason) {
15673 * // error: handle the error if possible and
15674 * // resolve promiseB with newPromiseOrValue,
15675 * // otherwise forward the rejection to promiseB
15676 * if (canHandle(reason)) {
15677 * // handle the error and recover
15678 * return newPromiseOrValue;
15680 * return $q.reject(reason);
15684 * @param {*} reason Constant, message, exception or an object representing the rejection reason.
15685 * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
15687 var reject = function(reason) {
15688 var result = new Deferred();
15689 result.reject(reason);
15690 return result.promise;
15693 var makePromise = function makePromise(value, resolved) {
15694 var result = new Deferred();
15696 result.resolve(value);
15698 result.reject(value);
15700 return result.promise;
15703 var handleCallback = function handleCallback(value, isResolved, callback) {
15704 var callbackOutput = null;
15706 if (isFunction(callback)) callbackOutput = callback();
15708 return makePromise(e, false);
15710 if (isPromiseLike(callbackOutput)) {
15711 return callbackOutput.then(function() {
15712 return makePromise(value, isResolved);
15713 }, function(error) {
15714 return makePromise(error, false);
15717 return makePromise(value, isResolved);
15727 * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
15728 * This is useful when you are dealing with an object that might or might not be a promise, or if
15729 * the promise comes from a source that can't be trusted.
15731 * @param {*} value Value or a promise
15732 * @param {Function=} successCallback
15733 * @param {Function=} errorCallback
15734 * @param {Function=} progressCallback
15735 * @returns {Promise} Returns a promise of the passed value or promise
15739 var when = function(value, callback, errback, progressBack) {
15740 var result = new Deferred();
15741 result.resolve(value);
15742 return result.promise.then(callback, errback, progressBack);
15751 * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
15753 * @param {*} value Value or a promise
15754 * @param {Function=} successCallback
15755 * @param {Function=} errorCallback
15756 * @param {Function=} progressCallback
15757 * @returns {Promise} Returns a promise of the passed value or promise
15759 var resolve = when;
15767 * Combines multiple promises into a single promise that is resolved when all of the input
15768 * promises are resolved.
15770 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
15771 * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
15772 * each value corresponding to the promise at the same index/key in the `promises` array/hash.
15773 * If any of the promises is resolved with a rejection, this resulting promise will be rejected
15774 * with the same rejection value.
15777 function all(promises) {
15778 var deferred = new Deferred(),
15780 results = isArray(promises) ? [] : {};
15782 forEach(promises, function(promise, key) {
15784 when(promise).then(function(value) {
15785 if (results.hasOwnProperty(key)) return;
15786 results[key] = value;
15787 if (!(--counter)) deferred.resolve(results);
15788 }, function(reason) {
15789 if (results.hasOwnProperty(key)) return;
15790 deferred.reject(reason);
15794 if (counter === 0) {
15795 deferred.resolve(results);
15798 return deferred.promise;
15801 var $Q = function Q(resolver) {
15802 if (!isFunction(resolver)) {
15803 throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
15806 var deferred = new Deferred();
15808 function resolveFn(value) {
15809 deferred.resolve(value);
15812 function rejectFn(reason) {
15813 deferred.reject(reason);
15816 resolver(resolveFn, rejectFn);
15818 return deferred.promise;
15821 // Let's make the instanceof operator work for promises, so that
15822 // `new $q(fn) instanceof $q` would evaluate to true.
15823 $Q.prototype = Promise.prototype;
15826 $Q.reject = reject;
15828 $Q.resolve = resolve;
15834 function $$RAFProvider() { //rAF
15835 this.$get = ['$window', '$timeout', function($window, $timeout) {
15836 var requestAnimationFrame = $window.requestAnimationFrame ||
15837 $window.webkitRequestAnimationFrame;
15839 var cancelAnimationFrame = $window.cancelAnimationFrame ||
15840 $window.webkitCancelAnimationFrame ||
15841 $window.webkitCancelRequestAnimationFrame;
15843 var rafSupported = !!requestAnimationFrame;
15844 var raf = rafSupported
15846 var id = requestAnimationFrame(fn);
15847 return function() {
15848 cancelAnimationFrame(id);
15852 var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
15853 return function() {
15854 $timeout.cancel(timer);
15858 raf.supported = rafSupported;
15867 * The design decisions behind the scope are heavily favored for speed and memory consumption.
15869 * The typical use of scope is to watch the expressions, which most of the time return the same
15870 * value as last time so we optimize the operation.
15872 * Closures construction is expensive in terms of speed as well as memory:
15873 * - No closures, instead use prototypical inheritance for API
15874 * - Internal state needs to be stored on scope directly, which means that private state is
15875 * exposed as $$____ properties
15877 * Loop operations are optimized by using while(count--) { ... }
15878 * - This means that in order to keep the same order of execution as addition we have to add
15879 * items to the array at the beginning (unshift) instead of at the end (push)
15881 * Child scopes are created and removed often
15882 * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
15884 * There are fewer watches than observers. This is why you don't want the observer to be implemented
15885 * in the same way as watch. Watch requires return of the initialization function which is expensive
15892 * @name $rootScopeProvider
15895 * Provider for the $rootScope service.
15900 * @name $rootScopeProvider#digestTtl
15903 * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
15904 * assuming that the model is unstable.
15906 * The current default is 10 iterations.
15908 * In complex applications it's possible that the dependencies between `$watch`s will result in
15909 * several digest iterations. However if an application needs more than the default 10 digest
15910 * iterations for its model to stabilize then you should investigate what is causing the model to
15911 * continuously change during the digest.
15913 * Increasing the TTL could have performance implications, so you should not change it without
15914 * proper justification.
15916 * @param {number} limit The number of digest iterations.
15925 * Every application has a single root {@link ng.$rootScope.Scope scope}.
15926 * All other scopes are descendant scopes of the root scope. Scopes provide separation
15927 * between the model and the view, via a mechanism for watching the model for changes.
15928 * They also provide event emission/broadcast and subscription facility. See the
15929 * {@link guide/scope developer guide on scopes}.
15931 function $RootScopeProvider() {
15933 var $rootScopeMinErr = minErr('$rootScope');
15934 var lastDirtyWatch = null;
15935 var applyAsyncId = null;
15937 this.digestTtl = function(value) {
15938 if (arguments.length) {
15944 function createChildScopeClass(parent) {
15945 function ChildScope() {
15946 this.$$watchers = this.$$nextSibling =
15947 this.$$childHead = this.$$childTail = null;
15948 this.$$listeners = {};
15949 this.$$listenerCount = {};
15950 this.$$watchersCount = 0;
15951 this.$id = nextUid();
15952 this.$$ChildScope = null;
15954 ChildScope.prototype = parent;
15958 this.$get = ['$exceptionHandler', '$parse', '$browser',
15959 function($exceptionHandler, $parse, $browser) {
15961 function destroyChildScope($event) {
15962 $event.currentScope.$$destroyed = true;
15965 function cleanUpScope($scope) {
15968 // There is a memory leak in IE9 if all child scopes are not disconnected
15969 // completely when a scope is destroyed. So this code will recurse up through
15970 // all this scopes children
15972 // See issue https://github.com/angular/angular.js/issues/10706
15973 $scope.$$childHead && cleanUpScope($scope.$$childHead);
15974 $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
15977 // The code below works around IE9 and V8's memory leaks
15980 // - https://code.google.com/p/v8/issues/detail?id=2073#c26
15981 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
15982 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
15984 $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
15985 $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
15990 * @name $rootScope.Scope
15993 * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
15994 * {@link auto.$injector $injector}. Child scopes are created using the
15995 * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
15996 * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
15997 * an in-depth introduction and usage examples.
16001 * A scope can inherit from a parent scope, as in this example:
16003 var parent = $rootScope;
16004 var child = parent.$new();
16006 parent.salutation = "Hello";
16007 expect(child.salutation).toEqual('Hello');
16009 child.salutation = "Welcome";
16010 expect(child.salutation).toEqual('Welcome');
16011 expect(parent.salutation).toEqual('Hello');
16014 * When interacting with `Scope` in tests, additional helper methods are available on the
16015 * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
16019 * @param {Object.<string, function()>=} providers Map of service factory which need to be
16020 * provided for the current scope. Defaults to {@link ng}.
16021 * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
16022 * append/override services provided by `providers`. This is handy
16023 * when unit-testing and having the need to override a default
16025 * @returns {Object} Newly created scope.
16029 this.$id = nextUid();
16030 this.$$phase = this.$parent = this.$$watchers =
16031 this.$$nextSibling = this.$$prevSibling =
16032 this.$$childHead = this.$$childTail = null;
16034 this.$$destroyed = false;
16035 this.$$listeners = {};
16036 this.$$listenerCount = {};
16037 this.$$watchersCount = 0;
16038 this.$$isolateBindings = null;
16043 * @name $rootScope.Scope#$id
16046 * Unique scope ID (monotonically increasing) useful for debugging.
16051 * @name $rootScope.Scope#$parent
16054 * Reference to the parent scope.
16059 * @name $rootScope.Scope#$root
16062 * Reference to the root scope.
16065 Scope.prototype = {
16066 constructor: Scope,
16069 * @name $rootScope.Scope#$new
16073 * Creates a new child {@link ng.$rootScope.Scope scope}.
16075 * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
16076 * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
16078 * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
16079 * desired for the scope and its child scopes to be permanently detached from the parent and
16080 * thus stop participating in model change detection and listener notification by invoking.
16082 * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
16083 * parent scope. The scope is isolated, as it can not see parent scope properties.
16084 * When creating widgets, it is useful for the widget to not accidentally read parent
16087 * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
16088 * of the newly created scope. Defaults to `this` scope if not provided.
16089 * This is used when creating a transclude scope to correctly place it
16090 * in the scope hierarchy while maintaining the correct prototypical
16093 * @returns {Object} The newly created child scope.
16096 $new: function(isolate, parent) {
16099 parent = parent || this;
16102 child = new Scope();
16103 child.$root = this.$root;
16105 // Only create a child scope class if somebody asks for one,
16106 // but cache it to allow the VM to optimize lookups.
16107 if (!this.$$ChildScope) {
16108 this.$$ChildScope = createChildScopeClass(this);
16110 child = new this.$$ChildScope();
16112 child.$parent = parent;
16113 child.$$prevSibling = parent.$$childTail;
16114 if (parent.$$childHead) {
16115 parent.$$childTail.$$nextSibling = child;
16116 parent.$$childTail = child;
16118 parent.$$childHead = parent.$$childTail = child;
16121 // When the new scope is not isolated or we inherit from `this`, and
16122 // the parent scope is destroyed, the property `$$destroyed` is inherited
16123 // prototypically. In all other cases, this property needs to be set
16124 // when the parent scope is destroyed.
16125 // The listener needs to be added after the parent is set
16126 if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
16133 * @name $rootScope.Scope#$watch
16137 * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
16139 * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
16140 * $digest()} and should return the value that will be watched. (`watchExpression` should not change
16141 * its value when executed multiple times with the same input because it may be executed multiple
16142 * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
16143 * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
16144 * - The `listener` is called only when the value from the current `watchExpression` and the
16145 * previous call to `watchExpression` are not equal (with the exception of the initial run,
16146 * see below). Inequality is determined according to reference inequality,
16147 * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
16148 * via the `!==` Javascript operator, unless `objectEquality == true`
16150 * - When `objectEquality == true`, inequality of the `watchExpression` is determined
16151 * according to the {@link angular.equals} function. To save the value of the object for
16152 * later comparison, the {@link angular.copy} function is used. This therefore means that
16153 * watching complex objects will have adverse memory and performance implications.
16154 * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
16155 * This is achieved by rerunning the watchers until no changes are detected. The rerun
16156 * iteration limit is 10 to prevent an infinite loop deadlock.
16159 * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
16160 * you can register a `watchExpression` function with no `listener`. (Be prepared for
16161 * multiple calls to your `watchExpression` because it will execute multiple times in a
16162 * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
16164 * After a watcher is registered with the scope, the `listener` fn is called asynchronously
16165 * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
16166 * watcher. In rare cases, this is undesirable because the listener is called when the result
16167 * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
16168 * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
16169 * listener was called due to initialization.
16175 // let's assume that scope was dependency injected as the $rootScope
16176 var scope = $rootScope;
16177 scope.name = 'misko';
16180 expect(scope.counter).toEqual(0);
16181 scope.$watch('name', function(newValue, oldValue) {
16182 scope.counter = scope.counter + 1;
16184 expect(scope.counter).toEqual(0);
16187 // the listener is always called during the first $digest loop after it was registered
16188 expect(scope.counter).toEqual(1);
16191 // but now it will not be called unless the value changes
16192 expect(scope.counter).toEqual(1);
16194 scope.name = 'adam';
16196 expect(scope.counter).toEqual(2);
16200 // Using a function as a watchExpression
16202 scope.foodCounter = 0;
16203 expect(scope.foodCounter).toEqual(0);
16205 // This function returns the value being watched. It is called for each turn of the $digest loop
16206 function() { return food; },
16207 // This is the change listener, called when the value returned from the above function changes
16208 function(newValue, oldValue) {
16209 if ( newValue !== oldValue ) {
16210 // Only increment the counter if the value changed
16211 scope.foodCounter = scope.foodCounter + 1;
16215 // No digest has been run so the counter will be zero
16216 expect(scope.foodCounter).toEqual(0);
16218 // Run the digest but since food has not changed count will still be zero
16220 expect(scope.foodCounter).toEqual(0);
16222 // Update food and run digest. Now the counter will increment
16223 food = 'cheeseburger';
16225 expect(scope.foodCounter).toEqual(1);
16231 * @param {(function()|string)} watchExpression Expression that is evaluated on each
16232 * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
16233 * a call to the `listener`.
16235 * - `string`: Evaluated as {@link guide/expression expression}
16236 * - `function(scope)`: called with current `scope` as a parameter.
16237 * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
16238 * of `watchExpression` changes.
16240 * - `newVal` contains the current value of the `watchExpression`
16241 * - `oldVal` contains the previous value of the `watchExpression`
16242 * - `scope` refers to the current scope
16243 * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
16244 * comparing for reference equality.
16245 * @returns {function()} Returns a deregistration function for this listener.
16247 $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
16248 var get = $parse(watchExp);
16250 if (get.$$watchDelegate) {
16251 return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
16254 array = scope.$$watchers,
16257 last: initWatchVal,
16259 exp: prettyPrintExpression || watchExp,
16260 eq: !!objectEquality
16263 lastDirtyWatch = null;
16265 if (!isFunction(listener)) {
16270 array = scope.$$watchers = [];
16272 // we use unshift since we use a while loop in $digest for speed.
16273 // the while loop reads in reverse order.
16274 array.unshift(watcher);
16275 incrementWatchersCount(this, 1);
16277 return function deregisterWatch() {
16278 if (arrayRemove(array, watcher) >= 0) {
16279 incrementWatchersCount(scope, -1);
16281 lastDirtyWatch = null;
16287 * @name $rootScope.Scope#$watchGroup
16291 * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
16292 * If any one expression in the collection changes the `listener` is executed.
16294 * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
16295 * call to $digest() to see if any items changes.
16296 * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
16298 * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
16299 * watched using {@link ng.$rootScope.Scope#$watch $watch()}
16301 * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
16302 * expression in `watchExpressions` changes
16303 * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
16304 * those of `watchExpression`
16305 * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
16306 * those of `watchExpression`
16307 * The `scope` refers to the current scope.
16308 * @returns {function()} Returns a de-registration function for all listeners.
16310 $watchGroup: function(watchExpressions, listener) {
16311 var oldValues = new Array(watchExpressions.length);
16312 var newValues = new Array(watchExpressions.length);
16313 var deregisterFns = [];
16315 var changeReactionScheduled = false;
16316 var firstRun = true;
16318 if (!watchExpressions.length) {
16319 // No expressions means we call the listener ASAP
16320 var shouldCall = true;
16321 self.$evalAsync(function() {
16322 if (shouldCall) listener(newValues, newValues, self);
16324 return function deregisterWatchGroup() {
16325 shouldCall = false;
16329 if (watchExpressions.length === 1) {
16330 // Special case size of one
16331 return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
16332 newValues[0] = value;
16333 oldValues[0] = oldValue;
16334 listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
16338 forEach(watchExpressions, function(expr, i) {
16339 var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
16340 newValues[i] = value;
16341 oldValues[i] = oldValue;
16342 if (!changeReactionScheduled) {
16343 changeReactionScheduled = true;
16344 self.$evalAsync(watchGroupAction);
16347 deregisterFns.push(unwatchFn);
16350 function watchGroupAction() {
16351 changeReactionScheduled = false;
16355 listener(newValues, newValues, self);
16357 listener(newValues, oldValues, self);
16361 return function deregisterWatchGroup() {
16362 while (deregisterFns.length) {
16363 deregisterFns.shift()();
16371 * @name $rootScope.Scope#$watchCollection
16375 * Shallow watches the properties of an object and fires whenever any of the properties change
16376 * (for arrays, this implies watching the array items; for object maps, this implies watching
16377 * the properties). If a change is detected, the `listener` callback is fired.
16379 * - The `obj` collection is observed via standard $watch operation and is examined on every
16380 * call to $digest() to see if any items have been added, removed, or moved.
16381 * - The `listener` is called whenever anything within the `obj` has changed. Examples include
16382 * adding, removing, and moving items belonging to an object or array.
16387 $scope.names = ['igor', 'matias', 'misko', 'james'];
16388 $scope.dataCount = 4;
16390 $scope.$watchCollection('names', function(newNames, oldNames) {
16391 $scope.dataCount = newNames.length;
16394 expect($scope.dataCount).toEqual(4);
16397 //still at 4 ... no changes
16398 expect($scope.dataCount).toEqual(4);
16400 $scope.names.pop();
16403 //now there's been a change
16404 expect($scope.dataCount).toEqual(3);
16408 * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
16409 * expression value should evaluate to an object or an array which is observed on each
16410 * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
16411 * collection will trigger a call to the `listener`.
16413 * @param {function(newCollection, oldCollection, scope)} listener a callback function called
16414 * when a change is detected.
16415 * - The `newCollection` object is the newly modified data obtained from the `obj` expression
16416 * - The `oldCollection` object is a copy of the former collection data.
16417 * Due to performance considerations, the`oldCollection` value is computed only if the
16418 * `listener` function declares two or more arguments.
16419 * - The `scope` argument refers to the current scope.
16421 * @returns {function()} Returns a de-registration function for this listener. When the
16422 * de-registration function is executed, the internal watch operation is terminated.
16424 $watchCollection: function(obj, listener) {
16425 $watchCollectionInterceptor.$stateful = true;
16428 // the current value, updated on each dirty-check run
16430 // a shallow copy of the newValue from the last dirty-check run,
16431 // updated to match newValue during dirty-check run
16433 // a shallow copy of the newValue from when the last change happened
16435 // only track veryOldValue if the listener is asking for it
16436 var trackVeryOldValue = (listener.length > 1);
16437 var changeDetected = 0;
16438 var changeDetector = $parse(obj, $watchCollectionInterceptor);
16439 var internalArray = [];
16440 var internalObject = {};
16441 var initRun = true;
16444 function $watchCollectionInterceptor(_value) {
16446 var newLength, key, bothNaN, newItem, oldItem;
16448 // If the new value is undefined, then return undefined as the watch may be a one-time watch
16449 if (isUndefined(newValue)) return;
16451 if (!isObject(newValue)) { // if primitive
16452 if (oldValue !== newValue) {
16453 oldValue = newValue;
16456 } else if (isArrayLike(newValue)) {
16457 if (oldValue !== internalArray) {
16458 // we are transitioning from something which was not an array into array.
16459 oldValue = internalArray;
16460 oldLength = oldValue.length = 0;
16464 newLength = newValue.length;
16466 if (oldLength !== newLength) {
16467 // if lengths do not match we need to trigger change notification
16469 oldValue.length = oldLength = newLength;
16471 // copy the items to oldValue and look for changes.
16472 for (var i = 0; i < newLength; i++) {
16473 oldItem = oldValue[i];
16474 newItem = newValue[i];
16476 bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
16477 if (!bothNaN && (oldItem !== newItem)) {
16479 oldValue[i] = newItem;
16483 if (oldValue !== internalObject) {
16484 // we are transitioning from something which was not an object into object.
16485 oldValue = internalObject = {};
16489 // copy the items to oldValue and look for changes.
16491 for (key in newValue) {
16492 if (hasOwnProperty.call(newValue, key)) {
16494 newItem = newValue[key];
16495 oldItem = oldValue[key];
16497 if (key in oldValue) {
16498 bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
16499 if (!bothNaN && (oldItem !== newItem)) {
16501 oldValue[key] = newItem;
16505 oldValue[key] = newItem;
16510 if (oldLength > newLength) {
16511 // we used to have more keys, need to find them and destroy them.
16513 for (key in oldValue) {
16514 if (!hasOwnProperty.call(newValue, key)) {
16516 delete oldValue[key];
16521 return changeDetected;
16524 function $watchCollectionAction() {
16527 listener(newValue, newValue, self);
16529 listener(newValue, veryOldValue, self);
16532 // make a copy for the next time a collection is changed
16533 if (trackVeryOldValue) {
16534 if (!isObject(newValue)) {
16536 veryOldValue = newValue;
16537 } else if (isArrayLike(newValue)) {
16538 veryOldValue = new Array(newValue.length);
16539 for (var i = 0; i < newValue.length; i++) {
16540 veryOldValue[i] = newValue[i];
16542 } else { // if object
16544 for (var key in newValue) {
16545 if (hasOwnProperty.call(newValue, key)) {
16546 veryOldValue[key] = newValue[key];
16553 return this.$watch(changeDetector, $watchCollectionAction);
16558 * @name $rootScope.Scope#$digest
16562 * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
16563 * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
16564 * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
16565 * until no more listeners are firing. This means that it is possible to get into an infinite
16566 * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
16567 * iterations exceeds 10.
16569 * Usually, you don't call `$digest()` directly in
16570 * {@link ng.directive:ngController controllers} or in
16571 * {@link ng.$compileProvider#directive directives}.
16572 * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
16573 * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
16575 * If you want to be notified whenever `$digest()` is called,
16576 * you can register a `watchExpression` function with
16577 * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
16579 * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
16584 scope.name = 'misko';
16587 expect(scope.counter).toEqual(0);
16588 scope.$watch('name', function(newValue, oldValue) {
16589 scope.counter = scope.counter + 1;
16591 expect(scope.counter).toEqual(0);
16594 // the listener is always called during the first $digest loop after it was registered
16595 expect(scope.counter).toEqual(1);
16598 // but now it will not be called unless the value changes
16599 expect(scope.counter).toEqual(1);
16601 scope.name = 'adam';
16603 expect(scope.counter).toEqual(2);
16607 $digest: function() {
16608 var watch, value, last, fn, get,
16612 next, current, target = this,
16614 logIdx, logMsg, asyncTask;
16616 beginPhase('$digest');
16617 // Check for changes to browser url that happened in sync before the call to $digest
16618 $browser.$$checkUrlChange();
16620 if (this === $rootScope && applyAsyncId !== null) {
16621 // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
16622 // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
16623 $browser.defer.cancel(applyAsyncId);
16627 lastDirtyWatch = null;
16629 do { // "while dirty" loop
16633 while (asyncQueue.length) {
16635 asyncTask = asyncQueue.shift();
16636 asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
16638 $exceptionHandler(e);
16640 lastDirtyWatch = null;
16643 traverseScopesLoop:
16644 do { // "traverse the scopes" loop
16645 if ((watchers = current.$$watchers)) {
16646 // process our watches
16647 length = watchers.length;
16650 watch = watchers[length];
16651 // Most common watches are on primitives, in which case we can short
16652 // circuit it with === operator, only when === fails do we use .equals
16655 if ((value = get(current)) !== (last = watch.last) &&
16657 ? equals(value, last)
16658 : (typeof value === 'number' && typeof last === 'number'
16659 && isNaN(value) && isNaN(last)))) {
16661 lastDirtyWatch = watch;
16662 watch.last = watch.eq ? copy(value, null) : value;
16664 fn(value, ((last === initWatchVal) ? value : last), current);
16667 if (!watchLog[logIdx]) watchLog[logIdx] = [];
16668 watchLog[logIdx].push({
16669 msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
16674 } else if (watch === lastDirtyWatch) {
16675 // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
16676 // have already been tested.
16678 break traverseScopesLoop;
16682 $exceptionHandler(e);
16687 // Insanity Warning: scope depth-first traversal
16688 // yes, this code is a bit crazy, but it works and we have tests to prove it!
16689 // this piece should be kept in sync with the traversal in $broadcast
16690 if (!(next = ((current.$$watchersCount && current.$$childHead) ||
16691 (current !== target && current.$$nextSibling)))) {
16692 while (current !== target && !(next = current.$$nextSibling)) {
16693 current = current.$parent;
16696 } while ((current = next));
16698 // `break traverseScopesLoop;` takes us to here
16700 if ((dirty || asyncQueue.length) && !(ttl--)) {
16702 throw $rootScopeMinErr('infdig',
16703 '{0} $digest() iterations reached. Aborting!\n' +
16704 'Watchers fired in the last 5 iterations: {1}',
16708 } while (dirty || asyncQueue.length);
16712 while (postDigestQueue.length) {
16714 postDigestQueue.shift()();
16716 $exceptionHandler(e);
16724 * @name $rootScope.Scope#$destroy
16725 * @eventType broadcast on scope being destroyed
16728 * Broadcasted when a scope and its children are being destroyed.
16730 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
16731 * clean up DOM bindings before an element is removed from the DOM.
16736 * @name $rootScope.Scope#$destroy
16740 * Removes the current scope (and all of its children) from the parent scope. Removal implies
16741 * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
16742 * propagate to the current scope and its children. Removal also implies that the current
16743 * scope is eligible for garbage collection.
16745 * The `$destroy()` is usually used by directives such as
16746 * {@link ng.directive:ngRepeat ngRepeat} for managing the
16747 * unrolling of the loop.
16749 * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
16750 * Application code can register a `$destroy` event handler that will give it a chance to
16751 * perform any necessary cleanup.
16753 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
16754 * clean up DOM bindings before an element is removed from the DOM.
16756 $destroy: function() {
16757 // We can't destroy a scope that has been already destroyed.
16758 if (this.$$destroyed) return;
16759 var parent = this.$parent;
16761 this.$broadcast('$destroy');
16762 this.$$destroyed = true;
16764 if (this === $rootScope) {
16765 //Remove handlers attached to window when $rootScope is removed
16766 $browser.$$applicationDestroyed();
16769 incrementWatchersCount(this, -this.$$watchersCount);
16770 for (var eventName in this.$$listenerCount) {
16771 decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
16774 // sever all the references to parent scopes (after this cleanup, the current scope should
16775 // not be retained by any of our references and should be eligible for garbage collection)
16776 if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
16777 if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
16778 if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
16779 if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
16781 // Disable listeners, watchers and apply/digest methods
16782 this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
16783 this.$on = this.$watch = this.$watchGroup = function() { return noop; };
16784 this.$$listeners = {};
16786 // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
16787 this.$$nextSibling = null;
16788 cleanUpScope(this);
16793 * @name $rootScope.Scope#$eval
16797 * Executes the `expression` on the current scope and returns the result. Any exceptions in
16798 * the expression are propagated (uncaught). This is useful when evaluating Angular
16803 var scope = ng.$rootScope.Scope();
16807 expect(scope.$eval('a+b')).toEqual(3);
16808 expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
16811 * @param {(string|function())=} expression An angular expression to be executed.
16813 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
16814 * - `function(scope)`: execute the function with the current `scope` parameter.
16816 * @param {(object)=} locals Local variables object, useful for overriding values in scope.
16817 * @returns {*} The result of evaluating the expression.
16819 $eval: function(expr, locals) {
16820 return $parse(expr)(this, locals);
16825 * @name $rootScope.Scope#$evalAsync
16829 * Executes the expression on the current scope at a later point in time.
16831 * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
16834 * - it will execute after the function that scheduled the evaluation (preferably before DOM
16836 * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
16837 * `expression` execution.
16839 * Any exceptions from the execution of the expression are forwarded to the
16840 * {@link ng.$exceptionHandler $exceptionHandler} service.
16842 * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
16843 * will be scheduled. However, it is encouraged to always call code that changes the model
16844 * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
16846 * @param {(string|function())=} expression An angular expression to be executed.
16848 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
16849 * - `function(scope)`: execute the function with the current `scope` parameter.
16851 * @param {(object)=} locals Local variables object, useful for overriding values in scope.
16853 $evalAsync: function(expr, locals) {
16854 // if we are outside of an $digest loop and this is the first time we are scheduling async
16855 // task also schedule async auto-flush
16856 if (!$rootScope.$$phase && !asyncQueue.length) {
16857 $browser.defer(function() {
16858 if (asyncQueue.length) {
16859 $rootScope.$digest();
16864 asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
16867 $$postDigest: function(fn) {
16868 postDigestQueue.push(fn);
16873 * @name $rootScope.Scope#$apply
16877 * `$apply()` is used to execute an expression in angular from outside of the angular
16878 * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
16879 * Because we are calling into the angular framework we need to perform proper scope life
16880 * cycle of {@link ng.$exceptionHandler exception handling},
16881 * {@link ng.$rootScope.Scope#$digest executing watches}.
16885 * # Pseudo-Code of `$apply()`
16887 function $apply(expr) {
16889 return $eval(expr);
16891 $exceptionHandler(e);
16899 * Scope's `$apply()` method transitions through the following stages:
16901 * 1. The {@link guide/expression expression} is executed using the
16902 * {@link ng.$rootScope.Scope#$eval $eval()} method.
16903 * 2. Any exceptions from the execution of the expression are forwarded to the
16904 * {@link ng.$exceptionHandler $exceptionHandler} service.
16905 * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
16906 * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
16909 * @param {(string|function())=} exp An angular expression to be executed.
16911 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
16912 * - `function(scope)`: execute the function with current `scope` parameter.
16914 * @returns {*} The result of evaluating the expression.
16916 $apply: function(expr) {
16918 beginPhase('$apply');
16920 return this.$eval(expr);
16925 $exceptionHandler(e);
16928 $rootScope.$digest();
16930 $exceptionHandler(e);
16938 * @name $rootScope.Scope#$applyAsync
16942 * Schedule the invocation of $apply to occur at a later time. The actual time difference
16943 * varies across browsers, but is typically around ~10 milliseconds.
16945 * This can be used to queue up multiple expressions which need to be evaluated in the same
16948 * @param {(string|function())=} exp An angular expression to be executed.
16950 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
16951 * - `function(scope)`: execute the function with current `scope` parameter.
16953 $applyAsync: function(expr) {
16955 expr && applyAsyncQueue.push($applyAsyncExpression);
16956 expr = $parse(expr);
16957 scheduleApplyAsync();
16959 function $applyAsyncExpression() {
16966 * @name $rootScope.Scope#$on
16970 * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
16971 * discussion of event life cycle.
16973 * The event listener function format is: `function(event, args...)`. The `event` object
16974 * passed into the listener has the following attributes:
16976 * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
16978 * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
16979 * event propagates through the scope hierarchy, this property is set to null.
16980 * - `name` - `{string}`: name of the event.
16981 * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
16982 * further event propagation (available only for events that were `$emit`-ed).
16983 * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
16985 * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
16987 * @param {string} name Event name to listen on.
16988 * @param {function(event, ...args)} listener Function to call when the event is emitted.
16989 * @returns {function()} Returns a deregistration function for this listener.
16991 $on: function(name, listener) {
16992 var namedListeners = this.$$listeners[name];
16993 if (!namedListeners) {
16994 this.$$listeners[name] = namedListeners = [];
16996 namedListeners.push(listener);
16998 var current = this;
17000 if (!current.$$listenerCount[name]) {
17001 current.$$listenerCount[name] = 0;
17003 current.$$listenerCount[name]++;
17004 } while ((current = current.$parent));
17007 return function() {
17008 var indexOfListener = namedListeners.indexOf(listener);
17009 if (indexOfListener !== -1) {
17010 namedListeners[indexOfListener] = null;
17011 decrementListenerCount(self, 1, name);
17019 * @name $rootScope.Scope#$emit
17023 * Dispatches an event `name` upwards through the scope hierarchy notifying the
17024 * registered {@link ng.$rootScope.Scope#$on} listeners.
17026 * The event life cycle starts at the scope on which `$emit` was called. All
17027 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
17028 * notified. Afterwards, the event traverses upwards toward the root scope and calls all
17029 * registered listeners along the way. The event will stop propagating if one of the listeners
17032 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
17033 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
17035 * @param {string} name Event name to emit.
17036 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
17037 * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
17039 $emit: function(name, args) {
17043 stopPropagation = false,
17046 targetScope: scope,
17047 stopPropagation: function() {stopPropagation = true;},
17048 preventDefault: function() {
17049 event.defaultPrevented = true;
17051 defaultPrevented: false
17053 listenerArgs = concat([event], arguments, 1),
17057 namedListeners = scope.$$listeners[name] || empty;
17058 event.currentScope = scope;
17059 for (i = 0, length = namedListeners.length; i < length; i++) {
17061 // if listeners were deregistered, defragment the array
17062 if (!namedListeners[i]) {
17063 namedListeners.splice(i, 1);
17069 //allow all listeners attached to the current scope to run
17070 namedListeners[i].apply(null, listenerArgs);
17072 $exceptionHandler(e);
17075 //if any listener on the current scope stops propagation, prevent bubbling
17076 if (stopPropagation) {
17077 event.currentScope = null;
17081 scope = scope.$parent;
17084 event.currentScope = null;
17092 * @name $rootScope.Scope#$broadcast
17096 * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
17097 * registered {@link ng.$rootScope.Scope#$on} listeners.
17099 * The event life cycle starts at the scope on which `$broadcast` was called. All
17100 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
17101 * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
17102 * scope and calls all registered listeners along the way. The event cannot be canceled.
17104 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
17105 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
17107 * @param {string} name Event name to broadcast.
17108 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
17109 * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
17111 $broadcast: function(name, args) {
17117 targetScope: target,
17118 preventDefault: function() {
17119 event.defaultPrevented = true;
17121 defaultPrevented: false
17124 if (!target.$$listenerCount[name]) return event;
17126 var listenerArgs = concat([event], arguments, 1),
17127 listeners, i, length;
17129 //down while you can, then up and next sibling or up and next sibling until back at root
17130 while ((current = next)) {
17131 event.currentScope = current;
17132 listeners = current.$$listeners[name] || [];
17133 for (i = 0, length = listeners.length; i < length; i++) {
17134 // if listeners were deregistered, defragment the array
17135 if (!listeners[i]) {
17136 listeners.splice(i, 1);
17143 listeners[i].apply(null, listenerArgs);
17145 $exceptionHandler(e);
17149 // Insanity Warning: scope depth-first traversal
17150 // yes, this code is a bit crazy, but it works and we have tests to prove it!
17151 // this piece should be kept in sync with the traversal in $digest
17152 // (though it differs due to having the extra check for $$listenerCount)
17153 if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
17154 (current !== target && current.$$nextSibling)))) {
17155 while (current !== target && !(next = current.$$nextSibling)) {
17156 current = current.$parent;
17161 event.currentScope = null;
17166 var $rootScope = new Scope();
17168 //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
17169 var asyncQueue = $rootScope.$$asyncQueue = [];
17170 var postDigestQueue = $rootScope.$$postDigestQueue = [];
17171 var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
17176 function beginPhase(phase) {
17177 if ($rootScope.$$phase) {
17178 throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
17181 $rootScope.$$phase = phase;
17184 function clearPhase() {
17185 $rootScope.$$phase = null;
17188 function incrementWatchersCount(current, count) {
17190 current.$$watchersCount += count;
17191 } while ((current = current.$parent));
17194 function decrementListenerCount(current, count, name) {
17196 current.$$listenerCount[name] -= count;
17198 if (current.$$listenerCount[name] === 0) {
17199 delete current.$$listenerCount[name];
17201 } while ((current = current.$parent));
17205 * function used as an initial value for watchers.
17206 * because it's unique we can easily tell it apart from other values
17208 function initWatchVal() {}
17210 function flushApplyAsync() {
17211 while (applyAsyncQueue.length) {
17213 applyAsyncQueue.shift()();
17215 $exceptionHandler(e);
17218 applyAsyncId = null;
17221 function scheduleApplyAsync() {
17222 if (applyAsyncId === null) {
17223 applyAsyncId = $browser.defer(function() {
17224 $rootScope.$apply(flushApplyAsync);
17233 * @name $rootElement
17236 * The root element of Angular application. This is either the element where {@link
17237 * ng.directive:ngApp ngApp} was declared or the element passed into
17238 * {@link angular.bootstrap}. The element represents the root element of application. It is also the
17239 * location where the application's {@link auto.$injector $injector} service gets
17240 * published, and can be retrieved using `$rootElement.injector()`.
17244 // the implementation is in angular.bootstrap
17248 * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
17250 function $$SanitizeUriProvider() {
17251 var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
17252 imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
17256 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
17257 * urls during a[href] sanitization.
17259 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
17261 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
17262 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
17263 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
17264 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
17266 * @param {RegExp=} regexp New regexp to whitelist urls with.
17267 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
17268 * chaining otherwise.
17270 this.aHrefSanitizationWhitelist = function(regexp) {
17271 if (isDefined(regexp)) {
17272 aHrefSanitizationWhitelist = regexp;
17275 return aHrefSanitizationWhitelist;
17281 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
17282 * urls during img[src] sanitization.
17284 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
17286 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
17287 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
17288 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
17289 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
17291 * @param {RegExp=} regexp New regexp to whitelist urls with.
17292 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
17293 * chaining otherwise.
17295 this.imgSrcSanitizationWhitelist = function(regexp) {
17296 if (isDefined(regexp)) {
17297 imgSrcSanitizationWhitelist = regexp;
17300 return imgSrcSanitizationWhitelist;
17303 this.$get = function() {
17304 return function sanitizeUri(uri, isImage) {
17305 var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
17307 normalizedVal = urlResolve(uri).href;
17308 if (normalizedVal !== '' && !normalizedVal.match(regex)) {
17309 return 'unsafe:' + normalizedVal;
17316 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
17317 * Any commits to this file should be reviewed with security in mind. *
17318 * Changes to this file can potentially create security vulnerabilities. *
17319 * An approval from 2 Core members with history of modifying *
17320 * this file is required. *
17322 * Does the change somehow allow for arbitrary javascript to be executed? *
17323 * Or allows for someone to change the prototype of built-in objects? *
17324 * Or gives undesired access to variables likes document or window? *
17325 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
17327 var $sceMinErr = minErr('$sce');
17329 var SCE_CONTEXTS = {
17333 // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
17334 // url. (e.g. ng-include, script src, templateUrl)
17335 RESOURCE_URL: 'resourceUrl',
17339 // Helper functions follow.
17341 function adjustMatcher(matcher) {
17342 if (matcher === 'self') {
17344 } else if (isString(matcher)) {
17345 // Strings match exactly except for 2 wildcards - '*' and '**'.
17346 // '*' matches any character except those from the set ':/.?&'.
17347 // '**' matches any character (like .* in a RegExp).
17348 // More than 2 *'s raises an error as it's ill defined.
17349 if (matcher.indexOf('***') > -1) {
17350 throw $sceMinErr('iwcard',
17351 'Illegal sequence *** in string matcher. String: {0}', matcher);
17353 matcher = escapeForRegexp(matcher).
17354 replace('\\*\\*', '.*').
17355 replace('\\*', '[^:/.?&;]*');
17356 return new RegExp('^' + matcher + '$');
17357 } else if (isRegExp(matcher)) {
17358 // The only other type of matcher allowed is a Regexp.
17359 // Match entire URL / disallow partial matches.
17360 // Flags are reset (i.e. no global, ignoreCase or multiline)
17361 return new RegExp('^' + matcher.source + '$');
17363 throw $sceMinErr('imatcher',
17364 'Matchers may only be "self", string patterns or RegExp objects');
17369 function adjustMatchers(matchers) {
17370 var adjustedMatchers = [];
17371 if (isDefined(matchers)) {
17372 forEach(matchers, function(matcher) {
17373 adjustedMatchers.push(adjustMatcher(matcher));
17376 return adjustedMatchers;
17382 * @name $sceDelegate
17387 * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
17388 * Contextual Escaping (SCE)} services to AngularJS.
17390 * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
17391 * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
17392 * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
17393 * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
17394 * work because `$sce` delegates to `$sceDelegate` for these operations.
17396 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
17398 * The default instance of `$sceDelegate` should work out of the box with little pain. While you
17399 * can override it completely to change the behavior of `$sce`, the common case would
17400 * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
17401 * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
17402 * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
17403 * $sceDelegateProvider.resourceUrlWhitelist} and {@link
17404 * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
17409 * @name $sceDelegateProvider
17412 * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
17413 * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
17414 * that the URLs used for sourcing Angular templates are safe. Refer {@link
17415 * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
17416 * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
17418 * For the general details about this service in Angular, read the main page for {@link ng.$sce
17419 * Strict Contextual Escaping (SCE)}.
17421 * **Example**: Consider the following case. <a name="example"></a>
17423 * - your app is hosted at url `http://myapp.example.com/`
17424 * - but some of your templates are hosted on other domains you control such as
17425 * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
17426 * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
17428 * Here is what a secure configuration for this scenario might look like:
17431 * angular.module('myApp', []).config(function($sceDelegateProvider) {
17432 * $sceDelegateProvider.resourceUrlWhitelist([
17433 * // Allow same origin resource loads.
17435 * // Allow loading from our assets domain. Notice the difference between * and **.
17436 * 'http://srv*.assets.example.com/**'
17439 * // The blacklist overrides the whitelist so the open redirect here is blocked.
17440 * $sceDelegateProvider.resourceUrlBlacklist([
17441 * 'http://myapp.example.com/clickThru**'
17447 function $SceDelegateProvider() {
17448 this.SCE_CONTEXTS = SCE_CONTEXTS;
17450 // Resource URLs can also be trusted by policy.
17451 var resourceUrlWhitelist = ['self'],
17452 resourceUrlBlacklist = [];
17456 * @name $sceDelegateProvider#resourceUrlWhitelist
17459 * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
17460 * provided. This must be an array or null. A snapshot of this array is used so further
17461 * changes to the array are ignored.
17463 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
17464 * allowed in this array.
17466 * <div class="alert alert-warning">
17467 * **Note:** an empty whitelist array will block all URLs!
17470 * @return {Array} the currently set whitelist array.
17472 * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
17473 * same origin resource requests.
17476 * Sets/Gets the whitelist of trusted resource URLs.
17478 this.resourceUrlWhitelist = function(value) {
17479 if (arguments.length) {
17480 resourceUrlWhitelist = adjustMatchers(value);
17482 return resourceUrlWhitelist;
17487 * @name $sceDelegateProvider#resourceUrlBlacklist
17490 * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
17491 * provided. This must be an array or null. A snapshot of this array is used so further
17492 * changes to the array are ignored.
17494 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
17495 * allowed in this array.
17497 * The typical usage for the blacklist is to **block
17498 * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
17499 * these would otherwise be trusted but actually return content from the redirected domain.
17501 * Finally, **the blacklist overrides the whitelist** and has the final say.
17503 * @return {Array} the currently set blacklist array.
17505 * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
17506 * is no blacklist.)
17509 * Sets/Gets the blacklist of trusted resource URLs.
17512 this.resourceUrlBlacklist = function(value) {
17513 if (arguments.length) {
17514 resourceUrlBlacklist = adjustMatchers(value);
17516 return resourceUrlBlacklist;
17519 this.$get = ['$injector', function($injector) {
17521 var htmlSanitizer = function htmlSanitizer(html) {
17522 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
17525 if ($injector.has('$sanitize')) {
17526 htmlSanitizer = $injector.get('$sanitize');
17530 function matchUrl(matcher, parsedUrl) {
17531 if (matcher === 'self') {
17532 return urlIsSameOrigin(parsedUrl);
17534 // definitely a regex. See adjustMatchers()
17535 return !!matcher.exec(parsedUrl.href);
17539 function isResourceUrlAllowedByPolicy(url) {
17540 var parsedUrl = urlResolve(url.toString());
17541 var i, n, allowed = false;
17542 // Ensure that at least one item from the whitelist allows this url.
17543 for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
17544 if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
17550 // Ensure that no item from the blacklist blocked this url.
17551 for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
17552 if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
17561 function generateHolderType(Base) {
17562 var holderType = function TrustedValueHolderType(trustedValue) {
17563 this.$$unwrapTrustedValue = function() {
17564 return trustedValue;
17568 holderType.prototype = new Base();
17570 holderType.prototype.valueOf = function sceValueOf() {
17571 return this.$$unwrapTrustedValue();
17573 holderType.prototype.toString = function sceToString() {
17574 return this.$$unwrapTrustedValue().toString();
17579 var trustedValueHolderBase = generateHolderType(),
17582 byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
17583 byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
17584 byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
17585 byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
17586 byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
17590 * @name $sceDelegate#trustAs
17593 * Returns an object that is trusted by angular for use in specified strict
17594 * contextual escaping contexts (such as ng-bind-html, ng-include, any src
17595 * attribute interpolation, any dom event binding attribute interpolation
17596 * such as for onclick, etc.) that uses the provided value.
17597 * See {@link ng.$sce $sce} for enabling strict contextual escaping.
17599 * @param {string} type The kind of context in which this value is safe for use. e.g. url,
17600 * resourceUrl, html, js and css.
17601 * @param {*} value The value that that should be considered trusted/safe.
17602 * @returns {*} A value that can be used to stand in for the provided `value` in places
17603 * where Angular expects a $sce.trustAs() return value.
17605 function trustAs(type, trustedValue) {
17606 var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
17607 if (!Constructor) {
17608 throw $sceMinErr('icontext',
17609 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
17610 type, trustedValue);
17612 if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
17613 return trustedValue;
17615 // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
17616 // mutable objects, we ensure here that the value passed in is actually a string.
17617 if (typeof trustedValue !== 'string') {
17618 throw $sceMinErr('itype',
17619 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
17622 return new Constructor(trustedValue);
17627 * @name $sceDelegate#valueOf
17630 * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
17631 * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
17632 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
17634 * If the passed parameter is not a value that had been returned by {@link
17635 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
17637 * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
17638 * call or anything else.
17639 * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
17640 * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
17641 * `value` unchanged.
17643 function valueOf(maybeTrusted) {
17644 if (maybeTrusted instanceof trustedValueHolderBase) {
17645 return maybeTrusted.$$unwrapTrustedValue();
17647 return maybeTrusted;
17653 * @name $sceDelegate#getTrusted
17656 * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
17657 * returns the originally supplied value if the queried context type is a supertype of the
17658 * created type. If this condition isn't satisfied, throws an exception.
17660 * <div class="alert alert-danger">
17661 * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
17662 * (XSS) vulnerability in your application.
17665 * @param {string} type The kind of context in which this value is to be used.
17666 * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
17667 * `$sceDelegate.trustAs`} call.
17668 * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
17669 * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
17671 function getTrusted(type, maybeTrusted) {
17672 if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
17673 return maybeTrusted;
17675 var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
17676 if (constructor && maybeTrusted instanceof constructor) {
17677 return maybeTrusted.$$unwrapTrustedValue();
17679 // If we get here, then we may only take one of two actions.
17680 // 1. sanitize the value for the requested type, or
17681 // 2. throw an exception.
17682 if (type === SCE_CONTEXTS.RESOURCE_URL) {
17683 if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
17684 return maybeTrusted;
17686 throw $sceMinErr('insecurl',
17687 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
17688 maybeTrusted.toString());
17690 } else if (type === SCE_CONTEXTS.HTML) {
17691 return htmlSanitizer(maybeTrusted);
17693 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
17696 return { trustAs: trustAs,
17697 getTrusted: getTrusted,
17698 valueOf: valueOf };
17705 * @name $sceProvider
17708 * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
17709 * - enable/disable Strict Contextual Escaping (SCE) in a module
17710 * - override the default implementation with a custom delegate
17712 * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
17715 /* jshint maxlen: false*/
17724 * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
17726 * # Strict Contextual Escaping
17728 * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
17729 * contexts to result in a value that is marked as safe to use for that context. One example of
17730 * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
17731 * to these contexts as privileged or SCE contexts.
17733 * As of version 1.2, Angular ships with SCE enabled by default.
17735 * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
17736 * one to execute arbitrary javascript by the use of the expression() syntax. Refer
17737 * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
17738 * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
17739 * to the top of your HTML document.
17741 * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
17742 * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
17744 * Here's an example of a binding in a privileged context:
17747 * <input ng-model="userHtml" aria-label="User input">
17748 * <div ng-bind-html="userHtml"></div>
17751 * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
17752 * disabled, this application allows the user to render arbitrary HTML into the DIV.
17753 * In a more realistic example, one may be rendering user comments, blog articles, etc. via
17754 * bindings. (HTML is just one example of a context where rendering user controlled input creates
17755 * security vulnerabilities.)
17757 * For the case of HTML, you might use a library, either on the client side, or on the server side,
17758 * to sanitize unsafe HTML before binding to the value and rendering it in the document.
17760 * How would you ensure that every place that used these types of bindings was bound to a value that
17761 * was sanitized by your library (or returned as safe for rendering by your server?) How can you
17762 * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
17763 * properties/fields and forgot to update the binding to the sanitized value?
17765 * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
17766 * determine that something explicitly says it's safe to use a value for binding in that
17767 * context. You can then audit your code (a simple grep would do) to ensure that this is only done
17768 * for those values that you can easily tell are safe - because they were received from your server,
17769 * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
17770 * allowing only the files in a specific directory to do this. Ensuring that the internal API
17771 * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
17773 * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
17774 * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
17775 * obtain values that will be accepted by SCE / privileged contexts.
17778 * ## How does it work?
17780 * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
17781 * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
17782 * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
17783 * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
17785 * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
17786 * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
17790 * var ngBindHtmlDirective = ['$sce', function($sce) {
17791 * return function(scope, element, attr) {
17792 * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
17793 * element.html(value || '');
17799 * ## Impact on loading templates
17801 * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
17802 * `templateUrl`'s specified by {@link guide/directive directives}.
17804 * By default, Angular only loads templates from the same domain and protocol as the application
17805 * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
17806 * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
17807 * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
17808 * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
17812 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
17813 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
17814 * policy apply in addition to this and may further restrict whether the template is successfully
17815 * loaded. This means that without the right CORS policy, loading templates from a different domain
17816 * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
17819 * ## This feels like too much overhead
17821 * It's important to remember that SCE only applies to interpolation expressions.
17823 * If your expressions are constant literals, they're automatically trusted and you don't need to
17824 * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
17825 * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
17827 * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
17828 * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
17830 * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
17831 * templates in `ng-include` from your application's domain without having to even know about SCE.
17832 * It blocks loading templates from other domains or loading templates over http from an https
17833 * served document. You can change these by setting your own custom {@link
17834 * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
17835 * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
17837 * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
17838 * application that's secure and can be audited to verify that with much more ease than bolting
17839 * security onto an application later.
17841 * <a name="contexts"></a>
17842 * ## What trusted context types are supported?
17844 * | Context | Notes |
17845 * |---------------------|----------------|
17846 * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
17847 * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
17848 * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
17849 * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
17850 * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
17852 * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
17854 * Each element in these arrays must be one of the following:
17857 * - The special **string**, `'self'`, can be used to match against all URLs of the **same
17858 * domain** as the application document using the **same protocol**.
17859 * - **String** (except the special value `'self'`)
17860 * - The string is matched against the full *normalized / absolute URL* of the resource
17861 * being tested (substring matches are not good enough.)
17862 * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
17863 * match themselves.
17864 * - `*`: matches zero or more occurrences of any character other than one of the following 6
17865 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
17867 * - `**`: matches zero or more occurrences of *any* character. As such, it's not
17868 * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
17869 * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
17870 * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
17871 * http://foo.example.com/templates/**).
17872 * - **RegExp** (*see caveat below*)
17873 * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
17874 * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
17875 * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
17876 * have good test coverage). For instance, the use of `.` in the regex is correct only in a
17877 * small number of cases. A `.` character in the regex used when matching the scheme or a
17878 * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
17879 * is highly recommended to use the string patterns and only fall back to regular expressions
17880 * as a last resort.
17881 * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
17882 * matched against the **entire** *normalized / absolute URL* of the resource being tested
17883 * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
17884 * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
17885 * - If you are generating your JavaScript from some other templating engine (not
17886 * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
17887 * remember to escape your regular expression (and be aware that you might need more than
17888 * one level of escaping depending on your templating engine and the way you interpolated
17889 * the value.) Do make use of your platform's escaping mechanism as it might be good
17890 * enough before coding your own. E.g. Ruby has
17891 * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
17892 * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
17893 * Javascript lacks a similar built in function for escaping. Take a look at Google
17894 * Closure library's [goog.string.regExpEscape(s)](
17895 * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
17897 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
17899 * ## Show me an example using SCE.
17901 * <example module="mySceApp" deps="angular-sanitize.js">
17902 * <file name="index.html">
17903 * <div ng-controller="AppController as myCtrl">
17904 * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
17905 * <b>User comments</b><br>
17906 * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
17907 * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
17909 * <div class="well">
17910 * <div ng-repeat="userComment in myCtrl.userComments">
17911 * <b>{{userComment.name}}</b>:
17912 * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
17919 * <file name="script.js">
17920 * angular.module('mySceApp', ['ngSanitize'])
17921 * .controller('AppController', ['$http', '$templateCache', '$sce',
17922 * function($http, $templateCache, $sce) {
17924 * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
17925 * self.userComments = userComments;
17927 * self.explicitlyTrustedHtml = $sce.trustAsHtml(
17928 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
17929 * 'sanitization."">Hover over this text.</span>');
17933 * <file name="test_data.json">
17935 * { "name": "Alice",
17937 * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
17940 * "htmlComment": "<i>Yes!</i> Am I the only other one?"
17945 * <file name="protractor.js" type="protractor">
17946 * describe('SCE doc demo', function() {
17947 * it('should sanitize untrusted values', function() {
17948 * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
17949 * .toBe('<span>Is <i>anyone</i> reading this?</span>');
17952 * it('should NOT sanitize explicitly trusted values', function() {
17953 * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
17954 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
17955 * 'sanitization."">Hover over this text.</span>');
17963 * ## Can I disable SCE completely?
17965 * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
17966 * for little coding overhead. It will be much harder to take an SCE disabled application and
17967 * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
17968 * for cases where you have a lot of existing code that was written before SCE was introduced and
17969 * you're migrating them a module at a time.
17971 * That said, here's how you can completely disable SCE:
17974 * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
17975 * // Completely disable SCE. For demonstration purposes only!
17976 * // Do not use in new projects.
17977 * $sceProvider.enabled(false);
17982 /* jshint maxlen: 100 */
17984 function $SceProvider() {
17985 var enabled = true;
17989 * @name $sceProvider#enabled
17992 * @param {boolean=} value If provided, then enables/disables SCE.
17993 * @return {boolean} true if SCE is enabled, false otherwise.
17996 * Enables/disables SCE and returns the current value.
17998 this.enabled = function(value) {
17999 if (arguments.length) {
18006 /* Design notes on the default implementation for SCE.
18008 * The API contract for the SCE delegate
18009 * -------------------------------------
18010 * The SCE delegate object must provide the following 3 methods:
18012 * - trustAs(contextEnum, value)
18013 * This method is used to tell the SCE service that the provided value is OK to use in the
18014 * contexts specified by contextEnum. It must return an object that will be accepted by
18015 * getTrusted() for a compatible contextEnum and return this value.
18018 * For values that were not produced by trustAs(), return them as is. For values that were
18019 * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
18020 * trustAs is wrapping the given values into some type, this operation unwraps it when given
18023 * - getTrusted(contextEnum, value)
18024 * This function should return the a value that is safe to use in the context specified by
18025 * contextEnum or throw and exception otherwise.
18027 * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
18028 * opaque or wrapped in some holder object. That happens to be an implementation detail. For
18029 * instance, an implementation could maintain a registry of all trusted objects by context. In
18030 * such a case, trustAs() would return the same object that was passed in. getTrusted() would
18031 * return the same object passed in if it was found in the registry under a compatible context or
18032 * throw an exception otherwise. An implementation might only wrap values some of the time based
18033 * on some criteria. getTrusted() might return a value and not throw an exception for special
18034 * constants or objects even if not wrapped. All such implementations fulfill this contract.
18037 * A note on the inheritance model for SCE contexts
18038 * ------------------------------------------------
18039 * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
18040 * is purely an implementation details.
18042 * The contract is simply this:
18044 * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
18045 * will also succeed.
18047 * Inheritance happens to capture this in a natural way. In some future, we
18048 * may not use inheritance anymore. That is OK because no code outside of
18049 * sce.js and sceSpecs.js would need to be aware of this detail.
18052 this.$get = ['$parse', '$sceDelegate', function(
18053 $parse, $sceDelegate) {
18054 // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
18055 // the "expression(javascript expression)" syntax which is insecure.
18056 if (enabled && msie < 8) {
18057 throw $sceMinErr('iequirks',
18058 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
18059 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
18060 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
18063 var sce = shallowCopy(SCE_CONTEXTS);
18067 * @name $sce#isEnabled
18070 * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
18071 * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
18074 * Returns a boolean indicating if SCE is enabled.
18076 sce.isEnabled = function() {
18079 sce.trustAs = $sceDelegate.trustAs;
18080 sce.getTrusted = $sceDelegate.getTrusted;
18081 sce.valueOf = $sceDelegate.valueOf;
18084 sce.trustAs = sce.getTrusted = function(type, value) { return value; };
18085 sce.valueOf = identity;
18090 * @name $sce#parseAs
18093 * Converts Angular {@link guide/expression expression} into a function. This is like {@link
18094 * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
18095 * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
18098 * @param {string} type The kind of SCE context in which this result will be used.
18099 * @param {string} expression String expression to compile.
18100 * @returns {function(context, locals)} a function which represents the compiled expression:
18102 * * `context` – `{object}` – an object against which any expressions embedded in the strings
18103 * are evaluated against (typically a scope object).
18104 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
18107 sce.parseAs = function sceParseAs(type, expr) {
18108 var parsed = $parse(expr);
18109 if (parsed.literal && parsed.constant) {
18112 return $parse(expr, function(value) {
18113 return sce.getTrusted(type, value);
18120 * @name $sce#trustAs
18123 * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
18124 * returns an object that is trusted by angular for use in specified strict contextual
18125 * escaping contexts (such as ng-bind-html, ng-include, any src attribute
18126 * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
18127 * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
18130 * @param {string} type The kind of context in which this value is safe for use. e.g. url,
18131 * resourceUrl, html, js and css.
18132 * @param {*} value The value that that should be considered trusted/safe.
18133 * @returns {*} A value that can be used to stand in for the provided `value` in places
18134 * where Angular expects a $sce.trustAs() return value.
18139 * @name $sce#trustAsHtml
18142 * Shorthand method. `$sce.trustAsHtml(value)` →
18143 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
18145 * @param {*} value The value to trustAs.
18146 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
18147 * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
18148 * only accept expressions that are either literal constants or are the
18149 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
18154 * @name $sce#trustAsUrl
18157 * Shorthand method. `$sce.trustAsUrl(value)` →
18158 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
18160 * @param {*} value The value to trustAs.
18161 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
18162 * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
18163 * only accept expressions that are either literal constants or are the
18164 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
18169 * @name $sce#trustAsResourceUrl
18172 * Shorthand method. `$sce.trustAsResourceUrl(value)` →
18173 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
18175 * @param {*} value The value to trustAs.
18176 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
18177 * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
18178 * only accept expressions that are either literal constants or are the return
18179 * value of {@link ng.$sce#trustAs $sce.trustAs}.)
18184 * @name $sce#trustAsJs
18187 * Shorthand method. `$sce.trustAsJs(value)` →
18188 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
18190 * @param {*} value The value to trustAs.
18191 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
18192 * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
18193 * only accept expressions that are either literal constants or are the
18194 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
18199 * @name $sce#getTrusted
18202 * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
18203 * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
18204 * originally supplied value if the queried context type is a supertype of the created type.
18205 * If this condition isn't satisfied, throws an exception.
18207 * @param {string} type The kind of context in which this value is to be used.
18208 * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
18210 * @returns {*} The value the was originally provided to
18211 * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
18212 * Otherwise, throws an exception.
18217 * @name $sce#getTrustedHtml
18220 * Shorthand method. `$sce.getTrustedHtml(value)` →
18221 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
18223 * @param {*} value The value to pass to `$sce.getTrusted`.
18224 * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
18229 * @name $sce#getTrustedCss
18232 * Shorthand method. `$sce.getTrustedCss(value)` →
18233 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
18235 * @param {*} value The value to pass to `$sce.getTrusted`.
18236 * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
18241 * @name $sce#getTrustedUrl
18244 * Shorthand method. `$sce.getTrustedUrl(value)` →
18245 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
18247 * @param {*} value The value to pass to `$sce.getTrusted`.
18248 * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
18253 * @name $sce#getTrustedResourceUrl
18256 * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
18257 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
18259 * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
18260 * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
18265 * @name $sce#getTrustedJs
18268 * Shorthand method. `$sce.getTrustedJs(value)` →
18269 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
18271 * @param {*} value The value to pass to `$sce.getTrusted`.
18272 * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
18277 * @name $sce#parseAsHtml
18280 * Shorthand method. `$sce.parseAsHtml(expression string)` →
18281 * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
18283 * @param {string} expression String expression to compile.
18284 * @returns {function(context, locals)} a function which represents the compiled expression:
18286 * * `context` – `{object}` – an object against which any expressions embedded in the strings
18287 * are evaluated against (typically a scope object).
18288 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
18294 * @name $sce#parseAsCss
18297 * Shorthand method. `$sce.parseAsCss(value)` →
18298 * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
18300 * @param {string} expression String expression to compile.
18301 * @returns {function(context, locals)} a function which represents the compiled expression:
18303 * * `context` – `{object}` – an object against which any expressions embedded in the strings
18304 * are evaluated against (typically a scope object).
18305 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
18311 * @name $sce#parseAsUrl
18314 * Shorthand method. `$sce.parseAsUrl(value)` →
18315 * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
18317 * @param {string} expression String expression to compile.
18318 * @returns {function(context, locals)} a function which represents the compiled expression:
18320 * * `context` – `{object}` – an object against which any expressions embedded in the strings
18321 * are evaluated against (typically a scope object).
18322 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
18328 * @name $sce#parseAsResourceUrl
18331 * Shorthand method. `$sce.parseAsResourceUrl(value)` →
18332 * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
18334 * @param {string} expression String expression to compile.
18335 * @returns {function(context, locals)} a function which represents the compiled expression:
18337 * * `context` – `{object}` – an object against which any expressions embedded in the strings
18338 * are evaluated against (typically a scope object).
18339 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
18345 * @name $sce#parseAsJs
18348 * Shorthand method. `$sce.parseAsJs(value)` →
18349 * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
18351 * @param {string} expression String expression to compile.
18352 * @returns {function(context, locals)} a function which represents the compiled expression:
18354 * * `context` – `{object}` – an object against which any expressions embedded in the strings
18355 * are evaluated against (typically a scope object).
18356 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
18360 // Shorthand delegations.
18361 var parse = sce.parseAs,
18362 getTrusted = sce.getTrusted,
18363 trustAs = sce.trustAs;
18365 forEach(SCE_CONTEXTS, function(enumValue, name) {
18366 var lName = lowercase(name);
18367 sce[camelCase("parse_as_" + lName)] = function(expr) {
18368 return parse(enumValue, expr);
18370 sce[camelCase("get_trusted_" + lName)] = function(value) {
18371 return getTrusted(enumValue, value);
18373 sce[camelCase("trust_as_" + lName)] = function(value) {
18374 return trustAs(enumValue, value);
18383 * !!! This is an undocumented "private" service !!!
18386 * @requires $window
18387 * @requires $document
18389 * @property {boolean} history Does the browser support html5 history api ?
18390 * @property {boolean} transitions Does the browser support CSS transition events ?
18391 * @property {boolean} animations Does the browser support CSS animation events ?
18394 * This is very simple implementation of testing browser's features.
18396 function $SnifferProvider() {
18397 this.$get = ['$window', '$document', function($window, $document) {
18398 var eventSupport = {},
18400 toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
18401 boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
18402 document = $document[0] || {},
18404 vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
18405 bodyStyle = document.body && document.body.style,
18406 transitions = false,
18407 animations = false,
18411 for (var prop in bodyStyle) {
18412 if (match = vendorRegex.exec(prop)) {
18413 vendorPrefix = match[0];
18414 vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
18419 if (!vendorPrefix) {
18420 vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
18423 transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
18424 animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
18426 if (android && (!transitions || !animations)) {
18427 transitions = isString(bodyStyle.webkitTransition);
18428 animations = isString(bodyStyle.webkitAnimation);
18434 // Android has history.pushState, but it does not update location correctly
18435 // so let's not use the history API at all.
18436 // http://code.google.com/p/android/issues/detail?id=17471
18437 // https://github.com/angular/angular.js/issues/904
18439 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
18440 // so let's not use the history API also
18441 // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
18443 history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
18445 hasEvent: function(event) {
18446 // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
18447 // it. In particular the event is not fired when backspace or delete key are pressed or
18448 // when cut operation is performed.
18449 // IE10+ implements 'input' event but it erroneously fires under various situations,
18450 // e.g. when placeholder changes, or a form is focused.
18451 if (event === 'input' && msie <= 11) return false;
18453 if (isUndefined(eventSupport[event])) {
18454 var divElm = document.createElement('div');
18455 eventSupport[event] = 'on' + event in divElm;
18458 return eventSupport[event];
18461 vendorPrefix: vendorPrefix,
18462 transitions: transitions,
18463 animations: animations,
18469 var $compileMinErr = minErr('$compile');
18473 * @name $templateRequestProvider
18475 * Used to configure the options passed to the {@link $http} service when making a template request.
18477 * For example, it can be used for specifying the "Accept" header that is sent to the server, when
18478 * requesting a template.
18480 function $TemplateRequestProvider() {
18486 * @name $templateRequestProvider#httpOptions
18488 * The options to be passed to the {@link $http} service when making the request.
18489 * You can use this to override options such as the "Accept" header for template requests.
18491 * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
18492 * options if not overridden here.
18494 * @param {string=} value new value for the {@link $http} options.
18495 * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
18497 this.httpOptions = function(val) {
18502 return httpOptions;
18507 * @name $templateRequest
18510 * The `$templateRequest` service runs security checks then downloads the provided template using
18511 * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
18512 * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
18513 * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
18514 * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
18515 * when `tpl` is of type string and `$templateCache` has the matching entry.
18517 * If you want to pass custom options to the `$http` service, such as setting the Accept header you
18518 * can configure this via {@link $templateRequestProvider#httpOptions}.
18520 * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
18521 * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
18523 * @return {Promise} a promise for the HTTP response data of the given URL.
18525 * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
18527 this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
18529 function handleRequestFn(tpl, ignoreRequestError) {
18530 handleRequestFn.totalPendingRequests++;
18532 // We consider the template cache holds only trusted templates, so
18533 // there's no need to go through whitelisting again for keys that already
18534 // are included in there. This also makes Angular accept any script
18535 // directive, no matter its name. However, we still need to unwrap trusted
18537 if (!isString(tpl) || !$templateCache.get(tpl)) {
18538 tpl = $sce.getTrustedResourceUrl(tpl);
18541 var transformResponse = $http.defaults && $http.defaults.transformResponse;
18543 if (isArray(transformResponse)) {
18544 transformResponse = transformResponse.filter(function(transformer) {
18545 return transformer !== defaultHttpResponseTransform;
18547 } else if (transformResponse === defaultHttpResponseTransform) {
18548 transformResponse = null;
18551 return $http.get(tpl, extend({
18552 cache: $templateCache,
18553 transformResponse: transformResponse
18555 ['finally'](function() {
18556 handleRequestFn.totalPendingRequests--;
18558 .then(function(response) {
18559 $templateCache.put(tpl, response.data);
18560 return response.data;
18563 function handleError(resp) {
18564 if (!ignoreRequestError) {
18565 throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
18566 tpl, resp.status, resp.statusText);
18568 return $q.reject(resp);
18572 handleRequestFn.totalPendingRequests = 0;
18574 return handleRequestFn;
18578 function $$TestabilityProvider() {
18579 this.$get = ['$rootScope', '$browser', '$location',
18580 function($rootScope, $browser, $location) {
18583 * @name $testability
18586 * The private $$testability service provides a collection of methods for use when debugging
18587 * or by automated test and debugging tools.
18589 var testability = {};
18592 * @name $$testability#findBindings
18595 * Returns an array of elements that are bound (via ng-bind or {{}})
18596 * to expressions matching the input.
18598 * @param {Element} element The element root to search from.
18599 * @param {string} expression The binding expression to match.
18600 * @param {boolean} opt_exactMatch If true, only returns exact matches
18601 * for the expression. Filters and whitespace are ignored.
18603 testability.findBindings = function(element, expression, opt_exactMatch) {
18604 var bindings = element.getElementsByClassName('ng-binding');
18606 forEach(bindings, function(binding) {
18607 var dataBinding = angular.element(binding).data('$binding');
18609 forEach(dataBinding, function(bindingName) {
18610 if (opt_exactMatch) {
18611 var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
18612 if (matcher.test(bindingName)) {
18613 matches.push(binding);
18616 if (bindingName.indexOf(expression) != -1) {
18617 matches.push(binding);
18627 * @name $$testability#findModels
18630 * Returns an array of elements that are two-way found via ng-model to
18631 * expressions matching the input.
18633 * @param {Element} element The element root to search from.
18634 * @param {string} expression The model expression to match.
18635 * @param {boolean} opt_exactMatch If true, only returns exact matches
18636 * for the expression.
18638 testability.findModels = function(element, expression, opt_exactMatch) {
18639 var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
18640 for (var p = 0; p < prefixes.length; ++p) {
18641 var attributeEquals = opt_exactMatch ? '=' : '*=';
18642 var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
18643 var elements = element.querySelectorAll(selector);
18644 if (elements.length) {
18651 * @name $$testability#getLocation
18654 * Shortcut for getting the location in a browser agnostic way. Returns
18655 * the path, search, and hash. (e.g. /path?a=b#hash)
18657 testability.getLocation = function() {
18658 return $location.url();
18662 * @name $$testability#setLocation
18665 * Shortcut for navigating to a location without doing a full page reload.
18667 * @param {string} url The location url (path, search and hash,
18668 * e.g. /path?a=b#hash) to go to.
18670 testability.setLocation = function(url) {
18671 if (url !== $location.url()) {
18672 $location.url(url);
18673 $rootScope.$digest();
18678 * @name $$testability#whenStable
18681 * Calls the callback when $timeout and $http requests are completed.
18683 * @param {function} callback
18685 testability.whenStable = function(callback) {
18686 $browser.notifyWhenNoOutstandingRequests(callback);
18689 return testability;
18693 function $TimeoutProvider() {
18694 this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
18695 function($rootScope, $browser, $q, $$q, $exceptionHandler) {
18697 var deferreds = {};
18705 * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
18706 * block and delegates any exceptions to
18707 * {@link ng.$exceptionHandler $exceptionHandler} service.
18709 * The return value of calling `$timeout` is a promise, which will be resolved when
18710 * the delay has passed and the timeout function, if provided, is executed.
18712 * To cancel a timeout request, call `$timeout.cancel(promise)`.
18714 * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
18715 * synchronously flush the queue of deferred functions.
18717 * If you only want a promise that will be resolved after some specified delay
18718 * then you can call `$timeout` without the `fn` function.
18720 * @param {function()=} fn A function, whose execution should be delayed.
18721 * @param {number=} [delay=0] Delay in milliseconds.
18722 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
18723 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
18724 * @param {...*=} Pass additional parameters to the executed function.
18725 * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
18726 * will be resolved with the return value of the `fn` function.
18729 function timeout(fn, delay, invokeApply) {
18730 if (!isFunction(fn)) {
18731 invokeApply = delay;
18736 var args = sliceArgs(arguments, 3),
18737 skipApply = (isDefined(invokeApply) && !invokeApply),
18738 deferred = (skipApply ? $$q : $q).defer(),
18739 promise = deferred.promise,
18742 timeoutId = $browser.defer(function() {
18744 deferred.resolve(fn.apply(null, args));
18746 deferred.reject(e);
18747 $exceptionHandler(e);
18750 delete deferreds[promise.$$timeoutId];
18753 if (!skipApply) $rootScope.$apply();
18756 promise.$$timeoutId = timeoutId;
18757 deferreds[timeoutId] = deferred;
18765 * @name $timeout#cancel
18768 * Cancels a task associated with the `promise`. As a result of this, the promise will be
18769 * resolved with a rejection.
18771 * @param {Promise=} promise Promise returned by the `$timeout` function.
18772 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
18775 timeout.cancel = function(promise) {
18776 if (promise && promise.$$timeoutId in deferreds) {
18777 deferreds[promise.$$timeoutId].reject('canceled');
18778 delete deferreds[promise.$$timeoutId];
18779 return $browser.defer.cancel(promise.$$timeoutId);
18788 // NOTE: The usage of window and document instead of $window and $document here is
18789 // deliberate. This service depends on the specific behavior of anchor nodes created by the
18790 // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
18791 // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
18792 // doesn't know about mocked locations and resolves URLs to the real document - which is
18793 // exactly the behavior needed here. There is little value is mocking these out for this
18795 var urlParsingNode = document.createElement("a");
18796 var originUrl = urlResolve(window.location.href);
18801 * Implementation Notes for non-IE browsers
18802 * ----------------------------------------
18803 * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
18804 * results both in the normalizing and parsing of the URL. Normalizing means that a relative
18805 * URL will be resolved into an absolute URL in the context of the application document.
18806 * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
18807 * properties are all populated to reflect the normalized URL. This approach has wide
18808 * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
18809 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
18811 * Implementation Notes for IE
18812 * ---------------------------
18813 * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
18814 * browsers. However, the parsed components will not be set if the URL assigned did not specify
18815 * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
18816 * work around that by performing the parsing in a 2nd step by taking a previously normalized
18817 * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
18818 * properties such as protocol, hostname, port, etc.
18821 * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
18822 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
18823 * http://url.spec.whatwg.org/#urlutils
18824 * https://github.com/angular/angular.js/pull/2902
18825 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
18828 * @param {string} url The URL to be parsed.
18829 * @description Normalizes and parses a URL.
18830 * @returns {object} Returns the normalized URL as a dictionary.
18832 * | member name | Description |
18833 * |---------------|----------------|
18834 * | href | A normalized version of the provided URL if it was not an absolute URL |
18835 * | protocol | The protocol including the trailing colon |
18836 * | host | The host and port (if the port is non-default) of the normalizedUrl |
18837 * | search | The search params, minus the question mark |
18838 * | hash | The hash string, minus the hash symbol
18839 * | hostname | The hostname
18840 * | port | The port, without ":"
18841 * | pathname | The pathname, beginning with "/"
18844 function urlResolve(url) {
18848 // Normalize before parse. Refer Implementation Notes on why this is
18849 // done in two steps on IE.
18850 urlParsingNode.setAttribute("href", href);
18851 href = urlParsingNode.href;
18854 urlParsingNode.setAttribute('href', href);
18856 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
18858 href: urlParsingNode.href,
18859 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
18860 host: urlParsingNode.host,
18861 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
18862 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
18863 hostname: urlParsingNode.hostname,
18864 port: urlParsingNode.port,
18865 pathname: (urlParsingNode.pathname.charAt(0) === '/')
18866 ? urlParsingNode.pathname
18867 : '/' + urlParsingNode.pathname
18872 * Parse a request URL and determine whether this is a same-origin request as the application document.
18874 * @param {string|object} requestUrl The url of the request as a string that will be resolved
18875 * or a parsed URL object.
18876 * @returns {boolean} Whether the request is for the same origin as the application document.
18878 function urlIsSameOrigin(requestUrl) {
18879 var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
18880 return (parsed.protocol === originUrl.protocol &&
18881 parsed.host === originUrl.host);
18889 * A reference to the browser's `window` object. While `window`
18890 * is globally available in JavaScript, it causes testability problems, because
18891 * it is a global variable. In angular we always refer to it through the
18892 * `$window` service, so it may be overridden, removed or mocked for testing.
18894 * Expressions, like the one defined for the `ngClick` directive in the example
18895 * below, are evaluated with respect to the current scope. Therefore, there is
18896 * no risk of inadvertently coding in a dependency on a global value in such an
18900 <example module="windowExample">
18901 <file name="index.html">
18903 angular.module('windowExample', [])
18904 .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
18905 $scope.greeting = 'Hello, World!';
18906 $scope.doGreeting = function(greeting) {
18907 $window.alert(greeting);
18911 <div ng-controller="ExampleController">
18912 <input type="text" ng-model="greeting" aria-label="greeting" />
18913 <button ng-click="doGreeting(greeting)">ALERT</button>
18916 <file name="protractor.js" type="protractor">
18917 it('should display the greeting in the input box', function() {
18918 element(by.model('greeting')).sendKeys('Hello, E2E Tests');
18919 // If we click the button it will block the test runner
18920 // element(':button').click();
18925 function $WindowProvider() {
18926 this.$get = valueFn(window);
18930 * @name $$cookieReader
18931 * @requires $document
18934 * This is a private service for reading cookies used by $http and ngCookies
18936 * @return {Object} a key/value map of the current cookies
18938 function $$CookieReader($document) {
18939 var rawDocument = $document[0] || {};
18940 var lastCookies = {};
18941 var lastCookieString = '';
18943 function safeDecodeURIComponent(str) {
18945 return decodeURIComponent(str);
18951 return function() {
18952 var cookieArray, cookie, i, index, name;
18953 var currentCookieString = rawDocument.cookie || '';
18955 if (currentCookieString !== lastCookieString) {
18956 lastCookieString = currentCookieString;
18957 cookieArray = lastCookieString.split('; ');
18960 for (i = 0; i < cookieArray.length; i++) {
18961 cookie = cookieArray[i];
18962 index = cookie.indexOf('=');
18963 if (index > 0) { //ignore nameless cookies
18964 name = safeDecodeURIComponent(cookie.substring(0, index));
18965 // the first value that is seen for a cookie is the most
18966 // specific one. values for the same cookie name that
18967 // follow are for less specific paths.
18968 if (isUndefined(lastCookies[name])) {
18969 lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
18974 return lastCookies;
18978 $$CookieReader.$inject = ['$document'];
18980 function $$CookieReaderProvider() {
18981 this.$get = $$CookieReader;
18984 /* global currencyFilter: true,
18986 filterFilter: true,
18988 limitToFilter: true,
18989 lowercaseFilter: true,
18990 numberFilter: true,
18991 orderByFilter: true,
18992 uppercaseFilter: true,
18997 * @name $filterProvider
19000 * Filters are just functions which transform input to an output. However filters need to be
19001 * Dependency Injected. To achieve this a filter definition consists of a factory function which is
19002 * annotated with dependencies and is responsible for creating a filter function.
19004 * <div class="alert alert-warning">
19005 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
19006 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
19007 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
19008 * (`myapp_subsection_filterx`).
19012 * // Filter registration
19013 * function MyModule($provide, $filterProvider) {
19014 * // create a service to demonstrate injection (not always needed)
19015 * $provide.value('greet', function(name){
19016 * return 'Hello ' + name + '!';
19019 * // register a filter factory which uses the
19020 * // greet service to demonstrate DI.
19021 * $filterProvider.register('greet', function(greet){
19022 * // return the filter function which uses the greet service
19023 * // to generate salutation
19024 * return function(text) {
19025 * // filters need to be forgiving so check input validity
19026 * return text && greet(text) || text;
19032 * The filter function is registered with the `$injector` under the filter name suffix with
19036 * it('should be the same instance', inject(
19037 * function($filterProvider) {
19038 * $filterProvider.register('reverse', function(){
19042 * function($filter, reverseFilter) {
19043 * expect($filter('reverse')).toBe(reverseFilter);
19048 * For more information about how angular filters work, and how to create your own filters, see
19049 * {@link guide/filter Filters} in the Angular Developer Guide.
19057 * Filters are used for formatting data displayed to the user.
19059 * The general syntax in templates is as follows:
19061 * {{ expression [| filter_name[:parameter_value] ... ] }}
19063 * @param {String} name Name of the filter function to retrieve
19064 * @return {Function} the filter function
19066 <example name="$filter" module="filterExample">
19067 <file name="index.html">
19068 <div ng-controller="MainCtrl">
19069 <h3>{{ originalText }}</h3>
19070 <h3>{{ filteredText }}</h3>
19074 <file name="script.js">
19075 angular.module('filterExample', [])
19076 .controller('MainCtrl', function($scope, $filter) {
19077 $scope.originalText = 'hello';
19078 $scope.filteredText = $filter('uppercase')($scope.originalText);
19083 $FilterProvider.$inject = ['$provide'];
19084 function $FilterProvider($provide) {
19085 var suffix = 'Filter';
19089 * @name $filterProvider#register
19090 * @param {string|Object} name Name of the filter function, or an object map of filters where
19091 * the keys are the filter names and the values are the filter factories.
19093 * <div class="alert alert-warning">
19094 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
19095 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
19096 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
19097 * (`myapp_subsection_filterx`).
19099 * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
19100 * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
19101 * of the registered filter instances.
19103 function register(name, factory) {
19104 if (isObject(name)) {
19106 forEach(name, function(filter, key) {
19107 filters[key] = register(key, filter);
19111 return $provide.factory(name + suffix, factory);
19114 this.register = register;
19116 this.$get = ['$injector', function($injector) {
19117 return function(name) {
19118 return $injector.get(name + suffix);
19122 ////////////////////////////////////////
19125 currencyFilter: false,
19127 filterFilter: false,
19129 limitToFilter: false,
19130 lowercaseFilter: false,
19131 numberFilter: false,
19132 orderByFilter: false,
19133 uppercaseFilter: false,
19136 register('currency', currencyFilter);
19137 register('date', dateFilter);
19138 register('filter', filterFilter);
19139 register('json', jsonFilter);
19140 register('limitTo', limitToFilter);
19141 register('lowercase', lowercaseFilter);
19142 register('number', numberFilter);
19143 register('orderBy', orderByFilter);
19144 register('uppercase', uppercaseFilter);
19153 * Selects a subset of items from `array` and returns it as a new array.
19155 * @param {Array} array The source array.
19156 * @param {string|Object|function()} expression The predicate to be used for selecting items from
19161 * - `string`: The string is used for matching against the contents of the `array`. All strings or
19162 * objects with string properties in `array` that match this string will be returned. This also
19163 * applies to nested object properties.
19164 * The predicate can be negated by prefixing the string with `!`.
19166 * - `Object`: A pattern object can be used to filter specific properties on objects contained
19167 * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
19168 * which have property `name` containing "M" and property `phone` containing "1". A special
19169 * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
19170 * property of the object or its nested object properties. That's equivalent to the simple
19171 * substring match with a `string` as described above. The predicate can be negated by prefixing
19172 * the string with `!`.
19173 * For example `{name: "!M"}` predicate will return an array of items which have property `name`
19174 * not containing "M".
19176 * Note that a named property will match properties on the same level only, while the special
19177 * `$` property will match properties on the same level or deeper. E.g. an array item like
19178 * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
19179 * **will** be matched by `{$: 'John'}`.
19181 * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
19182 * The function is called for each element of the array, with the element, its index, and
19183 * the entire array itself as arguments.
19185 * The final result is an array of those elements that the predicate returned true for.
19187 * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
19188 * determining if the expected value (from the filter expression) and actual value (from
19189 * the object in the array) should be considered a match.
19193 * - `function(actual, expected)`:
19194 * The function will be given the object value and the predicate value to compare and
19195 * should return true if both values should be considered equal.
19197 * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
19198 * This is essentially strict comparison of expected and actual.
19200 * - `false|undefined`: A short hand for a function which will look for a substring match in case
19203 * Primitive values are converted to strings. Objects are not compared against primitives,
19204 * unless they have a custom `toString` method (e.g. `Date` objects).
19208 <file name="index.html">
19209 <div ng-init="friends = [{name:'John', phone:'555-1276'},
19210 {name:'Mary', phone:'800-BIG-MARY'},
19211 {name:'Mike', phone:'555-4321'},
19212 {name:'Adam', phone:'555-5678'},
19213 {name:'Julie', phone:'555-8765'},
19214 {name:'Juliette', phone:'555-5678'}]"></div>
19216 <label>Search: <input ng-model="searchText"></label>
19217 <table id="searchTextResults">
19218 <tr><th>Name</th><th>Phone</th></tr>
19219 <tr ng-repeat="friend in friends | filter:searchText">
19220 <td>{{friend.name}}</td>
19221 <td>{{friend.phone}}</td>
19225 <label>Any: <input ng-model="search.$"></label> <br>
19226 <label>Name only <input ng-model="search.name"></label><br>
19227 <label>Phone only <input ng-model="search.phone"></label><br>
19228 <label>Equality <input type="checkbox" ng-model="strict"></label><br>
19229 <table id="searchObjResults">
19230 <tr><th>Name</th><th>Phone</th></tr>
19231 <tr ng-repeat="friendObj in friends | filter:search:strict">
19232 <td>{{friendObj.name}}</td>
19233 <td>{{friendObj.phone}}</td>
19237 <file name="protractor.js" type="protractor">
19238 var expectFriendNames = function(expectedNames, key) {
19239 element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
19240 arr.forEach(function(wd, i) {
19241 expect(wd.getText()).toMatch(expectedNames[i]);
19246 it('should search across all fields when filtering with a string', function() {
19247 var searchText = element(by.model('searchText'));
19248 searchText.clear();
19249 searchText.sendKeys('m');
19250 expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
19252 searchText.clear();
19253 searchText.sendKeys('76');
19254 expectFriendNames(['John', 'Julie'], 'friend');
19257 it('should search in specific fields when filtering with a predicate object', function() {
19258 var searchAny = element(by.model('search.$'));
19260 searchAny.sendKeys('i');
19261 expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
19263 it('should use a equal comparison when comparator is true', function() {
19264 var searchName = element(by.model('search.name'));
19265 var strict = element(by.model('strict'));
19266 searchName.clear();
19267 searchName.sendKeys('Julie');
19269 expectFriendNames(['Julie'], 'friendObj');
19274 function filterFilter() {
19275 return function(array, expression, comparator) {
19276 if (!isArrayLike(array)) {
19277 if (array == null) {
19280 throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
19284 var expressionType = getTypeForFilter(expression);
19286 var matchAgainstAnyProp;
19288 switch (expressionType) {
19290 predicateFn = expression;
19296 matchAgainstAnyProp = true;
19300 predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
19306 return Array.prototype.filter.call(array, predicateFn);
19310 // Helper functions for `filterFilter`
19311 function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
19312 var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
19315 if (comparator === true) {
19316 comparator = equals;
19317 } else if (!isFunction(comparator)) {
19318 comparator = function(actual, expected) {
19319 if (isUndefined(actual)) {
19320 // No substring matching against `undefined`
19323 if ((actual === null) || (expected === null)) {
19324 // No substring matching against `null`; only match against `null`
19325 return actual === expected;
19327 if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
19328 // Should not compare primitives against objects, unless they have custom `toString` method
19332 actual = lowercase('' + actual);
19333 expected = lowercase('' + expected);
19334 return actual.indexOf(expected) !== -1;
19338 predicateFn = function(item) {
19339 if (shouldMatchPrimitives && !isObject(item)) {
19340 return deepCompare(item, expression.$, comparator, false);
19342 return deepCompare(item, expression, comparator, matchAgainstAnyProp);
19345 return predicateFn;
19348 function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
19349 var actualType = getTypeForFilter(actual);
19350 var expectedType = getTypeForFilter(expected);
19352 if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
19353 return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
19354 } else if (isArray(actual)) {
19355 // In case `actual` is an array, consider it a match
19356 // if ANY of it's items matches `expected`
19357 return actual.some(function(item) {
19358 return deepCompare(item, expected, comparator, matchAgainstAnyProp);
19362 switch (actualType) {
19365 if (matchAgainstAnyProp) {
19366 for (key in actual) {
19367 if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
19371 return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
19372 } else if (expectedType === 'object') {
19373 for (key in expected) {
19374 var expectedVal = expected[key];
19375 if (isFunction(expectedVal) || isUndefined(expectedVal)) {
19379 var matchAnyProperty = key === '$';
19380 var actualVal = matchAnyProperty ? actual : actual[key];
19381 if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
19387 return comparator(actual, expected);
19393 return comparator(actual, expected);
19397 // Used for easily differentiating between `null` and actual `object`
19398 function getTypeForFilter(val) {
19399 return (val === null) ? 'null' : typeof val;
19402 var MAX_DIGITS = 22;
19403 var DECIMAL_SEP = '.';
19404 var ZERO_CHAR = '0';
19412 * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
19413 * symbol for current locale is used.
19415 * @param {number} amount Input to filter.
19416 * @param {string=} symbol Currency symbol or identifier to be displayed.
19417 * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
19418 * @returns {string} Formatted number.
19422 <example module="currencyExample">
19423 <file name="index.html">
19425 angular.module('currencyExample', [])
19426 .controller('ExampleController', ['$scope', function($scope) {
19427 $scope.amount = 1234.56;
19430 <div ng-controller="ExampleController">
19431 <input type="number" ng-model="amount" aria-label="amount"> <br>
19432 default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
19433 custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
19434 no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
19437 <file name="protractor.js" type="protractor">
19438 it('should init with 1234.56', function() {
19439 expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
19440 expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
19441 expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
19443 it('should update', function() {
19444 if (browser.params.browser == 'safari') {
19445 // Safari does not understand the minus key. See
19446 // https://github.com/angular/protractor/issues/481
19449 element(by.model('amount')).clear();
19450 element(by.model('amount')).sendKeys('-1234');
19451 expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
19452 expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
19453 expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
19458 currencyFilter.$inject = ['$locale'];
19459 function currencyFilter($locale) {
19460 var formats = $locale.NUMBER_FORMATS;
19461 return function(amount, currencySymbol, fractionSize) {
19462 if (isUndefined(currencySymbol)) {
19463 currencySymbol = formats.CURRENCY_SYM;
19466 if (isUndefined(fractionSize)) {
19467 fractionSize = formats.PATTERNS[1].maxFrac;
19470 // if null or undefined pass it through
19471 return (amount == null)
19473 : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
19474 replace(/\u00A4/g, currencySymbol);
19484 * Formats a number as text.
19486 * If the input is null or undefined, it will just be returned.
19487 * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
19488 * If the input is not a number an empty string is returned.
19491 * @param {number|string} number Number to format.
19492 * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
19493 * If this is not provided then the fraction size is computed from the current locale's number
19494 * formatting pattern. In the case of the default locale, it will be 3.
19495 * @returns {string} Number rounded to fractionSize and places a “,” after each third digit.
19498 <example module="numberFilterExample">
19499 <file name="index.html">
19501 angular.module('numberFilterExample', [])
19502 .controller('ExampleController', ['$scope', function($scope) {
19503 $scope.val = 1234.56789;
19506 <div ng-controller="ExampleController">
19507 <label>Enter number: <input ng-model='val'></label><br>
19508 Default formatting: <span id='number-default'>{{val | number}}</span><br>
19509 No fractions: <span>{{val | number:0}}</span><br>
19510 Negative number: <span>{{-val | number:4}}</span>
19513 <file name="protractor.js" type="protractor">
19514 it('should format numbers', function() {
19515 expect(element(by.id('number-default')).getText()).toBe('1,234.568');
19516 expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
19517 expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
19520 it('should update', function() {
19521 element(by.model('val')).clear();
19522 element(by.model('val')).sendKeys('3374.333');
19523 expect(element(by.id('number-default')).getText()).toBe('3,374.333');
19524 expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
19525 expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
19530 numberFilter.$inject = ['$locale'];
19531 function numberFilter($locale) {
19532 var formats = $locale.NUMBER_FORMATS;
19533 return function(number, fractionSize) {
19535 // if null or undefined pass it through
19536 return (number == null)
19538 : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
19544 * Parse a number (as a string) into three components that can be used
19545 * for formatting the number.
19547 * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
19549 * @param {string} numStr The number to parse
19550 * @return {object} An object describing this number, containing the following keys:
19551 * - d : an array of digits containing leading zeros as necessary
19552 * - i : the number of the digits in `d` that are to the left of the decimal point
19553 * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
19556 function parse(numStr) {
19557 var exponent = 0, digits, numberOfIntegerDigits;
19561 if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
19562 numStr = numStr.replace(DECIMAL_SEP, '');
19565 // Exponential form?
19566 if ((i = numStr.search(/e/i)) > 0) {
19567 // Work out the exponent.
19568 if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
19569 numberOfIntegerDigits += +numStr.slice(i + 1);
19570 numStr = numStr.substring(0, i);
19571 } else if (numberOfIntegerDigits < 0) {
19572 // There was no decimal point or exponent so it is an integer.
19573 numberOfIntegerDigits = numStr.length;
19576 // Count the number of leading zeros.
19577 for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++);
19579 if (i == (zeros = numStr.length)) {
19580 // The digits are all zero.
19582 numberOfIntegerDigits = 1;
19584 // Count the number of trailing zeros
19586 while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
19588 // Trailing zeros are insignificant so ignore them
19589 numberOfIntegerDigits -= i;
19591 // Convert string to array of digits without leading/trailing zeros.
19592 for (j = 0; i <= zeros; i++, j++) {
19593 digits[j] = +numStr.charAt(i);
19597 // If the number overflows the maximum allowed digits then use an exponent.
19598 if (numberOfIntegerDigits > MAX_DIGITS) {
19599 digits = digits.splice(0, MAX_DIGITS - 1);
19600 exponent = numberOfIntegerDigits - 1;
19601 numberOfIntegerDigits = 1;
19604 return { d: digits, e: exponent, i: numberOfIntegerDigits };
19608 * Round the parsed number to the specified number of decimal places
19609 * This function changed the parsedNumber in-place
19611 function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
19612 var digits = parsedNumber.d;
19613 var fractionLen = digits.length - parsedNumber.i;
19615 // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
19616 fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
19618 // The index of the digit to where rounding is to occur
19619 var roundAt = fractionSize + parsedNumber.i;
19620 var digit = digits[roundAt];
19623 digits.splice(roundAt);
19625 // We rounded to zero so reset the parsedNumber
19626 parsedNumber.i = 1;
19627 digits.length = roundAt = fractionSize + 1;
19628 for (var i=0; i < roundAt; i++) digits[i] = 0;
19631 if (digit >= 5) digits[roundAt - 1]++;
19633 // Pad out with zeros to get the required fraction length
19634 for (; fractionLen < fractionSize; fractionLen++) digits.push(0);
19637 // Do any carrying, e.g. a digit was rounded up to 10
19638 var carry = digits.reduceRight(function(carry, d, i, digits) {
19640 digits[i] = d % 10;
19641 return Math.floor(d / 10);
19644 digits.unshift(carry);
19650 * Format a number into a string
19651 * @param {number} number The number to format
19653 * minFrac, // the minimum number of digits required in the fraction part of the number
19654 * maxFrac, // the maximum number of digits required in the fraction part of the number
19655 * gSize, // number of digits in each group of separated digits
19656 * lgSize, // number of digits in the last group of digits before the decimal separator
19657 * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
19658 * posPre, // the string to go in front of a positive number
19659 * negSuf, // the string to go after a negative number (e.g. `)`)
19660 * posSuf // the string to go after a positive number
19662 * @param {string} groupSep The string to separate groups of number (e.g. `,`)
19663 * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
19664 * @param {[type]} fractionSize The size of the fractional part of the number
19665 * @return {string} The number formatted as a string
19667 function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
19669 if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
19671 var isInfinity = !isFinite(number);
19672 var isZero = false;
19673 var numStr = Math.abs(number) + '',
19674 formattedText = '',
19678 formattedText = '\u221e';
19680 parsedNumber = parse(numStr);
19682 roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
19684 var digits = parsedNumber.d;
19685 var integerLen = parsedNumber.i;
19686 var exponent = parsedNumber.e;
19688 isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
19690 // pad zeros for small numbers
19691 while (integerLen < 0) {
19696 // extract decimals digits
19697 if (integerLen > 0) {
19698 decimals = digits.splice(integerLen);
19704 // format the integer digits with grouping separators
19706 if (digits.length > pattern.lgSize) {
19707 groups.unshift(digits.splice(-pattern.lgSize).join(''));
19709 while (digits.length > pattern.gSize) {
19710 groups.unshift(digits.splice(-pattern.gSize).join(''));
19712 if (digits.length) {
19713 groups.unshift(digits.join(''));
19715 formattedText = groups.join(groupSep);
19717 // append the decimal digits
19718 if (decimals.length) {
19719 formattedText += decimalSep + decimals.join('');
19723 formattedText += 'e+' + exponent;
19726 if (number < 0 && !isZero) {
19727 return pattern.negPre + formattedText + pattern.negSuf;
19729 return pattern.posPre + formattedText + pattern.posSuf;
19733 function padNumber(num, digits, trim) {
19740 while (num.length < digits) num = ZERO_CHAR + num;
19742 num = num.substr(num.length - digits);
19748 function dateGetter(name, size, offset, trim) {
19749 offset = offset || 0;
19750 return function(date) {
19751 var value = date['get' + name]();
19752 if (offset > 0 || value > -offset) {
19755 if (value === 0 && offset == -12) value = 12;
19756 return padNumber(value, size, trim);
19760 function dateStrGetter(name, shortForm) {
19761 return function(date, formats) {
19762 var value = date['get' + name]();
19763 var get = uppercase(shortForm ? ('SHORT' + name) : name);
19765 return formats[get][value];
19769 function timeZoneGetter(date, formats, offset) {
19770 var zone = -1 * offset;
19771 var paddedZone = (zone >= 0) ? "+" : "";
19773 paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
19774 padNumber(Math.abs(zone % 60), 2);
19779 function getFirstThursdayOfYear(year) {
19780 // 0 = index of January
19781 var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
19782 // 4 = index of Thursday (+1 to account for 1st = 5)
19783 // 11 = index of *next* Thursday (+1 account for 1st = 12)
19784 return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
19787 function getThursdayThisWeek(datetime) {
19788 return new Date(datetime.getFullYear(), datetime.getMonth(),
19789 // 4 = index of Thursday
19790 datetime.getDate() + (4 - datetime.getDay()));
19793 function weekGetter(size) {
19794 return function(date) {
19795 var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
19796 thisThurs = getThursdayThisWeek(date);
19798 var diff = +thisThurs - +firstThurs,
19799 result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
19801 return padNumber(result, size);
19805 function ampmGetter(date, formats) {
19806 return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
19809 function eraGetter(date, formats) {
19810 return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
19813 function longEraGetter(date, formats) {
19814 return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
19817 var DATE_FORMATS = {
19818 yyyy: dateGetter('FullYear', 4),
19819 yy: dateGetter('FullYear', 2, 0, true),
19820 y: dateGetter('FullYear', 1),
19821 MMMM: dateStrGetter('Month'),
19822 MMM: dateStrGetter('Month', true),
19823 MM: dateGetter('Month', 2, 1),
19824 M: dateGetter('Month', 1, 1),
19825 dd: dateGetter('Date', 2),
19826 d: dateGetter('Date', 1),
19827 HH: dateGetter('Hours', 2),
19828 H: dateGetter('Hours', 1),
19829 hh: dateGetter('Hours', 2, -12),
19830 h: dateGetter('Hours', 1, -12),
19831 mm: dateGetter('Minutes', 2),
19832 m: dateGetter('Minutes', 1),
19833 ss: dateGetter('Seconds', 2),
19834 s: dateGetter('Seconds', 1),
19835 // while ISO 8601 requires fractions to be prefixed with `.` or `,`
19836 // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
19837 sss: dateGetter('Milliseconds', 3),
19838 EEEE: dateStrGetter('Day'),
19839 EEE: dateStrGetter('Day', true),
19847 GGGG: longEraGetter
19850 var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
19851 NUMBER_STRING = /^\-?\d+$/;
19859 * Formats `date` to a string based on the requested `format`.
19861 * `format` string can be composed of the following elements:
19863 * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
19864 * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
19865 * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
19866 * * `'MMMM'`: Month in year (January-December)
19867 * * `'MMM'`: Month in year (Jan-Dec)
19868 * * `'MM'`: Month in year, padded (01-12)
19869 * * `'M'`: Month in year (1-12)
19870 * * `'dd'`: Day in month, padded (01-31)
19871 * * `'d'`: Day in month (1-31)
19872 * * `'EEEE'`: Day in Week,(Sunday-Saturday)
19873 * * `'EEE'`: Day in Week, (Sun-Sat)
19874 * * `'HH'`: Hour in day, padded (00-23)
19875 * * `'H'`: Hour in day (0-23)
19876 * * `'hh'`: Hour in AM/PM, padded (01-12)
19877 * * `'h'`: Hour in AM/PM, (1-12)
19878 * * `'mm'`: Minute in hour, padded (00-59)
19879 * * `'m'`: Minute in hour (0-59)
19880 * * `'ss'`: Second in minute, padded (00-59)
19881 * * `'s'`: Second in minute (0-59)
19882 * * `'sss'`: Millisecond in second, padded (000-999)
19883 * * `'a'`: AM/PM marker
19884 * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
19885 * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
19886 * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
19887 * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
19888 * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
19890 * `format` string can also be one of the following predefined
19891 * {@link guide/i18n localizable formats}:
19893 * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
19894 * (e.g. Sep 3, 2010 12:05:08 PM)
19895 * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
19896 * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
19897 * (e.g. Friday, September 3, 2010)
19898 * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
19899 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
19900 * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
19901 * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
19902 * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
19904 * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
19905 * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
19906 * (e.g. `"h 'o''clock'"`).
19908 * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
19909 * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
19910 * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
19911 * specified in the string input, the time is considered to be in the local timezone.
19912 * @param {string=} format Formatting rules (see Description). If not specified,
19913 * `mediumDate` is used.
19914 * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
19915 * continental US time zone abbreviations, but for general use, use a time zone offset, for
19916 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
19917 * If not specified, the timezone of the browser will be used.
19918 * @returns {string} Formatted string or the input if input is not recognized as date/millis.
19922 <file name="index.html">
19923 <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
19924 <span>{{1288323623006 | date:'medium'}}</span><br>
19925 <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
19926 <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
19927 <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
19928 <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
19929 <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
19930 <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
19932 <file name="protractor.js" type="protractor">
19933 it('should format date', function() {
19934 expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
19935 toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
19936 expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
19937 toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
19938 expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
19939 toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
19940 expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
19941 toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
19946 dateFilter.$inject = ['$locale'];
19947 function dateFilter($locale) {
19950 var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
19951 // 1 2 3 4 5 6 7 8 9 10 11
19952 function jsonStringToDate(string) {
19954 if (match = string.match(R_ISO8601_STR)) {
19955 var date = new Date(0),
19958 dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
19959 timeSetter = match[8] ? date.setUTCHours : date.setHours;
19962 tzHour = toInt(match[9] + match[10]);
19963 tzMin = toInt(match[9] + match[11]);
19965 dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
19966 var h = toInt(match[4] || 0) - tzHour;
19967 var m = toInt(match[5] || 0) - tzMin;
19968 var s = toInt(match[6] || 0);
19969 var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
19970 timeSetter.call(date, h, m, s, ms);
19977 return function(date, format, timezone) {
19982 format = format || 'mediumDate';
19983 format = $locale.DATETIME_FORMATS[format] || format;
19984 if (isString(date)) {
19985 date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
19988 if (isNumber(date)) {
19989 date = new Date(date);
19992 if (!isDate(date) || !isFinite(date.getTime())) {
19997 match = DATE_FORMATS_SPLIT.exec(format);
19999 parts = concat(parts, match, 1);
20000 format = parts.pop();
20002 parts.push(format);
20007 var dateTimezoneOffset = date.getTimezoneOffset();
20009 dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
20010 date = convertTimezoneToLocal(date, timezone, true);
20012 forEach(parts, function(value) {
20013 fn = DATE_FORMATS[value];
20014 text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
20015 : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
20029 * Allows you to convert a JavaScript object into JSON string.
20031 * This filter is mostly useful for debugging. When using the double curly {{value}} notation
20032 * the binding is automatically converted to JSON.
20034 * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
20035 * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
20036 * @returns {string} JSON string.
20041 <file name="index.html">
20042 <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
20043 <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
20045 <file name="protractor.js" type="protractor">
20046 it('should jsonify filtered objects', function() {
20047 expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
20048 expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
20054 function jsonFilter() {
20055 return function(object, spacing) {
20056 if (isUndefined(spacing)) {
20059 return toJson(object, spacing);
20069 * Converts string to lowercase.
20070 * @see angular.lowercase
20072 var lowercaseFilter = valueFn(lowercase);
20080 * Converts string to uppercase.
20081 * @see angular.uppercase
20083 var uppercaseFilter = valueFn(uppercase);
20091 * Creates a new array or string containing only a specified number of elements. The elements
20092 * are taken from either the beginning or the end of the source array, string or number, as specified by
20093 * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
20094 * converted to a string.
20096 * @param {Array|string|number} input Source array, string or number to be limited.
20097 * @param {string|number} limit The length of the returned array or string. If the `limit` number
20098 * is positive, `limit` number of items from the beginning of the source array/string are copied.
20099 * If the number is negative, `limit` number of items from the end of the source array/string
20100 * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
20101 * the input will be returned unchanged.
20102 * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
20103 * indicates an offset from the end of `input`. Defaults to `0`.
20104 * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
20105 * had less than `limit` elements.
20108 <example module="limitToExample">
20109 <file name="index.html">
20111 angular.module('limitToExample', [])
20112 .controller('ExampleController', ['$scope', function($scope) {
20113 $scope.numbers = [1,2,3,4,5,6,7,8,9];
20114 $scope.letters = "abcdefghi";
20115 $scope.longNumber = 2345432342;
20116 $scope.numLimit = 3;
20117 $scope.letterLimit = 3;
20118 $scope.longNumberLimit = 3;
20121 <div ng-controller="ExampleController">
20123 Limit {{numbers}} to:
20124 <input type="number" step="1" ng-model="numLimit">
20126 <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
20128 Limit {{letters}} to:
20129 <input type="number" step="1" ng-model="letterLimit">
20131 <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
20133 Limit {{longNumber}} to:
20134 <input type="number" step="1" ng-model="longNumberLimit">
20136 <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
20139 <file name="protractor.js" type="protractor">
20140 var numLimitInput = element(by.model('numLimit'));
20141 var letterLimitInput = element(by.model('letterLimit'));
20142 var longNumberLimitInput = element(by.model('longNumberLimit'));
20143 var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
20144 var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
20145 var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
20147 it('should limit the number array to first three items', function() {
20148 expect(numLimitInput.getAttribute('value')).toBe('3');
20149 expect(letterLimitInput.getAttribute('value')).toBe('3');
20150 expect(longNumberLimitInput.getAttribute('value')).toBe('3');
20151 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
20152 expect(limitedLetters.getText()).toEqual('Output letters: abc');
20153 expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
20156 // There is a bug in safari and protractor that doesn't like the minus key
20157 // it('should update the output when -3 is entered', function() {
20158 // numLimitInput.clear();
20159 // numLimitInput.sendKeys('-3');
20160 // letterLimitInput.clear();
20161 // letterLimitInput.sendKeys('-3');
20162 // longNumberLimitInput.clear();
20163 // longNumberLimitInput.sendKeys('-3');
20164 // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
20165 // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
20166 // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
20169 it('should not exceed the maximum size of input array', function() {
20170 numLimitInput.clear();
20171 numLimitInput.sendKeys('100');
20172 letterLimitInput.clear();
20173 letterLimitInput.sendKeys('100');
20174 longNumberLimitInput.clear();
20175 longNumberLimitInput.sendKeys('100');
20176 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
20177 expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
20178 expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
20183 function limitToFilter() {
20184 return function(input, limit, begin) {
20185 if (Math.abs(Number(limit)) === Infinity) {
20186 limit = Number(limit);
20188 limit = toInt(limit);
20190 if (isNaN(limit)) return input;
20192 if (isNumber(input)) input = input.toString();
20193 if (!isArray(input) && !isString(input)) return input;
20195 begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
20196 begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
20199 return input.slice(begin, begin + limit);
20202 return input.slice(limit, input.length);
20204 return input.slice(Math.max(0, begin + limit), begin);
20216 * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
20217 * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
20218 * as expected, make sure they are actually being saved as numbers and not strings.
20219 * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
20221 * @param {Array} array The array (or array-like object) to sort.
20222 * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
20223 * used by the comparator to determine the order of elements.
20227 * - `function`: Getter function. The result of this function will be sorted using the
20228 * `<`, `===`, `>` operator.
20229 * - `string`: An Angular expression. The result of this expression is used to compare elements
20230 * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
20231 * 3 first characters of a property called `name`). The result of a constant expression
20232 * is interpreted as a property name to be used in comparisons (for example `"special name"`
20233 * to sort object by the value of their `special name` property). An expression can be
20234 * optionally prefixed with `+` or `-` to control ascending or descending sort order
20235 * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
20236 * element itself is used to compare where sorting.
20237 * - `Array`: An array of function or string predicates. The first predicate in the array
20238 * is used for sorting, but when two items are equivalent, the next predicate is used.
20240 * If the predicate is missing or empty then it defaults to `'+'`.
20242 * @param {boolean=} reverse Reverse the order of the array.
20243 * @returns {Array} Sorted copy of the source array.
20247 * The example below demonstrates a simple ngRepeat, where the data is sorted
20248 * by age in descending order (predicate is set to `'-age'`).
20249 * `reverse` is not set, which means it defaults to `false`.
20250 <example module="orderByExample">
20251 <file name="index.html">
20252 <div ng-controller="ExampleController">
20253 <table class="friend">
20256 <th>Phone Number</th>
20259 <tr ng-repeat="friend in friends | orderBy:'-age'">
20260 <td>{{friend.name}}</td>
20261 <td>{{friend.phone}}</td>
20262 <td>{{friend.age}}</td>
20267 <file name="script.js">
20268 angular.module('orderByExample', [])
20269 .controller('ExampleController', ['$scope', function($scope) {
20271 [{name:'John', phone:'555-1212', age:10},
20272 {name:'Mary', phone:'555-9876', age:19},
20273 {name:'Mike', phone:'555-4321', age:21},
20274 {name:'Adam', phone:'555-5678', age:35},
20275 {name:'Julie', phone:'555-8765', age:29}];
20280 * The predicate and reverse parameters can be controlled dynamically through scope properties,
20281 * as shown in the next example.
20283 <example module="orderByExample">
20284 <file name="index.html">
20285 <div ng-controller="ExampleController">
20286 <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
20288 <button ng-click="predicate=''">Set to unsorted</button>
20289 <table class="friend">
20292 <button ng-click="order('name')">Name</button>
20293 <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
20296 <button ng-click="order('phone')">Phone Number</button>
20297 <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
20300 <button ng-click="order('age')">Age</button>
20301 <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
20304 <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
20305 <td>{{friend.name}}</td>
20306 <td>{{friend.phone}}</td>
20307 <td>{{friend.age}}</td>
20312 <file name="script.js">
20313 angular.module('orderByExample', [])
20314 .controller('ExampleController', ['$scope', function($scope) {
20316 [{name:'John', phone:'555-1212', age:10},
20317 {name:'Mary', phone:'555-9876', age:19},
20318 {name:'Mike', phone:'555-4321', age:21},
20319 {name:'Adam', phone:'555-5678', age:35},
20320 {name:'Julie', phone:'555-8765', age:29}];
20321 $scope.predicate = 'age';
20322 $scope.reverse = true;
20323 $scope.order = function(predicate) {
20324 $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
20325 $scope.predicate = predicate;
20329 <file name="style.css">
20333 .sortorder.reverse:after {
20339 * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
20340 * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
20341 * desired parameters.
20346 <example module="orderByExample">
20347 <file name="index.html">
20348 <div ng-controller="ExampleController">
20349 <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
20350 <table class="friend">
20353 <button ng-click="order('name')">Name</button>
20354 <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
20357 <button ng-click="order('phone')">Phone Number</button>
20358 <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
20361 <button ng-click="order('age')">Age</button>
20362 <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
20365 <tr ng-repeat="friend in friends">
20366 <td>{{friend.name}}</td>
20367 <td>{{friend.phone}}</td>
20368 <td>{{friend.age}}</td>
20374 <file name="script.js">
20375 angular.module('orderByExample', [])
20376 .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
20377 var orderBy = $filter('orderBy');
20379 { name: 'John', phone: '555-1212', age: 10 },
20380 { name: 'Mary', phone: '555-9876', age: 19 },
20381 { name: 'Mike', phone: '555-4321', age: 21 },
20382 { name: 'Adam', phone: '555-5678', age: 35 },
20383 { name: 'Julie', phone: '555-8765', age: 29 }
20385 $scope.order = function(predicate) {
20386 $scope.predicate = predicate;
20387 $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
20388 $scope.friends = orderBy($scope.friends, predicate, $scope.reverse);
20390 $scope.order('age', true);
20394 <file name="style.css">
20398 .sortorder.reverse:after {
20404 orderByFilter.$inject = ['$parse'];
20405 function orderByFilter($parse) {
20406 return function(array, sortPredicate, reverseOrder) {
20408 if (array == null) return array;
20409 if (!isArrayLike(array)) {
20410 throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
20413 if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
20414 if (sortPredicate.length === 0) { sortPredicate = ['+']; }
20416 var predicates = processPredicates(sortPredicate, reverseOrder);
20417 // Add a predicate at the end that evaluates to the element index. This makes the
20418 // sort stable as it works as a tie-breaker when all the input predicates cannot
20419 // distinguish between two elements.
20420 predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
20422 // The next three lines are a version of a Swartzian Transform idiom from Perl
20423 // (sometimes called the Decorate-Sort-Undecorate idiom)
20424 // See https://en.wikipedia.org/wiki/Schwartzian_transform
20425 var compareValues = Array.prototype.map.call(array, getComparisonObject);
20426 compareValues.sort(doComparison);
20427 array = compareValues.map(function(item) { return item.value; });
20431 function getComparisonObject(value, index) {
20434 predicateValues: predicates.map(function(predicate) {
20435 return getPredicateValue(predicate.get(value), index);
20440 function doComparison(v1, v2) {
20442 for (var index=0, length = predicates.length; index < length; ++index) {
20443 result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
20450 function processPredicates(sortPredicate, reverseOrder) {
20451 reverseOrder = reverseOrder ? -1 : 1;
20452 return sortPredicate.map(function(predicate) {
20453 var descending = 1, get = identity;
20455 if (isFunction(predicate)) {
20457 } else if (isString(predicate)) {
20458 if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
20459 descending = predicate.charAt(0) == '-' ? -1 : 1;
20460 predicate = predicate.substring(1);
20462 if (predicate !== '') {
20463 get = $parse(predicate);
20464 if (get.constant) {
20466 get = function(value) { return value[key]; };
20470 return { get: get, descending: descending * reverseOrder };
20474 function isPrimitive(value) {
20475 switch (typeof value) {
20476 case 'number': /* falls through */
20477 case 'boolean': /* falls through */
20485 function objectValue(value, index) {
20486 // If `valueOf` is a valid function use that
20487 if (typeof value.valueOf === 'function') {
20488 value = value.valueOf();
20489 if (isPrimitive(value)) return value;
20491 // If `toString` is a valid function and not the one from `Object.prototype` use that
20492 if (hasCustomToString(value)) {
20493 value = value.toString();
20494 if (isPrimitive(value)) return value;
20496 // We have a basic object so we use the position of the object in the collection
20500 function getPredicateValue(value, index) {
20501 var type = typeof value;
20502 if (value === null) {
20505 } else if (type === 'string') {
20506 value = value.toLowerCase();
20507 } else if (type === 'object') {
20508 value = objectValue(value, index);
20510 return { value: value, type: type };
20513 function compare(v1, v2) {
20515 if (v1.type === v2.type) {
20516 if (v1.value !== v2.value) {
20517 result = v1.value < v2.value ? -1 : 1;
20520 result = v1.type < v2.type ? -1 : 1;
20526 function ngDirective(directive) {
20527 if (isFunction(directive)) {
20532 directive.restrict = directive.restrict || 'AC';
20533 return valueFn(directive);
20542 * Modifies the default behavior of the html A tag so that the default action is prevented when
20543 * the href attribute is empty.
20545 * This change permits the easy creation of action links with the `ngClick` directive
20546 * without changing the location or causing page reloads, e.g.:
20547 * `<a href="" ng-click="list.addItem()">Add Item</a>`
20549 var htmlAnchorDirective = valueFn({
20551 compile: function(element, attr) {
20552 if (!attr.href && !attr.xlinkHref) {
20553 return function(scope, element) {
20554 // If the linked element is not an anchor tag anymore, do nothing
20555 if (element[0].nodeName.toLowerCase() !== 'a') return;
20557 // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
20558 var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
20559 'xlink:href' : 'href';
20560 element.on('click', function(event) {
20561 // if we have no href url, then don't navigate anywhere.
20562 if (!element.attr(href)) {
20563 event.preventDefault();
20578 * Using Angular markup like `{{hash}}` in an href attribute will
20579 * make the link go to the wrong URL if the user clicks it before
20580 * Angular has a chance to replace the `{{hash}}` markup with its
20581 * value. Until Angular replaces the markup the link will be broken
20582 * and will most likely return a 404 error. The `ngHref` directive
20583 * solves this problem.
20585 * The wrong way to write it:
20587 * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
20590 * The correct way to write it:
20592 * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
20596 * @param {template} ngHref any string which can contain `{{}}` markup.
20599 * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
20600 * in links and their different behaviors:
20602 <file name="index.html">
20603 <input ng-model="value" /><br />
20604 <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
20605 <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
20606 <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
20607 <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
20608 <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
20609 <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
20611 <file name="protractor.js" type="protractor">
20612 it('should execute ng-click but not reload when href without value', function() {
20613 element(by.id('link-1')).click();
20614 expect(element(by.model('value')).getAttribute('value')).toEqual('1');
20615 expect(element(by.id('link-1')).getAttribute('href')).toBe('');
20618 it('should execute ng-click but not reload when href empty string', function() {
20619 element(by.id('link-2')).click();
20620 expect(element(by.model('value')).getAttribute('value')).toEqual('2');
20621 expect(element(by.id('link-2')).getAttribute('href')).toBe('');
20624 it('should execute ng-click and change url when ng-href specified', function() {
20625 expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
20627 element(by.id('link-3')).click();
20629 // At this point, we navigate away from an Angular page, so we need
20630 // to use browser.driver to get the base webdriver.
20632 browser.wait(function() {
20633 return browser.driver.getCurrentUrl().then(function(url) {
20634 return url.match(/\/123$/);
20636 }, 5000, 'page should navigate to /123');
20639 it('should execute ng-click but not reload when href empty string and name specified', function() {
20640 element(by.id('link-4')).click();
20641 expect(element(by.model('value')).getAttribute('value')).toEqual('4');
20642 expect(element(by.id('link-4')).getAttribute('href')).toBe('');
20645 it('should execute ng-click but not reload when no href but name specified', function() {
20646 element(by.id('link-5')).click();
20647 expect(element(by.model('value')).getAttribute('value')).toEqual('5');
20648 expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
20651 it('should only change url when only ng-href', function() {
20652 element(by.model('value')).clear();
20653 element(by.model('value')).sendKeys('6');
20654 expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
20656 element(by.id('link-6')).click();
20658 // At this point, we navigate away from an Angular page, so we need
20659 // to use browser.driver to get the base webdriver.
20660 browser.wait(function() {
20661 return browser.driver.getCurrentUrl().then(function(url) {
20662 return url.match(/\/6$/);
20664 }, 5000, 'page should navigate to /6');
20677 * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
20678 * work right: The browser will fetch from the URL with the literal
20679 * text `{{hash}}` until Angular replaces the expression inside
20680 * `{{hash}}`. The `ngSrc` directive solves this problem.
20682 * The buggy way to write it:
20684 * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
20687 * The correct way to write it:
20689 * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
20693 * @param {template} ngSrc any string which can contain `{{}}` markup.
20703 * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
20704 * work right: The browser will fetch from the URL with the literal
20705 * text `{{hash}}` until Angular replaces the expression inside
20706 * `{{hash}}`. The `ngSrcset` directive solves this problem.
20708 * The buggy way to write it:
20710 * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
20713 * The correct way to write it:
20715 * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
20719 * @param {template} ngSrcset any string which can contain `{{}}` markup.
20730 * This directive sets the `disabled` attribute on the element if the
20731 * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
20733 * A special directive is necessary because we cannot use interpolation inside the `disabled`
20734 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20738 <file name="index.html">
20739 <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
20740 <button ng-model="button" ng-disabled="checked">Button</button>
20742 <file name="protractor.js" type="protractor">
20743 it('should toggle button', function() {
20744 expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
20745 element(by.model('checked')).click();
20746 expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
20752 * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
20753 * then the `disabled` attribute will be set on the element
20764 * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
20766 * Note that this directive should not be used together with {@link ngModel `ngModel`},
20767 * as this can lead to unexpected behavior.
20769 * A special directive is necessary because we cannot use interpolation inside the `checked`
20770 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20774 <file name="index.html">
20775 <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
20776 <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
20778 <file name="protractor.js" type="protractor">
20779 it('should check both checkBoxes', function() {
20780 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
20781 element(by.model('master')).click();
20782 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
20788 * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
20789 * then the `checked` attribute will be set on the element
20801 * Sets the `readOnly` attribute on the element, if the expression inside `ngReadonly` is truthy.
20803 * A special directive is necessary because we cannot use interpolation inside the `readOnly`
20804 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20808 <file name="index.html">
20809 <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
20810 <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
20812 <file name="protractor.js" type="protractor">
20813 it('should toggle readonly attr', function() {
20814 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
20815 element(by.model('checked')).click();
20816 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
20822 * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
20823 * then special attribute "readonly" will be set on the element
20835 * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
20837 * A special directive is necessary because we cannot use interpolation inside the `selected`
20838 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20842 <file name="index.html">
20843 <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
20844 <select aria-label="ngSelected demo">
20845 <option>Hello!</option>
20846 <option id="greet" ng-selected="selected">Greetings!</option>
20849 <file name="protractor.js" type="protractor">
20850 it('should select Greetings!', function() {
20851 expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
20852 element(by.model('selected')).click();
20853 expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
20859 * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
20860 * then special attribute "selected" will be set on the element
20871 * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
20873 * A special directive is necessary because we cannot use interpolation inside the `open`
20874 * attribute. See the {@link guide/interpolation interpolation guide} for more info.
20878 <file name="index.html">
20879 <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
20880 <details id="details" ng-open="open">
20881 <summary>Show/Hide me</summary>
20884 <file name="protractor.js" type="protractor">
20885 it('should toggle open', function() {
20886 expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
20887 element(by.model('open')).click();
20888 expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
20894 * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
20895 * then special attribute "open" will be set on the element
20898 var ngAttributeAliasDirectives = {};
20900 // boolean attrs are evaluated
20901 forEach(BOOLEAN_ATTR, function(propName, attrName) {
20902 // binding to multiple is not supported
20903 if (propName == "multiple") return;
20905 function defaultLinkFn(scope, element, attr) {
20906 scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
20907 attr.$set(attrName, !!value);
20911 var normalized = directiveNormalize('ng-' + attrName);
20912 var linkFn = defaultLinkFn;
20914 if (propName === 'checked') {
20915 linkFn = function(scope, element, attr) {
20916 // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
20917 if (attr.ngModel !== attr[normalized]) {
20918 defaultLinkFn(scope, element, attr);
20923 ngAttributeAliasDirectives[normalized] = function() {
20932 // aliased input attrs are evaluated
20933 forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
20934 ngAttributeAliasDirectives[ngAttr] = function() {
20937 link: function(scope, element, attr) {
20938 //special case ngPattern when a literal regular expression value
20939 //is used as the expression (this way we don't have to watch anything).
20940 if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
20941 var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
20943 attr.$set("ngPattern", new RegExp(match[1], match[2]));
20948 scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
20949 attr.$set(ngAttr, value);
20956 // ng-src, ng-srcset, ng-href are interpolated
20957 forEach(['src', 'srcset', 'href'], function(attrName) {
20958 var normalized = directiveNormalize('ng-' + attrName);
20959 ngAttributeAliasDirectives[normalized] = function() {
20961 priority: 99, // it needs to run after the attributes are interpolated
20962 link: function(scope, element, attr) {
20963 var propName = attrName,
20966 if (attrName === 'href' &&
20967 toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
20968 name = 'xlinkHref';
20969 attr.$attr[name] = 'xlink:href';
20973 attr.$observe(normalized, function(value) {
20975 if (attrName === 'href') {
20976 attr.$set(name, null);
20981 attr.$set(name, value);
20983 // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
20984 // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
20985 // to set the property as well to achieve the desired effect.
20986 // we use attr[attrName] value since $set can sanitize the url.
20987 if (msie && propName) element.prop(propName, attr[name]);
20994 /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
20996 var nullFormCtrl = {
20998 $$renameControl: nullFormRenameControl,
20999 $removeControl: noop,
21000 $setValidity: noop,
21002 $setPristine: noop,
21003 $setSubmitted: noop
21005 SUBMITTED_CLASS = 'ng-submitted';
21007 function nullFormRenameControl(control, name) {
21008 control.$name = name;
21013 * @name form.FormController
21015 * @property {boolean} $pristine True if user has not interacted with the form yet.
21016 * @property {boolean} $dirty True if user has already interacted with the form.
21017 * @property {boolean} $valid True if all of the containing forms and controls are valid.
21018 * @property {boolean} $invalid True if at least one containing control or form is invalid.
21019 * @property {boolean} $pending True if at least one containing control or form is pending.
21020 * @property {boolean} $submitted True if user has submitted the form even if its invalid.
21022 * @property {Object} $error Is an object hash, containing references to controls or
21023 * forms with failing validators, where:
21025 * - keys are validation tokens (error names),
21026 * - values are arrays of controls or forms that have a failing validator for given error name.
21028 * Built-in validation tokens:
21040 * - `datetimelocal`
21046 * `FormController` keeps track of all its controls and nested forms as well as the state of them,
21047 * such as being valid/invalid or dirty/pristine.
21049 * Each {@link ng.directive:form form} directive creates an instance
21050 * of `FormController`.
21053 //asks for $scope to fool the BC controller module
21054 FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
21055 function FormController(element, attrs, $scope, $animate, $interpolate) {
21061 form.$$success = {};
21062 form.$pending = undefined;
21063 form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
21064 form.$dirty = false;
21065 form.$pristine = true;
21066 form.$valid = true;
21067 form.$invalid = false;
21068 form.$submitted = false;
21069 form.$$parentForm = nullFormCtrl;
21073 * @name form.FormController#$rollbackViewValue
21076 * Rollback all form controls pending updates to the `$modelValue`.
21078 * Updates may be pending by a debounced event or because the input is waiting for a some future
21079 * event defined in `ng-model-options`. This method is typically needed by the reset button of
21080 * a form that uses `ng-model-options` to pend updates.
21082 form.$rollbackViewValue = function() {
21083 forEach(controls, function(control) {
21084 control.$rollbackViewValue();
21090 * @name form.FormController#$commitViewValue
21093 * Commit all form controls pending updates to the `$modelValue`.
21095 * Updates may be pending by a debounced event or because the input is waiting for a some future
21096 * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
21097 * usually handles calling this in response to input events.
21099 form.$commitViewValue = function() {
21100 forEach(controls, function(control) {
21101 control.$commitViewValue();
21107 * @name form.FormController#$addControl
21108 * @param {object} control control object, either a {@link form.FormController} or an
21109 * {@link ngModel.NgModelController}
21112 * Register a control with the form. Input elements using ngModelController do this automatically
21113 * when they are linked.
21115 * Note that the current state of the control will not be reflected on the new parent form. This
21116 * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
21119 * However, if the method is used programmatically, for example by adding dynamically created controls,
21120 * or controls that have been previously removed without destroying their corresponding DOM element,
21121 * it's the developers responsibility to make sure the current state propagates to the parent form.
21123 * For example, if an input control is added that is already `$dirty` and has `$error` properties,
21124 * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
21126 form.$addControl = function(control) {
21127 // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
21128 // and not added to the scope. Now we throw an error.
21129 assertNotHasOwnProperty(control.$name, 'input');
21130 controls.push(control);
21132 if (control.$name) {
21133 form[control.$name] = control;
21136 control.$$parentForm = form;
21139 // Private API: rename a form control
21140 form.$$renameControl = function(control, newName) {
21141 var oldName = control.$name;
21143 if (form[oldName] === control) {
21144 delete form[oldName];
21146 form[newName] = control;
21147 control.$name = newName;
21152 * @name form.FormController#$removeControl
21153 * @param {object} control control object, either a {@link form.FormController} or an
21154 * {@link ngModel.NgModelController}
21157 * Deregister a control from the form.
21159 * Input elements using ngModelController do this automatically when they are destroyed.
21161 * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
21162 * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
21163 * different from case to case. For example, removing the only `$dirty` control from a form may or
21164 * may not mean that the form is still `$dirty`.
21166 form.$removeControl = function(control) {
21167 if (control.$name && form[control.$name] === control) {
21168 delete form[control.$name];
21170 forEach(form.$pending, function(value, name) {
21171 form.$setValidity(name, null, control);
21173 forEach(form.$error, function(value, name) {
21174 form.$setValidity(name, null, control);
21176 forEach(form.$$success, function(value, name) {
21177 form.$setValidity(name, null, control);
21180 arrayRemove(controls, control);
21181 control.$$parentForm = nullFormCtrl;
21187 * @name form.FormController#$setValidity
21190 * Sets the validity of a form control.
21192 * This method will also propagate to parent forms.
21194 addSetValidityMethod({
21197 set: function(object, property, controller) {
21198 var list = object[property];
21200 object[property] = [controller];
21202 var index = list.indexOf(controller);
21203 if (index === -1) {
21204 list.push(controller);
21208 unset: function(object, property, controller) {
21209 var list = object[property];
21213 arrayRemove(list, controller);
21214 if (list.length === 0) {
21215 delete object[property];
21223 * @name form.FormController#$setDirty
21226 * Sets the form to a dirty state.
21228 * This method can be called to add the 'ng-dirty' class and set the form to a dirty
21229 * state (ng-dirty class). This method will also propagate to parent forms.
21231 form.$setDirty = function() {
21232 $animate.removeClass(element, PRISTINE_CLASS);
21233 $animate.addClass(element, DIRTY_CLASS);
21234 form.$dirty = true;
21235 form.$pristine = false;
21236 form.$$parentForm.$setDirty();
21241 * @name form.FormController#$setPristine
21244 * Sets the form to its pristine state.
21246 * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
21247 * state (ng-pristine class). This method will also propagate to all the controls contained
21250 * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
21251 * saving or resetting it.
21253 form.$setPristine = function() {
21254 $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
21255 form.$dirty = false;
21256 form.$pristine = true;
21257 form.$submitted = false;
21258 forEach(controls, function(control) {
21259 control.$setPristine();
21265 * @name form.FormController#$setUntouched
21268 * Sets the form to its untouched state.
21270 * This method can be called to remove the 'ng-touched' class and set the form controls to their
21271 * untouched state (ng-untouched class).
21273 * Setting a form controls back to their untouched state is often useful when setting the form
21274 * back to its pristine state.
21276 form.$setUntouched = function() {
21277 forEach(controls, function(control) {
21278 control.$setUntouched();
21284 * @name form.FormController#$setSubmitted
21287 * Sets the form to its submitted state.
21289 form.$setSubmitted = function() {
21290 $animate.addClass(element, SUBMITTED_CLASS);
21291 form.$submitted = true;
21292 form.$$parentForm.$setSubmitted();
21302 * Nestable alias of {@link ng.directive:form `form`} directive. HTML
21303 * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
21304 * sub-group of controls needs to be determined.
21306 * Note: the purpose of `ngForm` is to group controls,
21307 * but not to be a replacement for the `<form>` tag with all of its capabilities
21308 * (e.g. posting to the server, ...).
21310 * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
21311 * related scope, under this name.
21321 * Directive that instantiates
21322 * {@link form.FormController FormController}.
21324 * If the `name` attribute is specified, the form controller is published onto the current scope under
21327 * # Alias: {@link ng.directive:ngForm `ngForm`}
21329 * In Angular, forms can be nested. This means that the outer form is valid when all of the child
21330 * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
21331 * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
21332 * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
21333 * of controls needs to be determined.
21336 * - `ng-valid` is set if the form is valid.
21337 * - `ng-invalid` is set if the form is invalid.
21338 * - `ng-pending` is set if the form is pending.
21339 * - `ng-pristine` is set if the form is pristine.
21340 * - `ng-dirty` is set if the form is dirty.
21341 * - `ng-submitted` is set if the form was submitted.
21343 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
21346 * # Submitting a form and preventing the default action
21348 * Since the role of forms in client-side Angular applications is different than in classical
21349 * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
21350 * page reload that sends the data to the server. Instead some javascript logic should be triggered
21351 * to handle the form submission in an application-specific way.
21353 * For this reason, Angular prevents the default action (form submission to the server) unless the
21354 * `<form>` element has an `action` attribute specified.
21356 * You can use one of the following two ways to specify what javascript method should be called when
21357 * a form is submitted:
21359 * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
21360 * - {@link ng.directive:ngClick ngClick} directive on the first
21361 * button or input field of type submit (input[type=submit])
21363 * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
21364 * or {@link ng.directive:ngClick ngClick} directives.
21365 * This is because of the following form submission rules in the HTML specification:
21367 * - If a form has only one input field then hitting enter in this field triggers form submit
21369 * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
21370 * doesn't trigger submit
21371 * - if a form has one or more input fields and one or more buttons or input[type=submit] then
21372 * hitting enter in any of the input fields will trigger the click handler on the *first* button or
21373 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
21375 * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
21376 * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
21377 * to have access to the updated model.
21379 * ## Animation Hooks
21381 * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
21382 * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
21383 * other validations that are performed within the form. Animations in ngForm are similar to how
21384 * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
21385 * as JS animations.
21387 * The following example shows a simple way to utilize CSS transitions to style a form element
21388 * that has been rendered as invalid after it has been validated:
21391 * //be sure to include ngAnimate as a module to hook into more
21392 * //advanced animations
21394 * transition:0.5s linear all;
21395 * background: white;
21397 * .my-form.ng-invalid {
21404 <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
21405 <file name="index.html">
21407 angular.module('formExample', [])
21408 .controller('FormController', ['$scope', function($scope) {
21409 $scope.userType = 'guest';
21414 transition:all linear 0.5s;
21415 background: transparent;
21417 .my-form.ng-invalid {
21421 <form name="myForm" ng-controller="FormController" class="my-form">
21422 userType: <input name="input" ng-model="userType" required>
21423 <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
21424 <code>userType = {{userType}}</code><br>
21425 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
21426 <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
21427 <code>myForm.$valid = {{myForm.$valid}}</code><br>
21428 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
21431 <file name="protractor.js" type="protractor">
21432 it('should initialize to model', function() {
21433 var userType = element(by.binding('userType'));
21434 var valid = element(by.binding('myForm.input.$valid'));
21436 expect(userType.getText()).toContain('guest');
21437 expect(valid.getText()).toContain('true');
21440 it('should be invalid if empty', function() {
21441 var userType = element(by.binding('userType'));
21442 var valid = element(by.binding('myForm.input.$valid'));
21443 var userInput = element(by.model('userType'));
21446 userInput.sendKeys('');
21448 expect(userType.getText()).toEqual('userType =');
21449 expect(valid.getText()).toContain('false');
21454 * @param {string=} name Name of the form. If specified, the form controller will be published into
21455 * related scope, under this name.
21457 var formDirectiveFactory = function(isNgForm) {
21458 return ['$timeout', '$parse', function($timeout, $parse) {
21459 var formDirective = {
21461 restrict: isNgForm ? 'EAC' : 'E',
21462 require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
21463 controller: FormController,
21464 compile: function ngFormCompile(formElement, attr) {
21465 // Setup initial state of the control
21466 formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
21468 var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
21471 pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
21472 var controller = ctrls[0];
21474 // if `action` attr is not present on the form, prevent the default action (submission)
21475 if (!('action' in attr)) {
21476 // we can't use jq events because if a form is destroyed during submission the default
21477 // action is not prevented. see #1238
21479 // IE 9 is not affected because it doesn't fire a submit event and try to do a full
21480 // page reload if the form was destroyed by submission of the form via a click handler
21481 // on a button in the form. Looks like an IE9 specific bug.
21482 var handleFormSubmission = function(event) {
21483 scope.$apply(function() {
21484 controller.$commitViewValue();
21485 controller.$setSubmitted();
21488 event.preventDefault();
21491 addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
21493 // unregister the preventDefault listener so that we don't not leak memory but in a
21494 // way that will achieve the prevention of the default action.
21495 formElement.on('$destroy', function() {
21496 $timeout(function() {
21497 removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
21502 var parentFormCtrl = ctrls[1] || controller.$$parentForm;
21503 parentFormCtrl.$addControl(controller);
21505 var setter = nameAttr ? getSetter(controller.$name) : noop;
21508 setter(scope, controller);
21509 attr.$observe(nameAttr, function(newValue) {
21510 if (controller.$name === newValue) return;
21511 setter(scope, undefined);
21512 controller.$$parentForm.$$renameControl(controller, newValue);
21513 setter = getSetter(controller.$name);
21514 setter(scope, controller);
21517 formElement.on('$destroy', function() {
21518 controller.$$parentForm.$removeControl(controller);
21519 setter(scope, undefined);
21520 extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
21527 return formDirective;
21529 function getSetter(expression) {
21530 if (expression === '') {
21531 //create an assignable expression, so forms with an empty name can be renamed later
21532 return $parse('this[""]').assign;
21534 return $parse(expression).assign || noop;
21539 var formDirective = formDirectiveFactory();
21540 var ngFormDirective = formDirectiveFactory(true);
21542 /* global VALID_CLASS: false,
21543 INVALID_CLASS: false,
21544 PRISTINE_CLASS: false,
21545 DIRTY_CLASS: false,
21546 UNTOUCHED_CLASS: false,
21547 TOUCHED_CLASS: false,
21548 ngModelMinErr: false,
21551 // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
21552 var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
21553 // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
21554 // Note: We are being more lenient, because browsers are too.
21564 // 1111111111111111 222 333333 44444 555555555555555555555555 666 77777777 8888888 999
21565 var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
21566 var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
21567 var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
21568 var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
21569 var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
21570 var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
21571 var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
21572 var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
21578 * @name input[text]
21581 * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
21584 * @param {string} ngModel Assignable angular expression to data-bind to.
21585 * @param {string=} name Property name of the form under which the control is published.
21586 * @param {string=} required Adds `required` validation error key if the value is not entered.
21587 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21588 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21589 * `required` when you want to data-bind to the `required` attribute.
21590 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
21592 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
21593 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
21595 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
21596 * that contains the regular expression body that will be converted to a regular expression
21597 * as in the ngPattern directive.
21598 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
21599 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
21600 * If the expression evaluates to a RegExp object, then this is used directly.
21601 * If the expression evaluates to a string, then it will be converted to a RegExp
21602 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
21603 * `new RegExp('^abc$')`.<br />
21604 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
21605 * start at the index of the last search's match, thus not taking the whole input value into
21607 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21608 * interaction with the input element.
21609 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
21610 * This parameter is ignored for input[type=password] controls, which will never trim the
21614 <example name="text-input-directive" module="textInputExample">
21615 <file name="index.html">
21617 angular.module('textInputExample', [])
21618 .controller('ExampleController', ['$scope', function($scope) {
21621 word: /^\s*\w*\s*$/
21625 <form name="myForm" ng-controller="ExampleController">
21626 <label>Single word:
21627 <input type="text" name="input" ng-model="example.text"
21628 ng-pattern="example.word" required ng-trim="false">
21631 <span class="error" ng-show="myForm.input.$error.required">
21633 <span class="error" ng-show="myForm.input.$error.pattern">
21634 Single word only!</span>
21636 <tt>text = {{example.text}}</tt><br/>
21637 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21638 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21639 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21640 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21643 <file name="protractor.js" type="protractor">
21644 var text = element(by.binding('example.text'));
21645 var valid = element(by.binding('myForm.input.$valid'));
21646 var input = element(by.model('example.text'));
21648 it('should initialize to model', function() {
21649 expect(text.getText()).toContain('guest');
21650 expect(valid.getText()).toContain('true');
21653 it('should be invalid if empty', function() {
21655 input.sendKeys('');
21657 expect(text.getText()).toEqual('text =');
21658 expect(valid.getText()).toContain('false');
21661 it('should be invalid if multi word', function() {
21663 input.sendKeys('hello world');
21665 expect(valid.getText()).toContain('false');
21670 'text': textInputType,
21674 * @name input[date]
21677 * Input with date validation and transformation. In browsers that do not yet support
21678 * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
21679 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
21680 * modern browsers do not yet support this input type, it is important to provide cues to users on the
21681 * expected input format via a placeholder or label.
21683 * The model must always be a Date object, otherwise Angular will throw an error.
21684 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21686 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21687 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21689 * @param {string} ngModel Assignable angular expression to data-bind to.
21690 * @param {string=} name Property name of the form under which the control is published.
21691 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
21692 * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
21693 * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
21694 * constraint validation.
21695 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
21696 * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
21697 * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
21698 * constraint validation.
21699 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
21700 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21701 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
21702 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21703 * @param {string=} required Sets `required` validation error key if the value is not entered.
21704 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21705 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21706 * `required` when you want to data-bind to the `required` attribute.
21707 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21708 * interaction with the input element.
21711 <example name="date-input-directive" module="dateInputExample">
21712 <file name="index.html">
21714 angular.module('dateInputExample', [])
21715 .controller('DateController', ['$scope', function($scope) {
21717 value: new Date(2013, 9, 22)
21721 <form name="myForm" ng-controller="DateController as dateCtrl">
21722 <label for="exampleInput">Pick a date in 2013:</label>
21723 <input type="date" id="exampleInput" name="input" ng-model="example.value"
21724 placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
21726 <span class="error" ng-show="myForm.input.$error.required">
21728 <span class="error" ng-show="myForm.input.$error.date">
21729 Not a valid date!</span>
21731 <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
21732 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21733 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21734 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21735 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21738 <file name="protractor.js" type="protractor">
21739 var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
21740 var valid = element(by.binding('myForm.input.$valid'));
21741 var input = element(by.model('example.value'));
21743 // currently protractor/webdriver does not support
21744 // sending keys to all known HTML5 input controls
21745 // for various browsers (see https://github.com/angular/protractor/issues/562).
21746 function setInput(val) {
21747 // set the value of the element and force validation.
21748 var scr = "var ipt = document.getElementById('exampleInput'); " +
21749 "ipt.value = '" + val + "';" +
21750 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21751 browser.executeScript(scr);
21754 it('should initialize to model', function() {
21755 expect(value.getText()).toContain('2013-10-22');
21756 expect(valid.getText()).toContain('myForm.input.$valid = true');
21759 it('should be invalid if empty', function() {
21761 expect(value.getText()).toEqual('value =');
21762 expect(valid.getText()).toContain('myForm.input.$valid = false');
21765 it('should be invalid if over max', function() {
21766 setInput('2015-01-01');
21767 expect(value.getText()).toContain('');
21768 expect(valid.getText()).toContain('myForm.input.$valid = false');
21773 'date': createDateInputType('date', DATE_REGEXP,
21774 createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
21779 * @name input[datetime-local]
21782 * Input with datetime validation and transformation. In browsers that do not yet support
21783 * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21784 * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
21786 * The model must always be a Date object, otherwise Angular will throw an error.
21787 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21789 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21790 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21792 * @param {string} ngModel Assignable angular expression to data-bind to.
21793 * @param {string=} name Property name of the form under which the control is published.
21794 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21795 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
21796 * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
21797 * Note that `min` will also add native HTML5 constraint validation.
21798 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21799 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
21800 * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
21801 * Note that `max` will also add native HTML5 constraint validation.
21802 * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
21803 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21804 * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
21805 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21806 * @param {string=} required Sets `required` validation error key if the value is not entered.
21807 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21808 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21809 * `required` when you want to data-bind to the `required` attribute.
21810 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21811 * interaction with the input element.
21814 <example name="datetimelocal-input-directive" module="dateExample">
21815 <file name="index.html">
21817 angular.module('dateExample', [])
21818 .controller('DateController', ['$scope', function($scope) {
21820 value: new Date(2010, 11, 28, 14, 57)
21824 <form name="myForm" ng-controller="DateController as dateCtrl">
21825 <label for="exampleInput">Pick a date between in 2013:</label>
21826 <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
21827 placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
21829 <span class="error" ng-show="myForm.input.$error.required">
21831 <span class="error" ng-show="myForm.input.$error.datetimelocal">
21832 Not a valid date!</span>
21834 <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
21835 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21836 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21837 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21838 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21841 <file name="protractor.js" type="protractor">
21842 var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
21843 var valid = element(by.binding('myForm.input.$valid'));
21844 var input = element(by.model('example.value'));
21846 // currently protractor/webdriver does not support
21847 // sending keys to all known HTML5 input controls
21848 // for various browsers (https://github.com/angular/protractor/issues/562).
21849 function setInput(val) {
21850 // set the value of the element and force validation.
21851 var scr = "var ipt = document.getElementById('exampleInput'); " +
21852 "ipt.value = '" + val + "';" +
21853 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21854 browser.executeScript(scr);
21857 it('should initialize to model', function() {
21858 expect(value.getText()).toContain('2010-12-28T14:57:00');
21859 expect(valid.getText()).toContain('myForm.input.$valid = true');
21862 it('should be invalid if empty', function() {
21864 expect(value.getText()).toEqual('value =');
21865 expect(valid.getText()).toContain('myForm.input.$valid = false');
21868 it('should be invalid if over max', function() {
21869 setInput('2015-01-01T23:59:00');
21870 expect(value.getText()).toContain('');
21871 expect(valid.getText()).toContain('myForm.input.$valid = false');
21876 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
21877 createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
21878 'yyyy-MM-ddTHH:mm:ss.sss'),
21882 * @name input[time]
21885 * Input with time validation and transformation. In browsers that do not yet support
21886 * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21887 * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
21888 * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
21890 * The model must always be a Date object, otherwise Angular will throw an error.
21891 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21893 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21894 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21896 * @param {string} ngModel Assignable angular expression to data-bind to.
21897 * @param {string=} name Property name of the form under which the control is published.
21898 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21899 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
21900 * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
21901 * native HTML5 constraint validation.
21902 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21903 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
21904 * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
21905 * native HTML5 constraint validation.
21906 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
21907 * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21908 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
21909 * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21910 * @param {string=} required Sets `required` validation error key if the value is not entered.
21911 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21912 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21913 * `required` when you want to data-bind to the `required` attribute.
21914 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21915 * interaction with the input element.
21918 <example name="time-input-directive" module="timeExample">
21919 <file name="index.html">
21921 angular.module('timeExample', [])
21922 .controller('DateController', ['$scope', function($scope) {
21924 value: new Date(1970, 0, 1, 14, 57, 0)
21928 <form name="myForm" ng-controller="DateController as dateCtrl">
21929 <label for="exampleInput">Pick a between 8am and 5pm:</label>
21930 <input type="time" id="exampleInput" name="input" ng-model="example.value"
21931 placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
21933 <span class="error" ng-show="myForm.input.$error.required">
21935 <span class="error" ng-show="myForm.input.$error.time">
21936 Not a valid date!</span>
21938 <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
21939 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21940 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21941 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21942 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21945 <file name="protractor.js" type="protractor">
21946 var value = element(by.binding('example.value | date: "HH:mm:ss"'));
21947 var valid = element(by.binding('myForm.input.$valid'));
21948 var input = element(by.model('example.value'));
21950 // currently protractor/webdriver does not support
21951 // sending keys to all known HTML5 input controls
21952 // for various browsers (https://github.com/angular/protractor/issues/562).
21953 function setInput(val) {
21954 // set the value of the element and force validation.
21955 var scr = "var ipt = document.getElementById('exampleInput'); " +
21956 "ipt.value = '" + val + "';" +
21957 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21958 browser.executeScript(scr);
21961 it('should initialize to model', function() {
21962 expect(value.getText()).toContain('14:57:00');
21963 expect(valid.getText()).toContain('myForm.input.$valid = true');
21966 it('should be invalid if empty', function() {
21968 expect(value.getText()).toEqual('value =');
21969 expect(valid.getText()).toContain('myForm.input.$valid = false');
21972 it('should be invalid if over max', function() {
21973 setInput('23:59:00');
21974 expect(value.getText()).toContain('');
21975 expect(valid.getText()).toContain('myForm.input.$valid = false');
21980 'time': createDateInputType('time', TIME_REGEXP,
21981 createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
21986 * @name input[week]
21989 * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
21990 * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21991 * week format (yyyy-W##), for example: `2013-W02`.
21993 * The model must always be a Date object, otherwise Angular will throw an error.
21994 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21996 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21997 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21999 * @param {string} ngModel Assignable angular expression to data-bind to.
22000 * @param {string=} name Property name of the form under which the control is published.
22001 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
22002 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
22003 * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
22004 * native HTML5 constraint validation.
22005 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
22006 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
22007 * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
22008 * native HTML5 constraint validation.
22009 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
22010 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
22011 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
22012 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
22013 * @param {string=} required Sets `required` validation error key if the value is not entered.
22014 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22015 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22016 * `required` when you want to data-bind to the `required` attribute.
22017 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22018 * interaction with the input element.
22021 <example name="week-input-directive" module="weekExample">
22022 <file name="index.html">
22024 angular.module('weekExample', [])
22025 .controller('DateController', ['$scope', function($scope) {
22027 value: new Date(2013, 0, 3)
22031 <form name="myForm" ng-controller="DateController as dateCtrl">
22032 <label>Pick a date between in 2013:
22033 <input id="exampleInput" type="week" name="input" ng-model="example.value"
22034 placeholder="YYYY-W##" min="2012-W32"
22035 max="2013-W52" required />
22038 <span class="error" ng-show="myForm.input.$error.required">
22040 <span class="error" ng-show="myForm.input.$error.week">
22041 Not a valid date!</span>
22043 <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
22044 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22045 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22046 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22047 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22050 <file name="protractor.js" type="protractor">
22051 var value = element(by.binding('example.value | date: "yyyy-Www"'));
22052 var valid = element(by.binding('myForm.input.$valid'));
22053 var input = element(by.model('example.value'));
22055 // currently protractor/webdriver does not support
22056 // sending keys to all known HTML5 input controls
22057 // for various browsers (https://github.com/angular/protractor/issues/562).
22058 function setInput(val) {
22059 // set the value of the element and force validation.
22060 var scr = "var ipt = document.getElementById('exampleInput'); " +
22061 "ipt.value = '" + val + "';" +
22062 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
22063 browser.executeScript(scr);
22066 it('should initialize to model', function() {
22067 expect(value.getText()).toContain('2013-W01');
22068 expect(valid.getText()).toContain('myForm.input.$valid = true');
22071 it('should be invalid if empty', function() {
22073 expect(value.getText()).toEqual('value =');
22074 expect(valid.getText()).toContain('myForm.input.$valid = false');
22077 it('should be invalid if over max', function() {
22078 setInput('2015-W01');
22079 expect(value.getText()).toContain('');
22080 expect(valid.getText()).toContain('myForm.input.$valid = false');
22085 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
22089 * @name input[month]
22092 * Input with month validation and transformation. In browsers that do not yet support
22093 * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
22094 * month format (yyyy-MM), for example: `2009-01`.
22096 * The model must always be a Date object, otherwise Angular will throw an error.
22097 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
22098 * If the model is not set to the first of the month, the next view to model update will set it
22099 * to the first of the month.
22101 * The timezone to be used to read/write the `Date` instance in the model can be defined using
22102 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
22104 * @param {string} ngModel Assignable angular expression to data-bind to.
22105 * @param {string=} name Property name of the form under which the control is published.
22106 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
22107 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
22108 * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
22109 * native HTML5 constraint validation.
22110 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
22111 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
22112 * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
22113 * native HTML5 constraint validation.
22114 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
22115 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
22116 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
22117 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
22119 * @param {string=} required Sets `required` validation error key if the value is not entered.
22120 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22121 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22122 * `required` when you want to data-bind to the `required` attribute.
22123 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22124 * interaction with the input element.
22127 <example name="month-input-directive" module="monthExample">
22128 <file name="index.html">
22130 angular.module('monthExample', [])
22131 .controller('DateController', ['$scope', function($scope) {
22133 value: new Date(2013, 9, 1)
22137 <form name="myForm" ng-controller="DateController as dateCtrl">
22138 <label for="exampleInput">Pick a month in 2013:</label>
22139 <input id="exampleInput" type="month" name="input" ng-model="example.value"
22140 placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
22142 <span class="error" ng-show="myForm.input.$error.required">
22144 <span class="error" ng-show="myForm.input.$error.month">
22145 Not a valid month!</span>
22147 <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
22148 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22149 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22150 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22151 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22154 <file name="protractor.js" type="protractor">
22155 var value = element(by.binding('example.value | date: "yyyy-MM"'));
22156 var valid = element(by.binding('myForm.input.$valid'));
22157 var input = element(by.model('example.value'));
22159 // currently protractor/webdriver does not support
22160 // sending keys to all known HTML5 input controls
22161 // for various browsers (https://github.com/angular/protractor/issues/562).
22162 function setInput(val) {
22163 // set the value of the element and force validation.
22164 var scr = "var ipt = document.getElementById('exampleInput'); " +
22165 "ipt.value = '" + val + "';" +
22166 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
22167 browser.executeScript(scr);
22170 it('should initialize to model', function() {
22171 expect(value.getText()).toContain('2013-10');
22172 expect(valid.getText()).toContain('myForm.input.$valid = true');
22175 it('should be invalid if empty', function() {
22177 expect(value.getText()).toEqual('value =');
22178 expect(valid.getText()).toContain('myForm.input.$valid = false');
22181 it('should be invalid if over max', function() {
22182 setInput('2015-01');
22183 expect(value.getText()).toContain('');
22184 expect(valid.getText()).toContain('myForm.input.$valid = false');
22189 'month': createDateInputType('month', MONTH_REGEXP,
22190 createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
22195 * @name input[number]
22198 * Text input with number validation and transformation. Sets the `number` validation
22199 * error if not a valid number.
22201 * <div class="alert alert-warning">
22202 * The model must always be of type `number` otherwise Angular will throw an error.
22203 * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
22204 * error docs for more information and an example of how to convert your model if necessary.
22207 * ## Issues with HTML5 constraint validation
22209 * In browsers that follow the
22210 * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
22211 * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
22212 * If a non-number is entered in the input, the browser will report the value as an empty string,
22213 * which means the view / model values in `ngModel` and subsequently the scope value
22214 * will also be an empty string.
22217 * @param {string} ngModel Assignable angular expression to data-bind to.
22218 * @param {string=} name Property name of the form under which the control is published.
22219 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
22220 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
22221 * @param {string=} required Sets `required` validation error key if the value is not entered.
22222 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22223 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22224 * `required` when you want to data-bind to the `required` attribute.
22225 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22227 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22228 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
22230 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
22231 * that contains the regular expression body that will be converted to a regular expression
22232 * as in the ngPattern directive.
22233 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
22234 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
22235 * If the expression evaluates to a RegExp object, then this is used directly.
22236 * If the expression evaluates to a string, then it will be converted to a RegExp
22237 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22238 * `new RegExp('^abc$')`.<br />
22239 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22240 * start at the index of the last search's match, thus not taking the whole input value into
22242 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22243 * interaction with the input element.
22246 <example name="number-input-directive" module="numberExample">
22247 <file name="index.html">
22249 angular.module('numberExample', [])
22250 .controller('ExampleController', ['$scope', function($scope) {
22256 <form name="myForm" ng-controller="ExampleController">
22258 <input type="number" name="input" ng-model="example.value"
22259 min="0" max="99" required>
22262 <span class="error" ng-show="myForm.input.$error.required">
22264 <span class="error" ng-show="myForm.input.$error.number">
22265 Not valid number!</span>
22267 <tt>value = {{example.value}}</tt><br/>
22268 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22269 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22270 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22271 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22274 <file name="protractor.js" type="protractor">
22275 var value = element(by.binding('example.value'));
22276 var valid = element(by.binding('myForm.input.$valid'));
22277 var input = element(by.model('example.value'));
22279 it('should initialize to model', function() {
22280 expect(value.getText()).toContain('12');
22281 expect(valid.getText()).toContain('true');
22284 it('should be invalid if empty', function() {
22286 input.sendKeys('');
22287 expect(value.getText()).toEqual('value =');
22288 expect(valid.getText()).toContain('false');
22291 it('should be invalid if over max', function() {
22293 input.sendKeys('123');
22294 expect(value.getText()).toEqual('value =');
22295 expect(valid.getText()).toContain('false');
22300 'number': numberInputType,
22308 * Text input with URL validation. Sets the `url` validation error key if the content is not a
22311 * <div class="alert alert-warning">
22312 * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
22313 * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
22314 * the built-in validators (see the {@link guide/forms Forms guide})
22317 * @param {string} ngModel Assignable angular expression to data-bind to.
22318 * @param {string=} name Property name of the form under which the control is published.
22319 * @param {string=} required Sets `required` validation error key if the value is not entered.
22320 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22321 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22322 * `required` when you want to data-bind to the `required` attribute.
22323 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22325 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22326 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
22328 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
22329 * that contains the regular expression body that will be converted to a regular expression
22330 * as in the ngPattern directive.
22331 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
22332 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
22333 * If the expression evaluates to a RegExp object, then this is used directly.
22334 * If the expression evaluates to a string, then it will be converted to a RegExp
22335 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22336 * `new RegExp('^abc$')`.<br />
22337 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22338 * start at the index of the last search's match, thus not taking the whole input value into
22340 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22341 * interaction with the input element.
22344 <example name="url-input-directive" module="urlExample">
22345 <file name="index.html">
22347 angular.module('urlExample', [])
22348 .controller('ExampleController', ['$scope', function($scope) {
22350 text: 'http://google.com'
22354 <form name="myForm" ng-controller="ExampleController">
22356 <input type="url" name="input" ng-model="url.text" required>
22359 <span class="error" ng-show="myForm.input.$error.required">
22361 <span class="error" ng-show="myForm.input.$error.url">
22362 Not valid url!</span>
22364 <tt>text = {{url.text}}</tt><br/>
22365 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22366 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22367 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22368 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22369 <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
22372 <file name="protractor.js" type="protractor">
22373 var text = element(by.binding('url.text'));
22374 var valid = element(by.binding('myForm.input.$valid'));
22375 var input = element(by.model('url.text'));
22377 it('should initialize to model', function() {
22378 expect(text.getText()).toContain('http://google.com');
22379 expect(valid.getText()).toContain('true');
22382 it('should be invalid if empty', function() {
22384 input.sendKeys('');
22386 expect(text.getText()).toEqual('text =');
22387 expect(valid.getText()).toContain('false');
22390 it('should be invalid if not url', function() {
22392 input.sendKeys('box');
22394 expect(valid.getText()).toContain('false');
22399 'url': urlInputType,
22404 * @name input[email]
22407 * Text input with email validation. Sets the `email` validation error key if not a valid email
22410 * <div class="alert alert-warning">
22411 * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
22412 * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
22413 * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
22416 * @param {string} ngModel Assignable angular expression to data-bind to.
22417 * @param {string=} name Property name of the form under which the control is published.
22418 * @param {string=} required Sets `required` validation error key if the value is not entered.
22419 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22420 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22421 * `required` when you want to data-bind to the `required` attribute.
22422 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22424 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22425 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
22427 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
22428 * that contains the regular expression body that will be converted to a regular expression
22429 * as in the ngPattern directive.
22430 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
22431 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
22432 * If the expression evaluates to a RegExp object, then this is used directly.
22433 * If the expression evaluates to a string, then it will be converted to a RegExp
22434 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22435 * `new RegExp('^abc$')`.<br />
22436 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22437 * start at the index of the last search's match, thus not taking the whole input value into
22439 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22440 * interaction with the input element.
22443 <example name="email-input-directive" module="emailExample">
22444 <file name="index.html">
22446 angular.module('emailExample', [])
22447 .controller('ExampleController', ['$scope', function($scope) {
22449 text: 'me@example.com'
22453 <form name="myForm" ng-controller="ExampleController">
22455 <input type="email" name="input" ng-model="email.text" required>
22458 <span class="error" ng-show="myForm.input.$error.required">
22460 <span class="error" ng-show="myForm.input.$error.email">
22461 Not valid email!</span>
22463 <tt>text = {{email.text}}</tt><br/>
22464 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
22465 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
22466 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22467 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22468 <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
22471 <file name="protractor.js" type="protractor">
22472 var text = element(by.binding('email.text'));
22473 var valid = element(by.binding('myForm.input.$valid'));
22474 var input = element(by.model('email.text'));
22476 it('should initialize to model', function() {
22477 expect(text.getText()).toContain('me@example.com');
22478 expect(valid.getText()).toContain('true');
22481 it('should be invalid if empty', function() {
22483 input.sendKeys('');
22484 expect(text.getText()).toEqual('text =');
22485 expect(valid.getText()).toContain('false');
22488 it('should be invalid if not email', function() {
22490 input.sendKeys('xxx');
22492 expect(valid.getText()).toContain('false');
22497 'email': emailInputType,
22502 * @name input[radio]
22505 * HTML radio button.
22507 * @param {string} ngModel Assignable angular expression to data-bind to.
22508 * @param {string} value The value to which the `ngModel` expression should be set when selected.
22509 * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
22510 * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
22511 * @param {string=} name Property name of the form under which the control is published.
22512 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22513 * interaction with the input element.
22514 * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
22515 * is selected. Should be used instead of the `value` attribute if you need
22516 * a non-string `ngModel` (`boolean`, `array`, ...).
22519 <example name="radio-input-directive" module="radioExample">
22520 <file name="index.html">
22522 angular.module('radioExample', [])
22523 .controller('ExampleController', ['$scope', function($scope) {
22527 $scope.specialValue = {
22533 <form name="myForm" ng-controller="ExampleController">
22535 <input type="radio" ng-model="color.name" value="red">
22539 <input type="radio" ng-model="color.name" ng-value="specialValue">
22543 <input type="radio" ng-model="color.name" value="blue">
22546 <tt>color = {{color.name | json}}</tt><br/>
22548 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
22550 <file name="protractor.js" type="protractor">
22551 it('should change state', function() {
22552 var color = element(by.binding('color.name'));
22554 expect(color.getText()).toContain('blue');
22556 element.all(by.model('color.name')).get(0).click();
22558 expect(color.getText()).toContain('red');
22563 'radio': radioInputType,
22568 * @name input[checkbox]
22573 * @param {string} ngModel Assignable angular expression to data-bind to.
22574 * @param {string=} name Property name of the form under which the control is published.
22575 * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
22576 * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
22577 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22578 * interaction with the input element.
22581 <example name="checkbox-input-directive" module="checkboxExample">
22582 <file name="index.html">
22584 angular.module('checkboxExample', [])
22585 .controller('ExampleController', ['$scope', function($scope) {
22586 $scope.checkboxModel = {
22592 <form name="myForm" ng-controller="ExampleController">
22594 <input type="checkbox" ng-model="checkboxModel.value1">
22597 <input type="checkbox" ng-model="checkboxModel.value2"
22598 ng-true-value="'YES'" ng-false-value="'NO'">
22600 <tt>value1 = {{checkboxModel.value1}}</tt><br/>
22601 <tt>value2 = {{checkboxModel.value2}}</tt><br/>
22604 <file name="protractor.js" type="protractor">
22605 it('should change state', function() {
22606 var value1 = element(by.binding('checkboxModel.value1'));
22607 var value2 = element(by.binding('checkboxModel.value2'));
22609 expect(value1.getText()).toContain('true');
22610 expect(value2.getText()).toContain('YES');
22612 element(by.model('checkboxModel.value1')).click();
22613 element(by.model('checkboxModel.value2')).click();
22615 expect(value1.getText()).toContain('false');
22616 expect(value2.getText()).toContain('NO');
22621 'checkbox': checkboxInputType,
22630 function stringBasedInputType(ctrl) {
22631 ctrl.$formatters.push(function(value) {
22632 return ctrl.$isEmpty(value) ? value : value.toString();
22636 function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22637 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22638 stringBasedInputType(ctrl);
22641 function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22642 var type = lowercase(element[0].type);
22644 // In composition mode, users are still inputing intermediate text buffer,
22645 // hold the listener until composition is done.
22646 // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
22647 if (!$sniffer.android) {
22648 var composing = false;
22650 element.on('compositionstart', function(data) {
22654 element.on('compositionend', function() {
22660 var listener = function(ev) {
22662 $browser.defer.cancel(timeout);
22665 if (composing) return;
22666 var value = element.val(),
22667 event = ev && ev.type;
22669 // By default we will trim the value
22670 // If the attribute ng-trim exists we will avoid trimming
22671 // If input type is 'password', the value is never trimmed
22672 if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
22673 value = trim(value);
22676 // If a control is suffering from bad input (due to native validators), browsers discard its
22677 // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
22678 // control's value is the same empty value twice in a row.
22679 if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
22680 ctrl.$setViewValue(value, event);
22684 // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
22685 // input event on backspace, delete or cut
22686 if ($sniffer.hasEvent('input')) {
22687 element.on('input', listener);
22691 var deferListener = function(ev, input, origValue) {
22693 timeout = $browser.defer(function() {
22695 if (!input || input.value !== origValue) {
22702 element.on('keydown', function(event) {
22703 var key = event.keyCode;
22706 // command modifiers arrows
22707 if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
22709 deferListener(event, this, this.value);
22712 // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
22713 if ($sniffer.hasEvent('paste')) {
22714 element.on('paste cut', deferListener);
22718 // if user paste into input using mouse on older browser
22719 // or form autocomplete on newer browser, we need "change" event to catch it
22720 element.on('change', listener);
22722 ctrl.$render = function() {
22723 // Workaround for Firefox validation #12102.
22724 var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
22725 if (element.val() !== value) {
22726 element.val(value);
22731 function weekParser(isoWeek, existingDate) {
22732 if (isDate(isoWeek)) {
22736 if (isString(isoWeek)) {
22737 WEEK_REGEXP.lastIndex = 0;
22738 var parts = WEEK_REGEXP.exec(isoWeek);
22740 var year = +parts[1],
22746 firstThurs = getFirstThursdayOfYear(year),
22747 addDays = (week - 1) * 7;
22749 if (existingDate) {
22750 hours = existingDate.getHours();
22751 minutes = existingDate.getMinutes();
22752 seconds = existingDate.getSeconds();
22753 milliseconds = existingDate.getMilliseconds();
22756 return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
22763 function createDateParser(regexp, mapping) {
22764 return function(iso, date) {
22771 if (isString(iso)) {
22772 // When a date is JSON'ified to wraps itself inside of an extra
22773 // set of double quotes. This makes the date parsing code unable
22774 // to match the date string and parse it as a date.
22775 if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
22776 iso = iso.substring(1, iso.length - 1);
22778 if (ISO_DATE_REGEXP.test(iso)) {
22779 return new Date(iso);
22781 regexp.lastIndex = 0;
22782 parts = regexp.exec(iso);
22788 yyyy: date.getFullYear(),
22789 MM: date.getMonth() + 1,
22790 dd: date.getDate(),
22791 HH: date.getHours(),
22792 mm: date.getMinutes(),
22793 ss: date.getSeconds(),
22794 sss: date.getMilliseconds() / 1000
22797 map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
22800 forEach(parts, function(part, index) {
22801 if (index < mapping.length) {
22802 map[mapping[index]] = +part;
22805 return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
22813 function createDateInputType(type, regexp, parseDate, format) {
22814 return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
22815 badInputChecker(scope, element, attr, ctrl);
22816 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22817 var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
22820 ctrl.$$parserName = type;
22821 ctrl.$parsers.push(function(value) {
22822 if (ctrl.$isEmpty(value)) return null;
22823 if (regexp.test(value)) {
22824 // Note: We cannot read ctrl.$modelValue, as there might be a different
22825 // parser/formatter in the processing chain so that the model
22826 // contains some different data format!
22827 var parsedDate = parseDate(value, previousDate);
22829 parsedDate = convertTimezoneToLocal(parsedDate, timezone);
22836 ctrl.$formatters.push(function(value) {
22837 if (value && !isDate(value)) {
22838 throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
22840 if (isValidDate(value)) {
22841 previousDate = value;
22842 if (previousDate && timezone) {
22843 previousDate = convertTimezoneToLocal(previousDate, timezone, true);
22845 return $filter('date')(value, format, timezone);
22847 previousDate = null;
22852 if (isDefined(attr.min) || attr.ngMin) {
22854 ctrl.$validators.min = function(value) {
22855 return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
22857 attr.$observe('min', function(val) {
22858 minVal = parseObservedDateValue(val);
22863 if (isDefined(attr.max) || attr.ngMax) {
22865 ctrl.$validators.max = function(value) {
22866 return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
22868 attr.$observe('max', function(val) {
22869 maxVal = parseObservedDateValue(val);
22874 function isValidDate(value) {
22875 // Invalid Date: getTime() returns NaN
22876 return value && !(value.getTime && value.getTime() !== value.getTime());
22879 function parseObservedDateValue(val) {
22880 return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
22885 function badInputChecker(scope, element, attr, ctrl) {
22886 var node = element[0];
22887 var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
22888 if (nativeValidation) {
22889 ctrl.$parsers.push(function(value) {
22890 var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
22891 return validity.badInput || validity.typeMismatch ? undefined : value;
22896 function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22897 badInputChecker(scope, element, attr, ctrl);
22898 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22900 ctrl.$$parserName = 'number';
22901 ctrl.$parsers.push(function(value) {
22902 if (ctrl.$isEmpty(value)) return null;
22903 if (NUMBER_REGEXP.test(value)) return parseFloat(value);
22907 ctrl.$formatters.push(function(value) {
22908 if (!ctrl.$isEmpty(value)) {
22909 if (!isNumber(value)) {
22910 throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
22912 value = value.toString();
22917 if (isDefined(attr.min) || attr.ngMin) {
22919 ctrl.$validators.min = function(value) {
22920 return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
22923 attr.$observe('min', function(val) {
22924 if (isDefined(val) && !isNumber(val)) {
22925 val = parseFloat(val, 10);
22927 minVal = isNumber(val) && !isNaN(val) ? val : undefined;
22928 // TODO(matsko): implement validateLater to reduce number of validations
22933 if (isDefined(attr.max) || attr.ngMax) {
22935 ctrl.$validators.max = function(value) {
22936 return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
22939 attr.$observe('max', function(val) {
22940 if (isDefined(val) && !isNumber(val)) {
22941 val = parseFloat(val, 10);
22943 maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
22944 // TODO(matsko): implement validateLater to reduce number of validations
22950 function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22951 // Note: no badInputChecker here by purpose as `url` is only a validation
22952 // in browsers, i.e. we can always read out input.value even if it is not valid!
22953 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22954 stringBasedInputType(ctrl);
22956 ctrl.$$parserName = 'url';
22957 ctrl.$validators.url = function(modelValue, viewValue) {
22958 var value = modelValue || viewValue;
22959 return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
22963 function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22964 // Note: no badInputChecker here by purpose as `url` is only a validation
22965 // in browsers, i.e. we can always read out input.value even if it is not valid!
22966 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22967 stringBasedInputType(ctrl);
22969 ctrl.$$parserName = 'email';
22970 ctrl.$validators.email = function(modelValue, viewValue) {
22971 var value = modelValue || viewValue;
22972 return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
22976 function radioInputType(scope, element, attr, ctrl) {
22977 // make the name unique, if not defined
22978 if (isUndefined(attr.name)) {
22979 element.attr('name', nextUid());
22982 var listener = function(ev) {
22983 if (element[0].checked) {
22984 ctrl.$setViewValue(attr.value, ev && ev.type);
22988 element.on('click', listener);
22990 ctrl.$render = function() {
22991 var value = attr.value;
22992 element[0].checked = (value == ctrl.$viewValue);
22995 attr.$observe('value', ctrl.$render);
22998 function parseConstantExpr($parse, context, name, expression, fallback) {
23000 if (isDefined(expression)) {
23001 parseFn = $parse(expression);
23002 if (!parseFn.constant) {
23003 throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
23004 '`{1}`.', name, expression);
23006 return parseFn(context);
23011 function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
23012 var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
23013 var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
23015 var listener = function(ev) {
23016 ctrl.$setViewValue(element[0].checked, ev && ev.type);
23019 element.on('click', listener);
23021 ctrl.$render = function() {
23022 element[0].checked = ctrl.$viewValue;
23025 // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
23026 // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
23027 // it to a boolean.
23028 ctrl.$isEmpty = function(value) {
23029 return value === false;
23032 ctrl.$formatters.push(function(value) {
23033 return equals(value, trueValue);
23036 ctrl.$parsers.push(function(value) {
23037 return value ? trueValue : falseValue;
23048 * HTML textarea element control with angular data-binding. The data-binding and validation
23049 * properties of this element are exactly the same as those of the
23050 * {@link ng.directive:input input element}.
23052 * @param {string} ngModel Assignable angular expression to data-bind to.
23053 * @param {string=} name Property name of the form under which the control is published.
23054 * @param {string=} required Sets `required` validation error key if the value is not entered.
23055 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
23056 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
23057 * `required` when you want to data-bind to the `required` attribute.
23058 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
23060 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
23061 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
23063 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
23064 * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
23065 * If the expression evaluates to a RegExp object, then this is used directly.
23066 * If the expression evaluates to a string, then it will be converted to a RegExp
23067 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
23068 * `new RegExp('^abc$')`.<br />
23069 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
23070 * start at the index of the last search's match, thus not taking the whole input value into
23072 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23073 * interaction with the input element.
23074 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
23084 * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
23085 * input state control, and validation.
23086 * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
23088 * <div class="alert alert-warning">
23089 * **Note:** Not every feature offered is available for all input types.
23090 * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
23093 * @param {string} ngModel Assignable angular expression to data-bind to.
23094 * @param {string=} name Property name of the form under which the control is published.
23095 * @param {string=} required Sets `required` validation error key if the value is not entered.
23096 * @param {boolean=} ngRequired Sets `required` attribute if set to true
23097 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
23099 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
23100 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
23102 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
23103 * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
23104 * If the expression evaluates to a RegExp object, then this is used directly.
23105 * If the expression evaluates to a string, then it will be converted to a RegExp
23106 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
23107 * `new RegExp('^abc$')`.<br />
23108 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
23109 * start at the index of the last search's match, thus not taking the whole input value into
23111 * @param {string=} ngChange Angular expression to be executed when input changes due to user
23112 * interaction with the input element.
23113 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
23114 * This parameter is ignored for input[type=password] controls, which will never trim the
23118 <example name="input-directive" module="inputExample">
23119 <file name="index.html">
23121 angular.module('inputExample', [])
23122 .controller('ExampleController', ['$scope', function($scope) {
23123 $scope.user = {name: 'guest', last: 'visitor'};
23126 <div ng-controller="ExampleController">
23127 <form name="myForm">
23130 <input type="text" name="userName" ng-model="user.name" required>
23133 <span class="error" ng-show="myForm.userName.$error.required">
23138 <input type="text" name="lastName" ng-model="user.last"
23139 ng-minlength="3" ng-maxlength="10">
23142 <span class="error" ng-show="myForm.lastName.$error.minlength">
23144 <span class="error" ng-show="myForm.lastName.$error.maxlength">
23149 <tt>user = {{user}}</tt><br/>
23150 <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
23151 <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
23152 <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
23153 <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
23154 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
23155 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
23156 <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
23157 <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
23160 <file name="protractor.js" type="protractor">
23161 var user = element(by.exactBinding('user'));
23162 var userNameValid = element(by.binding('myForm.userName.$valid'));
23163 var lastNameValid = element(by.binding('myForm.lastName.$valid'));
23164 var lastNameError = element(by.binding('myForm.lastName.$error'));
23165 var formValid = element(by.binding('myForm.$valid'));
23166 var userNameInput = element(by.model('user.name'));
23167 var userLastInput = element(by.model('user.last'));
23169 it('should initialize to model', function() {
23170 expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
23171 expect(userNameValid.getText()).toContain('true');
23172 expect(formValid.getText()).toContain('true');
23175 it('should be invalid if empty when required', function() {
23176 userNameInput.clear();
23177 userNameInput.sendKeys('');
23179 expect(user.getText()).toContain('{"last":"visitor"}');
23180 expect(userNameValid.getText()).toContain('false');
23181 expect(formValid.getText()).toContain('false');
23184 it('should be valid if empty when min length is set', function() {
23185 userLastInput.clear();
23186 userLastInput.sendKeys('');
23188 expect(user.getText()).toContain('{"name":"guest","last":""}');
23189 expect(lastNameValid.getText()).toContain('true');
23190 expect(formValid.getText()).toContain('true');
23193 it('should be invalid if less than required min length', function() {
23194 userLastInput.clear();
23195 userLastInput.sendKeys('xx');
23197 expect(user.getText()).toContain('{"name":"guest"}');
23198 expect(lastNameValid.getText()).toContain('false');
23199 expect(lastNameError.getText()).toContain('minlength');
23200 expect(formValid.getText()).toContain('false');
23203 it('should be invalid if longer than max length', function() {
23204 userLastInput.clear();
23205 userLastInput.sendKeys('some ridiculously long name');
23207 expect(user.getText()).toContain('{"name":"guest"}');
23208 expect(lastNameValid.getText()).toContain('false');
23209 expect(lastNameError.getText()).toContain('maxlength');
23210 expect(formValid.getText()).toContain('false');
23215 var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
23216 function($browser, $sniffer, $filter, $parse) {
23219 require: ['?ngModel'],
23221 pre: function(scope, element, attr, ctrls) {
23223 (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
23224 $browser, $filter, $parse);
23233 var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
23239 * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
23240 * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
23243 * `ngValue` is useful when dynamically generating lists of radio buttons using
23244 * {@link ngRepeat `ngRepeat`}, as shown below.
23246 * Likewise, `ngValue` can be used to generate `<option>` elements for
23247 * the {@link select `select`} element. In that case however, only strings are supported
23248 * for the `value `attribute, so the resulting `ngModel` will always be a string.
23249 * Support for `select` models with non-string values is available via `ngOptions`.
23252 * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
23253 * of the `input` element
23256 <example name="ngValue-directive" module="valueExample">
23257 <file name="index.html">
23259 angular.module('valueExample', [])
23260 .controller('ExampleController', ['$scope', function($scope) {
23261 $scope.names = ['pizza', 'unicorns', 'robots'];
23262 $scope.my = { favorite: 'unicorns' };
23265 <form ng-controller="ExampleController">
23266 <h2>Which is your favorite?</h2>
23267 <label ng-repeat="name in names" for="{{name}}">
23269 <input type="radio"
23270 ng-model="my.favorite"
23275 <div>You chose {{my.favorite}}</div>
23278 <file name="protractor.js" type="protractor">
23279 var favorite = element(by.binding('my.favorite'));
23281 it('should initialize to model', function() {
23282 expect(favorite.getText()).toContain('unicorns');
23284 it('should bind the values to the inputs', function() {
23285 element.all(by.model('my.favorite')).get(0).click();
23286 expect(favorite.getText()).toContain('pizza');
23291 var ngValueDirective = function() {
23295 compile: function(tpl, tplAttr) {
23296 if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
23297 return function ngValueConstantLink(scope, elm, attr) {
23298 attr.$set('value', scope.$eval(attr.ngValue));
23301 return function ngValueLink(scope, elm, attr) {
23302 scope.$watch(attr.ngValue, function valueWatchAction(value) {
23303 attr.$set('value', value);
23317 * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
23318 * with the value of a given expression, and to update the text content when the value of that
23319 * expression changes.
23321 * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
23322 * `{{ expression }}` which is similar but less verbose.
23324 * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
23325 * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
23326 * element attribute, it makes the bindings invisible to the user while the page is loading.
23328 * An alternative solution to this problem would be using the
23329 * {@link ng.directive:ngCloak ngCloak} directive.
23333 * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
23336 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
23337 <example module="bindExample">
23338 <file name="index.html">
23340 angular.module('bindExample', [])
23341 .controller('ExampleController', ['$scope', function($scope) {
23342 $scope.name = 'Whirled';
23345 <div ng-controller="ExampleController">
23346 <label>Enter name: <input type="text" ng-model="name"></label><br>
23347 Hello <span ng-bind="name"></span>!
23350 <file name="protractor.js" type="protractor">
23351 it('should check ng-bind', function() {
23352 var nameInput = element(by.model('name'));
23354 expect(element(by.binding('name')).getText()).toBe('Whirled');
23356 nameInput.sendKeys('world');
23357 expect(element(by.binding('name')).getText()).toBe('world');
23362 var ngBindDirective = ['$compile', function($compile) {
23365 compile: function ngBindCompile(templateElement) {
23366 $compile.$$addBindingClass(templateElement);
23367 return function ngBindLink(scope, element, attr) {
23368 $compile.$$addBindingInfo(element, attr.ngBind);
23369 element = element[0];
23370 scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
23371 element.textContent = isUndefined(value) ? '' : value;
23381 * @name ngBindTemplate
23384 * The `ngBindTemplate` directive specifies that the element
23385 * text content should be replaced with the interpolation of the template
23386 * in the `ngBindTemplate` attribute.
23387 * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
23388 * expressions. This directive is needed since some HTML elements
23389 * (such as TITLE and OPTION) cannot contain SPAN elements.
23392 * @param {string} ngBindTemplate template of form
23393 * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
23396 * Try it here: enter text in text box and watch the greeting change.
23397 <example module="bindExample">
23398 <file name="index.html">
23400 angular.module('bindExample', [])
23401 .controller('ExampleController', ['$scope', function($scope) {
23402 $scope.salutation = 'Hello';
23403 $scope.name = 'World';
23406 <div ng-controller="ExampleController">
23407 <label>Salutation: <input type="text" ng-model="salutation"></label><br>
23408 <label>Name: <input type="text" ng-model="name"></label><br>
23409 <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
23412 <file name="protractor.js" type="protractor">
23413 it('should check ng-bind', function() {
23414 var salutationElem = element(by.binding('salutation'));
23415 var salutationInput = element(by.model('salutation'));
23416 var nameInput = element(by.model('name'));
23418 expect(salutationElem.getText()).toBe('Hello World!');
23420 salutationInput.clear();
23421 salutationInput.sendKeys('Greetings');
23423 nameInput.sendKeys('user');
23425 expect(salutationElem.getText()).toBe('Greetings user!');
23430 var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
23432 compile: function ngBindTemplateCompile(templateElement) {
23433 $compile.$$addBindingClass(templateElement);
23434 return function ngBindTemplateLink(scope, element, attr) {
23435 var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
23436 $compile.$$addBindingInfo(element, interpolateFn.expressions);
23437 element = element[0];
23438 attr.$observe('ngBindTemplate', function(value) {
23439 element.textContent = isUndefined(value) ? '' : value;
23452 * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
23453 * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
23454 * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
23455 * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
23456 * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
23458 * You may also bypass sanitization for values you know are safe. To do so, bind to
23459 * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
23460 * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
23462 * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
23463 * will have an exception (instead of an exploit.)
23466 * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
23470 <example module="bindHtmlExample" deps="angular-sanitize.js">
23471 <file name="index.html">
23472 <div ng-controller="ExampleController">
23473 <p ng-bind-html="myHTML"></p>
23477 <file name="script.js">
23478 angular.module('bindHtmlExample', ['ngSanitize'])
23479 .controller('ExampleController', ['$scope', function($scope) {
23481 'I am an <code>HTML</code>string with ' +
23482 '<a href="#">links!</a> and other <em>stuff</em>';
23486 <file name="protractor.js" type="protractor">
23487 it('should check ng-bind-html', function() {
23488 expect(element(by.binding('myHTML')).getText()).toBe(
23489 'I am an HTMLstring with links! and other stuff');
23494 var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
23497 compile: function ngBindHtmlCompile(tElement, tAttrs) {
23498 var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
23499 var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
23500 return (value || '').toString();
23502 $compile.$$addBindingClass(tElement);
23504 return function ngBindHtmlLink(scope, element, attr) {
23505 $compile.$$addBindingInfo(element, attr.ngBindHtml);
23507 scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
23508 // we re-evaluate the expr because we want a TrustedValueHolderType
23509 // for $sce, not a string
23510 element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
23522 * Evaluate the given expression when the user changes the input.
23523 * The expression is evaluated immediately, unlike the JavaScript onchange event
23524 * which only triggers at the end of a change (usually, when the user leaves the
23525 * form element or presses the return key).
23527 * The `ngChange` expression is only evaluated when a change in the input value causes
23528 * a new value to be committed to the model.
23530 * It will not be evaluated:
23531 * * if the value returned from the `$parsers` transformation pipeline has not changed
23532 * * if the input has continued to be invalid since the model will stay `null`
23533 * * if the model is changed programmatically and not by a change to the input value
23536 * Note, this directive requires `ngModel` to be present.
23539 * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
23543 * <example name="ngChange-directive" module="changeExample">
23544 * <file name="index.html">
23546 * angular.module('changeExample', [])
23547 * .controller('ExampleController', ['$scope', function($scope) {
23548 * $scope.counter = 0;
23549 * $scope.change = function() {
23550 * $scope.counter++;
23554 * <div ng-controller="ExampleController">
23555 * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
23556 * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
23557 * <label for="ng-change-example2">Confirmed</label><br />
23558 * <tt>debug = {{confirmed}}</tt><br/>
23559 * <tt>counter = {{counter}}</tt><br/>
23562 * <file name="protractor.js" type="protractor">
23563 * var counter = element(by.binding('counter'));
23564 * var debug = element(by.binding('confirmed'));
23566 * it('should evaluate the expression if changing from view', function() {
23567 * expect(counter.getText()).toContain('0');
23569 * element(by.id('ng-change-example1')).click();
23571 * expect(counter.getText()).toContain('1');
23572 * expect(debug.getText()).toContain('true');
23575 * it('should not evaluate the expression if changing from model', function() {
23576 * element(by.id('ng-change-example2')).click();
23578 * expect(counter.getText()).toContain('0');
23579 * expect(debug.getText()).toContain('true');
23584 var ngChangeDirective = valueFn({
23586 require: 'ngModel',
23587 link: function(scope, element, attr, ctrl) {
23588 ctrl.$viewChangeListeners.push(function() {
23589 scope.$eval(attr.ngChange);
23594 function classDirective(name, selector) {
23595 name = 'ngClass' + name;
23596 return ['$animate', function($animate) {
23599 link: function(scope, element, attr) {
23602 scope.$watch(attr[name], ngClassWatchAction, true);
23604 attr.$observe('class', function(value) {
23605 ngClassWatchAction(scope.$eval(attr[name]));
23609 if (name !== 'ngClass') {
23610 scope.$watch('$index', function($index, old$index) {
23611 // jshint bitwise: false
23612 var mod = $index & 1;
23613 if (mod !== (old$index & 1)) {
23614 var classes = arrayClasses(scope.$eval(attr[name]));
23616 addClasses(classes) :
23617 removeClasses(classes);
23622 function addClasses(classes) {
23623 var newClasses = digestClassCounts(classes, 1);
23624 attr.$addClass(newClasses);
23627 function removeClasses(classes) {
23628 var newClasses = digestClassCounts(classes, -1);
23629 attr.$removeClass(newClasses);
23632 function digestClassCounts(classes, count) {
23633 // Use createMap() to prevent class assumptions involving property
23634 // names in Object.prototype
23635 var classCounts = element.data('$classCounts') || createMap();
23636 var classesToUpdate = [];
23637 forEach(classes, function(className) {
23638 if (count > 0 || classCounts[className]) {
23639 classCounts[className] = (classCounts[className] || 0) + count;
23640 if (classCounts[className] === +(count > 0)) {
23641 classesToUpdate.push(className);
23645 element.data('$classCounts', classCounts);
23646 return classesToUpdate.join(' ');
23649 function updateClasses(oldClasses, newClasses) {
23650 var toAdd = arrayDifference(newClasses, oldClasses);
23651 var toRemove = arrayDifference(oldClasses, newClasses);
23652 toAdd = digestClassCounts(toAdd, 1);
23653 toRemove = digestClassCounts(toRemove, -1);
23654 if (toAdd && toAdd.length) {
23655 $animate.addClass(element, toAdd);
23657 if (toRemove && toRemove.length) {
23658 $animate.removeClass(element, toRemove);
23662 function ngClassWatchAction(newVal) {
23663 if (selector === true || scope.$index % 2 === selector) {
23664 var newClasses = arrayClasses(newVal || []);
23666 addClasses(newClasses);
23667 } else if (!equals(newVal,oldVal)) {
23668 var oldClasses = arrayClasses(oldVal);
23669 updateClasses(oldClasses, newClasses);
23672 oldVal = shallowCopy(newVal);
23677 function arrayDifference(tokens1, tokens2) {
23681 for (var i = 0; i < tokens1.length; i++) {
23682 var token = tokens1[i];
23683 for (var j = 0; j < tokens2.length; j++) {
23684 if (token == tokens2[j]) continue outer;
23686 values.push(token);
23691 function arrayClasses(classVal) {
23693 if (isArray(classVal)) {
23694 forEach(classVal, function(v) {
23695 classes = classes.concat(arrayClasses(v));
23698 } else if (isString(classVal)) {
23699 return classVal.split(' ');
23700 } else if (isObject(classVal)) {
23701 forEach(classVal, function(v, k) {
23703 classes = classes.concat(k.split(' '));
23719 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
23720 * an expression that represents all classes to be added.
23722 * The directive operates in three different ways, depending on which of three types the expression
23725 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
23728 * 2. If the expression evaluates to an object, then for each key-value pair of the
23729 * object with a truthy value the corresponding key is used as a class name.
23731 * 3. If the expression evaluates to an array, each element of the array should either be a string as in
23732 * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
23733 * to give you more control over what CSS classes appear. See the code below for an example of this.
23736 * The directive won't add duplicate classes if a particular class was already set.
23738 * When the expression changes, the previously added classes are removed and only then are the
23739 * new classes added.
23742 * **add** - happens just before the class is applied to the elements
23744 * **remove** - happens just before the class is removed from the element
23747 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
23748 * of the evaluation can be a string representing space delimited class
23749 * names, an array, or a map of class names to boolean values. In the case of a map, the
23750 * names of the properties whose values are truthy will be added as css classes to the
23753 * @example Example that demonstrates basic bindings via ngClass directive.
23755 <file name="index.html">
23756 <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
23758 <input type="checkbox" ng-model="deleted">
23759 deleted (apply "strike" class)
23762 <input type="checkbox" ng-model="important">
23763 important (apply "bold" class)
23766 <input type="checkbox" ng-model="error">
23767 error (apply "has-error" class)
23770 <p ng-class="style">Using String Syntax</p>
23771 <input type="text" ng-model="style"
23772 placeholder="Type: bold strike red" aria-label="Type: bold strike red">
23774 <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
23775 <input ng-model="style1"
23776 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
23777 <input ng-model="style2"
23778 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
23779 <input ng-model="style3"
23780 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
23782 <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
23783 <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
23784 <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
23786 <file name="style.css">
23788 text-decoration: line-through;
23798 background-color: yellow;
23804 <file name="protractor.js" type="protractor">
23805 var ps = element.all(by.css('p'));
23807 it('should let you toggle the class', function() {
23809 expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
23810 expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
23812 element(by.model('important')).click();
23813 expect(ps.first().getAttribute('class')).toMatch(/bold/);
23815 element(by.model('error')).click();
23816 expect(ps.first().getAttribute('class')).toMatch(/has-error/);
23819 it('should let you toggle string example', function() {
23820 expect(ps.get(1).getAttribute('class')).toBe('');
23821 element(by.model('style')).clear();
23822 element(by.model('style')).sendKeys('red');
23823 expect(ps.get(1).getAttribute('class')).toBe('red');
23826 it('array example should have 3 classes', function() {
23827 expect(ps.get(2).getAttribute('class')).toBe('');
23828 element(by.model('style1')).sendKeys('bold');
23829 element(by.model('style2')).sendKeys('strike');
23830 element(by.model('style3')).sendKeys('red');
23831 expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
23834 it('array with map example should have 2 classes', function() {
23835 expect(ps.last().getAttribute('class')).toBe('');
23836 element(by.model('style4')).sendKeys('bold');
23837 element(by.model('warning')).click();
23838 expect(ps.last().getAttribute('class')).toBe('bold orange');
23845 The example below demonstrates how to perform animations using ngClass.
23847 <example module="ngAnimate" deps="angular-animate.js" animations="true">
23848 <file name="index.html">
23849 <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
23850 <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
23852 <span class="base-class" ng-class="myVar">Sample Text</span>
23854 <file name="style.css">
23856 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
23859 .base-class.my-class {
23864 <file name="protractor.js" type="protractor">
23865 it('should check ng-class', function() {
23866 expect(element(by.css('.base-class')).getAttribute('class')).not.
23867 toMatch(/my-class/);
23869 element(by.id('setbtn')).click();
23871 expect(element(by.css('.base-class')).getAttribute('class')).
23872 toMatch(/my-class/);
23874 element(by.id('clearbtn')).click();
23876 expect(element(by.css('.base-class')).getAttribute('class')).not.
23877 toMatch(/my-class/);
23883 ## ngClass and pre-existing CSS3 Transitions/Animations
23884 The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
23885 Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
23886 any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
23887 to view the step by step details of {@link $animate#addClass $animate.addClass} and
23888 {@link $animate#removeClass $animate.removeClass}.
23890 var ngClassDirective = classDirective('', true);
23898 * The `ngClassOdd` and `ngClassEven` directives work exactly as
23899 * {@link ng.directive:ngClass ngClass}, except they work in
23900 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
23902 * This directive can be applied only within the scope of an
23903 * {@link ng.directive:ngRepeat ngRepeat}.
23906 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
23907 * of the evaluation can be a string representing space delimited class names or an array.
23911 <file name="index.html">
23912 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23913 <li ng-repeat="name in names">
23914 <span ng-class-odd="'odd'" ng-class-even="'even'">
23920 <file name="style.css">
23928 <file name="protractor.js" type="protractor">
23929 it('should check ng-class-odd and ng-class-even', function() {
23930 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
23932 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
23938 var ngClassOddDirective = classDirective('Odd', 0);
23942 * @name ngClassEven
23946 * The `ngClassOdd` and `ngClassEven` directives work exactly as
23947 * {@link ng.directive:ngClass ngClass}, except they work in
23948 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
23950 * This directive can be applied only within the scope of an
23951 * {@link ng.directive:ngRepeat ngRepeat}.
23954 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
23955 * result of the evaluation can be a string representing space delimited class names or an array.
23959 <file name="index.html">
23960 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23961 <li ng-repeat="name in names">
23962 <span ng-class-odd="'odd'" ng-class-even="'even'">
23963 {{name}}
23968 <file name="style.css">
23976 <file name="protractor.js" type="protractor">
23977 it('should check ng-class-odd and ng-class-even', function() {
23978 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
23980 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
23986 var ngClassEvenDirective = classDirective('Even', 1);
23994 * The `ngCloak` directive is used to prevent the Angular html template from being briefly
23995 * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
23996 * directive to avoid the undesirable flicker effect caused by the html template display.
23998 * The directive can be applied to the `<body>` element, but the preferred usage is to apply
23999 * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
24000 * of the browser view.
24002 * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
24003 * `angular.min.js`.
24004 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
24007 * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
24008 * display: none !important;
24012 * When this css rule is loaded by the browser, all html elements (including their children) that
24013 * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
24014 * during the compilation of the template it deletes the `ngCloak` element attribute, making
24015 * the compiled element visible.
24017 * For the best result, the `angular.js` script must be loaded in the head section of the html
24018 * document; alternatively, the css rule above must be included in the external stylesheet of the
24025 <file name="index.html">
24026 <div id="template1" ng-cloak>{{ 'hello' }}</div>
24027 <div id="template2" class="ng-cloak">{{ 'world' }}</div>
24029 <file name="protractor.js" type="protractor">
24030 it('should remove the template directive and css class', function() {
24031 expect($('#template1').getAttribute('ng-cloak')).
24033 expect($('#template2').getAttribute('ng-cloak')).
24040 var ngCloakDirective = ngDirective({
24041 compile: function(element, attr) {
24042 attr.$set('ngCloak', undefined);
24043 element.removeClass('ng-cloak');
24049 * @name ngController
24052 * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
24053 * supports the principles behind the Model-View-Controller design pattern.
24055 * MVC components in angular:
24057 * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
24058 * are accessed through bindings.
24059 * * View — The template (HTML with data bindings) that is rendered into the View.
24060 * * Controller — The `ngController` directive specifies a Controller class; the class contains business
24061 * logic behind the application to decorate the scope with functions and values
24063 * Note that you can also attach controllers to the DOM by declaring it in a route definition
24064 * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
24065 * again using `ng-controller` in the template itself. This will cause the controller to be attached
24066 * and executed twice.
24071 * @param {expression} ngController Name of a constructor function registered with the current
24072 * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
24073 * that on the current scope evaluates to a constructor function.
24075 * The controller instance can be published into a scope property by specifying
24076 * `ng-controller="as propertyName"`.
24078 * If the current `$controllerProvider` is configured to use globals (via
24079 * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
24080 * also be the name of a globally accessible constructor function (not recommended).
24083 * Here is a simple form for editing user contact information. Adding, removing, clearing, and
24084 * greeting are methods declared on the controller (see source tab). These methods can
24085 * easily be called from the angular markup. Any changes to the data are automatically reflected
24086 * in the View without the need for a manual update.
24088 * Two different declaration styles are included below:
24090 * * one binds methods and properties directly onto the controller using `this`:
24091 * `ng-controller="SettingsController1 as settings"`
24092 * * one injects `$scope` into the controller:
24093 * `ng-controller="SettingsController2"`
24095 * The second option is more common in the Angular community, and is generally used in boilerplates
24096 * and in this guide. However, there are advantages to binding properties directly to the controller
24097 * and avoiding scope.
24099 * * Using `controller as` makes it obvious which controller you are accessing in the template when
24100 * multiple controllers apply to an element.
24101 * * If you are writing your controllers as classes you have easier access to the properties and
24102 * methods, which will appear on the scope, from inside the controller code.
24103 * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
24104 * inheritance masking primitives.
24106 * This example demonstrates the `controller as` syntax.
24108 * <example name="ngControllerAs" module="controllerAsExample">
24109 * <file name="index.html">
24110 * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
24111 * <label>Name: <input type="text" ng-model="settings.name"/></label>
24112 * <button ng-click="settings.greet()">greet</button><br/>
24115 * <li ng-repeat="contact in settings.contacts">
24116 * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
24117 * <option>phone</option>
24118 * <option>email</option>
24120 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
24121 * <button ng-click="settings.clearContact(contact)">clear</button>
24122 * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
24124 * <li><button ng-click="settings.addContact()">add</button></li>
24128 * <file name="app.js">
24129 * angular.module('controllerAsExample', [])
24130 * .controller('SettingsController1', SettingsController1);
24132 * function SettingsController1() {
24133 * this.name = "John Smith";
24134 * this.contacts = [
24135 * {type: 'phone', value: '408 555 1212'},
24136 * {type: 'email', value: 'john.smith@example.org'} ];
24139 * SettingsController1.prototype.greet = function() {
24140 * alert(this.name);
24143 * SettingsController1.prototype.addContact = function() {
24144 * this.contacts.push({type: 'email', value: 'yourname@example.org'});
24147 * SettingsController1.prototype.removeContact = function(contactToRemove) {
24148 * var index = this.contacts.indexOf(contactToRemove);
24149 * this.contacts.splice(index, 1);
24152 * SettingsController1.prototype.clearContact = function(contact) {
24153 * contact.type = 'phone';
24154 * contact.value = '';
24157 * <file name="protractor.js" type="protractor">
24158 * it('should check controller as', function() {
24159 * var container = element(by.id('ctrl-as-exmpl'));
24160 * expect(container.element(by.model('settings.name'))
24161 * .getAttribute('value')).toBe('John Smith');
24163 * var firstRepeat =
24164 * container.element(by.repeater('contact in settings.contacts').row(0));
24165 * var secondRepeat =
24166 * container.element(by.repeater('contact in settings.contacts').row(1));
24168 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
24169 * .toBe('408 555 1212');
24171 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
24172 * .toBe('john.smith@example.org');
24174 * firstRepeat.element(by.buttonText('clear')).click();
24176 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
24179 * container.element(by.buttonText('add')).click();
24181 * expect(container.element(by.repeater('contact in settings.contacts').row(2))
24182 * .element(by.model('contact.value'))
24183 * .getAttribute('value'))
24184 * .toBe('yourname@example.org');
24189 * This example demonstrates the "attach to `$scope`" style of controller.
24191 * <example name="ngController" module="controllerExample">
24192 * <file name="index.html">
24193 * <div id="ctrl-exmpl" ng-controller="SettingsController2">
24194 * <label>Name: <input type="text" ng-model="name"/></label>
24195 * <button ng-click="greet()">greet</button><br/>
24198 * <li ng-repeat="contact in contacts">
24199 * <select ng-model="contact.type" id="select_{{$index}}">
24200 * <option>phone</option>
24201 * <option>email</option>
24203 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
24204 * <button ng-click="clearContact(contact)">clear</button>
24205 * <button ng-click="removeContact(contact)">X</button>
24207 * <li>[ <button ng-click="addContact()">add</button> ]</li>
24211 * <file name="app.js">
24212 * angular.module('controllerExample', [])
24213 * .controller('SettingsController2', ['$scope', SettingsController2]);
24215 * function SettingsController2($scope) {
24216 * $scope.name = "John Smith";
24217 * $scope.contacts = [
24218 * {type:'phone', value:'408 555 1212'},
24219 * {type:'email', value:'john.smith@example.org'} ];
24221 * $scope.greet = function() {
24222 * alert($scope.name);
24225 * $scope.addContact = function() {
24226 * $scope.contacts.push({type:'email', value:'yourname@example.org'});
24229 * $scope.removeContact = function(contactToRemove) {
24230 * var index = $scope.contacts.indexOf(contactToRemove);
24231 * $scope.contacts.splice(index, 1);
24234 * $scope.clearContact = function(contact) {
24235 * contact.type = 'phone';
24236 * contact.value = '';
24240 * <file name="protractor.js" type="protractor">
24241 * it('should check controller', function() {
24242 * var container = element(by.id('ctrl-exmpl'));
24244 * expect(container.element(by.model('name'))
24245 * .getAttribute('value')).toBe('John Smith');
24247 * var firstRepeat =
24248 * container.element(by.repeater('contact in contacts').row(0));
24249 * var secondRepeat =
24250 * container.element(by.repeater('contact in contacts').row(1));
24252 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
24253 * .toBe('408 555 1212');
24254 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
24255 * .toBe('john.smith@example.org');
24257 * firstRepeat.element(by.buttonText('clear')).click();
24259 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
24262 * container.element(by.buttonText('add')).click();
24264 * expect(container.element(by.repeater('contact in contacts').row(2))
24265 * .element(by.model('contact.value'))
24266 * .getAttribute('value'))
24267 * .toBe('yourname@example.org');
24273 var ngControllerDirective = [function() {
24289 * Angular has some features that can break certain
24290 * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
24292 * If you intend to implement these rules then you must tell Angular not to use these features.
24294 * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
24297 * The following rules affect Angular:
24299 * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
24300 * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
24301 * increase in the speed of evaluating Angular expressions.
24303 * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
24304 * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
24305 * To make these directives work when a CSP rule is blocking inline styles, you must link to the
24306 * `angular-csp.css` in your HTML manually.
24308 * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
24309 * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
24310 * however, triggers a CSP error to be logged in the console:
24313 * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
24314 * script in the following Content Security Policy directive: "default-src 'self'". Note that
24315 * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
24318 * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
24319 * directive on an element of the HTML document that appears before the `<script>` tag that loads
24320 * the `angular.js` file.
24322 * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
24324 * You can specify which of the CSP related Angular features should be deactivated by providing
24325 * a value for the `ng-csp` attribute. The options are as follows:
24327 * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
24329 * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
24331 * You can use these values in the following combinations:
24334 * * No declaration means that Angular will assume that you can do inline styles, but it will do
24335 * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
24338 * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
24339 * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
24342 * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
24343 * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
24345 * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
24346 * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
24348 * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
24349 * styles nor use eval, which is the same as an empty: ng-csp.
24350 * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
24353 * This example shows how to apply the `ngCsp` directive to the `html` tag.
24356 <html ng-app ng-csp>
24362 // Note: the suffix `.csp` in the example name triggers
24363 // csp mode in our http server!
24364 <example name="example.csp" module="cspExample" ng-csp="true">
24365 <file name="index.html">
24366 <div ng-controller="MainController as ctrl">
24368 <button ng-click="ctrl.inc()" id="inc">Increment</button>
24369 <span id="counter">
24375 <button ng-click="ctrl.evil()" id="evil">Evil</button>
24376 <span id="evilError">
24382 <file name="script.js">
24383 angular.module('cspExample', [])
24384 .controller('MainController', function() {
24386 this.inc = function() {
24389 this.evil = function() {
24390 // jshint evil:true
24394 this.evilError = e.message;
24399 <file name="protractor.js" type="protractor">
24400 var util, webdriver;
24402 var incBtn = element(by.id('inc'));
24403 var counter = element(by.id('counter'));
24404 var evilBtn = element(by.id('evil'));
24405 var evilError = element(by.id('evilError'));
24407 function getAndClearSevereErrors() {
24408 return browser.manage().logs().get('browser').then(function(browserLog) {
24409 return browserLog.filter(function(logEntry) {
24410 return logEntry.level.value > webdriver.logging.Level.WARNING.value;
24415 function clearErrors() {
24416 getAndClearSevereErrors();
24419 function expectNoErrors() {
24420 getAndClearSevereErrors().then(function(filteredLog) {
24421 expect(filteredLog.length).toEqual(0);
24422 if (filteredLog.length) {
24423 console.log('browser console errors: ' + util.inspect(filteredLog));
24428 function expectError(regex) {
24429 getAndClearSevereErrors().then(function(filteredLog) {
24431 filteredLog.forEach(function(log) {
24432 if (log.message.match(regex)) {
24437 throw new Error('expected an error that matches ' + regex);
24442 beforeEach(function() {
24443 util = require('util');
24444 webdriver = require('protractor/node_modules/selenium-webdriver');
24447 // For now, we only test on Chrome,
24448 // as Safari does not load the page with Protractor's injected scripts,
24449 // and Firefox webdriver always disables content security policy (#6358)
24450 if (browser.params.browser !== 'chrome') {
24454 it('should not report errors when the page is loaded', function() {
24455 // clear errors so we are not dependent on previous tests
24457 // Need to reload the page as the page is already loaded when
24459 browser.driver.getCurrentUrl().then(function(url) {
24465 it('should evaluate expressions', function() {
24466 expect(counter.getText()).toEqual('0');
24468 expect(counter.getText()).toEqual('1');
24472 it('should throw and report an error when using "eval"', function() {
24474 expect(evilError.getText()).toMatch(/Content Security Policy/);
24475 expectError(/Content Security Policy/);
24481 // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
24482 // bootstrap the system (before $parse is instantiated), for this reason we just have
24483 // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
24490 * The ngClick directive allows you to specify custom behavior when
24491 * an element is clicked.
24495 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
24496 * click. ({@link guide/expression#-event- Event object is available as `$event`})
24500 <file name="index.html">
24501 <button ng-click="count = count + 1" ng-init="count=0">
24508 <file name="protractor.js" type="protractor">
24509 it('should check ng-click', function() {
24510 expect(element(by.binding('count')).getText()).toMatch('0');
24511 element(by.css('button')).click();
24512 expect(element(by.binding('count')).getText()).toMatch('1');
24518 * A collection of directives that allows creation of custom event handlers that are defined as
24519 * angular expressions and are compiled and executed within the current scope.
24521 var ngEventDirectives = {};
24523 // For events that might fire synchronously during DOM manipulation
24524 // we need to execute their event handlers asynchronously using $evalAsync,
24525 // so that they are not executed in an inconsistent state.
24526 var forceAsyncEvents = {
24531 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
24532 function(eventName) {
24533 var directiveName = directiveNormalize('ng-' + eventName);
24534 ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
24537 compile: function($element, attr) {
24538 // We expose the powerful $event object on the scope that provides access to the Window,
24539 // etc. that isn't protected by the fast paths in $parse. We explicitly request better
24540 // checks at the cost of speed since event handler expressions are not executed as
24541 // frequently as regular change detection.
24542 var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
24543 return function ngEventHandler(scope, element) {
24544 element.on(eventName, function(event) {
24545 var callback = function() {
24546 fn(scope, {$event:event});
24548 if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
24549 scope.$evalAsync(callback);
24551 scope.$apply(callback);
24566 * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
24570 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
24571 * a dblclick. (The Event object is available as `$event`)
24575 <file name="index.html">
24576 <button ng-dblclick="count = count + 1" ng-init="count=0">
24577 Increment (on double click)
24587 * @name ngMousedown
24590 * The ngMousedown directive allows you to specify custom behavior on mousedown event.
24594 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
24595 * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
24599 <file name="index.html">
24600 <button ng-mousedown="count = count + 1" ng-init="count=0">
24601 Increment (on mouse down)
24614 * Specify custom behavior on mouseup event.
24618 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
24619 * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
24623 <file name="index.html">
24624 <button ng-mouseup="count = count + 1" ng-init="count=0">
24625 Increment (on mouse up)
24634 * @name ngMouseover
24637 * Specify custom behavior on mouseover event.
24641 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
24642 * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
24646 <file name="index.html">
24647 <button ng-mouseover="count = count + 1" ng-init="count=0">
24648 Increment (when mouse is over)
24658 * @name ngMouseenter
24661 * Specify custom behavior on mouseenter event.
24665 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
24666 * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
24670 <file name="index.html">
24671 <button ng-mouseenter="count = count + 1" ng-init="count=0">
24672 Increment (when mouse enters)
24682 * @name ngMouseleave
24685 * Specify custom behavior on mouseleave event.
24689 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
24690 * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
24694 <file name="index.html">
24695 <button ng-mouseleave="count = count + 1" ng-init="count=0">
24696 Increment (when mouse leaves)
24706 * @name ngMousemove
24709 * Specify custom behavior on mousemove event.
24713 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
24714 * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
24718 <file name="index.html">
24719 <button ng-mousemove="count = count + 1" ng-init="count=0">
24720 Increment (when mouse moves)
24733 * Specify custom behavior on keydown event.
24737 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
24738 * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
24742 <file name="index.html">
24743 <input ng-keydown="count = count + 1" ng-init="count=0">
24744 key down count: {{count}}
24755 * Specify custom behavior on keyup event.
24759 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
24760 * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
24764 <file name="index.html">
24765 <p>Typing in the input box below updates the key count</p>
24766 <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
24768 <p>Typing in the input box below updates the keycode</p>
24769 <input ng-keyup="event=$event">
24770 <p>event keyCode: {{ event.keyCode }}</p>
24771 <p>event altKey: {{ event.altKey }}</p>
24782 * Specify custom behavior on keypress event.
24785 * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
24786 * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
24787 * and can be interrogated for keyCode, altKey, etc.)
24791 <file name="index.html">
24792 <input ng-keypress="count = count + 1" ng-init="count=0">
24793 key press count: {{count}}
24804 * Enables binding angular expressions to onsubmit events.
24806 * Additionally it prevents the default action (which for form means sending the request to the
24807 * server and reloading the current page), but only if the form does not contain `action`,
24808 * `data-action`, or `x-action` attributes.
24810 * <div class="alert alert-warning">
24811 * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
24812 * `ngSubmit` handlers together. See the
24813 * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
24814 * for a detailed discussion of when `ngSubmit` may be triggered.
24819 * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
24820 * ({@link guide/expression#-event- Event object is available as `$event`})
24823 <example module="submitExample">
24824 <file name="index.html">
24826 angular.module('submitExample', [])
24827 .controller('ExampleController', ['$scope', function($scope) {
24829 $scope.text = 'hello';
24830 $scope.submit = function() {
24832 $scope.list.push(this.text);
24838 <form ng-submit="submit()" ng-controller="ExampleController">
24839 Enter text and hit enter:
24840 <input type="text" ng-model="text" name="text" />
24841 <input type="submit" id="submit" value="Submit" />
24842 <pre>list={{list}}</pre>
24845 <file name="protractor.js" type="protractor">
24846 it('should check ng-submit', function() {
24847 expect(element(by.binding('list')).getText()).toBe('list=[]');
24848 element(by.css('#submit')).click();
24849 expect(element(by.binding('list')).getText()).toContain('hello');
24850 expect(element(by.model('text')).getAttribute('value')).toBe('');
24852 it('should ignore empty strings', function() {
24853 expect(element(by.binding('list')).getText()).toBe('list=[]');
24854 element(by.css('#submit')).click();
24855 element(by.css('#submit')).click();
24856 expect(element(by.binding('list')).getText()).toContain('hello');
24867 * Specify custom behavior on focus event.
24869 * Note: As the `focus` event is executed synchronously when calling `input.focus()`
24870 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
24871 * during an `$apply` to ensure a consistent state.
24873 * @element window, input, select, textarea, a
24875 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
24876 * focus. ({@link guide/expression#-event- Event object is available as `$event`})
24879 * See {@link ng.directive:ngClick ngClick}
24887 * Specify custom behavior on blur event.
24889 * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
24890 * an element has lost focus.
24892 * Note: As the `blur` event is executed synchronously also during DOM manipulations
24893 * (e.g. removing a focussed input),
24894 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
24895 * during an `$apply` to ensure a consistent state.
24897 * @element window, input, select, textarea, a
24899 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
24900 * blur. ({@link guide/expression#-event- Event object is available as `$event`})
24903 * See {@link ng.directive:ngClick ngClick}
24911 * Specify custom behavior on copy event.
24913 * @element window, input, select, textarea, a
24915 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
24916 * copy. ({@link guide/expression#-event- Event object is available as `$event`})
24920 <file name="index.html">
24921 <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
24932 * Specify custom behavior on cut event.
24934 * @element window, input, select, textarea, a
24936 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
24937 * cut. ({@link guide/expression#-event- Event object is available as `$event`})
24941 <file name="index.html">
24942 <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
24953 * Specify custom behavior on paste event.
24955 * @element window, input, select, textarea, a
24957 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
24958 * paste. ({@link guide/expression#-event- Event object is available as `$event`})
24962 <file name="index.html">
24963 <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
24976 * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
24977 * {expression}. If the expression assigned to `ngIf` evaluates to a false
24978 * value then the element is removed from the DOM, otherwise a clone of the
24979 * element is reinserted into the DOM.
24981 * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
24982 * element in the DOM rather than changing its visibility via the `display` css property. A common
24983 * case when this difference is significant is when using css selectors that rely on an element's
24984 * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
24986 * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
24987 * is created when the element is restored. The scope created within `ngIf` inherits from
24988 * its parent scope using
24989 * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
24990 * An important implication of this is if `ngModel` is used within `ngIf` to bind to
24991 * a javascript primitive defined in the parent scope. In this case any modifications made to the
24992 * variable within the child scope will override (hide) the value in the parent scope.
24994 * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
24995 * is if an element's class attribute is directly modified after it's compiled, using something like
24996 * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
24997 * the added class will be lost because the original compiled state is used to regenerate the element.
24999 * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
25000 * and `leave` effects.
25003 * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
25004 * leave - happens just before the `ngIf` contents are removed from the DOM
25009 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
25010 * the element is removed from the DOM tree. If it is truthy a copy of the compiled
25011 * element is added to the DOM tree.
25014 <example module="ngAnimate" deps="angular-animate.js" animations="true">
25015 <file name="index.html">
25016 <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
25018 <span ng-if="checked" class="animate-if">
25019 This is removed when the checkbox is unchecked.
25022 <file name="animations.css">
25025 border:1px solid black;
25029 .animate-if.ng-enter, .animate-if.ng-leave {
25030 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
25033 .animate-if.ng-enter,
25034 .animate-if.ng-leave.ng-leave-active {
25038 .animate-if.ng-leave,
25039 .animate-if.ng-enter.ng-enter-active {
25045 var ngIfDirective = ['$animate', function($animate) {
25047 multiElement: true,
25048 transclude: 'element',
25053 link: function($scope, $element, $attr, ctrl, $transclude) {
25054 var block, childScope, previousElements;
25055 $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
25059 $transclude(function(clone, newScope) {
25060 childScope = newScope;
25061 clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
25062 // Note: We only need the first/last node of the cloned nodes.
25063 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
25064 // by a directive with templateUrl when its template arrives.
25068 $animate.enter(clone, $element.parent(), $element);
25072 if (previousElements) {
25073 previousElements.remove();
25074 previousElements = null;
25077 childScope.$destroy();
25081 previousElements = getBlockNodes(block.clone);
25082 $animate.leave(previousElements).then(function() {
25083 previousElements = null;
25099 * Fetches, compiles and includes an external HTML fragment.
25101 * By default, the template URL is restricted to the same domain and protocol as the
25102 * application document. This is done by calling {@link $sce#getTrustedResourceUrl
25103 * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
25104 * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
25105 * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
25106 * ng.$sce Strict Contextual Escaping}.
25108 * In addition, the browser's
25109 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
25110 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
25111 * policy may further restrict whether the template is successfully loaded.
25112 * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
25113 * access on some browsers.
25116 * enter - animation is used to bring new content into the browser.
25117 * leave - animation is used to animate existing content away.
25119 * The enter and leave animation occur concurrently.
25124 * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
25125 * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
25126 * @param {string=} onload Expression to evaluate when a new partial is loaded.
25127 * <div class="alert alert-warning">
25128 * **Note:** When using onload on SVG elements in IE11, the browser will try to call
25129 * a function with the name on the window element, which will usually throw a
25130 * "function is undefined" error. To fix this, you can instead use `data-onload` or a
25131 * different form that {@link guide/directive#normalization matches} `onload`.
25134 * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
25135 * $anchorScroll} to scroll the viewport after the content is loaded.
25137 * - If the attribute is not set, disable scrolling.
25138 * - If the attribute is set without value, enable scrolling.
25139 * - Otherwise enable scrolling only if the expression evaluates to truthy value.
25142 <example module="includeExample" deps="angular-animate.js" animations="true">
25143 <file name="index.html">
25144 <div ng-controller="ExampleController">
25145 <select ng-model="template" ng-options="t.name for t in templates">
25146 <option value="">(blank)</option>
25148 url of the template: <code>{{template.url}}</code>
25150 <div class="slide-animate-container">
25151 <div class="slide-animate" ng-include="template.url"></div>
25155 <file name="script.js">
25156 angular.module('includeExample', ['ngAnimate'])
25157 .controller('ExampleController', ['$scope', function($scope) {
25159 [ { name: 'template1.html', url: 'template1.html'},
25160 { name: 'template2.html', url: 'template2.html'} ];
25161 $scope.template = $scope.templates[0];
25164 <file name="template1.html">
25165 Content of template1.html
25167 <file name="template2.html">
25168 Content of template2.html
25170 <file name="animations.css">
25171 .slide-animate-container {
25174 border:1px solid black;
25183 .slide-animate.ng-enter, .slide-animate.ng-leave {
25184 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
25195 .slide-animate.ng-enter {
25198 .slide-animate.ng-enter.ng-enter-active {
25202 .slide-animate.ng-leave {
25205 .slide-animate.ng-leave.ng-leave-active {
25209 <file name="protractor.js" type="protractor">
25210 var templateSelect = element(by.model('template'));
25211 var includeElem = element(by.css('[ng-include]'));
25213 it('should load template1.html', function() {
25214 expect(includeElem.getText()).toMatch(/Content of template1.html/);
25217 it('should load template2.html', function() {
25218 if (browser.params.browser == 'firefox') {
25219 // Firefox can't handle using selects
25220 // See https://github.com/angular/protractor/issues/480
25223 templateSelect.click();
25224 templateSelect.all(by.css('option')).get(2).click();
25225 expect(includeElem.getText()).toMatch(/Content of template2.html/);
25228 it('should change to blank', function() {
25229 if (browser.params.browser == 'firefox') {
25230 // Firefox can't handle using selects
25233 templateSelect.click();
25234 templateSelect.all(by.css('option')).get(0).click();
25235 expect(includeElem.isPresent()).toBe(false);
25244 * @name ngInclude#$includeContentRequested
25245 * @eventType emit on the scope ngInclude was declared in
25247 * Emitted every time the ngInclude content is requested.
25249 * @param {Object} angularEvent Synthetic event object.
25250 * @param {String} src URL of content to load.
25256 * @name ngInclude#$includeContentLoaded
25257 * @eventType emit on the current ngInclude scope
25259 * Emitted every time the ngInclude content is reloaded.
25261 * @param {Object} angularEvent Synthetic event object.
25262 * @param {String} src URL of content to load.
25268 * @name ngInclude#$includeContentError
25269 * @eventType emit on the scope ngInclude was declared in
25271 * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
25273 * @param {Object} angularEvent Synthetic event object.
25274 * @param {String} src URL of content to load.
25276 var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
25277 function($templateRequest, $anchorScroll, $animate) {
25282 transclude: 'element',
25283 controller: angular.noop,
25284 compile: function(element, attr) {
25285 var srcExp = attr.ngInclude || attr.src,
25286 onloadExp = attr.onload || '',
25287 autoScrollExp = attr.autoscroll;
25289 return function(scope, $element, $attr, ctrl, $transclude) {
25290 var changeCounter = 0,
25295 var cleanupLastIncludeContent = function() {
25296 if (previousElement) {
25297 previousElement.remove();
25298 previousElement = null;
25300 if (currentScope) {
25301 currentScope.$destroy();
25302 currentScope = null;
25304 if (currentElement) {
25305 $animate.leave(currentElement).then(function() {
25306 previousElement = null;
25308 previousElement = currentElement;
25309 currentElement = null;
25313 scope.$watch(srcExp, function ngIncludeWatchAction(src) {
25314 var afterAnimation = function() {
25315 if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
25319 var thisChangeId = ++changeCounter;
25322 //set the 2nd param to true to ignore the template request error so that the inner
25323 //contents and scope can be cleaned up.
25324 $templateRequest(src, true).then(function(response) {
25325 if (scope.$$destroyed) return;
25327 if (thisChangeId !== changeCounter) return;
25328 var newScope = scope.$new();
25329 ctrl.template = response;
25331 // Note: This will also link all children of ng-include that were contained in the original
25332 // html. If that content contains controllers, ... they could pollute/change the scope.
25333 // However, using ng-include on an element with additional content does not make sense...
25334 // Note: We can't remove them in the cloneAttchFn of $transclude as that
25335 // function is called before linking the content, which would apply child
25336 // directives to non existing elements.
25337 var clone = $transclude(newScope, function(clone) {
25338 cleanupLastIncludeContent();
25339 $animate.enter(clone, null, $element).then(afterAnimation);
25342 currentScope = newScope;
25343 currentElement = clone;
25345 currentScope.$emit('$includeContentLoaded', src);
25346 scope.$eval(onloadExp);
25348 if (scope.$$destroyed) return;
25350 if (thisChangeId === changeCounter) {
25351 cleanupLastIncludeContent();
25352 scope.$emit('$includeContentError', src);
25355 scope.$emit('$includeContentRequested', src);
25357 cleanupLastIncludeContent();
25358 ctrl.template = null;
25366 // This directive is called during the $transclude call of the first `ngInclude` directive.
25367 // It will replace and compile the content of the element with the loaded template.
25368 // We need this directive so that the element content is already filled when
25369 // the link function of another directive on the same element as ngInclude
25371 var ngIncludeFillContentDirective = ['$compile',
25372 function($compile) {
25376 require: 'ngInclude',
25377 link: function(scope, $element, $attr, ctrl) {
25378 if (toString.call($element[0]).match(/SVG/)) {
25379 // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
25380 // support innerHTML, so detect this here and try to generate the contents
25383 $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
25384 function namespaceAdaptedClone(clone) {
25385 $element.append(clone);
25386 }, {futureParentElement: $element});
25390 $element.html(ctrl.template);
25391 $compile($element.contents())(scope);
25402 * The `ngInit` directive allows you to evaluate an expression in the
25405 * <div class="alert alert-danger">
25406 * This directive can be abused to add unnecessary amounts of logic into your templates.
25407 * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
25408 * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
25409 * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
25410 * rather than `ngInit` to initialize values on a scope.
25413 * <div class="alert alert-warning">
25414 * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
25415 * sure you have parentheses to ensure correct operator precedence:
25416 * <pre class="prettyprint">
25417 * `<div ng-init="test1 = ($index | toString)"></div>`
25424 * @param {expression} ngInit {@link guide/expression Expression} to eval.
25427 <example module="initExample">
25428 <file name="index.html">
25430 angular.module('initExample', [])
25431 .controller('ExampleController', ['$scope', function($scope) {
25432 $scope.list = [['a', 'b'], ['c', 'd']];
25435 <div ng-controller="ExampleController">
25436 <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
25437 <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
25438 <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
25443 <file name="protractor.js" type="protractor">
25444 it('should alias index positions', function() {
25445 var elements = element.all(by.css('.example-init'));
25446 expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
25447 expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
25448 expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
25449 expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
25454 var ngInitDirective = ngDirective({
25456 compile: function() {
25458 pre: function(scope, element, attrs) {
25459 scope.$eval(attrs.ngInit);
25470 * Text input that converts between a delimited string and an array of strings. The default
25471 * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
25472 * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
25474 * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
25475 * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
25476 * list item is respected. This implies that the user of the directive is responsible for
25477 * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
25478 * tab or newline character.
25479 * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
25480 * when joining the list items back together) and whitespace around each list item is stripped
25481 * before it is added to the model.
25483 * ### Example with Validation
25485 * <example name="ngList-directive" module="listExample">
25486 * <file name="app.js">
25487 * angular.module('listExample', [])
25488 * .controller('ExampleController', ['$scope', function($scope) {
25489 * $scope.names = ['morpheus', 'neo', 'trinity'];
25492 * <file name="index.html">
25493 * <form name="myForm" ng-controller="ExampleController">
25494 * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
25495 * <span role="alert">
25496 * <span class="error" ng-show="myForm.namesInput.$error.required">
25500 * <tt>names = {{names}}</tt><br/>
25501 * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
25502 * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
25503 * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
25504 * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
25507 * <file name="protractor.js" type="protractor">
25508 * var listInput = element(by.model('names'));
25509 * var names = element(by.exactBinding('names'));
25510 * var valid = element(by.binding('myForm.namesInput.$valid'));
25511 * var error = element(by.css('span.error'));
25513 * it('should initialize to model', function() {
25514 * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
25515 * expect(valid.getText()).toContain('true');
25516 * expect(error.getCssValue('display')).toBe('none');
25519 * it('should be invalid if empty', function() {
25520 * listInput.clear();
25521 * listInput.sendKeys('');
25523 * expect(names.getText()).toContain('');
25524 * expect(valid.getText()).toContain('false');
25525 * expect(error.getCssValue('display')).not.toBe('none');
25530 * ### Example - splitting on newline
25531 * <example name="ngList-directive-newlines">
25532 * <file name="index.html">
25533 * <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
25534 * <pre>{{ list | json }}</pre>
25536 * <file name="protractor.js" type="protractor">
25537 * it("should split the text by newlines", function() {
25538 * var listInput = element(by.model('list'));
25539 * var output = element(by.binding('list | json'));
25540 * listInput.sendKeys('abc\ndef\nghi');
25541 * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
25547 * @param {string=} ngList optional delimiter that should be used to split the value.
25549 var ngListDirective = function() {
25553 require: 'ngModel',
25554 link: function(scope, element, attr, ctrl) {
25555 // We want to control whitespace trimming so we use this convoluted approach
25556 // to access the ngList attribute, which doesn't pre-trim the attribute
25557 var ngList = element.attr(attr.$attr.ngList) || ', ';
25558 var trimValues = attr.ngTrim !== 'false';
25559 var separator = trimValues ? trim(ngList) : ngList;
25561 var parse = function(viewValue) {
25562 // If the viewValue is invalid (say required but empty) it will be `undefined`
25563 if (isUndefined(viewValue)) return;
25568 forEach(viewValue.split(separator), function(value) {
25569 if (value) list.push(trimValues ? trim(value) : value);
25576 ctrl.$parsers.push(parse);
25577 ctrl.$formatters.push(function(value) {
25578 if (isArray(value)) {
25579 return value.join(ngList);
25585 // Override the standard $isEmpty because an empty array means the input is empty.
25586 ctrl.$isEmpty = function(value) {
25587 return !value || !value.length;
25593 /* global VALID_CLASS: true,
25594 INVALID_CLASS: true,
25595 PRISTINE_CLASS: true,
25597 UNTOUCHED_CLASS: true,
25598 TOUCHED_CLASS: true,
25601 var VALID_CLASS = 'ng-valid',
25602 INVALID_CLASS = 'ng-invalid',
25603 PRISTINE_CLASS = 'ng-pristine',
25604 DIRTY_CLASS = 'ng-dirty',
25605 UNTOUCHED_CLASS = 'ng-untouched',
25606 TOUCHED_CLASS = 'ng-touched',
25607 PENDING_CLASS = 'ng-pending',
25608 EMPTY_CLASS = 'ng-empty',
25609 NOT_EMPTY_CLASS = 'ng-not-empty';
25611 var ngModelMinErr = minErr('ngModel');
25615 * @name ngModel.NgModelController
25617 * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
25618 * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
25620 * @property {*} $modelValue The value in the model that the control is bound to.
25621 * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
25622 the control reads value from the DOM. The functions are called in array order, each passing
25623 its return value through to the next. The last return value is forwarded to the
25624 {@link ngModel.NgModelController#$validators `$validators`} collection.
25626 Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
25629 Returning `undefined` from a parser means a parse error occurred. In that case,
25630 no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
25631 will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
25632 is set to `true`. The parse error is stored in `ngModel.$error.parse`.
25635 * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
25636 the model value changes. The functions are called in reverse array order, each passing the value through to the
25637 next. The last return value is used as the actual DOM value.
25638 Used to format / convert values for display in the control.
25640 * function formatter(value) {
25642 * return value.toUpperCase();
25645 * ngModel.$formatters.push(formatter);
25648 * @property {Object.<string, function>} $validators A collection of validators that are applied
25649 * whenever the model value changes. The key value within the object refers to the name of the
25650 * validator while the function refers to the validation operation. The validation operation is
25651 * provided with the model value as an argument and must return a true or false value depending
25652 * on the response of that validation.
25655 * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
25656 * var value = modelValue || viewValue;
25657 * return /[0-9]+/.test(value) &&
25658 * /[a-z]+/.test(value) &&
25659 * /[A-Z]+/.test(value) &&
25660 * /\W+/.test(value);
25664 * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
25665 * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
25666 * is expected to return a promise when it is run during the model validation process. Once the promise
25667 * is delivered then the validation status will be set to true when fulfilled and false when rejected.
25668 * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
25669 * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
25670 * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
25671 * will only run once all synchronous validators have passed.
25673 * Please note that if $http is used then it is important that the server returns a success HTTP response code
25674 * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
25677 * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
25678 * var value = modelValue || viewValue;
25680 * // Lookup user by username
25681 * return $http.get('/api/users/' + value).
25682 * then(function resolved() {
25683 * //username exists, this means validation fails
25684 * return $q.reject('exists');
25685 * }, function rejected() {
25686 * //username does not exist, therefore this validation passes
25692 * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
25693 * view value has changed. It is called with no arguments, and its return value is ignored.
25694 * This can be used in place of additional $watches against the model value.
25696 * @property {Object} $error An object hash with all failing validator ids as keys.
25697 * @property {Object} $pending An object hash with all pending validator ids as keys.
25699 * @property {boolean} $untouched True if control has not lost focus yet.
25700 * @property {boolean} $touched True if control has lost focus.
25701 * @property {boolean} $pristine True if user has not interacted with the control yet.
25702 * @property {boolean} $dirty True if user has already interacted with the control.
25703 * @property {boolean} $valid True if there is no error.
25704 * @property {boolean} $invalid True if at least one error on the control.
25705 * @property {string} $name The name attribute of the control.
25709 * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
25710 * The controller contains services for data-binding, validation, CSS updates, and value formatting
25711 * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
25712 * listening to DOM events.
25713 * Such DOM related logic should be provided by other directives which make use of
25714 * `NgModelController` for data-binding to control elements.
25715 * Angular provides this DOM logic for most {@link input `input`} elements.
25716 * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
25717 * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
25720 * ### Custom Control Example
25721 * This example shows how to use `NgModelController` with a custom control to achieve
25722 * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
25723 * collaborate together to achieve the desired result.
25725 * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
25726 * contents be edited in place by the user.
25728 * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
25729 * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
25730 * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
25731 * that content using the `$sce` service.
25733 * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
25734 <file name="style.css">
25735 [contenteditable] {
25736 border: 1px solid black;
25737 background-color: white;
25742 border: 1px solid red;
25746 <file name="script.js">
25747 angular.module('customControl', ['ngSanitize']).
25748 directive('contenteditable', ['$sce', function($sce) {
25750 restrict: 'A', // only activate on element attribute
25751 require: '?ngModel', // get a hold of NgModelController
25752 link: function(scope, element, attrs, ngModel) {
25753 if (!ngModel) return; // do nothing if no ng-model
25755 // Specify how UI should be updated
25756 ngModel.$render = function() {
25757 element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
25760 // Listen for change events to enable binding
25761 element.on('blur keyup change', function() {
25762 scope.$evalAsync(read);
25764 read(); // initialize
25766 // Write data to the model
25768 var html = element.html();
25769 // When we clear the content editable the browser leaves a <br> behind
25770 // If strip-br attribute is provided then we strip this out
25771 if ( attrs.stripBr && html == '<br>' ) {
25774 ngModel.$setViewValue(html);
25780 <file name="index.html">
25781 <form name="myForm">
25782 <div contenteditable
25783 name="myWidget" ng-model="userContent"
25785 required>Change me!</div>
25786 <span ng-show="myForm.myWidget.$error.required">Required!</span>
25788 <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
25791 <file name="protractor.js" type="protractor">
25792 it('should data-bind and become invalid', function() {
25793 if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
25794 // SafariDriver can't handle contenteditable
25795 // and Firefox driver can't clear contenteditables very well
25798 var contentEditable = element(by.css('[contenteditable]'));
25799 var content = 'Change me!';
25801 expect(contentEditable.getText()).toEqual(content);
25803 contentEditable.clear();
25804 contentEditable.sendKeys(protractor.Key.BACK_SPACE);
25805 expect(contentEditable.getText()).toEqual('');
25806 expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
25813 var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
25814 function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
25815 this.$viewValue = Number.NaN;
25816 this.$modelValue = Number.NaN;
25817 this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
25818 this.$validators = {};
25819 this.$asyncValidators = {};
25820 this.$parsers = [];
25821 this.$formatters = [];
25822 this.$viewChangeListeners = [];
25823 this.$untouched = true;
25824 this.$touched = false;
25825 this.$pristine = true;
25826 this.$dirty = false;
25827 this.$valid = true;
25828 this.$invalid = false;
25829 this.$error = {}; // keep invalid keys here
25830 this.$$success = {}; // keep valid keys here
25831 this.$pending = undefined; // keep pending keys here
25832 this.$name = $interpolate($attr.name || '', false)($scope);
25833 this.$$parentForm = nullFormCtrl;
25835 var parsedNgModel = $parse($attr.ngModel),
25836 parsedNgModelAssign = parsedNgModel.assign,
25837 ngModelGet = parsedNgModel,
25838 ngModelSet = parsedNgModelAssign,
25839 pendingDebounce = null,
25843 this.$$setOptions = function(options) {
25844 ctrl.$options = options;
25845 if (options && options.getterSetter) {
25846 var invokeModelGetter = $parse($attr.ngModel + '()'),
25847 invokeModelSetter = $parse($attr.ngModel + '($$$p)');
25849 ngModelGet = function($scope) {
25850 var modelValue = parsedNgModel($scope);
25851 if (isFunction(modelValue)) {
25852 modelValue = invokeModelGetter($scope);
25856 ngModelSet = function($scope, newValue) {
25857 if (isFunction(parsedNgModel($scope))) {
25858 invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
25860 parsedNgModelAssign($scope, ctrl.$modelValue);
25863 } else if (!parsedNgModel.assign) {
25864 throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
25865 $attr.ngModel, startingTag($element));
25871 * @name ngModel.NgModelController#$render
25874 * Called when the view needs to be updated. It is expected that the user of the ng-model
25875 * directive will implement this method.
25877 * The `$render()` method is invoked in the following situations:
25879 * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
25880 * committed value then `$render()` is called to update the input control.
25881 * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
25882 * the `$viewValue` are different from last time.
25884 * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
25885 * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
25886 * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
25887 * invoked if you only change a property on the objects.
25889 this.$render = noop;
25893 * @name ngModel.NgModelController#$isEmpty
25896 * This is called when we need to determine if the value of an input is empty.
25898 * For instance, the required directive does this to work out if the input has data or not.
25900 * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
25902 * You can override this for input directives whose concept of being empty is different from the
25903 * default. The `checkboxInputType` directive does this because in its case a value of `false`
25906 * @param {*} value The value of the input to check for emptiness.
25907 * @returns {boolean} True if `value` is "empty".
25909 this.$isEmpty = function(value) {
25910 return isUndefined(value) || value === '' || value === null || value !== value;
25913 this.$$updateEmptyClasses = function(value) {
25914 if (ctrl.$isEmpty(value)) {
25915 $animate.removeClass($element, NOT_EMPTY_CLASS);
25916 $animate.addClass($element, EMPTY_CLASS);
25918 $animate.removeClass($element, EMPTY_CLASS);
25919 $animate.addClass($element, NOT_EMPTY_CLASS);
25924 var currentValidationRunId = 0;
25928 * @name ngModel.NgModelController#$setValidity
25931 * Change the validity state, and notify the form.
25933 * This method can be called within $parsers/$formatters or a custom validation implementation.
25934 * However, in most cases it should be sufficient to use the `ngModel.$validators` and
25935 * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
25937 * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
25938 * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
25939 * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
25940 * The `validationErrorKey` should be in camelCase and will get converted into dash-case
25941 * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
25942 * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
25943 * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
25944 * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
25945 * Skipped is used by Angular when validators do not run because of parse errors and
25946 * when `$asyncValidators` do not run because any of the `$validators` failed.
25948 addSetValidityMethod({
25950 $element: $element,
25951 set: function(object, property) {
25952 object[property] = true;
25954 unset: function(object, property) {
25955 delete object[property];
25962 * @name ngModel.NgModelController#$setPristine
25965 * Sets the control to its pristine state.
25967 * This method can be called to remove the `ng-dirty` class and set the control to its pristine
25968 * state (`ng-pristine` class). A model is considered to be pristine when the control
25969 * has not been changed from when first compiled.
25971 this.$setPristine = function() {
25972 ctrl.$dirty = false;
25973 ctrl.$pristine = true;
25974 $animate.removeClass($element, DIRTY_CLASS);
25975 $animate.addClass($element, PRISTINE_CLASS);
25980 * @name ngModel.NgModelController#$setDirty
25983 * Sets the control to its dirty state.
25985 * This method can be called to remove the `ng-pristine` class and set the control to its dirty
25986 * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
25987 * from when first compiled.
25989 this.$setDirty = function() {
25990 ctrl.$dirty = true;
25991 ctrl.$pristine = false;
25992 $animate.removeClass($element, PRISTINE_CLASS);
25993 $animate.addClass($element, DIRTY_CLASS);
25994 ctrl.$$parentForm.$setDirty();
25999 * @name ngModel.NgModelController#$setUntouched
26002 * Sets the control to its untouched state.
26004 * This method can be called to remove the `ng-touched` class and set the control to its
26005 * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
26006 * by default, however this function can be used to restore that state if the model has
26007 * already been touched by the user.
26009 this.$setUntouched = function() {
26010 ctrl.$touched = false;
26011 ctrl.$untouched = true;
26012 $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
26017 * @name ngModel.NgModelController#$setTouched
26020 * Sets the control to its touched state.
26022 * This method can be called to remove the `ng-untouched` class and set the control to its
26023 * touched state (`ng-touched` class). A model is considered to be touched when the user has
26024 * first focused the control element and then shifted focus away from the control (blur event).
26026 this.$setTouched = function() {
26027 ctrl.$touched = true;
26028 ctrl.$untouched = false;
26029 $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
26034 * @name ngModel.NgModelController#$rollbackViewValue
26037 * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
26038 * which may be caused by a pending debounced event or because the input is waiting for a some
26041 * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
26042 * depend on special events such as blur, you can have a situation where there is a period when
26043 * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
26045 * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
26046 * and reset the input to the last committed view value.
26048 * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
26049 * programmatically before these debounced/future events have resolved/occurred, because Angular's
26050 * dirty checking mechanism is not able to tell whether the model has actually changed or not.
26052 * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
26053 * input which may have such events pending. This is important in order to make sure that the
26054 * input field will be updated with the new model value and any pending operations are cancelled.
26056 * <example name="ng-model-cancel-update" module="cancel-update-example">
26057 * <file name="app.js">
26058 * angular.module('cancel-update-example', [])
26060 * .controller('CancelUpdateController', ['$scope', function($scope) {
26061 * $scope.model = {};
26063 * $scope.setEmpty = function(e, value, rollback) {
26064 * if (e.keyCode == 27) {
26065 * e.preventDefault();
26067 * $scope.myForm[value].$rollbackViewValue();
26069 * $scope.model[value] = '';
26074 * <file name="index.html">
26075 * <div ng-controller="CancelUpdateController">
26076 * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
26077 * empty them. Follow these steps and observe the difference:</p>
26079 * <li>Type something in the input. You will see that the model is not yet updated</li>
26080 * <li>Press the Escape key.
26082 * <li> In the first example, nothing happens, because the model is already '', and no
26083 * update is detected. If you blur the input, the model will be set to the current view.
26085 * <li> In the second example, the pending update is cancelled, and the input is set back
26086 * to the last committed view value (''). Blurring the input does nothing.
26092 * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
26094 * <p id="inputDescription1">Without $rollbackViewValue():</p>
26095 * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
26096 * ng-keydown="setEmpty($event, 'value1')">
26097 * value1: "{{ model.value1 }}"
26101 * <p id="inputDescription2">With $rollbackViewValue():</p>
26102 * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
26103 * ng-keydown="setEmpty($event, 'value2', true)">
26104 * value2: "{{ model.value2 }}"
26109 <file name="style.css">
26111 display: table-cell;
26114 padding-right: 30px;
26120 this.$rollbackViewValue = function() {
26121 $timeout.cancel(pendingDebounce);
26122 ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
26128 * @name ngModel.NgModelController#$validate
26131 * Runs each of the registered validators (first synchronous validators and then
26132 * asynchronous validators).
26133 * If the validity changes to invalid, the model will be set to `undefined`,
26134 * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
26135 * If the validity changes to valid, it will set the model to the last available valid
26136 * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
26138 this.$validate = function() {
26139 // ignore $validate before model is initialized
26140 if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
26144 var viewValue = ctrl.$$lastCommittedViewValue;
26145 // Note: we use the $$rawModelValue as $modelValue might have been
26146 // set to undefined during a view -> model update that found validation
26147 // errors. We can't parse the view here, since that could change
26148 // the model although neither viewValue nor the model on the scope changed
26149 var modelValue = ctrl.$$rawModelValue;
26151 var prevValid = ctrl.$valid;
26152 var prevModelValue = ctrl.$modelValue;
26154 var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
26156 ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
26157 // If there was no change in validity, don't update the model
26158 // This prevents changing an invalid modelValue to undefined
26159 if (!allowInvalid && prevValid !== allValid) {
26160 // Note: Don't check ctrl.$valid here, as we could have
26161 // external validators (e.g. calculated on the server),
26162 // that just call $setValidity and need the model value
26163 // to calculate their validity.
26164 ctrl.$modelValue = allValid ? modelValue : undefined;
26166 if (ctrl.$modelValue !== prevModelValue) {
26167 ctrl.$$writeModelToScope();
26174 this.$$runValidators = function(modelValue, viewValue, doneCallback) {
26175 currentValidationRunId++;
26176 var localValidationRunId = currentValidationRunId;
26178 // check parser error
26179 if (!processParseErrors()) {
26180 validationDone(false);
26183 if (!processSyncValidators()) {
26184 validationDone(false);
26187 processAsyncValidators();
26189 function processParseErrors() {
26190 var errorKey = ctrl.$$parserName || 'parse';
26191 if (isUndefined(parserValid)) {
26192 setValidity(errorKey, null);
26194 if (!parserValid) {
26195 forEach(ctrl.$validators, function(v, name) {
26196 setValidity(name, null);
26198 forEach(ctrl.$asyncValidators, function(v, name) {
26199 setValidity(name, null);
26202 // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
26203 setValidity(errorKey, parserValid);
26204 return parserValid;
26209 function processSyncValidators() {
26210 var syncValidatorsValid = true;
26211 forEach(ctrl.$validators, function(validator, name) {
26212 var result = validator(modelValue, viewValue);
26213 syncValidatorsValid = syncValidatorsValid && result;
26214 setValidity(name, result);
26216 if (!syncValidatorsValid) {
26217 forEach(ctrl.$asyncValidators, function(v, name) {
26218 setValidity(name, null);
26225 function processAsyncValidators() {
26226 var validatorPromises = [];
26227 var allValid = true;
26228 forEach(ctrl.$asyncValidators, function(validator, name) {
26229 var promise = validator(modelValue, viewValue);
26230 if (!isPromiseLike(promise)) {
26231 throw ngModelMinErr('nopromise',
26232 "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
26234 setValidity(name, undefined);
26235 validatorPromises.push(promise.then(function() {
26236 setValidity(name, true);
26237 }, function(error) {
26239 setValidity(name, false);
26242 if (!validatorPromises.length) {
26243 validationDone(true);
26245 $q.all(validatorPromises).then(function() {
26246 validationDone(allValid);
26251 function setValidity(name, isValid) {
26252 if (localValidationRunId === currentValidationRunId) {
26253 ctrl.$setValidity(name, isValid);
26257 function validationDone(allValid) {
26258 if (localValidationRunId === currentValidationRunId) {
26260 doneCallback(allValid);
26267 * @name ngModel.NgModelController#$commitViewValue
26270 * Commit a pending update to the `$modelValue`.
26272 * Updates may be pending by a debounced event or because the input is waiting for a some future
26273 * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
26274 * usually handles calling this in response to input events.
26276 this.$commitViewValue = function() {
26277 var viewValue = ctrl.$viewValue;
26279 $timeout.cancel(pendingDebounce);
26281 // If the view value has not changed then we should just exit, except in the case where there is
26282 // a native validator on the element. In this case the validation state may have changed even though
26283 // the viewValue has stayed empty.
26284 if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
26287 ctrl.$$updateEmptyClasses(viewValue);
26288 ctrl.$$lastCommittedViewValue = viewValue;
26291 if (ctrl.$pristine) {
26294 this.$$parseAndValidate();
26297 this.$$parseAndValidate = function() {
26298 var viewValue = ctrl.$$lastCommittedViewValue;
26299 var modelValue = viewValue;
26300 parserValid = isUndefined(modelValue) ? undefined : true;
26303 for (var i = 0; i < ctrl.$parsers.length; i++) {
26304 modelValue = ctrl.$parsers[i](modelValue);
26305 if (isUndefined(modelValue)) {
26306 parserValid = false;
26311 if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
26312 // ctrl.$modelValue has not been touched yet...
26313 ctrl.$modelValue = ngModelGet($scope);
26315 var prevModelValue = ctrl.$modelValue;
26316 var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
26317 ctrl.$$rawModelValue = modelValue;
26319 if (allowInvalid) {
26320 ctrl.$modelValue = modelValue;
26321 writeToModelIfNeeded();
26324 // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
26325 // This can happen if e.g. $setViewValue is called from inside a parser
26326 ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
26327 if (!allowInvalid) {
26328 // Note: Don't check ctrl.$valid here, as we could have
26329 // external validators (e.g. calculated on the server),
26330 // that just call $setValidity and need the model value
26331 // to calculate their validity.
26332 ctrl.$modelValue = allValid ? modelValue : undefined;
26333 writeToModelIfNeeded();
26337 function writeToModelIfNeeded() {
26338 if (ctrl.$modelValue !== prevModelValue) {
26339 ctrl.$$writeModelToScope();
26344 this.$$writeModelToScope = function() {
26345 ngModelSet($scope, ctrl.$modelValue);
26346 forEach(ctrl.$viewChangeListeners, function(listener) {
26350 $exceptionHandler(e);
26357 * @name ngModel.NgModelController#$setViewValue
26360 * Update the view value.
26362 * This method should be called when a control wants to change the view value; typically,
26363 * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
26364 * directive calls it when the value of the input changes and {@link ng.directive:select select}
26365 * calls it when an option is selected.
26367 * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
26368 * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
26369 * value sent directly for processing, finally to be applied to `$modelValue` and then the
26370 * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
26371 * in the `$viewChangeListeners` list, are called.
26373 * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
26374 * and the `default` trigger is not listed, all those actions will remain pending until one of the
26375 * `updateOn` events is triggered on the DOM element.
26376 * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
26377 * directive is used with a custom debounce for this particular event.
26378 * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
26379 * is specified, once the timer runs out.
26381 * When used with standard inputs, the view value will always be a string (which is in some cases
26382 * parsed into another type, such as a `Date` object for `input[date]`.)
26383 * However, custom controls might also pass objects to this method. In this case, we should make
26384 * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
26385 * perform a deep watch of objects, it only looks for a change of identity. If you only change
26386 * the property of the object then ngModel will not realize that the object has changed and
26387 * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
26388 * not change properties of the copy once it has been passed to `$setViewValue`.
26389 * Otherwise you may cause the model value on the scope to change incorrectly.
26391 * <div class="alert alert-info">
26392 * In any case, the value passed to the method should always reflect the current value
26393 * of the control. For example, if you are calling `$setViewValue` for an input element,
26394 * you should pass the input DOM value. Otherwise, the control and the scope model become
26395 * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
26396 * the control's DOM value in any way. If we want to change the control's DOM value
26397 * programmatically, we should update the `ngModel` scope expression. Its new value will be
26398 * picked up by the model controller, which will run it through the `$formatters`, `$render` it
26399 * to update the DOM, and finally call `$validate` on it.
26402 * @param {*} value value from the view.
26403 * @param {string} trigger Event that triggered the update.
26405 this.$setViewValue = function(value, trigger) {
26406 ctrl.$viewValue = value;
26407 if (!ctrl.$options || ctrl.$options.updateOnDefault) {
26408 ctrl.$$debounceViewValueCommit(trigger);
26412 this.$$debounceViewValueCommit = function(trigger) {
26413 var debounceDelay = 0,
26414 options = ctrl.$options,
26417 if (options && isDefined(options.debounce)) {
26418 debounce = options.debounce;
26419 if (isNumber(debounce)) {
26420 debounceDelay = debounce;
26421 } else if (isNumber(debounce[trigger])) {
26422 debounceDelay = debounce[trigger];
26423 } else if (isNumber(debounce['default'])) {
26424 debounceDelay = debounce['default'];
26428 $timeout.cancel(pendingDebounce);
26429 if (debounceDelay) {
26430 pendingDebounce = $timeout(function() {
26431 ctrl.$commitViewValue();
26433 } else if ($rootScope.$$phase) {
26434 ctrl.$commitViewValue();
26436 $scope.$apply(function() {
26437 ctrl.$commitViewValue();
26443 // Note: we cannot use a normal scope.$watch as we want to detect the following:
26444 // 1. scope value is 'a'
26445 // 2. user enters 'b'
26446 // 3. ng-change kicks in and reverts scope value to 'a'
26447 // -> scope value did not change since the last digest as
26448 // ng-change executes in apply phase
26449 // 4. view should be changed back to 'a'
26450 $scope.$watch(function ngModelWatch() {
26451 var modelValue = ngModelGet($scope);
26453 // if scope model value and ngModel value are out of sync
26454 // TODO(perf): why not move this to the action fn?
26455 if (modelValue !== ctrl.$modelValue &&
26456 // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
26457 (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
26459 ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
26460 parserValid = undefined;
26462 var formatters = ctrl.$formatters,
26463 idx = formatters.length;
26465 var viewValue = modelValue;
26467 viewValue = formatters[idx](viewValue);
26469 if (ctrl.$viewValue !== viewValue) {
26470 ctrl.$$updateEmptyClasses(viewValue);
26471 ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
26474 ctrl.$$runValidators(modelValue, viewValue, noop);
26491 * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
26492 * property on the scope using {@link ngModel.NgModelController NgModelController},
26493 * which is created and exposed by this directive.
26495 * `ngModel` is responsible for:
26497 * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
26499 * - Providing validation behavior (i.e. required, number, email, url).
26500 * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
26501 * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
26502 * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
26503 * - Registering the control with its parent {@link ng.directive:form form}.
26505 * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
26506 * current scope. If the property doesn't already exist on this scope, it will be created
26507 * implicitly and added to the scope.
26509 * For best practices on using `ngModel`, see:
26511 * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
26513 * For basic examples, how to use `ngModel`, see:
26515 * - {@link ng.directive:input input}
26516 * - {@link input[text] text}
26517 * - {@link input[checkbox] checkbox}
26518 * - {@link input[radio] radio}
26519 * - {@link input[number] number}
26520 * - {@link input[email] email}
26521 * - {@link input[url] url}
26522 * - {@link input[date] date}
26523 * - {@link input[datetime-local] datetime-local}
26524 * - {@link input[time] time}
26525 * - {@link input[month] month}
26526 * - {@link input[week] week}
26527 * - {@link ng.directive:select select}
26528 * - {@link ng.directive:textarea textarea}
26530 * # Complex Models (objects or collections)
26532 * By default, `ngModel` watches the model by reference, not value. This is important to know when
26533 * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
26534 * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
26536 * The model must be assigned an entirely new object or collection before a re-rendering will occur.
26538 * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
26539 * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
26540 * if the select is given the `multiple` attribute.
26542 * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
26543 * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
26544 * not trigger a re-rendering of the model.
26547 * The following CSS classes are added and removed on the associated input/select/textarea element
26548 * depending on the validity of the model.
26550 * - `ng-valid`: the model is valid
26551 * - `ng-invalid`: the model is invalid
26552 * - `ng-valid-[key]`: for each valid key added by `$setValidity`
26553 * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
26554 * - `ng-pristine`: the control hasn't been interacted with yet
26555 * - `ng-dirty`: the control has been interacted with
26556 * - `ng-touched`: the control has been blurred
26557 * - `ng-untouched`: the control hasn't been blurred
26558 * - `ng-pending`: any `$asyncValidators` are unfulfilled
26559 * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
26560 * by the {@link ngModel.NgModelController#$isEmpty} method
26561 * - `ng-not-empty`: the view contains a non-empty value
26563 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
26565 * ## Animation Hooks
26567 * Animations within models are triggered when any of the associated CSS classes are added and removed
26568 * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
26569 * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
26570 * The animations that are triggered within ngModel are similar to how they work in ngClass and
26571 * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
26573 * The following example shows a simple way to utilize CSS transitions to style an input element
26574 * that has been rendered as invalid after it has been validated:
26577 * //be sure to include ngAnimate as a module to hook into more
26578 * //advanced animations
26580 * transition:0.5s linear all;
26581 * background: white;
26583 * .my-input.ng-invalid {
26590 * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
26591 <file name="index.html">
26593 angular.module('inputExample', [])
26594 .controller('ExampleController', ['$scope', function($scope) {
26600 transition:all linear 0.5s;
26601 background: transparent;
26603 .my-input.ng-invalid {
26608 <p id="inputDescription">
26609 Update input to see transitions when valid/invalid.
26610 Integer is a valid value.
26612 <form name="testForm" ng-controller="ExampleController">
26613 <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
26614 aria-describedby="inputDescription" />
26619 * ## Binding to a getter/setter
26621 * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
26622 * function that returns a representation of the model when called with zero arguments, and sets
26623 * the internal state of a model when called with an argument. It's sometimes useful to use this
26624 * for models that have an internal representation that's different from what the model exposes
26627 * <div class="alert alert-success">
26628 * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
26629 * frequently than other parts of your code.
26632 * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
26633 * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
26634 * a `<form>`, which will enable this behavior for all `<input>`s within it. See
26635 * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
26637 * The following example shows how to use `ngModel` with a getter/setter:
26640 * <example name="ngModel-getter-setter" module="getterSetterExample">
26641 <file name="index.html">
26642 <div ng-controller="ExampleController">
26643 <form name="userForm">
26645 <input type="text" name="userName"
26646 ng-model="user.name"
26647 ng-model-options="{ getterSetter: true }" />
26650 <pre>user.name = <span ng-bind="user.name()"></span></pre>
26653 <file name="app.js">
26654 angular.module('getterSetterExample', [])
26655 .controller('ExampleController', ['$scope', function($scope) {
26656 var _name = 'Brian';
26658 name: function(newName) {
26659 // Note that newName can be undefined for two reasons:
26660 // 1. Because it is called as a getter and thus called with no arguments
26661 // 2. Because the property should actually be set to undefined. This happens e.g. if the
26662 // input is invalid
26663 return arguments.length ? (_name = newName) : _name;
26670 var ngModelDirective = ['$rootScope', function($rootScope) {
26673 require: ['ngModel', '^?form', '^?ngModelOptions'],
26674 controller: NgModelController,
26675 // Prelink needs to run before any input directive
26676 // so that we can set the NgModelOptions in NgModelController
26677 // before anyone else uses it.
26679 compile: function ngModelCompile(element) {
26680 // Setup initial state of the control
26681 element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
26684 pre: function ngModelPreLink(scope, element, attr, ctrls) {
26685 var modelCtrl = ctrls[0],
26686 formCtrl = ctrls[1] || modelCtrl.$$parentForm;
26688 modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
26690 // notify others, especially parent forms
26691 formCtrl.$addControl(modelCtrl);
26693 attr.$observe('name', function(newValue) {
26694 if (modelCtrl.$name !== newValue) {
26695 modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
26699 scope.$on('$destroy', function() {
26700 modelCtrl.$$parentForm.$removeControl(modelCtrl);
26703 post: function ngModelPostLink(scope, element, attr, ctrls) {
26704 var modelCtrl = ctrls[0];
26705 if (modelCtrl.$options && modelCtrl.$options.updateOn) {
26706 element.on(modelCtrl.$options.updateOn, function(ev) {
26707 modelCtrl.$$debounceViewValueCommit(ev && ev.type);
26711 element.on('blur', function(ev) {
26712 if (modelCtrl.$touched) return;
26714 if ($rootScope.$$phase) {
26715 scope.$evalAsync(modelCtrl.$setTouched);
26717 scope.$apply(modelCtrl.$setTouched);
26726 var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
26730 * @name ngModelOptions
26733 * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
26734 * events that will trigger a model update and/or a debouncing delay so that the actual update only
26735 * takes place when a timer expires; this timer will be reset after another change takes place.
26737 * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
26738 * be different from the value in the actual model. This means that if you update the model you
26739 * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
26740 * order to make sure it is synchronized with the model and that any debounced action is canceled.
26742 * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
26743 * method is by making sure the input is placed inside a form that has a `name` attribute. This is
26744 * important because `form` controllers are published to the related scope under the name in their
26745 * `name` attribute.
26747 * Any pending changes will take place immediately when an enclosing form is submitted via the
26748 * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
26749 * to have access to the updated model.
26751 * `ngModelOptions` has an effect on the element it's declared on and its descendants.
26753 * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
26754 * - `updateOn`: string specifying which event should the input be bound to. You can set several
26755 * events using an space delimited list. There is a special event called `default` that
26756 * matches the default events belonging of the control.
26757 * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
26758 * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
26759 * custom value for each event. For example:
26760 * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
26761 * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
26762 * not validate correctly instead of the default behavior of setting the model to undefined.
26763 * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
26764 `ngModel` as getters/setters.
26765 * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
26766 * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
26767 * continental US time zone abbreviations, but for general use, use a time zone offset, for
26768 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
26769 * If not specified, the timezone of the browser will be used.
26773 The following example shows how to override immediate updates. Changes on the inputs within the
26774 form will update the model only when the control loses focus (blur event). If `escape` key is
26775 pressed while the input field is focused, the value is reset to the value in the current model.
26777 <example name="ngModelOptions-directive-blur" module="optionsExample">
26778 <file name="index.html">
26779 <div ng-controller="ExampleController">
26780 <form name="userForm">
26782 <input type="text" name="userName"
26783 ng-model="user.name"
26784 ng-model-options="{ updateOn: 'blur' }"
26785 ng-keyup="cancel($event)" />
26788 <input type="text" ng-model="user.data" />
26791 <pre>user.name = <span ng-bind="user.name"></span></pre>
26792 <pre>user.data = <span ng-bind="user.data"></span></pre>
26795 <file name="app.js">
26796 angular.module('optionsExample', [])
26797 .controller('ExampleController', ['$scope', function($scope) {
26798 $scope.user = { name: 'John', data: '' };
26800 $scope.cancel = function(e) {
26801 if (e.keyCode == 27) {
26802 $scope.userForm.userName.$rollbackViewValue();
26807 <file name="protractor.js" type="protractor">
26808 var model = element(by.binding('user.name'));
26809 var input = element(by.model('user.name'));
26810 var other = element(by.model('user.data'));
26812 it('should allow custom events', function() {
26813 input.sendKeys(' Doe');
26815 expect(model.getText()).toEqual('John');
26817 expect(model.getText()).toEqual('John Doe');
26820 it('should $rollbackViewValue when model changes', function() {
26821 input.sendKeys(' Doe');
26822 expect(input.getAttribute('value')).toEqual('John Doe');
26823 input.sendKeys(protractor.Key.ESCAPE);
26824 expect(input.getAttribute('value')).toEqual('John');
26826 expect(model.getText()).toEqual('John');
26831 This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
26832 If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
26834 <example name="ngModelOptions-directive-debounce" module="optionsExample">
26835 <file name="index.html">
26836 <div ng-controller="ExampleController">
26837 <form name="userForm">
26839 <input type="text" name="userName"
26840 ng-model="user.name"
26841 ng-model-options="{ debounce: 1000 }" />
26843 <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
26846 <pre>user.name = <span ng-bind="user.name"></span></pre>
26849 <file name="app.js">
26850 angular.module('optionsExample', [])
26851 .controller('ExampleController', ['$scope', function($scope) {
26852 $scope.user = { name: 'Igor' };
26857 This one shows how to bind to getter/setters:
26859 <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
26860 <file name="index.html">
26861 <div ng-controller="ExampleController">
26862 <form name="userForm">
26864 <input type="text" name="userName"
26865 ng-model="user.name"
26866 ng-model-options="{ getterSetter: true }" />
26869 <pre>user.name = <span ng-bind="user.name()"></span></pre>
26872 <file name="app.js">
26873 angular.module('getterSetterExample', [])
26874 .controller('ExampleController', ['$scope', function($scope) {
26875 var _name = 'Brian';
26877 name: function(newName) {
26878 // Note that newName can be undefined for two reasons:
26879 // 1. Because it is called as a getter and thus called with no arguments
26880 // 2. Because the property should actually be set to undefined. This happens e.g. if the
26881 // input is invalid
26882 return arguments.length ? (_name = newName) : _name;
26889 var ngModelOptionsDirective = function() {
26892 controller: ['$scope', '$attrs', function($scope, $attrs) {
26894 this.$options = copy($scope.$eval($attrs.ngModelOptions));
26895 // Allow adding/overriding bound events
26896 if (isDefined(this.$options.updateOn)) {
26897 this.$options.updateOnDefault = false;
26898 // extract "default" pseudo-event from list of events that can trigger a model update
26899 this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
26900 that.$options.updateOnDefault = true;
26904 this.$options.updateOnDefault = true;
26913 function addSetValidityMethod(context) {
26914 var ctrl = context.ctrl,
26915 $element = context.$element,
26918 unset = context.unset,
26919 $animate = context.$animate;
26921 classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
26923 ctrl.$setValidity = setValidity;
26925 function setValidity(validationErrorKey, state, controller) {
26926 if (isUndefined(state)) {
26927 createAndSet('$pending', validationErrorKey, controller);
26929 unsetAndCleanup('$pending', validationErrorKey, controller);
26931 if (!isBoolean(state)) {
26932 unset(ctrl.$error, validationErrorKey, controller);
26933 unset(ctrl.$$success, validationErrorKey, controller);
26936 unset(ctrl.$error, validationErrorKey, controller);
26937 set(ctrl.$$success, validationErrorKey, controller);
26939 set(ctrl.$error, validationErrorKey, controller);
26940 unset(ctrl.$$success, validationErrorKey, controller);
26943 if (ctrl.$pending) {
26944 cachedToggleClass(PENDING_CLASS, true);
26945 ctrl.$valid = ctrl.$invalid = undefined;
26946 toggleValidationCss('', null);
26948 cachedToggleClass(PENDING_CLASS, false);
26949 ctrl.$valid = isObjectEmpty(ctrl.$error);
26950 ctrl.$invalid = !ctrl.$valid;
26951 toggleValidationCss('', ctrl.$valid);
26954 // re-read the state as the set/unset methods could have
26955 // combined state in ctrl.$error[validationError] (used for forms),
26956 // where setting/unsetting only increments/decrements the value,
26957 // and does not replace it.
26959 if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
26960 combinedState = undefined;
26961 } else if (ctrl.$error[validationErrorKey]) {
26962 combinedState = false;
26963 } else if (ctrl.$$success[validationErrorKey]) {
26964 combinedState = true;
26966 combinedState = null;
26969 toggleValidationCss(validationErrorKey, combinedState);
26970 ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
26973 function createAndSet(name, value, controller) {
26977 set(ctrl[name], value, controller);
26980 function unsetAndCleanup(name, value, controller) {
26982 unset(ctrl[name], value, controller);
26984 if (isObjectEmpty(ctrl[name])) {
26985 ctrl[name] = undefined;
26989 function cachedToggleClass(className, switchValue) {
26990 if (switchValue && !classCache[className]) {
26991 $animate.addClass($element, className);
26992 classCache[className] = true;
26993 } else if (!switchValue && classCache[className]) {
26994 $animate.removeClass($element, className);
26995 classCache[className] = false;
26999 function toggleValidationCss(validationErrorKey, isValid) {
27000 validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
27002 cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
27003 cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
27007 function isObjectEmpty(obj) {
27009 for (var prop in obj) {
27010 if (obj.hasOwnProperty(prop)) {
27020 * @name ngNonBindable
27025 * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
27026 * DOM element. This is useful if the element contains what appears to be Angular directives and
27027 * bindings but which should be ignored by Angular. This could be the case if you have a site that
27028 * displays snippets of code, for instance.
27033 * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
27034 * but the one wrapped in `ngNonBindable` is left alone.
27038 <file name="index.html">
27039 <div>Normal: {{1 + 2}}</div>
27040 <div ng-non-bindable>Ignored: {{1 + 2}}</div>
27042 <file name="protractor.js" type="protractor">
27043 it('should check ng-non-bindable', function() {
27044 expect(element(by.binding('1 + 2')).getText()).toContain('3');
27045 expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
27050 var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
27052 /* global jqLiteRemove */
27054 var ngOptionsMinErr = minErr('ngOptions');
27063 * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
27064 * elements for the `<select>` element using the array or object obtained by evaluating the
27065 * `ngOptions` comprehension expression.
27067 * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
27068 * similar result. However, `ngOptions` provides some benefits such as reducing memory and
27069 * increasing speed by not creating a new scope for each repeated instance, as well as providing
27070 * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
27071 * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
27072 * to a non-string value. This is because an option element can only be bound to string values at
27075 * When an item in the `<select>` menu is selected, the array element or object property
27076 * represented by the selected option will be bound to the model identified by the `ngModel`
27079 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
27080 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
27081 * option. See example below for demonstration.
27083 * ## Complex Models (objects or collections)
27085 * By default, `ngModel` watches the model by reference, not value. This is important to know when
27086 * binding the select to a model that is an object or a collection.
27088 * One issue occurs if you want to preselect an option. For example, if you set
27089 * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
27090 * because the objects are not identical. So by default, you should always reference the item in your collection
27091 * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
27093 * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
27094 * of the item not by reference, but by the result of the `track by` expression. For example, if your
27095 * collection items have an id property, you would `track by item.id`.
27097 * A different issue with objects or collections is that ngModel won't detect if an object property or
27098 * a collection item changes. For that reason, `ngOptions` additionally watches the model using
27099 * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
27100 * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
27101 * has not changed identity, but only a property on the object or an item in the collection changes.
27103 * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
27104 * if the model is an array). This means that changing a property deeper than the first level inside the
27105 * object/collection will not trigger a re-rendering.
27107 * ## `select` **`as`**
27109 * Using `select` **`as`** will bind the result of the `select` expression to the model, but
27110 * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
27111 * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
27112 * is used, the result of that expression will be set as the value of the `option` and `select` elements.
27115 * ### `select` **`as`** and **`track by`**
27117 * <div class="alert alert-warning">
27118 * Be careful when using `select` **`as`** and **`track by`** in the same expression.
27121 * Given this array of items on the $scope:
27124 * $scope.items = [{
27127 * subItem: { name: 'aSubItem' }
27131 * subItem: { name: 'bSubItem' }
27138 * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
27141 * $scope.selected = $scope.items[0];
27144 * but this will not work:
27147 * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
27150 * $scope.selected = $scope.items[0].subItem;
27153 * In both examples, the **`track by`** expression is applied successfully to each `item` in the
27154 * `items` array. Because the selected option has been set programmatically in the controller, the
27155 * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
27156 * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
27157 * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
27158 * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
27159 * is not matched against any `<option>` and the `<select>` appears as having no selected value.
27162 * @param {string} ngModel Assignable angular expression to data-bind to.
27163 * @param {string=} name Property name of the form under which the control is published.
27164 * @param {string=} required The control is considered valid only if value is entered.
27165 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
27166 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
27167 * `required` when you want to data-bind to the `required` attribute.
27168 * @param {comprehension_expression=} ngOptions in one of the following forms:
27170 * * for array data sources:
27171 * * `label` **`for`** `value` **`in`** `array`
27172 * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
27173 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
27174 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
27175 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
27176 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
27177 * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
27178 * (for including a filter with `track by`)
27179 * * for object data sources:
27180 * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
27181 * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
27182 * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
27183 * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
27184 * * `select` **`as`** `label` **`group by`** `group`
27185 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
27186 * * `select` **`as`** `label` **`disable when`** `disable`
27187 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
27191 * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
27192 * * `value`: local variable which will refer to each item in the `array` or each property value
27193 * of `object` during iteration.
27194 * * `key`: local variable which will refer to a property name in `object` during iteration.
27195 * * `label`: The result of this expression will be the label for `<option>` element. The
27196 * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
27197 * * `select`: The result of this expression will be bound to the model of the parent `<select>`
27198 * element. If not specified, `select` expression will default to `value`.
27199 * * `group`: The result of this expression will be used to group options using the `<optgroup>`
27201 * * `disable`: The result of this expression will be used to disable the rendered `<option>`
27202 * element. Return `true` to disable.
27203 * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
27204 * used to identify the objects in the array. The `trackexpr` will most likely refer to the
27205 * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
27206 * even when the options are recreated (e.g. reloaded from the server).
27209 <example module="selectExample">
27210 <file name="index.html">
27212 angular.module('selectExample', [])
27213 .controller('ExampleController', ['$scope', function($scope) {
27215 {name:'black', shade:'dark'},
27216 {name:'white', shade:'light', notAnOption: true},
27217 {name:'red', shade:'dark'},
27218 {name:'blue', shade:'dark', notAnOption: true},
27219 {name:'yellow', shade:'light', notAnOption: false}
27221 $scope.myColor = $scope.colors[2]; // red
27224 <div ng-controller="ExampleController">
27226 <li ng-repeat="color in colors">
27227 <label>Name: <input ng-model="color.name"></label>
27228 <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
27229 <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
27232 <button ng-click="colors.push({})">add</button>
27236 <label>Color (null not allowed):
27237 <select ng-model="myColor" ng-options="color.name for color in colors"></select>
27239 <label>Color (null allowed):
27240 <span class="nullable">
27241 <select ng-model="myColor" ng-options="color.name for color in colors">
27242 <option value="">-- choose color --</option>
27244 </span></label><br/>
27246 <label>Color grouped by shade:
27247 <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
27251 <label>Color grouped by shade, with some disabled:
27252 <select ng-model="myColor"
27253 ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
27259 Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
27262 Currently selected: {{ {selected_color:myColor} }}
27263 <div style="border:solid 1px black; height:20px"
27264 ng-style="{'background-color':myColor.name}">
27268 <file name="protractor.js" type="protractor">
27269 it('should check ng-options', function() {
27270 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
27271 element.all(by.model('myColor')).first().click();
27272 element.all(by.css('select[ng-model="myColor"] option')).first().click();
27273 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
27274 element(by.css('.nullable select[ng-model="myColor"]')).click();
27275 element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
27276 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
27282 // jshint maxlen: false
27283 // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
27284 var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
27285 // 1: value expression (valueFn)
27286 // 2: label expression (displayFn)
27287 // 3: group by expression (groupByFn)
27288 // 4: disable when expression (disableWhenFn)
27289 // 5: array item variable name
27290 // 6: object item key variable name
27291 // 7: object item value variable name
27292 // 8: collection expression
27293 // 9: track by expression
27294 // jshint maxlen: 100
27297 var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
27299 function parseOptionsExpression(optionsExp, selectElement, scope) {
27301 var match = optionsExp.match(NG_OPTIONS_REGEXP);
27303 throw ngOptionsMinErr('iexp',
27304 "Expected expression in form of " +
27305 "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
27306 " but got '{0}'. Element: {1}",
27307 optionsExp, startingTag(selectElement));
27310 // Extract the parts from the ngOptions expression
27312 // The variable name for the value of the item in the collection
27313 var valueName = match[5] || match[7];
27314 // The variable name for the key of the item in the collection
27315 var keyName = match[6];
27317 // An expression that generates the viewValue for an option if there is a label expression
27318 var selectAs = / as /.test(match[0]) && match[1];
27319 // An expression that is used to track the id of each object in the options collection
27320 var trackBy = match[9];
27321 // An expression that generates the viewValue for an option if there is no label expression
27322 var valueFn = $parse(match[2] ? match[1] : valueName);
27323 var selectAsFn = selectAs && $parse(selectAs);
27324 var viewValueFn = selectAsFn || valueFn;
27325 var trackByFn = trackBy && $parse(trackBy);
27327 // Get the value by which we are going to track the option
27328 // if we have a trackFn then use that (passing scope and locals)
27329 // otherwise just hash the given viewValue
27330 var getTrackByValueFn = trackBy ?
27331 function(value, locals) { return trackByFn(scope, locals); } :
27332 function getHashOfValue(value) { return hashKey(value); };
27333 var getTrackByValue = function(value, key) {
27334 return getTrackByValueFn(value, getLocals(value, key));
27337 var displayFn = $parse(match[2] || match[1]);
27338 var groupByFn = $parse(match[3] || '');
27339 var disableWhenFn = $parse(match[4] || '');
27340 var valuesFn = $parse(match[8]);
27343 var getLocals = keyName ? function(value, key) {
27344 locals[keyName] = key;
27345 locals[valueName] = value;
27347 } : function(value) {
27348 locals[valueName] = value;
27353 function Option(selectValue, viewValue, label, group, disabled) {
27354 this.selectValue = selectValue;
27355 this.viewValue = viewValue;
27356 this.label = label;
27357 this.group = group;
27358 this.disabled = disabled;
27361 function getOptionValuesKeys(optionValues) {
27362 var optionValuesKeys;
27364 if (!keyName && isArrayLike(optionValues)) {
27365 optionValuesKeys = optionValues;
27367 // if object, extract keys, in enumeration order, unsorted
27368 optionValuesKeys = [];
27369 for (var itemKey in optionValues) {
27370 if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
27371 optionValuesKeys.push(itemKey);
27375 return optionValuesKeys;
27380 getTrackByValue: getTrackByValue,
27381 getWatchables: $parse(valuesFn, function(optionValues) {
27382 // Create a collection of things that we would like to watch (watchedArray)
27383 // so that they can all be watched using a single $watchCollection
27384 // that only runs the handler once if anything changes
27385 var watchedArray = [];
27386 optionValues = optionValues || [];
27388 var optionValuesKeys = getOptionValuesKeys(optionValues);
27389 var optionValuesLength = optionValuesKeys.length;
27390 for (var index = 0; index < optionValuesLength; index++) {
27391 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
27392 var value = optionValues[key];
27394 var locals = getLocals(optionValues[key], key);
27395 var selectValue = getTrackByValueFn(optionValues[key], locals);
27396 watchedArray.push(selectValue);
27398 // Only need to watch the displayFn if there is a specific label expression
27399 if (match[2] || match[1]) {
27400 var label = displayFn(scope, locals);
27401 watchedArray.push(label);
27404 // Only need to watch the disableWhenFn if there is a specific disable expression
27406 var disableWhen = disableWhenFn(scope, locals);
27407 watchedArray.push(disableWhen);
27410 return watchedArray;
27413 getOptions: function() {
27415 var optionItems = [];
27416 var selectValueMap = {};
27418 // The option values were already computed in the `getWatchables` fn,
27419 // which must have been called to trigger `getOptions`
27420 var optionValues = valuesFn(scope) || [];
27421 var optionValuesKeys = getOptionValuesKeys(optionValues);
27422 var optionValuesLength = optionValuesKeys.length;
27424 for (var index = 0; index < optionValuesLength; index++) {
27425 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
27426 var value = optionValues[key];
27427 var locals = getLocals(value, key);
27428 var viewValue = viewValueFn(scope, locals);
27429 var selectValue = getTrackByValueFn(viewValue, locals);
27430 var label = displayFn(scope, locals);
27431 var group = groupByFn(scope, locals);
27432 var disabled = disableWhenFn(scope, locals);
27433 var optionItem = new Option(selectValue, viewValue, label, group, disabled);
27435 optionItems.push(optionItem);
27436 selectValueMap[selectValue] = optionItem;
27440 items: optionItems,
27441 selectValueMap: selectValueMap,
27442 getOptionFromViewValue: function(value) {
27443 return selectValueMap[getTrackByValue(value)];
27445 getViewValueFromOption: function(option) {
27446 // If the viewValue could be an object that may be mutated by the application,
27447 // we need to make a copy and not return the reference to the value on the option.
27448 return trackBy ? angular.copy(option.viewValue) : option.viewValue;
27456 // we can't just jqLite('<option>') since jqLite is not smart enough
27457 // to create it in <select> and IE barfs otherwise.
27458 var optionTemplate = document.createElement('option'),
27459 optGroupTemplate = document.createElement('optgroup');
27461 function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
27463 var selectCtrl = ctrls[0];
27464 var ngModelCtrl = ctrls[1];
27465 var multiple = attr.multiple;
27467 // The emptyOption allows the application developer to provide their own custom "empty"
27468 // option when the viewValue does not match any of the option values.
27470 for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
27471 if (children[i].value === '') {
27472 emptyOption = children.eq(i);
27477 var providedEmptyOption = !!emptyOption;
27479 var unknownOption = jqLite(optionTemplate.cloneNode(false));
27480 unknownOption.val('?');
27483 var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
27486 var renderEmptyOption = function() {
27487 if (!providedEmptyOption) {
27488 selectElement.prepend(emptyOption);
27490 selectElement.val('');
27491 emptyOption.prop('selected', true); // needed for IE
27492 emptyOption.attr('selected', true);
27495 var removeEmptyOption = function() {
27496 if (!providedEmptyOption) {
27497 emptyOption.remove();
27502 var renderUnknownOption = function() {
27503 selectElement.prepend(unknownOption);
27504 selectElement.val('?');
27505 unknownOption.prop('selected', true); // needed for IE
27506 unknownOption.attr('selected', true);
27509 var removeUnknownOption = function() {
27510 unknownOption.remove();
27513 // Update the controller methods for multiple selectable options
27516 selectCtrl.writeValue = function writeNgOptionsValue(value) {
27517 var option = options.getOptionFromViewValue(value);
27519 if (option && !option.disabled) {
27520 if (selectElement[0].value !== option.selectValue) {
27521 removeUnknownOption();
27522 removeEmptyOption();
27524 selectElement[0].value = option.selectValue;
27525 option.element.selected = true;
27526 option.element.setAttribute('selected', 'selected');
27529 if (value === null || providedEmptyOption) {
27530 removeUnknownOption();
27531 renderEmptyOption();
27533 removeEmptyOption();
27534 renderUnknownOption();
27539 selectCtrl.readValue = function readNgOptionsValue() {
27541 var selectedOption = options.selectValueMap[selectElement.val()];
27543 if (selectedOption && !selectedOption.disabled) {
27544 removeEmptyOption();
27545 removeUnknownOption();
27546 return options.getViewValueFromOption(selectedOption);
27551 // If we are using `track by` then we must watch the tracked value on the model
27552 // since ngModel only watches for object identity change
27553 if (ngOptions.trackBy) {
27555 function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
27556 function() { ngModelCtrl.$render(); }
27562 ngModelCtrl.$isEmpty = function(value) {
27563 return !value || value.length === 0;
27567 selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
27568 options.items.forEach(function(option) {
27569 option.element.selected = false;
27573 value.forEach(function(item) {
27574 var option = options.getOptionFromViewValue(item);
27575 if (option && !option.disabled) option.element.selected = true;
27581 selectCtrl.readValue = function readNgOptionsMultiple() {
27582 var selectedValues = selectElement.val() || [],
27585 forEach(selectedValues, function(value) {
27586 var option = options.selectValueMap[value];
27587 if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
27593 // If we are using `track by` then we must watch these tracked values on the model
27594 // since ngModel only watches for object identity change
27595 if (ngOptions.trackBy) {
27597 scope.$watchCollection(function() {
27598 if (isArray(ngModelCtrl.$viewValue)) {
27599 return ngModelCtrl.$viewValue.map(function(value) {
27600 return ngOptions.getTrackByValue(value);
27604 ngModelCtrl.$render();
27611 if (providedEmptyOption) {
27613 // we need to remove it before calling selectElement.empty() because otherwise IE will
27614 // remove the label from the element. wtf?
27615 emptyOption.remove();
27617 // compile the element since there might be bindings in it
27618 $compile(emptyOption)(scope);
27620 // remove the class, which is added automatically because we recompile the element and it
27621 // becomes the compilation root
27622 emptyOption.removeClass('ng-scope');
27624 emptyOption = jqLite(optionTemplate.cloneNode(false));
27627 // We need to do this here to ensure that the options object is defined
27628 // when we first hit it in writeNgOptionsValue
27631 // We will re-render the option elements if the option values or labels change
27632 scope.$watchCollection(ngOptions.getWatchables, updateOptions);
27634 // ------------------------------------------------------------------ //
27637 function updateOptionElement(option, element) {
27638 option.element = element;
27639 element.disabled = option.disabled;
27640 // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
27641 // selects in certain circumstances when multiple selects are next to each other and display
27642 // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
27643 // See https://github.com/angular/angular.js/issues/11314 for more info.
27644 // This is unfortunately untestable with unit / e2e tests
27645 if (option.label !== element.label) {
27646 element.label = option.label;
27647 element.textContent = option.label;
27649 if (option.value !== element.value) element.value = option.selectValue;
27652 function addOrReuseElement(parent, current, type, templateElement) {
27654 // Check whether we can reuse the next element
27655 if (current && lowercase(current.nodeName) === type) {
27656 // The next element is the right type so reuse it
27659 // The next element is not the right type so create a new one
27660 element = templateElement.cloneNode(false);
27662 // There are no more elements so just append it to the select
27663 parent.appendChild(element);
27665 // The next element is not a group so insert the new one
27666 parent.insertBefore(element, current);
27673 function removeExcessElements(current) {
27676 next = current.nextSibling;
27677 jqLiteRemove(current);
27683 function skipEmptyAndUnknownOptions(current) {
27684 var emptyOption_ = emptyOption && emptyOption[0];
27685 var unknownOption_ = unknownOption && unknownOption[0];
27687 // We cannot rely on the extracted empty option being the same as the compiled empty option,
27688 // because the compiled empty option might have been replaced by a comment because
27689 // it had an "element" transclusion directive on it (such as ngIf)
27690 if (emptyOption_ || unknownOption_) {
27692 (current === emptyOption_ ||
27693 current === unknownOption_ ||
27694 current.nodeType === NODE_TYPE_COMMENT ||
27695 (nodeName_(current) === 'option' && current.value === ''))) {
27696 current = current.nextSibling;
27703 function updateOptions() {
27705 var previousValue = options && selectCtrl.readValue();
27707 options = ngOptions.getOptions();
27710 var currentElement = selectElement[0].firstChild;
27712 // Ensure that the empty option is always there if it was explicitly provided
27713 if (providedEmptyOption) {
27714 selectElement.prepend(emptyOption);
27717 currentElement = skipEmptyAndUnknownOptions(currentElement);
27719 options.items.forEach(function updateOption(option) {
27724 if (isDefined(option.group)) {
27726 // This option is to live in a group
27727 // See if we have already created this group
27728 group = groupMap[option.group];
27732 // We have not already created this group
27733 groupElement = addOrReuseElement(selectElement[0],
27737 // Move to the next element
27738 currentElement = groupElement.nextSibling;
27740 // Update the label on the group element
27741 groupElement.label = option.group;
27743 // Store it for use later
27744 group = groupMap[option.group] = {
27745 groupElement: groupElement,
27746 currentOptionElement: groupElement.firstChild
27751 // So now we have a group for this option we add the option to the group
27752 optionElement = addOrReuseElement(group.groupElement,
27753 group.currentOptionElement,
27756 updateOptionElement(option, optionElement);
27757 // Move to the next element
27758 group.currentOptionElement = optionElement.nextSibling;
27762 // This option is not in a group
27763 optionElement = addOrReuseElement(selectElement[0],
27767 updateOptionElement(option, optionElement);
27768 // Move to the next element
27769 currentElement = optionElement.nextSibling;
27774 // Now remove all excess options and group
27775 Object.keys(groupMap).forEach(function(key) {
27776 removeExcessElements(groupMap[key].currentOptionElement);
27778 removeExcessElements(currentElement);
27780 ngModelCtrl.$render();
27782 // Check to see if the value has changed due to the update to the options
27783 if (!ngModelCtrl.$isEmpty(previousValue)) {
27784 var nextValue = selectCtrl.readValue();
27785 var isNotPrimitive = ngOptions.trackBy || multiple;
27786 if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
27787 ngModelCtrl.$setViewValue(nextValue);
27788 ngModelCtrl.$render();
27798 require: ['select', 'ngModel'],
27800 pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
27801 // Deactivate the SelectController.register method to prevent
27802 // option directives from accidentally registering themselves
27803 // (and unwanted $destroy handlers etc.)
27804 ctrls[0].registerOption = noop;
27806 post: ngOptionsPostLink
27813 * @name ngPluralize
27817 * `ngPluralize` is a directive that displays messages according to en-US localization rules.
27818 * These rules are bundled with angular.js, but can be overridden
27819 * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
27820 * by specifying the mappings between
27821 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
27822 * and the strings to be displayed.
27824 * # Plural categories and explicit number rules
27826 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
27827 * in Angular's default en-US locale: "one" and "other".
27829 * While a plural category may match many numbers (for example, in en-US locale, "other" can match
27830 * any number that is not 1), an explicit number rule can only match one number. For example, the
27831 * explicit number rule for "3" matches the number 3. There are examples of plural categories
27832 * and explicit number rules throughout the rest of this documentation.
27834 * # Configuring ngPluralize
27835 * You configure ngPluralize by providing 2 attributes: `count` and `when`.
27836 * You can also provide an optional attribute, `offset`.
27838 * The value of the `count` attribute can be either a string or an {@link guide/expression
27839 * Angular expression}; these are evaluated on the current scope for its bound value.
27841 * The `when` attribute specifies the mappings between plural categories and the actual
27842 * string to be displayed. The value of the attribute should be a JSON object.
27844 * The following example shows how to configure ngPluralize:
27847 * <ng-pluralize count="personCount"
27848 when="{'0': 'Nobody is viewing.',
27849 * 'one': '1 person is viewing.',
27850 * 'other': '{} people are viewing.'}">
27854 * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
27855 * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
27856 * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
27857 * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
27858 * show "a dozen people are viewing".
27860 * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
27861 * into pluralized strings. In the previous example, Angular will replace `{}` with
27862 * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
27863 * for <span ng-non-bindable>{{numberExpression}}</span>.
27865 * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
27866 * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
27868 * # Configuring ngPluralize with offset
27869 * The `offset` attribute allows further customization of pluralized text, which can result in
27870 * a better user experience. For example, instead of the message "4 people are viewing this document",
27871 * you might display "John, Kate and 2 others are viewing this document".
27872 * The offset attribute allows you to offset a number by any desired value.
27873 * Let's take a look at an example:
27876 * <ng-pluralize count="personCount" offset=2
27877 * when="{'0': 'Nobody is viewing.',
27878 * '1': '{{person1}} is viewing.',
27879 * '2': '{{person1}} and {{person2}} are viewing.',
27880 * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
27881 * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
27885 * Notice that we are still using two plural categories(one, other), but we added
27886 * three explicit number rules 0, 1 and 2.
27887 * When one person, perhaps John, views the document, "John is viewing" will be shown.
27888 * When three people view the document, no explicit number rule is found, so
27889 * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
27890 * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
27893 * Note that when you specify offsets, you must provide explicit number rules for
27894 * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
27895 * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
27896 * plural categories "one" and "other".
27898 * @param {string|expression} count The variable to be bound to.
27899 * @param {string} when The mapping between plural category to its corresponding strings.
27900 * @param {number=} offset Offset to deduct from the total number.
27903 <example module="pluralizeExample">
27904 <file name="index.html">
27906 angular.module('pluralizeExample', [])
27907 .controller('ExampleController', ['$scope', function($scope) {
27908 $scope.person1 = 'Igor';
27909 $scope.person2 = 'Misko';
27910 $scope.personCount = 1;
27913 <div ng-controller="ExampleController">
27914 <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
27915 <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
27916 <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
27918 <!--- Example with simple pluralization rules for en locale --->
27920 <ng-pluralize count="personCount"
27921 when="{'0': 'Nobody is viewing.',
27922 'one': '1 person is viewing.',
27923 'other': '{} people are viewing.'}">
27924 </ng-pluralize><br>
27926 <!--- Example with offset --->
27928 <ng-pluralize count="personCount" offset=2
27929 when="{'0': 'Nobody is viewing.',
27930 '1': '{{person1}} is viewing.',
27931 '2': '{{person1}} and {{person2}} are viewing.',
27932 'one': '{{person1}}, {{person2}} and one other person are viewing.',
27933 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
27937 <file name="protractor.js" type="protractor">
27938 it('should show correct pluralized string', function() {
27939 var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
27940 var withOffset = element.all(by.css('ng-pluralize')).get(1);
27941 var countInput = element(by.model('personCount'));
27943 expect(withoutOffset.getText()).toEqual('1 person is viewing.');
27944 expect(withOffset.getText()).toEqual('Igor is viewing.');
27946 countInput.clear();
27947 countInput.sendKeys('0');
27949 expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
27950 expect(withOffset.getText()).toEqual('Nobody is viewing.');
27952 countInput.clear();
27953 countInput.sendKeys('2');
27955 expect(withoutOffset.getText()).toEqual('2 people are viewing.');
27956 expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
27958 countInput.clear();
27959 countInput.sendKeys('3');
27961 expect(withoutOffset.getText()).toEqual('3 people are viewing.');
27962 expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
27964 countInput.clear();
27965 countInput.sendKeys('4');
27967 expect(withoutOffset.getText()).toEqual('4 people are viewing.');
27968 expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
27970 it('should show data-bound names', function() {
27971 var withOffset = element.all(by.css('ng-pluralize')).get(1);
27972 var personCount = element(by.model('personCount'));
27973 var person1 = element(by.model('person1'));
27974 var person2 = element(by.model('person2'));
27975 personCount.clear();
27976 personCount.sendKeys('4');
27978 person1.sendKeys('Di');
27980 person2.sendKeys('Vojta');
27981 expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
27986 var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
27988 IS_WHEN = /^when(Minus)?(.+)$/;
27991 link: function(scope, element, attr) {
27992 var numberExp = attr.count,
27993 whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
27994 offset = attr.offset || 0,
27995 whens = scope.$eval(whenExp) || {},
27997 startSymbol = $interpolate.startSymbol(),
27998 endSymbol = $interpolate.endSymbol(),
27999 braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
28000 watchRemover = angular.noop,
28003 forEach(attr, function(expression, attributeName) {
28004 var tmpMatch = IS_WHEN.exec(attributeName);
28006 var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
28007 whens[whenKey] = element.attr(attr.$attr[attributeName]);
28010 forEach(whens, function(expression, key) {
28011 whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
28015 scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
28016 var count = parseFloat(newVal);
28017 var countIsNaN = isNaN(count);
28019 if (!countIsNaN && !(count in whens)) {
28020 // If an explicit number rule such as 1, 2, 3... is defined, just use it.
28021 // Otherwise, check it against pluralization rules in $locale service.
28022 count = $locale.pluralCat(count - offset);
28025 // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
28026 // In JS `NaN !== NaN`, so we have to explicitly check.
28027 if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
28029 var whenExpFn = whensExpFns[count];
28030 if (isUndefined(whenExpFn)) {
28031 if (newVal != null) {
28032 $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
28034 watchRemover = noop;
28035 updateElementText();
28037 watchRemover = scope.$watch(whenExpFn, updateElementText);
28043 function updateElementText(newText) {
28044 element.text(newText || '');
28056 * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
28057 * instance gets its own scope, where the given loop variable is set to the current collection item,
28058 * and `$index` is set to the item index or key.
28060 * Special properties are exposed on the local scope of each template instance, including:
28062 * | Variable | Type | Details |
28063 * |-----------|-----------------|-----------------------------------------------------------------------------|
28064 * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
28065 * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
28066 * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
28067 * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
28068 * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
28069 * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
28071 * <div class="alert alert-info">
28072 * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
28073 * This may be useful when, for instance, nesting ngRepeats.
28077 * # Iterating over object properties
28079 * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
28083 * <div ng-repeat="(key, value) in myObj"> ... </div>
28086 * You need to be aware that the JavaScript specification does not define the order of keys
28087 * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
28088 * used to sort the keys alphabetically.)
28090 * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
28091 * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
28092 * keys in the order in which they were defined, although there are exceptions when keys are deleted
28093 * and reinstated. See the [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
28095 * If this is not desired, the recommended workaround is to convert your object into an array
28096 * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
28097 * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
28098 * or implement a `$watch` on the object yourself.
28101 * # Tracking and Duplicates
28103 * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
28104 * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
28106 * * When an item is added, a new instance of the template is added to the DOM.
28107 * * When an item is removed, its template instance is removed from the DOM.
28108 * * When items are reordered, their respective templates are reordered in the DOM.
28110 * To minimize creation of DOM elements, `ngRepeat` uses a function
28111 * to "keep track" of all items in the collection and their corresponding DOM elements.
28112 * For example, if an item is added to the collection, ngRepeat will know that all other items
28113 * already have DOM elements, and will not re-render them.
28115 * The default tracking function (which tracks items by their identity) does not allow
28116 * duplicate items in arrays. This is because when there are duplicates, it is not possible
28117 * to maintain a one-to-one mapping between collection items and DOM elements.
28119 * If you do need to repeat duplicate items, you can substitute the default tracking behavior
28120 * with your own using the `track by` expression.
28122 * For example, you may track items by the index of each item in the collection, using the
28123 * special scope property `$index`:
28125 * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
28130 * You may also use arbitrary expressions in `track by`, including references to custom functions
28133 * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
28138 * <div class="alert alert-success">
28139 * If you are working with objects that have an identifier property, you should track
28140 * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
28141 * will not have to rebuild the DOM elements for items it has already rendered, even if the
28142 * JavaScript objects in the collection have been substituted for new ones. For large collections,
28143 * this significantly improves rendering performance. If you don't have a unique identifier,
28144 * `track by $index` can also provide a performance boost.
28147 * <div ng-repeat="model in collection track by model.id">
28152 * When no `track by` expression is provided, it is equivalent to tracking by the built-in
28153 * `$id` function, which tracks items by their identity:
28155 * <div ng-repeat="obj in collection track by $id(obj)">
28160 * <div class="alert alert-warning">
28161 * **Note:** `track by` must always be the last expression:
28164 * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
28169 * # Special repeat start and end points
28170 * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
28171 * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
28172 * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
28173 * up to and including the ending HTML tag where **ng-repeat-end** is placed.
28175 * The example below makes use of this feature:
28177 * <header ng-repeat-start="item in items">
28178 * Header {{ item }}
28180 * <div class="body">
28183 * <footer ng-repeat-end>
28184 * Footer {{ item }}
28188 * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
28193 * <div class="body">
28202 * <div class="body">
28210 * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
28211 * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
28214 * **.enter** - when a new item is added to the list or when an item is revealed after a filter
28216 * **.leave** - when an item is removed from the list or when an item is filtered out
28218 * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
28220 * See the example below for defining CSS animations with ngRepeat.
28225 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
28226 * formats are currently supported:
28228 * * `variable in expression` – where variable is the user defined loop variable and `expression`
28229 * is a scope expression giving the collection to enumerate.
28231 * For example: `album in artist.albums`.
28233 * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
28234 * and `expression` is the scope expression giving the collection to enumerate.
28236 * For example: `(name, age) in {'adam':10, 'amalie':12}`.
28238 * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
28239 * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
28240 * is specified, ng-repeat associates elements by identity. It is an error to have
28241 * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
28242 * mapped to the same DOM element, which is not possible.)
28244 * Note that the tracking expression must come last, after any filters, and the alias expression.
28246 * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
28247 * will be associated by item identity in the array.
28249 * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
28250 * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
28251 * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
28252 * element in the same way in the DOM.
28254 * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
28255 * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
28256 * property is same.
28258 * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
28259 * to items in conjunction with a tracking expression.
28261 * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
28262 * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
28263 * when a filter is active on the repeater, but the filtered result set is empty.
28265 * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
28266 * the items have been processed through the filter.
28268 * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
28269 * (and not as operator, inside an expression).
28271 * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
28274 * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
28275 * results by name. New (entering) and removed (leaving) items are animated.
28276 <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
28277 <file name="index.html">
28278 <div ng-controller="repeatController">
28279 I have {{friends.length}} friends. They are:
28280 <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
28281 <ul class="example-animate-container">
28282 <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
28283 [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
28285 <li class="animate-repeat" ng-if="results.length == 0">
28286 <strong>No results found...</strong>
28291 <file name="script.js">
28292 angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
28294 {name:'John', age:25, gender:'boy'},
28295 {name:'Jessie', age:30, gender:'girl'},
28296 {name:'Johanna', age:28, gender:'girl'},
28297 {name:'Joy', age:15, gender:'girl'},
28298 {name:'Mary', age:28, gender:'girl'},
28299 {name:'Peter', age:95, gender:'boy'},
28300 {name:'Sebastian', age:50, gender:'boy'},
28301 {name:'Erika', age:27, gender:'girl'},
28302 {name:'Patrick', age:40, gender:'boy'},
28303 {name:'Samantha', age:60, gender:'girl'}
28307 <file name="animations.css">
28308 .example-animate-container {
28310 border:1px solid black;
28319 box-sizing:border-box;
28322 .animate-repeat.ng-move,
28323 .animate-repeat.ng-enter,
28324 .animate-repeat.ng-leave {
28325 transition:all linear 0.5s;
28328 .animate-repeat.ng-leave.ng-leave-active,
28329 .animate-repeat.ng-move,
28330 .animate-repeat.ng-enter {
28335 .animate-repeat.ng-leave,
28336 .animate-repeat.ng-move.ng-move-active,
28337 .animate-repeat.ng-enter.ng-enter-active {
28342 <file name="protractor.js" type="protractor">
28343 var friends = element.all(by.repeater('friend in friends'));
28345 it('should render initial data set', function() {
28346 expect(friends.count()).toBe(10);
28347 expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
28348 expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
28349 expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
28350 expect(element(by.binding('friends.length')).getText())
28351 .toMatch("I have 10 friends. They are:");
28354 it('should update repeater when filter predicate changes', function() {
28355 expect(friends.count()).toBe(10);
28357 element(by.model('q')).sendKeys('ma');
28359 expect(friends.count()).toBe(2);
28360 expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
28361 expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
28366 var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
28367 var NG_REMOVED = '$$NG_REMOVED';
28368 var ngRepeatMinErr = minErr('ngRepeat');
28370 var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
28371 // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
28372 scope[valueIdentifier] = value;
28373 if (keyIdentifier) scope[keyIdentifier] = key;
28374 scope.$index = index;
28375 scope.$first = (index === 0);
28376 scope.$last = (index === (arrayLength - 1));
28377 scope.$middle = !(scope.$first || scope.$last);
28378 // jshint bitwise: false
28379 scope.$odd = !(scope.$even = (index&1) === 0);
28380 // jshint bitwise: true
28383 var getBlockStart = function(block) {
28384 return block.clone[0];
28387 var getBlockEnd = function(block) {
28388 return block.clone[block.clone.length - 1];
28394 multiElement: true,
28395 transclude: 'element',
28399 compile: function ngRepeatCompile($element, $attr) {
28400 var expression = $attr.ngRepeat;
28401 var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
28403 var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
28406 throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
28410 var lhs = match[1];
28411 var rhs = match[2];
28412 var aliasAs = match[3];
28413 var trackByExp = match[4];
28415 match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
28418 throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
28421 var valueIdentifier = match[3] || match[1];
28422 var keyIdentifier = match[2];
28424 if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
28425 /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
28426 throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
28430 var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
28431 var hashFnLocals = {$id: hashKey};
28434 trackByExpGetter = $parse(trackByExp);
28436 trackByIdArrayFn = function(key, value) {
28437 return hashKey(value);
28439 trackByIdObjFn = function(key) {
28444 return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
28446 if (trackByExpGetter) {
28447 trackByIdExpFn = function(key, value, index) {
28448 // assign key, value, and $index to the locals so that they can be used in hash functions
28449 if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
28450 hashFnLocals[valueIdentifier] = value;
28451 hashFnLocals.$index = index;
28452 return trackByExpGetter($scope, hashFnLocals);
28456 // Store a list of elements from previous run. This is a hash where key is the item from the
28457 // iterator, and the value is objects with following properties.
28458 // - scope: bound scope
28459 // - element: previous element.
28460 // - index: position
28462 // We are using no-proto object so that we don't need to guard against inherited props via
28464 var lastBlockMap = createMap();
28467 $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
28469 previousNode = $element[0], // node that cloned nodes should be inserted after
28470 // initialized to the comment node anchor
28472 // Same as lastBlockMap but it has the current state. It will become the
28473 // lastBlockMap on the next iteration.
28474 nextBlockMap = createMap(),
28476 key, value, // key/value of iteration
28480 block, // last object information {scope, element, id}
28485 $scope[aliasAs] = collection;
28488 if (isArrayLike(collection)) {
28489 collectionKeys = collection;
28490 trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
28492 trackByIdFn = trackByIdExpFn || trackByIdObjFn;
28493 // if object, extract keys, in enumeration order, unsorted
28494 collectionKeys = [];
28495 for (var itemKey in collection) {
28496 if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
28497 collectionKeys.push(itemKey);
28502 collectionLength = collectionKeys.length;
28503 nextBlockOrder = new Array(collectionLength);
28505 // locate existing items
28506 for (index = 0; index < collectionLength; index++) {
28507 key = (collection === collectionKeys) ? index : collectionKeys[index];
28508 value = collection[key];
28509 trackById = trackByIdFn(key, value, index);
28510 if (lastBlockMap[trackById]) {
28511 // found previously seen block
28512 block = lastBlockMap[trackById];
28513 delete lastBlockMap[trackById];
28514 nextBlockMap[trackById] = block;
28515 nextBlockOrder[index] = block;
28516 } else if (nextBlockMap[trackById]) {
28517 // if collision detected. restore lastBlockMap and throw an error
28518 forEach(nextBlockOrder, function(block) {
28519 if (block && block.scope) lastBlockMap[block.id] = block;
28521 throw ngRepeatMinErr('dupes',
28522 "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
28523 expression, trackById, value);
28525 // new never before seen block
28526 nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
28527 nextBlockMap[trackById] = true;
28531 // remove leftover items
28532 for (var blockKey in lastBlockMap) {
28533 block = lastBlockMap[blockKey];
28534 elementsToRemove = getBlockNodes(block.clone);
28535 $animate.leave(elementsToRemove);
28536 if (elementsToRemove[0].parentNode) {
28537 // if the element was not removed yet because of pending animation, mark it as deleted
28538 // so that we can ignore it later
28539 for (index = 0, length = elementsToRemove.length; index < length; index++) {
28540 elementsToRemove[index][NG_REMOVED] = true;
28543 block.scope.$destroy();
28546 // we are not using forEach for perf reasons (trying to avoid #call)
28547 for (index = 0; index < collectionLength; index++) {
28548 key = (collection === collectionKeys) ? index : collectionKeys[index];
28549 value = collection[key];
28550 block = nextBlockOrder[index];
28553 // if we have already seen this object, then we need to reuse the
28554 // associated scope/element
28556 nextNode = previousNode;
28558 // skip nodes that are already pending removal via leave animation
28560 nextNode = nextNode.nextSibling;
28561 } while (nextNode && nextNode[NG_REMOVED]);
28563 if (getBlockStart(block) != nextNode) {
28564 // existing item which got moved
28565 $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
28567 previousNode = getBlockEnd(block);
28568 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
28570 // new item which we don't know about
28571 $transclude(function ngRepeatTransclude(clone, scope) {
28572 block.scope = scope;
28573 // http://jsperf.com/clone-vs-createcomment
28574 var endNode = ngRepeatEndComment.cloneNode(false);
28575 clone[clone.length++] = endNode;
28577 // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
28578 $animate.enter(clone, null, jqLite(previousNode));
28579 previousNode = endNode;
28580 // Note: We only need the first/last node of the cloned nodes.
28581 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
28582 // by a directive with templateUrl when its template arrives.
28583 block.clone = clone;
28584 nextBlockMap[block.id] = block;
28585 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
28589 lastBlockMap = nextBlockMap;
28596 var NG_HIDE_CLASS = 'ng-hide';
28597 var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
28604 * The `ngShow` directive shows or hides the given HTML element based on the expression
28605 * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
28606 * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
28607 * in AngularJS and sets the display style to none (using an !important flag).
28608 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
28611 * <!-- when $scope.myValue is truthy (element is visible) -->
28612 * <div ng-show="myValue"></div>
28614 * <!-- when $scope.myValue is falsy (element is hidden) -->
28615 * <div ng-show="myValue" class="ng-hide"></div>
28618 * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
28619 * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
28620 * from the element causing the element not to appear hidden.
28622 * ## Why is !important used?
28624 * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
28625 * can be easily overridden by heavier selectors. For example, something as simple
28626 * as changing the display style on a HTML list item would make hidden elements appear visible.
28627 * This also becomes a bigger issue when dealing with CSS frameworks.
28629 * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
28630 * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
28631 * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
28633 * ### Overriding `.ng-hide`
28635 * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
28636 * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
28637 * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
28638 * with extra animation classes that can be added.
28641 * .ng-hide:not(.ng-hide-animate) {
28642 * /* this is just another form of hiding an element */
28643 * display: block!important;
28644 * position: absolute;
28650 * By default you don't need to override in CSS anything and the animations will work around the display style.
28652 * ## A note about animations with `ngShow`
28654 * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
28655 * is true and false. This system works like the animation system present with ngClass except that
28656 * you must also include the !important flag to override the display property
28657 * so that you can perform an animation when the element is hidden during the time of the animation.
28661 * //a working example can be found at the bottom of this page
28663 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
28664 * /* this is required as of 1.3x to properly
28665 * apply all styling in a show/hide animation */
28666 * transition: 0s linear all;
28669 * .my-element.ng-hide-add-active,
28670 * .my-element.ng-hide-remove-active {
28671 * /* the transition is defined in the active class */
28672 * transition: 1s linear all;
28675 * .my-element.ng-hide-add { ... }
28676 * .my-element.ng-hide-add.ng-hide-add-active { ... }
28677 * .my-element.ng-hide-remove { ... }
28678 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
28681 * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
28682 * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
28685 * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
28686 * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
28689 * @param {expression} ngShow If the {@link guide/expression expression} is truthy
28690 * then the element is shown or hidden respectively.
28693 <example module="ngAnimate" deps="angular-animate.js" animations="true">
28694 <file name="index.html">
28695 Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
28698 <div class="check-element animate-show" ng-show="checked">
28699 <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
28704 <div class="check-element animate-show" ng-hide="checked">
28705 <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
28709 <file name="glyphicons.css">
28710 @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
28712 <file name="animations.css">
28717 border: 1px solid black;
28721 .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
28722 transition: all linear 0.5s;
28725 .animate-show.ng-hide {
28733 border: 1px solid black;
28737 <file name="protractor.js" type="protractor">
28738 var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
28739 var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
28741 it('should check ng-show / ng-hide', function() {
28742 expect(thumbsUp.isDisplayed()).toBeFalsy();
28743 expect(thumbsDown.isDisplayed()).toBeTruthy();
28745 element(by.model('checked')).click();
28747 expect(thumbsUp.isDisplayed()).toBeTruthy();
28748 expect(thumbsDown.isDisplayed()).toBeFalsy();
28753 var ngShowDirective = ['$animate', function($animate) {
28756 multiElement: true,
28757 link: function(scope, element, attr) {
28758 scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
28759 // we're adding a temporary, animation-specific class for ng-hide since this way
28760 // we can control when the element is actually displayed on screen without having
28761 // to have a global/greedy CSS selector that breaks when other animations are run.
28762 // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
28763 $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
28764 tempClasses: NG_HIDE_IN_PROGRESS_CLASS
28778 * The `ngHide` directive shows or hides the given HTML element based on the expression
28779 * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
28780 * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
28781 * in AngularJS and sets the display style to none (using an !important flag).
28782 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
28785 * <!-- when $scope.myValue is truthy (element is hidden) -->
28786 * <div ng-hide="myValue" class="ng-hide"></div>
28788 * <!-- when $scope.myValue is falsy (element is visible) -->
28789 * <div ng-hide="myValue"></div>
28792 * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
28793 * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
28794 * from the element causing the element not to appear hidden.
28796 * ## Why is !important used?
28798 * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
28799 * can be easily overridden by heavier selectors. For example, something as simple
28800 * as changing the display style on a HTML list item would make hidden elements appear visible.
28801 * This also becomes a bigger issue when dealing with CSS frameworks.
28803 * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
28804 * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
28805 * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
28807 * ### Overriding `.ng-hide`
28809 * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
28810 * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
28815 * /* this is just another form of hiding an element */
28816 * display: block!important;
28817 * position: absolute;
28823 * By default you don't need to override in CSS anything and the animations will work around the display style.
28825 * ## A note about animations with `ngHide`
28827 * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
28828 * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
28829 * CSS class is added and removed for you instead of your own CSS class.
28833 * //a working example can be found at the bottom of this page
28835 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
28836 * transition: 0.5s linear all;
28839 * .my-element.ng-hide-add { ... }
28840 * .my-element.ng-hide-add.ng-hide-add-active { ... }
28841 * .my-element.ng-hide-remove { ... }
28842 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
28845 * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
28846 * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
28849 * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
28850 * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
28853 * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
28854 * the element is shown or hidden respectively.
28857 <example module="ngAnimate" deps="angular-animate.js" animations="true">
28858 <file name="index.html">
28859 Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
28862 <div class="check-element animate-hide" ng-show="checked">
28863 <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
28868 <div class="check-element animate-hide" ng-hide="checked">
28869 <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
28873 <file name="glyphicons.css">
28874 @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
28876 <file name="animations.css">
28878 transition: all linear 0.5s;
28882 border: 1px solid black;
28886 .animate-hide.ng-hide {
28894 border: 1px solid black;
28898 <file name="protractor.js" type="protractor">
28899 var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
28900 var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
28902 it('should check ng-show / ng-hide', function() {
28903 expect(thumbsUp.isDisplayed()).toBeFalsy();
28904 expect(thumbsDown.isDisplayed()).toBeTruthy();
28906 element(by.model('checked')).click();
28908 expect(thumbsUp.isDisplayed()).toBeTruthy();
28909 expect(thumbsDown.isDisplayed()).toBeFalsy();
28914 var ngHideDirective = ['$animate', function($animate) {
28917 multiElement: true,
28918 link: function(scope, element, attr) {
28919 scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
28920 // The comment inside of the ngShowDirective explains why we add and
28921 // remove a temporary class for the show/hide animation
28922 $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
28923 tempClasses: NG_HIDE_IN_PROGRESS_CLASS
28936 * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
28939 * @param {expression} ngStyle
28941 * {@link guide/expression Expression} which evals to an
28942 * object whose keys are CSS style names and values are corresponding values for those CSS
28945 * Since some CSS style names are not valid keys for an object, they must be quoted.
28946 * See the 'background-color' style in the example below.
28950 <file name="index.html">
28951 <input type="button" value="set color" ng-click="myStyle={color:'red'}">
28952 <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
28953 <input type="button" value="clear" ng-click="myStyle={}">
28955 <span ng-style="myStyle">Sample Text</span>
28956 <pre>myStyle={{myStyle}}</pre>
28958 <file name="style.css">
28963 <file name="protractor.js" type="protractor">
28964 var colorSpan = element(by.css('span'));
28966 it('should check ng-style', function() {
28967 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
28968 element(by.css('input[value=\'set color\']')).click();
28969 expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
28970 element(by.css('input[value=clear]')).click();
28971 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
28976 var ngStyleDirective = ngDirective(function(scope, element, attr) {
28977 scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
28978 if (oldStyles && (newStyles !== oldStyles)) {
28979 forEach(oldStyles, function(val, style) { element.css(style, '');});
28981 if (newStyles) element.css(newStyles);
28991 * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
28992 * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
28993 * as specified in the template.
28995 * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
28996 * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
28997 * matches the value obtained from the evaluated expression. In other words, you define a container element
28998 * (where you place the directive), place an expression on the **`on="..."` attribute**
28999 * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
29000 * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
29001 * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
29002 * attribute is displayed.
29004 * <div class="alert alert-info">
29005 * Be aware that the attribute values to match against cannot be expressions. They are interpreted
29006 * as literal string values to match against.
29007 * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
29008 * value of the expression `$scope.someVal`.
29012 * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
29013 * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
29018 * <ANY ng-switch="expression">
29019 * <ANY ng-switch-when="matchValue1">...</ANY>
29020 * <ANY ng-switch-when="matchValue2">...</ANY>
29021 * <ANY ng-switch-default>...</ANY>
29028 * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
29029 * On child elements add:
29031 * * `ngSwitchWhen`: the case statement to match against. If match then this
29032 * case will be displayed. If the same match appears multiple times, all the
29033 * elements will be displayed.
29034 * * `ngSwitchDefault`: the default case when no other case match. If there
29035 * are multiple default cases, all of them will be displayed when no other
29040 <example module="switchExample" deps="angular-animate.js" animations="true">
29041 <file name="index.html">
29042 <div ng-controller="ExampleController">
29043 <select ng-model="selection" ng-options="item for item in items">
29045 <code>selection={{selection}}</code>
29047 <div class="animate-switch-container"
29048 ng-switch on="selection">
29049 <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
29050 <div class="animate-switch" ng-switch-when="home">Home Span</div>
29051 <div class="animate-switch" ng-switch-default>default</div>
29055 <file name="script.js">
29056 angular.module('switchExample', ['ngAnimate'])
29057 .controller('ExampleController', ['$scope', function($scope) {
29058 $scope.items = ['settings', 'home', 'other'];
29059 $scope.selection = $scope.items[0];
29062 <file name="animations.css">
29063 .animate-switch-container {
29066 border:1px solid black;
29075 .animate-switch.ng-animate {
29076 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
29085 .animate-switch.ng-leave.ng-leave-active,
29086 .animate-switch.ng-enter {
29089 .animate-switch.ng-leave,
29090 .animate-switch.ng-enter.ng-enter-active {
29094 <file name="protractor.js" type="protractor">
29095 var switchElem = element(by.css('[ng-switch]'));
29096 var select = element(by.model('selection'));
29098 it('should start in settings', function() {
29099 expect(switchElem.getText()).toMatch(/Settings Div/);
29101 it('should change to home', function() {
29102 select.all(by.css('option')).get(1).click();
29103 expect(switchElem.getText()).toMatch(/Home Span/);
29105 it('should select default', function() {
29106 select.all(by.css('option')).get(2).click();
29107 expect(switchElem.getText()).toMatch(/default/);
29112 var ngSwitchDirective = ['$animate', function($animate) {
29114 require: 'ngSwitch',
29116 // asks for $scope to fool the BC controller module
29117 controller: ['$scope', function ngSwitchController() {
29120 link: function(scope, element, attr, ngSwitchController) {
29121 var watchExpr = attr.ngSwitch || attr.on,
29122 selectedTranscludes = [],
29123 selectedElements = [],
29124 previousLeaveAnimations = [],
29125 selectedScopes = [];
29127 var spliceFactory = function(array, index) {
29128 return function() { array.splice(index, 1); };
29131 scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
29133 for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
29134 $animate.cancel(previousLeaveAnimations[i]);
29136 previousLeaveAnimations.length = 0;
29138 for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
29139 var selected = getBlockNodes(selectedElements[i].clone);
29140 selectedScopes[i].$destroy();
29141 var promise = previousLeaveAnimations[i] = $animate.leave(selected);
29142 promise.then(spliceFactory(previousLeaveAnimations, i));
29145 selectedElements.length = 0;
29146 selectedScopes.length = 0;
29148 if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
29149 forEach(selectedTranscludes, function(selectedTransclude) {
29150 selectedTransclude.transclude(function(caseElement, selectedScope) {
29151 selectedScopes.push(selectedScope);
29152 var anchor = selectedTransclude.element;
29153 caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
29154 var block = { clone: caseElement };
29156 selectedElements.push(block);
29157 $animate.enter(caseElement, anchor.parent(), anchor);
29166 var ngSwitchWhenDirective = ngDirective({
29167 transclude: 'element',
29169 require: '^ngSwitch',
29170 multiElement: true,
29171 link: function(scope, element, attrs, ctrl, $transclude) {
29172 ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
29173 ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
29177 var ngSwitchDefaultDirective = ngDirective({
29178 transclude: 'element',
29180 require: '^ngSwitch',
29181 multiElement: true,
29182 link: function(scope, element, attr, ctrl, $transclude) {
29183 ctrl.cases['?'] = (ctrl.cases['?'] || []);
29184 ctrl.cases['?'].push({ transclude: $transclude, element: element });
29190 * @name ngTransclude
29194 * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
29196 * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
29197 * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
29199 * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
29200 * content of this element will be removed before the transcluded content is inserted.
29201 * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
29202 * that no transcluded content is provided.
29206 * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
29207 * or its value is the same as the name of the attribute then the default slot is used.
29210 * ### Basic transclusion
29211 * This example demonstrates basic transclusion of content into a component directive.
29212 * <example name="simpleTranscludeExample" module="transcludeExample">
29213 * <file name="index.html">
29215 * angular.module('transcludeExample', [])
29216 * .directive('pane', function(){
29219 * transclude: true,
29220 * scope: { title:'@' },
29221 * template: '<div style="border: 1px solid black;">' +
29222 * '<div style="background-color: gray">{{title}}</div>' +
29223 * '<ng-transclude></ng-transclude>' +
29227 * .controller('ExampleController', ['$scope', function($scope) {
29228 * $scope.title = 'Lorem Ipsum';
29229 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
29232 * <div ng-controller="ExampleController">
29233 * <input ng-model="title" aria-label="title"> <br/>
29234 * <textarea ng-model="text" aria-label="text"></textarea> <br/>
29235 * <pane title="{{title}}">{{text}}</pane>
29238 * <file name="protractor.js" type="protractor">
29239 * it('should have transcluded', function() {
29240 * var titleElement = element(by.model('title'));
29241 * titleElement.clear();
29242 * titleElement.sendKeys('TITLE');
29243 * var textElement = element(by.model('text'));
29244 * textElement.clear();
29245 * textElement.sendKeys('TEXT');
29246 * expect(element(by.binding('title')).getText()).toEqual('TITLE');
29247 * expect(element(by.binding('text')).getText()).toEqual('TEXT');
29253 * ### Transclude fallback content
29254 * This example shows how to use `NgTransclude` with fallback content, that
29255 * is displayed if no transcluded content is provided.
29257 * <example module="transcludeFallbackContentExample">
29258 * <file name="index.html">
29260 * angular.module('transcludeFallbackContentExample', [])
29261 * .directive('myButton', function(){
29264 * transclude: true,
29266 * template: '<button style="cursor: pointer;">' +
29267 * '<ng-transclude>' +
29268 * '<b style="color: red;">Button1</b>' +
29269 * '</ng-transclude>' +
29274 * <!-- fallback button content -->
29275 * <my-button id="fallback"></my-button>
29276 * <!-- modified button content -->
29277 * <my-button id="modified">
29278 * <i style="color: green;">Button2</i>
29281 * <file name="protractor.js" type="protractor">
29282 * it('should have different transclude element content', function() {
29283 * expect(element(by.id('fallback')).getText()).toBe('Button1');
29284 * expect(element(by.id('modified')).getText()).toBe('Button2');
29290 * ### Multi-slot transclusion
29291 * This example demonstrates using multi-slot transclusion in a component directive.
29292 * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
29293 * <file name="index.html">
29295 * .title, .footer {
29296 * background-color: gray
29299 * <div ng-controller="ExampleController">
29300 * <input ng-model="title" aria-label="title"> <br/>
29301 * <textarea ng-model="text" aria-label="text"></textarea> <br/>
29303 * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
29304 * <pane-body><p>{{text}}</p></pane-body>
29308 * <file name="app.js">
29309 * angular.module('multiSlotTranscludeExample', [])
29310 * .directive('pane', function(){
29314 * 'title': '?paneTitle',
29315 * 'body': 'paneBody',
29316 * 'footer': '?paneFooter'
29318 * template: '<div style="border: 1px solid black;">' +
29319 * '<div class="title" ng-transclude="title">Fallback Title</div>' +
29320 * '<div ng-transclude="body"></div>' +
29321 * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
29325 * .controller('ExampleController', ['$scope', function($scope) {
29326 * $scope.title = 'Lorem Ipsum';
29327 * $scope.link = "https://google.com";
29328 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
29331 * <file name="protractor.js" type="protractor">
29332 * it('should have transcluded the title and the body', function() {
29333 * var titleElement = element(by.model('title'));
29334 * titleElement.clear();
29335 * titleElement.sendKeys('TITLE');
29336 * var textElement = element(by.model('text'));
29337 * textElement.clear();
29338 * textElement.sendKeys('TEXT');
29339 * expect(element(by.css('.title')).getText()).toEqual('TITLE');
29340 * expect(element(by.binding('text')).getText()).toEqual('TEXT');
29341 * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
29346 var ngTranscludeMinErr = minErr('ngTransclude');
29347 var ngTranscludeDirective = ngDirective({
29349 link: function($scope, $element, $attrs, controller, $transclude) {
29351 if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
29352 // If the attribute is of the form: `ng-transclude="ng-transclude"`
29353 // then treat it like the default
29354 $attrs.ngTransclude = '';
29357 function ngTranscludeCloneAttachFn(clone) {
29358 if (clone.length) {
29360 $element.append(clone);
29364 if (!$transclude) {
29365 throw ngTranscludeMinErr('orphan',
29366 'Illegal use of ngTransclude directive in the template! ' +
29367 'No parent directive that requires a transclusion found. ' +
29369 startingTag($element));
29372 // If there is no slot name defined or the slot name is not optional
29373 // then transclude the slot
29374 var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
29375 $transclude(ngTranscludeCloneAttachFn, null, slotName);
29385 * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
29386 * template can be used by {@link ng.directive:ngInclude `ngInclude`},
29387 * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
29388 * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
29389 * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
29391 * @param {string} type Must be set to `'text/ng-template'`.
29392 * @param {string} id Cache name of the template.
29396 <file name="index.html">
29397 <script type="text/ng-template" id="/tpl.html">
29398 Content of the template.
29401 <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
29402 <div id="tpl-content" ng-include src="currentTpl"></div>
29404 <file name="protractor.js" type="protractor">
29405 it('should load template defined inside script tag', function() {
29406 element(by.css('#tpl-link')).click();
29407 expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
29412 var scriptDirective = ['$templateCache', function($templateCache) {
29416 compile: function(element, attr) {
29417 if (attr.type == 'text/ng-template') {
29418 var templateUrl = attr.id,
29419 text = element[0].text;
29421 $templateCache.put(templateUrl, text);
29427 var noopNgModelController = { $setViewValue: noop, $render: noop };
29429 function chromeHack(optionElement) {
29430 // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
29431 // Adding an <option selected="selected"> element to a <select required="required"> should
29432 // automatically select the new element
29433 if (optionElement[0].hasAttribute('selected')) {
29434 optionElement[0].selected = true;
29440 * @name select.SelectController
29442 * The controller for the `<select>` directive. This provides support for reading
29443 * and writing the selected value(s) of the control and also coordinates dynamically
29444 * added `<option>` elements, perhaps by an `ngRepeat` directive.
29446 var SelectController =
29447 ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
29450 optionsMap = new HashMap();
29452 // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
29453 self.ngModelCtrl = noopNgModelController;
29455 // The "unknown" option is one that is prepended to the list if the viewValue
29456 // does not match any of the options. When it is rendered the value of the unknown
29457 // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
29459 // We can't just jqLite('<option>') since jqLite is not smart enough
29460 // to create it in <select> and IE barfs otherwise.
29461 self.unknownOption = jqLite(document.createElement('option'));
29462 self.renderUnknownOption = function(val) {
29463 var unknownVal = '? ' + hashKey(val) + ' ?';
29464 self.unknownOption.val(unknownVal);
29465 $element.prepend(self.unknownOption);
29466 $element.val(unknownVal);
29469 $scope.$on('$destroy', function() {
29470 // disable unknown option so that we don't do work when the whole select is being destroyed
29471 self.renderUnknownOption = noop;
29474 self.removeUnknownOption = function() {
29475 if (self.unknownOption.parent()) self.unknownOption.remove();
29479 // Read the value of the select control, the implementation of this changes depending
29480 // upon whether the select can have multiple values and whether ngOptions is at work.
29481 self.readValue = function readSingleValue() {
29482 self.removeUnknownOption();
29483 return $element.val();
29487 // Write the value to the select control, the implementation of this changes depending
29488 // upon whether the select can have multiple values and whether ngOptions is at work.
29489 self.writeValue = function writeSingleValue(value) {
29490 if (self.hasOption(value)) {
29491 self.removeUnknownOption();
29492 $element.val(value);
29493 if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
29495 if (value == null && self.emptyOption) {
29496 self.removeUnknownOption();
29499 self.renderUnknownOption(value);
29505 // Tell the select control that an option, with the given value, has been added
29506 self.addOption = function(value, element) {
29507 // Skip comment nodes, as they only pollute the `optionsMap`
29508 if (element[0].nodeType === NODE_TYPE_COMMENT) return;
29510 assertNotHasOwnProperty(value, '"option value"');
29511 if (value === '') {
29512 self.emptyOption = element;
29514 var count = optionsMap.get(value) || 0;
29515 optionsMap.put(value, count + 1);
29516 self.ngModelCtrl.$render();
29517 chromeHack(element);
29520 // Tell the select control that an option, with the given value, has been removed
29521 self.removeOption = function(value) {
29522 var count = optionsMap.get(value);
29525 optionsMap.remove(value);
29526 if (value === '') {
29527 self.emptyOption = undefined;
29530 optionsMap.put(value, count - 1);
29535 // Check whether the select control has an option matching the given value
29536 self.hasOption = function(value) {
29537 return !!optionsMap.get(value);
29541 self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
29543 if (interpolateValueFn) {
29544 // The value attribute is interpolated
29546 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
29547 if (isDefined(oldVal)) {
29548 self.removeOption(oldVal);
29551 self.addOption(newVal, optionElement);
29553 } else if (interpolateTextFn) {
29554 // The text content is interpolated
29555 optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
29556 optionAttrs.$set('value', newVal);
29557 if (oldVal !== newVal) {
29558 self.removeOption(oldVal);
29560 self.addOption(newVal, optionElement);
29563 // The value attribute is static
29564 self.addOption(optionAttrs.value, optionElement);
29567 optionElement.on('$destroy', function() {
29568 self.removeOption(optionAttrs.value);
29569 self.ngModelCtrl.$render();
29580 * HTML `SELECT` element with angular data-binding.
29582 * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
29583 * between the scope and the `<select>` control (including setting default values).
29584 * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
29585 * {@link ngOptions `ngOptions`} directives.
29587 * When an item in the `<select>` menu is selected, the value of the selected option will be bound
29588 * to the model identified by the `ngModel` directive. With static or repeated options, this is
29589 * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
29590 * If you want dynamic value attributes, you can use interpolation inside the value attribute.
29592 * <div class="alert alert-warning">
29593 * Note that the value of a `select` directive used without `ngOptions` is always a string.
29594 * When the model needs to be bound to a non-string value, you must either explicitly convert it
29595 * using a directive (see example below) or use `ngOptions` to specify the set of options.
29596 * This is because an option element can only be bound to string values at present.
29599 * If the viewValue of `ngModel` does not match any of the options, then the control
29600 * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
29602 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
29603 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
29604 * option. See example below for demonstration.
29606 * <div class="alert alert-info">
29607 * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
29608 * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
29609 * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
29610 * comprehension expression, and additionally in reducing memory and increasing speed by not creating
29611 * a new scope for each repeated instance.
29615 * @param {string} ngModel Assignable angular expression to data-bind to.
29616 * @param {string=} name Property name of the form under which the control is published.
29617 * @param {string=} multiple Allows multiple options to be selected. The selected values will be
29618 * bound to the model as an array.
29619 * @param {string=} required Sets `required` validation error key if the value is not entered.
29620 * @param {string=} ngRequired Adds required attribute and required validation constraint to
29621 * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
29622 * when you want to data-bind to the required attribute.
29623 * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
29624 * interaction with the select element.
29625 * @param {string=} ngOptions sets the options that the select is populated with and defines what is
29626 * set on the model on selection. See {@link ngOptions `ngOptions`}.
29629 * ### Simple `select` elements with static options
29631 * <example name="static-select" module="staticSelect">
29632 * <file name="index.html">
29633 * <div ng-controller="ExampleController">
29634 * <form name="myForm">
29635 * <label for="singleSelect"> Single select: </label><br>
29636 * <select name="singleSelect" ng-model="data.singleSelect">
29637 * <option value="option-1">Option 1</option>
29638 * <option value="option-2">Option 2</option>
29641 * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
29642 * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
29643 * <option value="">---Please select---</option> <!-- not selected / blank option -->
29644 * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
29645 * <option value="option-2">Option 2</option>
29647 * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
29648 * <tt>singleSelect = {{data.singleSelect}}</tt>
29651 * <label for="multipleSelect"> Multiple select: </label><br>
29652 * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
29653 * <option value="option-1">Option 1</option>
29654 * <option value="option-2">Option 2</option>
29655 * <option value="option-3">Option 3</option>
29657 * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
29661 * <file name="app.js">
29662 * angular.module('staticSelect', [])
29663 * .controller('ExampleController', ['$scope', function($scope) {
29665 * singleSelect: null,
29666 * multipleSelect: [],
29667 * option1: 'option-1',
29670 * $scope.forceUnknownOption = function() {
29671 * $scope.data.singleSelect = 'nonsense';
29677 * ### Using `ngRepeat` to generate `select` options
29678 * <example name="ngrepeat-select" module="ngrepeatSelect">
29679 * <file name="index.html">
29680 * <div ng-controller="ExampleController">
29681 * <form name="myForm">
29682 * <label for="repeatSelect"> Repeat select: </label>
29683 * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
29684 * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
29688 * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
29691 * <file name="app.js">
29692 * angular.module('ngrepeatSelect', [])
29693 * .controller('ExampleController', ['$scope', function($scope) {
29695 * repeatSelect: null,
29696 * availableOptions: [
29697 * {id: '1', name: 'Option A'},
29698 * {id: '2', name: 'Option B'},
29699 * {id: '3', name: 'Option C'}
29707 * ### Using `select` with `ngOptions` and setting a default value
29708 * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
29710 * <example name="select-with-default-values" module="defaultValueSelect">
29711 * <file name="index.html">
29712 * <div ng-controller="ExampleController">
29713 * <form name="myForm">
29714 * <label for="mySelect">Make a choice:</label>
29715 * <select name="mySelect" id="mySelect"
29716 * ng-options="option.name for option in data.availableOptions track by option.id"
29717 * ng-model="data.selectedOption"></select>
29720 * <tt>option = {{data.selectedOption}}</tt><br/>
29723 * <file name="app.js">
29724 * angular.module('defaultValueSelect', [])
29725 * .controller('ExampleController', ['$scope', function($scope) {
29727 * availableOptions: [
29728 * {id: '1', name: 'Option A'},
29729 * {id: '2', name: 'Option B'},
29730 * {id: '3', name: 'Option C'}
29732 * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
29739 * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
29741 * <example name="select-with-non-string-options" module="nonStringSelect">
29742 * <file name="index.html">
29743 * <select ng-model="model.id" convert-to-number>
29744 * <option value="0">Zero</option>
29745 * <option value="1">One</option>
29746 * <option value="2">Two</option>
29750 * <file name="app.js">
29751 * angular.module('nonStringSelect', [])
29752 * .run(function($rootScope) {
29753 * $rootScope.model = { id: 2 };
29755 * .directive('convertToNumber', function() {
29757 * require: 'ngModel',
29758 * link: function(scope, element, attrs, ngModel) {
29759 * ngModel.$parsers.push(function(val) {
29760 * return parseInt(val, 10);
29762 * ngModel.$formatters.push(function(val) {
29769 * <file name="protractor.js" type="protractor">
29770 * it('should initialize to model', function() {
29771 * var select = element(by.css('select'));
29772 * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
29778 var selectDirective = function() {
29782 require: ['select', '?ngModel'],
29783 controller: SelectController,
29786 pre: selectPreLink,
29787 post: selectPostLink
29791 function selectPreLink(scope, element, attr, ctrls) {
29793 // if ngModel is not defined, we don't need to do anything
29794 var ngModelCtrl = ctrls[1];
29795 if (!ngModelCtrl) return;
29797 var selectCtrl = ctrls[0];
29799 selectCtrl.ngModelCtrl = ngModelCtrl;
29801 // When the selected item(s) changes we delegate getting the value of the select control
29802 // to the `readValue` method, which can be changed if the select can have multiple
29803 // selected values or if the options are being generated by `ngOptions`
29804 element.on('change', function() {
29805 scope.$apply(function() {
29806 ngModelCtrl.$setViewValue(selectCtrl.readValue());
29810 // If the select allows multiple values then we need to modify how we read and write
29811 // values from and to the control; also what it means for the value to be empty and
29812 // we have to add an extra watch since ngModel doesn't work well with arrays - it
29813 // doesn't trigger rendering if only an item in the array changes.
29814 if (attr.multiple) {
29816 // Read value now needs to check each option to see if it is selected
29817 selectCtrl.readValue = function readMultipleValue() {
29819 forEach(element.find('option'), function(option) {
29820 if (option.selected) {
29821 array.push(option.value);
29827 // Write value now needs to set the selected property of each matching option
29828 selectCtrl.writeValue = function writeMultipleValue(value) {
29829 var items = new HashMap(value);
29830 forEach(element.find('option'), function(option) {
29831 option.selected = isDefined(items.get(option.value));
29835 // we have to do it on each watch since ngModel watches reference, but
29836 // we need to work of an array, so we need to see if anything was inserted/removed
29837 var lastView, lastViewRef = NaN;
29838 scope.$watch(function selectMultipleWatch() {
29839 if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
29840 lastView = shallowCopy(ngModelCtrl.$viewValue);
29841 ngModelCtrl.$render();
29843 lastViewRef = ngModelCtrl.$viewValue;
29846 // If we are a multiple select then value is now a collection
29847 // so the meaning of $isEmpty changes
29848 ngModelCtrl.$isEmpty = function(value) {
29849 return !value || value.length === 0;
29855 function selectPostLink(scope, element, attrs, ctrls) {
29856 // if ngModel is not defined, we don't need to do anything
29857 var ngModelCtrl = ctrls[1];
29858 if (!ngModelCtrl) return;
29860 var selectCtrl = ctrls[0];
29862 // We delegate rendering to the `writeValue` method, which can be changed
29863 // if the select can have multiple selected values or if the options are being
29864 // generated by `ngOptions`.
29865 // This must be done in the postLink fn to prevent $render to be called before
29866 // all nodes have been linked correctly.
29867 ngModelCtrl.$render = function() {
29868 selectCtrl.writeValue(ngModelCtrl.$viewValue);
29874 // The option directive is purely designed to communicate the existence (or lack of)
29875 // of dynamically created (and destroyed) option elements to their containing select
29876 // directive via its controller.
29877 var optionDirective = ['$interpolate', function($interpolate) {
29881 compile: function(element, attr) {
29882 if (isDefined(attr.value)) {
29883 // If the value attribute is defined, check if it contains an interpolation
29884 var interpolateValueFn = $interpolate(attr.value, true);
29886 // If the value attribute is not defined then we fall back to the
29887 // text content of the option element, which may be interpolated
29888 var interpolateTextFn = $interpolate(element.text(), true);
29889 if (!interpolateTextFn) {
29890 attr.$set('value', element.text());
29894 return function(scope, element, attr) {
29895 // This is an optimization over using ^^ since we don't want to have to search
29896 // all the way to the root of the DOM for every single option element
29897 var selectCtrlName = '$selectController',
29898 parent = element.parent(),
29899 selectCtrl = parent.data(selectCtrlName) ||
29900 parent.parent().data(selectCtrlName); // in case we are in optgroup
29903 selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
29910 var styleDirective = valueFn({
29921 * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
29922 * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
29923 * applied to custom controls.
29925 * The directive sets the `required` attribute on the element if the Angular expression inside
29926 * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
29927 * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
29930 * The validator will set the `required` error key to true if the `required` attribute is set and
29931 * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
29932 * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
29933 * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
29934 * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
29937 * <example name="ngRequiredDirective" module="ngRequiredExample">
29938 * <file name="index.html">
29940 * angular.module('ngRequiredExample', [])
29941 * .controller('ExampleController', ['$scope', function($scope) {
29942 * $scope.required = true;
29945 * <div ng-controller="ExampleController">
29946 * <form name="form">
29947 * <label for="required">Toggle required: </label>
29948 * <input type="checkbox" ng-model="required" id="required" />
29950 * <label for="input">This input must be filled if `required` is true: </label>
29951 * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
29953 * required error set? = <code>{{form.input.$error.required}}</code><br>
29954 * model = <code>{{model}}</code>
29958 * <file name="protractor.js" type="protractor">
29959 var required = element(by.binding('form.input.$error.required'));
29960 var model = element(by.binding('model'));
29961 var input = element(by.id('input'));
29963 it('should set the required error', function() {
29964 expect(required.getText()).toContain('true');
29966 input.sendKeys('123');
29967 expect(required.getText()).not.toContain('true');
29968 expect(model.getText()).toContain('123');
29973 var requiredDirective = function() {
29976 require: '?ngModel',
29977 link: function(scope, elm, attr, ctrl) {
29979 attr.required = true; // force truthy in case we are on non input element
29981 ctrl.$validators.required = function(modelValue, viewValue) {
29982 return !attr.required || !ctrl.$isEmpty(viewValue);
29985 attr.$observe('required', function() {
29998 * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
29999 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
30001 * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
30002 * does not match a RegExp which is obtained by evaluating the Angular expression given in the
30003 * `ngPattern` attribute value:
30004 * * If the expression evaluates to a RegExp object, then this is used directly.
30005 * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
30006 * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
30008 * <div class="alert alert-info">
30009 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
30010 * start at the index of the last search's match, thus not taking the whole input value into
30014 * <div class="alert alert-info">
30015 * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
30019 * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
30023 * The `ngPattern` attribute must be an expression, while the `pattern` value must be
30030 * <example name="ngPatternDirective" module="ngPatternExample">
30031 * <file name="index.html">
30033 * angular.module('ngPatternExample', [])
30034 * .controller('ExampleController', ['$scope', function($scope) {
30035 * $scope.regex = '\\d+';
30038 * <div ng-controller="ExampleController">
30039 * <form name="form">
30040 * <label for="regex">Set a pattern (regex string): </label>
30041 * <input type="text" ng-model="regex" id="regex" />
30043 * <label for="input">This input is restricted by the current pattern: </label>
30044 * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
30046 * input valid? = <code>{{form.input.$valid}}</code><br>
30047 * model = <code>{{model}}</code>
30051 * <file name="protractor.js" type="protractor">
30052 var model = element(by.binding('model'));
30053 var input = element(by.id('input'));
30055 it('should validate the input with the default pattern', function() {
30056 input.sendKeys('aaa');
30057 expect(model.getText()).not.toContain('aaa');
30059 input.clear().then(function() {
30060 input.sendKeys('123');
30061 expect(model.getText()).toContain('123');
30067 var patternDirective = function() {
30070 require: '?ngModel',
30071 link: function(scope, elm, attr, ctrl) {
30074 var regexp, patternExp = attr.ngPattern || attr.pattern;
30075 attr.$observe('pattern', function(regex) {
30076 if (isString(regex) && regex.length > 0) {
30077 regex = new RegExp('^' + regex + '$');
30080 if (regex && !regex.test) {
30081 throw minErr('ngPattern')('noregexp',
30082 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
30083 regex, startingTag(elm));
30086 regexp = regex || undefined;
30090 ctrl.$validators.pattern = function(modelValue, viewValue) {
30091 // HTML5 pattern constraint validates the input value, so we validate the viewValue
30092 return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
30100 * @name ngMaxlength
30104 * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
30105 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
30107 * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
30108 * is longer than the integer obtained by evaluating the Angular expression given in the
30109 * `ngMaxlength` attribute value.
30111 * <div class="alert alert-info">
30112 * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
30116 * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
30117 * validation is not available.
30120 * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
30127 * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
30128 * <file name="index.html">
30130 * angular.module('ngMaxlengthExample', [])
30131 * .controller('ExampleController', ['$scope', function($scope) {
30132 * $scope.maxlength = 5;
30135 * <div ng-controller="ExampleController">
30136 * <form name="form">
30137 * <label for="maxlength">Set a maxlength: </label>
30138 * <input type="number" ng-model="maxlength" id="maxlength" />
30140 * <label for="input">This input is restricted by the current maxlength: </label>
30141 * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
30143 * input valid? = <code>{{form.input.$valid}}</code><br>
30144 * model = <code>{{model}}</code>
30148 * <file name="protractor.js" type="protractor">
30149 var model = element(by.binding('model'));
30150 var input = element(by.id('input'));
30152 it('should validate the input with the default maxlength', function() {
30153 input.sendKeys('abcdef');
30154 expect(model.getText()).not.toContain('abcdef');
30156 input.clear().then(function() {
30157 input.sendKeys('abcde');
30158 expect(model.getText()).toContain('abcde');
30164 var maxlengthDirective = function() {
30167 require: '?ngModel',
30168 link: function(scope, elm, attr, ctrl) {
30171 var maxlength = -1;
30172 attr.$observe('maxlength', function(value) {
30173 var intVal = toInt(value);
30174 maxlength = isNaN(intVal) ? -1 : intVal;
30177 ctrl.$validators.maxlength = function(modelValue, viewValue) {
30178 return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
30186 * @name ngMinlength
30190 * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
30191 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
30193 * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
30194 * is shorter than the integer obtained by evaluating the Angular expression given in the
30195 * `ngMinlength` attribute value.
30197 * <div class="alert alert-info">
30198 * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
30202 * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
30203 * validation is not available.
30206 * The `ngMinlength` value must be an expression, while the `minlength` value must be
30213 * <example name="ngMinlengthDirective" module="ngMinlengthExample">
30214 * <file name="index.html">
30216 * angular.module('ngMinlengthExample', [])
30217 * .controller('ExampleController', ['$scope', function($scope) {
30218 * $scope.minlength = 3;
30221 * <div ng-controller="ExampleController">
30222 * <form name="form">
30223 * <label for="minlength">Set a minlength: </label>
30224 * <input type="number" ng-model="minlength" id="minlength" />
30226 * <label for="input">This input is restricted by the current minlength: </label>
30227 * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
30229 * input valid? = <code>{{form.input.$valid}}</code><br>
30230 * model = <code>{{model}}</code>
30234 * <file name="protractor.js" type="protractor">
30235 var model = element(by.binding('model'));
30236 var input = element(by.id('input'));
30238 it('should validate the input with the default minlength', function() {
30239 input.sendKeys('ab');
30240 expect(model.getText()).not.toContain('ab');
30242 input.sendKeys('abc');
30243 expect(model.getText()).toContain('abc');
30248 var minlengthDirective = function() {
30251 require: '?ngModel',
30252 link: function(scope, elm, attr, ctrl) {
30256 attr.$observe('minlength', function(value) {
30257 minlength = toInt(value) || 0;
30260 ctrl.$validators.minlength = function(modelValue, viewValue) {
30261 return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
30267 if (window.angular.bootstrap) {
30268 //AngularJS is already loaded, so we can return here...
30269 console.log('WARNING: Tried to load angular more than once.');
30273 //try to bind to jquery now so that one can write jqLite(document).ready()
30274 //but we will rebind on bootstrap again.
30277 publishExternalAPI(angular);
30279 angular.module("ngLocale", [], ["$provide", function($provide) {
30280 var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
30281 function getDecimals(n) {
30283 var i = n.indexOf('.');
30284 return (i == -1) ? 0 : n.length - i - 1;
30287 function getVF(n, opt_precision) {
30288 var v = opt_precision;
30290 if (undefined === v) {
30291 v = Math.min(getDecimals(n), 3);
30294 var base = Math.pow(10, v);
30295 var f = ((n * base) | 0) % base;
30296 return {v: v, f: f};
30299 $provide.value("$locale", {
30300 "DATETIME_FORMATS": {
30322 "FIRSTDAYOFWEEK": 6,
30360 "STANDALONEMONTH": [
30378 "fullDate": "EEEE, MMMM d, y",
30379 "longDate": "MMMM d, y",
30380 "medium": "MMM d, y h:mm:ss a",
30381 "mediumDate": "MMM d, y",
30382 "mediumTime": "h:mm:ss a",
30383 "short": "M/d/yy h:mm a",
30384 "shortDate": "M/d/yy",
30385 "shortTime": "h:mm a"
30387 "NUMBER_FORMATS": {
30388 "CURRENCY_SYM": "$",
30389 "DECIMAL_SEP": ".",
30409 "negPre": "-\u00a4",
30411 "posPre": "\u00a4",
30417 "localeID": "en_US",
30418 "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
30422 jqLite(document).ready(function() {
30423 angularInit(document, bootstrap);
30426 })(window, document);
30428 !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');