2 * @license AngularJS v1.5.0-beta.2
3 * (c) 2010-2015 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-beta.2/' +
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';
193 * @name angular.lowercase
197 * @description Converts the specified string to lowercase.
198 * @param {string} string String to be converted to lowercase.
199 * @returns {string} Lowercased string.
201 var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
202 var hasOwnProperty = Object.prototype.hasOwnProperty;
206 * @name angular.uppercase
210 * @description Converts the specified string to uppercase.
211 * @param {string} string String to be converted to uppercase.
212 * @returns {string} Uppercased string.
214 var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
217 var manualLowercase = function(s) {
218 /* jshint bitwise: false */
220 ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
223 var manualUppercase = function(s) {
224 /* jshint bitwise: false */
226 ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
231 // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
232 // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
233 // with correct but slower alternatives.
234 if ('i' !== 'I'.toLowerCase()) {
235 lowercase = manualLowercase;
236 uppercase = manualUppercase;
241 msie, // holds major version number for IE, or NaN if UA is not IE.
242 jqLite, // delay binding since jQuery could be loaded after us.
243 jQuery, // delay binding
247 toString = Object.prototype.toString,
248 getPrototypeOf = Object.getPrototypeOf,
249 ngMinErr = minErr('ng'),
252 angular = window.angular || (window.angular = {}),
257 * documentMode is an IE-only property
258 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
260 msie = document.documentMode;
266 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
269 function isArrayLike(obj) {
271 // `null`, `undefined` and `window` are not array-like
272 if (obj == null || isWindow(obj)) return false;
274 // arrays, strings and jQuery/jqLite objects are array like
275 // * jqLite is either the jQuery or jqLite constructor function
276 // * we have to check the existance of jqLite first as this method is called
277 // via the forEach method when constructing the jqLite object in the first place
278 if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
280 // Support: iOS 8.2 (not reproducible in simulator)
281 // "length" in obj used to prevent JIT error (gh-11508)
282 var length = "length" in Object(obj) && obj.length;
284 // NodeList objects (with `item` method) and
285 // other objects with suitable length characteristics are array-like
286 return isNumber(length) &&
287 (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
292 * @name angular.forEach
297 * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
298 * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
299 * is the value of an object property or an array element, `key` is the object property key or
300 * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
302 * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
303 * using the `hasOwnProperty` method.
306 * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
307 * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
308 * return the value provided.
311 var values = {name: 'misko', gender: 'male'};
313 angular.forEach(values, function(value, key) {
314 this.push(key + ': ' + value);
316 expect(log).toEqual(['name: misko', 'gender: male']);
319 * @param {Object|Array} obj Object to iterate over.
320 * @param {Function} iterator Iterator function.
321 * @param {Object=} context Object to become context (`this`) for the iterator function.
322 * @returns {Object|Array} Reference to `obj`.
325 function forEach(obj, iterator, context) {
328 if (isFunction(obj)) {
330 // Need to check if hasOwnProperty exists,
331 // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
332 if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
333 iterator.call(context, obj[key], key, obj);
336 } else if (isArray(obj) || isArrayLike(obj)) {
337 var isPrimitive = typeof obj !== 'object';
338 for (key = 0, length = obj.length; key < length; key++) {
339 if (isPrimitive || key in obj) {
340 iterator.call(context, obj[key], key, obj);
343 } else if (obj.forEach && obj.forEach !== forEach) {
344 obj.forEach(iterator, context, obj);
345 } else if (isBlankObject(obj)) {
346 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
348 iterator.call(context, obj[key], key, obj);
350 } else if (typeof obj.hasOwnProperty === 'function') {
351 // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
353 if (obj.hasOwnProperty(key)) {
354 iterator.call(context, obj[key], key, obj);
358 // Slow path for objects which do not have a method `hasOwnProperty`
360 if (hasOwnProperty.call(obj, key)) {
361 iterator.call(context, obj[key], key, obj);
369 function forEachSorted(obj, iterator, context) {
370 var keys = Object.keys(obj).sort();
371 for (var i = 0; i < keys.length; i++) {
372 iterator.call(context, obj[keys[i]], keys[i]);
379 * when using forEach the params are value, key, but it is often useful to have key, value.
380 * @param {function(string, *)} iteratorFn
381 * @returns {function(*, string)}
383 function reverseParams(iteratorFn) {
384 return function(value, key) { iteratorFn(key, value); };
388 * A consistent way of creating unique IDs in angular.
390 * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
391 * we hit number precision issues in JavaScript.
393 * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
395 * @returns {number} an unique alpha-numeric string
403 * Set or clear the hashkey for an object.
405 * @param h the hashkey (!truthy to delete the hashkey)
407 function setHashKey(obj, h) {
411 delete obj.$$hashKey;
416 function baseExtend(dst, objs, deep) {
417 var h = dst.$$hashKey;
419 for (var i = 0, ii = objs.length; i < ii; ++i) {
421 if (!isObject(obj) && !isFunction(obj)) continue;
422 var keys = Object.keys(obj);
423 for (var j = 0, jj = keys.length; j < jj; j++) {
427 if (deep && isObject(src)) {
429 dst[key] = new Date(src.valueOf());
430 } else if (isRegExp(src)) {
431 dst[key] = new RegExp(src);
432 } else if (src.nodeName) {
433 dst[key] = src.cloneNode(true);
434 } else if (isElement(src)) {
435 dst[key] = src.clone();
437 if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
438 baseExtend(dst[key], [src], true);
452 * @name angular.extend
457 * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
458 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
459 * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
461 * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
462 * {@link angular.merge} for this.
464 * @param {Object} dst Destination object.
465 * @param {...Object} src Source object(s).
466 * @returns {Object} Reference to `dst`.
468 function extend(dst) {
469 return baseExtend(dst, slice.call(arguments, 1), false);
475 * @name angular.merge
480 * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
481 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
482 * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
484 * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
485 * objects, performing a deep copy.
487 * @param {Object} dst Destination object.
488 * @param {...Object} src Source object(s).
489 * @returns {Object} Reference to `dst`.
491 function merge(dst) {
492 return baseExtend(dst, slice.call(arguments, 1), true);
497 function toInt(str) {
498 return parseInt(str, 10);
502 function inherit(parent, extra) {
503 return extend(Object.create(parent), extra);
513 * A function that performs no operations. This function can be useful when writing code in the
516 function foo(callback) {
517 var result = calculateResult();
518 (callback || angular.noop)(result);
528 * @name angular.identity
533 * A function that returns its first argument. This function is useful when writing code in the
537 function transformer(transformationFn, value) {
538 return (transformationFn || angular.identity)(value);
541 * @param {*} value to be returned.
542 * @returns {*} the value passed in.
544 function identity($) {return $;}
545 identity.$inject = [];
548 function valueFn(value) {return function() {return value;};}
550 function hasCustomToString(obj) {
551 return isFunction(obj.toString) && obj.toString !== toString;
557 * @name angular.isUndefined
562 * Determines if a reference is undefined.
564 * @param {*} value Reference to check.
565 * @returns {boolean} True if `value` is undefined.
567 function isUndefined(value) {return typeof value === 'undefined';}
572 * @name angular.isDefined
577 * Determines if a reference is defined.
579 * @param {*} value Reference to check.
580 * @returns {boolean} True if `value` is defined.
582 function isDefined(value) {return typeof value !== 'undefined';}
587 * @name angular.isObject
592 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
593 * considered to be objects. Note that JavaScript arrays are objects.
595 * @param {*} value Reference to check.
596 * @returns {boolean} True if `value` is an `Object` but not `null`.
598 function isObject(value) {
599 // http://jsperf.com/isobject4
600 return value !== null && typeof value === 'object';
605 * Determine if a value is an object with a null prototype
607 * @returns {boolean} True if `value` is an `Object` with a null prototype
609 function isBlankObject(value) {
610 return value !== null && typeof value === 'object' && !getPrototypeOf(value);
616 * @name angular.isString
621 * Determines if a reference is a `String`.
623 * @param {*} value Reference to check.
624 * @returns {boolean} True if `value` is a `String`.
626 function isString(value) {return typeof value === 'string';}
631 * @name angular.isNumber
636 * Determines if a reference is a `Number`.
638 * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
640 * If you wish to exclude these then you can use the native
641 * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
644 * @param {*} value Reference to check.
645 * @returns {boolean} True if `value` is a `Number`.
647 function isNumber(value) {return typeof value === 'number';}
652 * @name angular.isDate
657 * Determines if a value is a date.
659 * @param {*} value Reference to check.
660 * @returns {boolean} True if `value` is a `Date`.
662 function isDate(value) {
663 return toString.call(value) === '[object Date]';
669 * @name angular.isArray
674 * Determines if a reference is an `Array`.
676 * @param {*} value Reference to check.
677 * @returns {boolean} True if `value` is an `Array`.
679 var isArray = Array.isArray;
683 * @name angular.isFunction
688 * Determines if a reference is a `Function`.
690 * @param {*} value Reference to check.
691 * @returns {boolean} True if `value` is a `Function`.
693 function isFunction(value) {return typeof value === 'function';}
697 * Determines if a value is a regular expression object.
700 * @param {*} value Reference to check.
701 * @returns {boolean} True if `value` is a `RegExp`.
703 function isRegExp(value) {
704 return toString.call(value) === '[object RegExp]';
709 * Checks if `obj` is a window object.
712 * @param {*} obj Object to check
713 * @returns {boolean} True if `obj` is a window obj.
715 function isWindow(obj) {
716 return obj && obj.window === obj;
720 function isScope(obj) {
721 return obj && obj.$evalAsync && obj.$watch;
725 function isFile(obj) {
726 return toString.call(obj) === '[object File]';
730 function isFormData(obj) {
731 return toString.call(obj) === '[object FormData]';
735 function isBlob(obj) {
736 return toString.call(obj) === '[object Blob]';
740 function isBoolean(value) {
741 return typeof value === 'boolean';
745 function isPromiseLike(obj) {
746 return obj && isFunction(obj.then);
750 var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
751 function isTypedArray(value) {
752 return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
756 var trim = function(value) {
757 return isString(value) ? value.trim() : value;
761 // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
762 // Prereq: s is a string.
763 var escapeForRegexp = function(s) {
764 return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
765 replace(/\x08/g, '\\x08');
771 * @name angular.isElement
776 * Determines if a reference is a DOM element (or wrapped jQuery element).
778 * @param {*} value Reference to check.
779 * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
781 function isElement(node) {
783 (node.nodeName // we are a direct element
784 || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
788 * @param str 'key1,key2,...'
789 * @returns {object} in the form of {key1:true, key2:true, ...}
791 function makeMap(str) {
792 var obj = {}, items = str.split(","), i;
793 for (i = 0; i < items.length; i++) {
794 obj[items[i]] = true;
800 function nodeName_(element) {
801 return lowercase(element.nodeName || (element[0] && element[0].nodeName));
804 function includes(array, obj) {
805 return Array.prototype.indexOf.call(array, obj) != -1;
808 function arrayRemove(array, value) {
809 var index = array.indexOf(value);
811 array.splice(index, 1);
823 * Creates a deep copy of `source`, which should be an object or an array.
825 * * If no destination is supplied, a copy of the object or array is created.
826 * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
827 * are deleted and then all elements/properties from the source are copied to it.
828 * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
829 * * If `source` is identical to 'destination' an exception will be thrown.
831 * @param {*} source The source that will be used to make a copy.
832 * Can be any type, including primitives, `null`, and `undefined`.
833 * @param {(Object|Array)=} destination Destination into which the source is copied. If
834 * provided, must be of the same type as `source`.
835 * @returns {*} The copy or updated `destination`, if `destination` was specified.
838 <example module="copyExample">
839 <file name="index.html">
840 <div ng-controller="ExampleController">
841 <form novalidate class="simple-form">
842 Name: <input type="text" ng-model="user.name" /><br />
843 E-mail: <input type="email" ng-model="user.email" /><br />
844 Gender: <input type="radio" ng-model="user.gender" value="male" />male
845 <input type="radio" ng-model="user.gender" value="female" />female<br />
846 <button ng-click="reset()">RESET</button>
847 <button ng-click="update(user)">SAVE</button>
849 <pre>form = {{user | json}}</pre>
850 <pre>master = {{master | json}}</pre>
854 angular.module('copyExample', [])
855 .controller('ExampleController', ['$scope', function($scope) {
858 $scope.update = function(user) {
859 // Example with 1 argument
860 $scope.master= angular.copy(user);
863 $scope.reset = function() {
864 // Example with 2 arguments
865 angular.copy($scope.master, $scope.user);
874 function copy(source, destination) {
875 var stackSource = [];
879 if (isTypedArray(destination)) {
880 throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
882 if (source === destination) {
883 throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
886 // Empty the destination object
887 if (isArray(destination)) {
888 destination.length = 0;
890 forEach(destination, function(value, key) {
891 if (key !== '$$hashKey') {
892 delete destination[key];
897 stackSource.push(source);
898 stackDest.push(destination);
899 return copyRecurse(source, destination);
902 return copyElement(source);
904 function copyRecurse(source, destination) {
905 var h = destination.$$hashKey;
907 if (isArray(source)) {
908 for (var i = 0, ii = source.length; i < ii; i++) {
909 destination.push(copyElement(source[i]));
911 } else if (isBlankObject(source)) {
912 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
913 for (key in source) {
914 destination[key] = copyElement(source[key]);
916 } else if (source && typeof source.hasOwnProperty === 'function') {
917 // Slow path, which must rely on hasOwnProperty
918 for (key in source) {
919 if (source.hasOwnProperty(key)) {
920 destination[key] = copyElement(source[key]);
924 // Slowest path --- hasOwnProperty can't be called as a method
925 for (key in source) {
926 if (hasOwnProperty.call(source, key)) {
927 destination[key] = copyElement(source[key]);
931 setHashKey(destination, h);
935 function copyElement(source) {
937 if (!isObject(source)) {
941 // Already copied values
942 var index = stackSource.indexOf(source);
944 return stackDest[index];
947 if (isWindow(source) || isScope(source)) {
948 throw ngMinErr('cpws',
949 "Can't copy! Making copies of Window or Scope instances is not supported.");
952 var needsRecurse = false;
955 if (isArray(source)) {
958 } else if (isTypedArray(source)) {
959 destination = new source.constructor(source);
960 } else if (isDate(source)) {
961 destination = new Date(source.getTime());
962 } else if (isRegExp(source)) {
963 destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
964 destination.lastIndex = source.lastIndex;
965 } else if (isFunction(source.cloneNode)) {
966 destination = source.cloneNode(true);
968 destination = Object.create(getPrototypeOf(source));
972 stackSource.push(source);
973 stackDest.push(destination);
976 ? copyRecurse(source, destination)
982 * Creates a shallow copy of an object, an array or a primitive.
984 * Assumes that there are no proto properties for objects.
986 function shallowCopy(src, dst) {
990 for (var i = 0, ii = src.length; i < ii; i++) {
993 } else if (isObject(src)) {
996 for (var key in src) {
997 if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
1009 * @name angular.equals
1014 * Determines if two objects or two values are equivalent. Supports value types, regular
1015 * expressions, arrays and objects.
1017 * Two objects or values are considered equivalent if at least one of the following is true:
1019 * * Both objects or values pass `===` comparison.
1020 * * Both objects or values are of the same type and all of their properties are equal by
1021 * comparing them with `angular.equals`.
1022 * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
1023 * * Both values represent the same regular expression (In JavaScript,
1024 * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
1025 * representation matches).
1027 * During a property comparison, properties of `function` type and properties with names
1028 * that begin with `$` are ignored.
1030 * Scope and DOMWindow objects are being compared only by identify (`===`).
1032 * @param {*} o1 Object or value to compare.
1033 * @param {*} o2 Object or value to compare.
1034 * @returns {boolean} True if arguments are equal.
1036 function equals(o1, o2) {
1037 if (o1 === o2) return true;
1038 if (o1 === null || o2 === null) return false;
1039 if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
1040 var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
1042 if (t1 == 'object') {
1044 if (!isArray(o2)) return false;
1045 if ((length = o1.length) == o2.length) {
1046 for (key = 0; key < length; key++) {
1047 if (!equals(o1[key], o2[key])) return false;
1051 } else if (isDate(o1)) {
1052 if (!isDate(o2)) return false;
1053 return equals(o1.getTime(), o2.getTime());
1054 } else if (isRegExp(o1)) {
1055 return isRegExp(o2) ? o1.toString() == o2.toString() : false;
1057 if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
1058 isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
1059 keySet = createMap();
1061 if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
1062 if (!equals(o1[key], o2[key])) return false;
1066 if (!(key in keySet) &&
1067 key.charAt(0) !== '$' &&
1068 isDefined(o2[key]) &&
1069 !isFunction(o2[key])) return false;
1078 var csp = function() {
1079 if (!isDefined(csp.rules)) {
1082 var ngCspElement = (document.querySelector('[ng-csp]') ||
1083 document.querySelector('[data-ng-csp]'));
1086 var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
1087 ngCspElement.getAttribute('data-ng-csp');
1089 noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
1090 noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
1094 noUnsafeEval: noUnsafeEval(),
1095 noInlineStyle: false
1102 function noUnsafeEval() {
1104 /* jshint -W031, -W054 */
1106 /* jshint +W031, +W054 */
1120 * @param {string=} ngJq the name of the library available under `window`
1121 * to be used for angular.element
1123 * Use this directive to force the angular.element library. This should be
1124 * used to force either jqLite by leaving ng-jq blank or setting the name of
1125 * the jquery variable under window (eg. jQuery).
1127 * Since angular looks for this directive when it is loaded (doesn't wait for the
1128 * DOMContentLoaded event), it must be placed on an element that comes before the script
1129 * which loads angular. Also, only the first instance of `ng-jq` will be used and all
1133 * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
1142 * This example shows how to use a jQuery based library of a different name.
1143 * The library name must be available at the top most 'window'.
1146 <html ng-app ng-jq="jQueryLib">
1152 var jq = function() {
1153 if (isDefined(jq.name_)) return jq.name_;
1155 var i, ii = ngAttrPrefixes.length, prefix, name;
1156 for (i = 0; i < ii; ++i) {
1157 prefix = ngAttrPrefixes[i];
1158 if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
1159 name = el.getAttribute(prefix + 'jq');
1164 return (jq.name_ = name);
1167 function concat(array1, array2, index) {
1168 return array1.concat(slice.call(array2, index));
1171 function sliceArgs(args, startIndex) {
1172 return slice.call(args, startIndex || 0);
1179 * @name angular.bind
1184 * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
1185 * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
1186 * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
1187 * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
1189 * @param {Object} self Context which `fn` should be evaluated in.
1190 * @param {function()} fn Function to be bound.
1191 * @param {...*} args Optional arguments to be prebound to the `fn` function call.
1192 * @returns {function()} Function that wraps the `fn` with all the specified bindings.
1195 function bind(self, fn) {
1196 var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
1197 if (isFunction(fn) && !(fn instanceof RegExp)) {
1198 return curryArgs.length
1200 return arguments.length
1201 ? fn.apply(self, concat(curryArgs, arguments, 0))
1202 : fn.apply(self, curryArgs);
1205 return arguments.length
1206 ? fn.apply(self, arguments)
1210 // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
1216 function toJsonReplacer(key, value) {
1219 if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
1221 } else if (isWindow(value)) {
1223 } else if (value && document === value) {
1225 } else if (isScope(value)) {
1235 * @name angular.toJson
1240 * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
1241 * stripped since angular uses this notation internally.
1243 * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
1244 * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
1245 * If set to an integer, the JSON output will contain that many spaces per indentation.
1246 * @returns {string|undefined} JSON-ified string representing `obj`.
1248 function toJson(obj, pretty) {
1249 if (typeof obj === 'undefined') return undefined;
1250 if (!isNumber(pretty)) {
1251 pretty = pretty ? 2 : null;
1253 return JSON.stringify(obj, toJsonReplacer, pretty);
1259 * @name angular.fromJson
1264 * Deserializes a JSON string.
1266 * @param {string} json JSON string to deserialize.
1267 * @returns {Object|Array|string|number} Deserialized JSON string.
1269 function fromJson(json) {
1270 return isString(json)
1276 function timezoneToOffset(timezone, fallback) {
1277 var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
1278 return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
1282 function addDateMinutes(date, minutes) {
1283 date = new Date(date.getTime());
1284 date.setMinutes(date.getMinutes() + minutes);
1289 function convertTimezoneToLocal(date, timezone, reverse) {
1290 reverse = reverse ? -1 : 1;
1291 var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
1292 return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
1297 * @returns {string} Returns the string representation of the element.
1299 function startingTag(element) {
1300 element = jqLite(element).clone();
1302 // turns out IE does not let you set .html() on elements which
1303 // are not allowed to have children. So we just ignore it.
1306 var elemHtml = jqLite('<div>').append(element).html();
1308 return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
1310 match(/^(<[^>]+>)/)[1].
1311 replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
1313 return lowercase(elemHtml);
1319 /////////////////////////////////////////////////
1322 * Tries to decode the URI component without throwing an exception.
1325 * @param str value potential URI component to check.
1326 * @returns {boolean} True if `value` can be decoded
1327 * with the decodeURIComponent function.
1329 function tryDecodeURIComponent(value) {
1331 return decodeURIComponent(value);
1333 // Ignore any invalid uri component
1339 * Parses an escaped url query string into key-value pairs.
1340 * @returns {Object.<string,boolean|Array>}
1342 function parseKeyValue(/**string*/keyValue) {
1344 forEach((keyValue || "").split('&'), function(keyValue) {
1345 var splitPoint, key, val;
1347 key = keyValue = keyValue.replace(/\+/g,'%20');
1348 splitPoint = keyValue.indexOf('=');
1349 if (splitPoint !== -1) {
1350 key = keyValue.substring(0, splitPoint);
1351 val = keyValue.substring(splitPoint + 1);
1353 key = tryDecodeURIComponent(key);
1354 if (isDefined(key)) {
1355 val = isDefined(val) ? tryDecodeURIComponent(val) : true;
1356 if (!hasOwnProperty.call(obj, key)) {
1358 } else if (isArray(obj[key])) {
1361 obj[key] = [obj[key],val];
1369 function toKeyValue(obj) {
1371 forEach(obj, function(value, key) {
1372 if (isArray(value)) {
1373 forEach(value, function(arrayValue) {
1374 parts.push(encodeUriQuery(key, true) +
1375 (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
1378 parts.push(encodeUriQuery(key, true) +
1379 (value === true ? '' : '=' + encodeUriQuery(value, true)));
1382 return parts.length ? parts.join('&') : '';
1387 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
1388 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
1391 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
1392 * pct-encoded = "%" HEXDIG HEXDIG
1393 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
1394 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
1395 * / "*" / "+" / "," / ";" / "="
1397 function encodeUriSegment(val) {
1398 return encodeUriQuery(val, true).
1399 replace(/%26/gi, '&').
1400 replace(/%3D/gi, '=').
1401 replace(/%2B/gi, '+');
1406 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
1407 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
1408 * encoded per http://tools.ietf.org/html/rfc3986:
1409 * query = *( pchar / "/" / "?" )
1410 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
1411 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
1412 * pct-encoded = "%" HEXDIG HEXDIG
1413 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
1414 * / "*" / "+" / "," / ";" / "="
1416 function encodeUriQuery(val, pctEncodeSpaces) {
1417 return encodeURIComponent(val).
1418 replace(/%40/gi, '@').
1419 replace(/%3A/gi, ':').
1420 replace(/%24/g, '$').
1421 replace(/%2C/gi, ',').
1422 replace(/%3B/gi, ';').
1423 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
1426 var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
1428 function getNgAttribute(element, ngAttr) {
1429 var attr, i, ii = ngAttrPrefixes.length;
1430 for (i = 0; i < ii; ++i) {
1431 attr = ngAttrPrefixes[i] + ngAttr;
1432 if (isString(attr = element.getAttribute(attr))) {
1445 * @param {angular.Module} ngApp an optional application
1446 * {@link angular.module module} name to load.
1447 * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
1448 * created in "strict-di" mode. This means that the application will fail to invoke functions which
1449 * do not use explicit function annotation (and are thus unsuitable for minification), as described
1450 * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
1451 * tracking down the root of these bugs.
1455 * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
1456 * designates the **root element** of the application and is typically placed near the root element
1457 * of the page - e.g. on the `<body>` or `<html>` tags.
1459 * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
1460 * found in the document will be used to define the root element to auto-bootstrap as an
1461 * application. To run multiple applications in an HTML document you must manually bootstrap them using
1462 * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
1464 * You can specify an **AngularJS module** to be used as the root module for the application. This
1465 * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
1466 * should contain the application code needed or have dependencies on other modules that will
1467 * contain the code. See {@link angular.module} for more information.
1469 * In the example below if the `ngApp` directive were not placed on the `html` element then the
1470 * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
1471 * would not be resolved to `3`.
1473 * `ngApp` is the easiest, and most common way to bootstrap an application.
1475 <example module="ngAppDemo">
1476 <file name="index.html">
1477 <div ng-controller="ngAppDemoController">
1478 I can add: {{a}} + {{b}} = {{ a+b }}
1481 <file name="script.js">
1482 angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
1489 * Using `ngStrictDi`, you would see something like this:
1491 <example ng-app-included="true">
1492 <file name="index.html">
1493 <div ng-app="ngAppStrictDemo" ng-strict-di>
1494 <div ng-controller="GoodController1">
1495 I can add: {{a}} + {{b}} = {{ a+b }}
1497 <p>This renders because the controller does not fail to
1498 instantiate, by using explicit annotation style (see
1499 script.js for details)
1503 <div ng-controller="GoodController2">
1504 Name: <input ng-model="name"><br />
1507 <p>This renders because the controller does not fail to
1508 instantiate, by using explicit annotation style
1509 (see script.js for details)
1513 <div ng-controller="BadController">
1514 I can add: {{a}} + {{b}} = {{ a+b }}
1516 <p>The controller could not be instantiated, due to relying
1517 on automatic function annotations (which are disabled in
1518 strict mode). As such, the content of this section is not
1519 interpolated, and there should be an error in your web console.
1524 <file name="script.js">
1525 angular.module('ngAppStrictDemo', [])
1526 // BadController will fail to instantiate, due to relying on automatic function annotation,
1527 // rather than an explicit annotation
1528 .controller('BadController', function($scope) {
1532 // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
1533 // due to using explicit annotations using the array style and $inject property, respectively.
1534 .controller('GoodController1', ['$scope', function($scope) {
1538 .controller('GoodController2', GoodController2);
1539 function GoodController2($scope) {
1540 $scope.name = "World";
1542 GoodController2.$inject = ['$scope'];
1544 <file name="style.css">
1545 div[ng-controller] {
1547 -webkit-border-radius: 4px;
1552 div[ng-controller^=Good] {
1553 border-color: #d6e9c6;
1554 background-color: #dff0d8;
1557 div[ng-controller^=Bad] {
1558 border-color: #ebccd1;
1559 background-color: #f2dede;
1566 function angularInit(element, bootstrap) {
1571 // The element `element` has priority over any other element
1572 forEach(ngAttrPrefixes, function(prefix) {
1573 var name = prefix + 'app';
1575 if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
1576 appElement = element;
1577 module = element.getAttribute(name);
1580 forEach(ngAttrPrefixes, function(prefix) {
1581 var name = prefix + 'app';
1584 if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
1585 appElement = candidate;
1586 module = candidate.getAttribute(name);
1590 config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
1591 bootstrap(appElement, module ? [module] : [], config);
1597 * @name angular.bootstrap
1600 * Use this function to manually start up angular application.
1602 * See: {@link guide/bootstrap Bootstrap}
1604 * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
1605 * They must use {@link ng.directive:ngApp ngApp}.
1607 * Angular will detect if it has been loaded into the browser more than once and only allow the
1608 * first loaded script to be bootstrapped and will report a warning to the browser console for
1609 * each of the subsequent scripts. This prevents strange results in applications, where otherwise
1610 * multiple instances of Angular try to work on the DOM.
1616 * <div ng-controller="WelcomeController">
1620 * <script src="angular.js"></script>
1622 * var app = angular.module('demo', [])
1623 * .controller('WelcomeController', function($scope) {
1624 * $scope.greeting = 'Welcome!';
1626 * angular.bootstrap(document, ['demo']);
1632 * @param {DOMElement} element DOM element which is the root of angular application.
1633 * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
1634 * Each item in the array should be the name of a predefined module or a (DI annotated)
1635 * function that will be invoked by the injector as a `config` block.
1636 * See: {@link angular.module modules}
1637 * @param {Object=} config an object for defining configuration options for the application. The
1638 * following keys are supported:
1640 * * `strictDi` - disable automatic function annotation for the application. This is meant to
1641 * assist in finding bugs which break minified code. Defaults to `false`.
1643 * @returns {auto.$injector} Returns the newly created injector for this app.
1645 function bootstrap(element, modules, config) {
1646 if (!isObject(config)) config = {};
1647 var defaultConfig = {
1650 config = extend(defaultConfig, config);
1651 var doBootstrap = function() {
1652 element = jqLite(element);
1654 if (element.injector()) {
1655 var tag = (element[0] === document) ? 'document' : startingTag(element);
1656 //Encode angle brackets to prevent input from being sanitized to empty string #8683
1659 "App Already Bootstrapped with this Element '{0}'",
1660 tag.replace(/</,'<').replace(/>/,'>'));
1663 modules = modules || [];
1664 modules.unshift(['$provide', function($provide) {
1665 $provide.value('$rootElement', element);
1668 if (config.debugInfoEnabled) {
1669 // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
1670 modules.push(['$compileProvider', function($compileProvider) {
1671 $compileProvider.debugInfoEnabled(true);
1675 modules.unshift('ng');
1676 var injector = createInjector(modules, config.strictDi);
1677 injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
1678 function bootstrapApply(scope, element, compile, injector) {
1679 scope.$apply(function() {
1680 element.data('$injector', injector);
1681 compile(element)(scope);
1688 var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
1689 var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
1691 if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
1692 config.debugInfoEnabled = true;
1693 window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
1696 if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
1697 return doBootstrap();
1700 window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
1701 angular.resumeBootstrap = function(extraModules) {
1702 forEach(extraModules, function(module) {
1703 modules.push(module);
1705 return doBootstrap();
1708 if (isFunction(angular.resumeDeferredBootstrap)) {
1709 angular.resumeDeferredBootstrap();
1715 * @name angular.reloadWithDebugInfo
1718 * Use this function to reload the current application with debug information turned on.
1719 * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
1721 * See {@link ng.$compileProvider#debugInfoEnabled} for more.
1723 function reloadWithDebugInfo() {
1724 window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
1725 window.location.reload();
1729 * @name angular.getTestability
1732 * Get the testability service for the instance of Angular on the given
1734 * @param {DOMElement} element DOM element which is the root of angular application.
1736 function getTestability(rootElement) {
1737 var injector = angular.element(rootElement).injector();
1739 throw ngMinErr('test',
1740 'no injector found for element argument to getTestability');
1742 return injector.get('$$testability');
1745 var SNAKE_CASE_REGEXP = /[A-Z]/g;
1746 function snake_case(name, separator) {
1747 separator = separator || '_';
1748 return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
1749 return (pos ? separator : '') + letter.toLowerCase();
1753 var bindJQueryFired = false;
1754 function bindJQuery() {
1755 var originalCleanData;
1757 if (bindJQueryFired) {
1761 // bind to jQuery if present;
1763 jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
1764 !jqName ? undefined : // use jqLite
1765 window[jqName]; // use jQuery specified by `ngJq`
1767 // Use jQuery if it exists with proper functionality, otherwise default to us.
1768 // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
1769 // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
1770 // versions. It will not work for sure with jQuery <1.7, though.
1771 if (jQuery && jQuery.fn.on) {
1774 scope: JQLitePrototype.scope,
1775 isolateScope: JQLitePrototype.isolateScope,
1776 controller: JQLitePrototype.controller,
1777 injector: JQLitePrototype.injector,
1778 inheritedData: JQLitePrototype.inheritedData
1781 // All nodes removed from the DOM via various jQuery APIs like .remove()
1782 // are passed through jQuery.cleanData. Monkey-patch this method to fire
1783 // the $destroy event on all removed nodes.
1784 originalCleanData = jQuery.cleanData;
1785 jQuery.cleanData = function(elems) {
1787 for (var i = 0, elem; (elem = elems[i]) != null; i++) {
1788 events = jQuery._data(elem, "events");
1789 if (events && events.$destroy) {
1790 jQuery(elem).triggerHandler('$destroy');
1793 originalCleanData(elems);
1799 angular.element = jqLite;
1801 // Prevent double-proxying.
1802 bindJQueryFired = true;
1806 * throw error if the argument is falsy.
1808 function assertArg(arg, name, reason) {
1810 throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
1815 function assertArgFn(arg, name, acceptArrayAnnotation) {
1816 if (acceptArrayAnnotation && isArray(arg)) {
1817 arg = arg[arg.length - 1];
1820 assertArg(isFunction(arg), name, 'not a function, got ' +
1821 (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
1826 * throw error if the name given is hasOwnProperty
1827 * @param {String} name the name to test
1828 * @param {String} context the context in which the name is used, such as module or directive
1830 function assertNotHasOwnProperty(name, context) {
1831 if (name === 'hasOwnProperty') {
1832 throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
1837 * Return the value accessible from the object by path. Any undefined traversals are ignored
1838 * @param {Object} obj starting object
1839 * @param {String} path path to traverse
1840 * @param {boolean} [bindFnToScope=true]
1841 * @returns {Object} value as accessible by path
1843 //TODO(misko): this function needs to be removed
1844 function getter(obj, path, bindFnToScope) {
1845 if (!path) return obj;
1846 var keys = path.split('.');
1848 var lastInstance = obj;
1849 var len = keys.length;
1851 for (var i = 0; i < len; i++) {
1854 obj = (lastInstance = obj)[key];
1857 if (!bindFnToScope && isFunction(obj)) {
1858 return bind(lastInstance, obj);
1864 * Return the DOM siblings between the first and last node in the given array.
1865 * @param {Array} array like object
1866 * @returns {Array} the inputted object or a jqLite collection containing the nodes
1868 function getBlockNodes(nodes) {
1869 // TODO(perf): update `nodes` instead of creating a new object?
1870 var node = nodes[0];
1871 var endNode = nodes[nodes.length - 1];
1874 for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
1875 if (blockNodes || nodes[i] !== node) {
1877 blockNodes = jqLite(slice.call(nodes, 0, i));
1879 blockNodes.push(node);
1883 return blockNodes || nodes;
1888 * Creates a new object without a prototype. This object is useful for lookup without having to
1889 * guard against prototypically inherited properties via hasOwnProperty.
1891 * Related micro-benchmarks:
1892 * - http://jsperf.com/object-create2
1893 * - http://jsperf.com/proto-map-lookup/2
1894 * - http://jsperf.com/for-in-vs-object-keys2
1898 function createMap() {
1899 return Object.create(null);
1902 var NODE_TYPE_ELEMENT = 1;
1903 var NODE_TYPE_ATTRIBUTE = 2;
1904 var NODE_TYPE_TEXT = 3;
1905 var NODE_TYPE_COMMENT = 8;
1906 var NODE_TYPE_DOCUMENT = 9;
1907 var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
1911 * @name angular.Module
1915 * Interface for configuring angular {@link angular.module modules}.
1918 function setupModuleLoader(window) {
1920 var $injectorMinErr = minErr('$injector');
1921 var ngMinErr = minErr('ng');
1923 function ensure(obj, name, factory) {
1924 return obj[name] || (obj[name] = factory());
1927 var angular = ensure(window, 'angular', Object);
1929 // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
1930 angular.$$minErr = angular.$$minErr || minErr;
1932 return ensure(angular, 'module', function() {
1933 /** @type {Object.<string, angular.Module>} */
1938 * @name angular.module
1942 * The `angular.module` is a global place for creating, registering and retrieving Angular
1944 * All modules (angular core or 3rd party) that should be available to an application must be
1945 * registered using this mechanism.
1947 * Passing one argument retrieves an existing {@link angular.Module},
1948 * whereas passing more than one argument creates a new {@link angular.Module}
1953 * A module is a collection of services, directives, controllers, filters, and configuration information.
1954 * `angular.module` is used to configure the {@link auto.$injector $injector}.
1957 * // Create a new module
1958 * var myModule = angular.module('myModule', []);
1960 * // register a new service
1961 * myModule.value('appName', 'MyCoolApp');
1963 * // configure existing services inside initialization blocks.
1964 * myModule.config(['$locationProvider', function($locationProvider) {
1965 * // Configure existing providers
1966 * $locationProvider.hashPrefix('!');
1970 * Then you can create an injector and load your modules like this:
1973 * var injector = angular.injector(['ng', 'myModule'])
1976 * However it's more likely that you'll just use
1977 * {@link ng.directive:ngApp ngApp} or
1978 * {@link angular.bootstrap} to simplify this process for you.
1980 * @param {!string} name The name of the module to create or retrieve.
1981 * @param {!Array.<string>=} requires If specified then new module is being created. If
1982 * unspecified then the module is being retrieved for further configuration.
1983 * @param {Function=} configFn Optional configuration function for the module. Same as
1984 * {@link angular.Module#config Module#config()}.
1985 * @returns {module} new module with the {@link angular.Module} api.
1987 return function module(name, requires, configFn) {
1988 var assertNotHasOwnProperty = function(name, context) {
1989 if (name === 'hasOwnProperty') {
1990 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
1994 assertNotHasOwnProperty(name, 'module');
1995 if (requires && modules.hasOwnProperty(name)) {
1996 modules[name] = null;
1998 return ensure(modules, name, function() {
2000 throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
2001 "the module name or forgot to load it. If registering a module ensure that you " +
2002 "specify the dependencies as the second argument.", name);
2005 /** @type {!Array.<Array.<*>>} */
2006 var invokeQueue = [];
2008 /** @type {!Array.<Function>} */
2009 var configBlocks = [];
2011 /** @type {!Array.<Function>} */
2014 var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
2016 /** @type {angular.Module} */
2017 var moduleInstance = {
2019 _invokeQueue: invokeQueue,
2020 _configBlocks: configBlocks,
2021 _runBlocks: runBlocks,
2025 * @name angular.Module#requires
2029 * Holds the list of modules which the injector will load before the current module is
2036 * @name angular.Module#name
2040 * Name of the module.
2047 * @name angular.Module#provider
2049 * @param {string} name service name
2050 * @param {Function} providerType Construction function for creating new instance of the
2053 * See {@link auto.$provide#provider $provide.provider()}.
2055 provider: invokeLaterAndSetModuleName('$provide', 'provider'),
2059 * @name angular.Module#factory
2061 * @param {string} name service name
2062 * @param {Function} providerFunction Function for creating new instance of the service.
2064 * See {@link auto.$provide#factory $provide.factory()}.
2066 factory: invokeLaterAndSetModuleName('$provide', 'factory'),
2070 * @name angular.Module#service
2072 * @param {string} name service name
2073 * @param {Function} constructor A constructor function that will be instantiated.
2075 * See {@link auto.$provide#service $provide.service()}.
2077 service: invokeLaterAndSetModuleName('$provide', 'service'),
2081 * @name angular.Module#value
2083 * @param {string} name service name
2084 * @param {*} object Service instance object.
2086 * See {@link auto.$provide#value $provide.value()}.
2088 value: invokeLater('$provide', 'value'),
2092 * @name angular.Module#constant
2094 * @param {string} name constant name
2095 * @param {*} object Constant value.
2097 * Because the constants are fixed, they get applied before other provide methods.
2098 * See {@link auto.$provide#constant $provide.constant()}.
2100 constant: invokeLater('$provide', 'constant', 'unshift'),
2104 * @name angular.Module#decorator
2106 * @param {string} The name of the service to decorate.
2107 * @param {Function} This function will be invoked when the service needs to be
2108 * instantiated and should return the decorated service instance.
2110 * See {@link auto.$provide#decorator $provide.decorator()}.
2112 decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
2116 * @name angular.Module#animation
2118 * @param {string} name animation name
2119 * @param {Function} animationFactory Factory function for creating new instance of an
2123 * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
2126 * Defines an animation hook that can be later used with
2127 * {@link $animate $animate} service and directives that use this service.
2130 * module.animation('.animation-name', function($inject1, $inject2) {
2132 * eventName : function(element, done) {
2133 * //code to run the animation
2134 * //once complete, then run done()
2135 * return function cancellationFunction(element) {
2136 * //code to cancel the animation
2143 * See {@link ng.$animateProvider#register $animateProvider.register()} and
2144 * {@link ngAnimate ngAnimate module} for more information.
2146 animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
2150 * @name angular.Module#filter
2152 * @param {string} name Filter name - this must be a valid angular expression identifier
2153 * @param {Function} filterFactory Factory function for creating new instance of filter.
2155 * See {@link ng.$filterProvider#register $filterProvider.register()}.
2157 * <div class="alert alert-warning">
2158 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
2159 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
2160 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
2161 * (`myapp_subsection_filterx`).
2164 filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
2168 * @name angular.Module#controller
2170 * @param {string|Object} name Controller name, or an object map of controllers where the
2171 * keys are the names and the values are the constructors.
2172 * @param {Function} constructor Controller constructor function.
2174 * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
2176 controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
2180 * @name angular.Module#directive
2182 * @param {string|Object} name Directive name, or an object map of directives where the
2183 * keys are the names and the values are the factories.
2184 * @param {Function} directiveFactory Factory function for creating new instance of
2187 * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
2189 directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
2193 * @name angular.Module#component
2195 * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
2196 * @param {Object} options Component definition object (a simplified
2197 * {@link ng.$compile#directive-definition-object directive definition object}),
2198 * has the following properties (all optional):
2200 * - `controller` – `{(string|function()=}` – Controller constructor function that should be
2201 * associated with newly created scope or the name of a {@link ng.$compile#-controller-
2202 * registered controller} if passed as a string. Empty function by default.
2203 * - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
2204 * If present, the controller will be published to scope under the `controllerAs` name.
2205 * If not present, this will default to be the same as the component name.
2206 * - `template` – `{string=|function()=}` – html template as a string or a function that
2207 * returns an html template as a string which should be used as the contents of this component.
2208 * Empty string by default.
2210 * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
2211 * the following locals:
2213 * - `$element` - Current element
2214 * - `$attrs` - Current attributes object for the element
2216 * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
2217 * template that should be used as the contents of this component.
2219 * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
2220 * the following locals:
2222 * - `$element` - Current element
2223 * - `$attrs` - Current attributes object for the element
2224 * - `bindings` – `{object=}` – Define DOM attribute binding to component properties.
2225 * Component properties are always bound to the component controller and not to the scope.
2226 * - `transclude` – `{boolean=}` – Whether {@link $compile#transclusion transclusion} is enabled.
2227 * Enabled by default.
2228 * - `isolate` – `{boolean=}` – Whether the new scope is isolated. Isolated by default.
2229 * - `restrict` - `{string=}` - String of subset of {@link ng.$compile#-restrict- EACM} which
2230 * restricts the component to specific directive declaration style. If omitted, this defaults to 'E'.
2231 * - `$canActivate` – `{function()=}` – TBD.
2232 * - `$routeConfig` – `{object=}` – TBD.
2235 * Register a component definition with the compiler. This is short for registering a specific
2236 * subset of directives which represents actual UI components in your application. Component
2237 * definitions are very simple and do not require the complexity behind defining directives.
2238 * Component definitions usually consist only of the template and the controller backing it.
2239 * In order to make the definition easier, components enforce best practices like controllerAs
2240 * and default behaviors like scope isolation, restrict to elements and allow transclusion.
2242 * Here are a few examples of how you would usually define components:
2245 * var myMod = angular.module(...);
2246 * myMod.component('myComp', {
2247 * template: '<div>My name is {{myComp.name}}</div>',
2248 * controller: function() {
2249 * this.name = 'shahar';
2253 * myMod.component('myComp', {
2254 * template: '<div>My name is {{myComp.name}}</div>',
2255 * bindings: {name: '@'}
2258 * myMod.component('myComp', {
2259 * templateUrl: 'views/my-comp.html',
2260 * controller: 'MyCtrl as ctrl',
2261 * bindings: {name: '@'}
2266 * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
2268 component: function(name, options) {
2269 function factory($injector) {
2270 function makeInjectable(fn) {
2271 if (angular.isFunction(fn)) {
2272 return function(tElement, tAttrs) {
2273 return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
2280 var template = (!options.template && !options.templateUrl ? '' : options.template);
2282 controller: options.controller || function() {},
2283 controllerAs: identifierForController(options.controller) || options.controllerAs || name,
2284 template: makeInjectable(template),
2285 templateUrl: makeInjectable(options.templateUrl),
2286 transclude: options.transclude === undefined ? true : options.transclude,
2287 scope: options.isolate === false ? true : {},
2288 bindToController: options.bindings || {},
2289 restrict: options.restrict || 'E'
2293 if (options.$canActivate) {
2294 factory.$canActivate = options.$canActivate;
2296 if (options.$routeConfig) {
2297 factory.$routeConfig = options.$routeConfig;
2299 factory.$inject = ['$injector'];
2301 return moduleInstance.directive(name, factory);
2306 * @name angular.Module#config
2308 * @param {Function} configFn Execute this function on module load. Useful for service
2311 * Use this method to register work which needs to be performed on module loading.
2312 * For more about how to configure services, see
2313 * {@link providers#provider-recipe Provider Recipe}.
2319 * @name angular.Module#run
2321 * @param {Function} initializationFn Execute this function after injector creation.
2322 * Useful for application initialization.
2324 * Use this method to register work which should be performed when the injector is done
2325 * loading all modules.
2327 run: function(block) {
2328 runBlocks.push(block);
2337 return moduleInstance;
2340 * @param {string} provider
2341 * @param {string} method
2342 * @param {String=} insertMethod
2343 * @returns {angular.Module}
2345 function invokeLater(provider, method, insertMethod, queue) {
2346 if (!queue) queue = invokeQueue;
2348 queue[insertMethod || 'push']([provider, method, arguments]);
2349 return moduleInstance;
2354 * @param {string} provider
2355 * @param {string} method
2356 * @returns {angular.Module}
2358 function invokeLaterAndSetModuleName(provider, method) {
2359 return function(recipeName, factoryFunction) {
2360 if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
2361 invokeQueue.push([provider, method, arguments]);
2362 return moduleInstance;
2371 /* global: toDebugString: true */
2373 function serializeObject(obj) {
2376 return JSON.stringify(obj, function(key, val) {
2377 val = toJsonReplacer(key, val);
2378 if (isObject(val)) {
2380 if (seen.indexOf(val) >= 0) return '...';
2388 function toDebugString(obj) {
2389 if (typeof obj === 'function') {
2390 return obj.toString().replace(/ \{[\s\S]*$/, '');
2391 } else if (isUndefined(obj)) {
2393 } else if (typeof obj !== 'string') {
2394 return serializeObject(obj);
2399 /* global angularModule: true,
2404 htmlAnchorDirective,
2413 ngBindHtmlDirective,
2414 ngBindTemplateDirective,
2416 ngClassEvenDirective,
2417 ngClassOddDirective,
2419 ngControllerDirective,
2424 ngIncludeFillContentDirective,
2426 ngNonBindableDirective,
2427 ngPluralizeDirective,
2432 ngSwitchWhenDirective,
2433 ngSwitchDefaultDirective,
2435 ngTranscludeDirective,
2448 ngModelOptionsDirective,
2449 ngAttributeAliasDirectives,
2452 $AnchorScrollProvider,
2454 $CoreAnimateCssProvider,
2455 $$CoreAnimateQueueProvider,
2456 $$CoreAnimateRunnerProvider,
2458 $CacheFactoryProvider,
2459 $ControllerProvider,
2462 $ExceptionHandlerProvider,
2464 $$ForceReflowProvider,
2465 $InterpolateProvider,
2469 $HttpParamSerializerProvider,
2470 $HttpParamSerializerJQLikeProvider,
2471 $HttpBackendProvider,
2472 $xhrFactoryProvider,
2479 $$SanitizeUriProvider,
2481 $SceDelegateProvider,
2483 $TemplateCacheProvider,
2484 $TemplateRequestProvider,
2485 $$TestabilityProvider,
2490 $$CookieReaderProvider
2496 * @name angular.version
2499 * An object that contains information about the current AngularJS version.
2501 * This object has the following properties:
2503 * - `full` – `{string}` – Full version string, such as "0.9.18".
2504 * - `major` – `{number}` – Major version number, such as "0".
2505 * - `minor` – `{number}` – Minor version number, such as "9".
2506 * - `dot` – `{number}` – Dot version number, such as "18".
2507 * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
2510 full: '1.5.0-beta.2', // all of these placeholder strings will be replaced by grunt's
2511 major: 1, // package task
2514 codeName: 'effective-delegation'
2518 function publishExternalAPI(angular) {
2520 'bootstrap': bootstrap,
2527 'injector': createInjector,
2531 'fromJson': fromJson,
2532 'identity': identity,
2533 'isUndefined': isUndefined,
2534 'isDefined': isDefined,
2535 'isString': isString,
2536 'isFunction': isFunction,
2537 'isObject': isObject,
2538 'isNumber': isNumber,
2539 'isElement': isElement,
2543 'lowercase': lowercase,
2544 'uppercase': uppercase,
2545 'callbacks': {counter: 0},
2546 'getTestability': getTestability,
2549 'reloadWithDebugInfo': reloadWithDebugInfo
2552 angularModule = setupModuleLoader(window);
2554 angularModule('ng', ['ngLocale'], ['$provide',
2555 function ngModule($provide) {
2556 // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
2558 $$sanitizeUri: $$SanitizeUriProvider
2560 $provide.provider('$compile', $CompileProvider).
2562 a: htmlAnchorDirective,
2563 input: inputDirective,
2564 textarea: inputDirective,
2565 form: formDirective,
2566 script: scriptDirective,
2567 select: selectDirective,
2568 style: styleDirective,
2569 option: optionDirective,
2570 ngBind: ngBindDirective,
2571 ngBindHtml: ngBindHtmlDirective,
2572 ngBindTemplate: ngBindTemplateDirective,
2573 ngClass: ngClassDirective,
2574 ngClassEven: ngClassEvenDirective,
2575 ngClassOdd: ngClassOddDirective,
2576 ngCloak: ngCloakDirective,
2577 ngController: ngControllerDirective,
2578 ngForm: ngFormDirective,
2579 ngHide: ngHideDirective,
2580 ngIf: ngIfDirective,
2581 ngInclude: ngIncludeDirective,
2582 ngInit: ngInitDirective,
2583 ngNonBindable: ngNonBindableDirective,
2584 ngPluralize: ngPluralizeDirective,
2585 ngRepeat: ngRepeatDirective,
2586 ngShow: ngShowDirective,
2587 ngStyle: ngStyleDirective,
2588 ngSwitch: ngSwitchDirective,
2589 ngSwitchWhen: ngSwitchWhenDirective,
2590 ngSwitchDefault: ngSwitchDefaultDirective,
2591 ngOptions: ngOptionsDirective,
2592 ngTransclude: ngTranscludeDirective,
2593 ngModel: ngModelDirective,
2594 ngList: ngListDirective,
2595 ngChange: ngChangeDirective,
2596 pattern: patternDirective,
2597 ngPattern: patternDirective,
2598 required: requiredDirective,
2599 ngRequired: requiredDirective,
2600 minlength: minlengthDirective,
2601 ngMinlength: minlengthDirective,
2602 maxlength: maxlengthDirective,
2603 ngMaxlength: maxlengthDirective,
2604 ngValue: ngValueDirective,
2605 ngModelOptions: ngModelOptionsDirective
2608 ngInclude: ngIncludeFillContentDirective
2610 directive(ngAttributeAliasDirectives).
2611 directive(ngEventDirectives);
2613 $anchorScroll: $AnchorScrollProvider,
2614 $animate: $AnimateProvider,
2615 $animateCss: $CoreAnimateCssProvider,
2616 $$animateQueue: $$CoreAnimateQueueProvider,
2617 $$AnimateRunner: $$CoreAnimateRunnerProvider,
2618 $browser: $BrowserProvider,
2619 $cacheFactory: $CacheFactoryProvider,
2620 $controller: $ControllerProvider,
2621 $document: $DocumentProvider,
2622 $exceptionHandler: $ExceptionHandlerProvider,
2623 $filter: $FilterProvider,
2624 $$forceReflow: $$ForceReflowProvider,
2625 $interpolate: $InterpolateProvider,
2626 $interval: $IntervalProvider,
2627 $http: $HttpProvider,
2628 $httpParamSerializer: $HttpParamSerializerProvider,
2629 $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
2630 $httpBackend: $HttpBackendProvider,
2631 $xhrFactory: $xhrFactoryProvider,
2632 $location: $LocationProvider,
2634 $parse: $ParseProvider,
2635 $rootScope: $RootScopeProvider,
2639 $sceDelegate: $SceDelegateProvider,
2640 $sniffer: $SnifferProvider,
2641 $templateCache: $TemplateCacheProvider,
2642 $templateRequest: $TemplateRequestProvider,
2643 $$testability: $$TestabilityProvider,
2644 $timeout: $TimeoutProvider,
2645 $window: $WindowProvider,
2646 $$rAF: $$RAFProvider,
2647 $$jqLite: $$jqLiteProvider,
2648 $$HashMap: $$HashMapProvider,
2649 $$cookieReader: $$CookieReaderProvider
2655 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2656 * Any commits to this file should be reviewed with security in mind. *
2657 * Changes to this file can potentially create security vulnerabilities. *
2658 * An approval from 2 Core members with history of modifying *
2659 * this file is required. *
2661 * Does the change somehow allow for arbitrary javascript to be executed? *
2662 * Or allows for someone to change the prototype of built-in objects? *
2663 * Or gives undesired access to variables likes document or window? *
2664 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2666 /* global JQLitePrototype: true,
2667 addEventListenerFn: true,
2668 removeEventListenerFn: true,
2673 //////////////////////////////////
2675 //////////////////////////////////
2679 * @name angular.element
2684 * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
2686 * If jQuery is available, `angular.element` is an alias for the
2687 * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
2688 * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
2690 * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
2691 * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
2692 * commonly needed functionality with the goal of having a very small footprint.</div>
2694 * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
2696 * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
2697 * jqLite; they are never raw DOM references.</div>
2699 * ## Angular's jqLite
2700 * jqLite provides only the following jQuery methods:
2702 * - [`addClass()`](http://api.jquery.com/addClass/)
2703 * - [`after()`](http://api.jquery.com/after/)
2704 * - [`append()`](http://api.jquery.com/append/)
2705 * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
2706 * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
2707 * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
2708 * - [`clone()`](http://api.jquery.com/clone/)
2709 * - [`contents()`](http://api.jquery.com/contents/)
2710 * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
2711 * - [`data()`](http://api.jquery.com/data/)
2712 * - [`detach()`](http://api.jquery.com/detach/)
2713 * - [`empty()`](http://api.jquery.com/empty/)
2714 * - [`eq()`](http://api.jquery.com/eq/)
2715 * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
2716 * - [`hasClass()`](http://api.jquery.com/hasClass/)
2717 * - [`html()`](http://api.jquery.com/html/)
2718 * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
2719 * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
2720 * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
2721 * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
2722 * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
2723 * - [`prepend()`](http://api.jquery.com/prepend/)
2724 * - [`prop()`](http://api.jquery.com/prop/)
2725 * - [`ready()`](http://api.jquery.com/ready/)
2726 * - [`remove()`](http://api.jquery.com/remove/)
2727 * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
2728 * - [`removeClass()`](http://api.jquery.com/removeClass/)
2729 * - [`removeData()`](http://api.jquery.com/removeData/)
2730 * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
2731 * - [`text()`](http://api.jquery.com/text/)
2732 * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
2733 * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
2734 * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
2735 * - [`val()`](http://api.jquery.com/val/)
2736 * - [`wrap()`](http://api.jquery.com/wrap/)
2738 * ## jQuery/jqLite Extras
2739 * Angular also provides the following additional methods and events to both jQuery and jqLite:
2742 * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
2743 * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
2744 * element before it is removed.
2747 * - `controller(name)` - retrieves the controller of the current element or its parent. By default
2748 * retrieves controller associated with the `ngController` directive. If `name` is provided as
2749 * camelCase directive name, then the controller for this directive will be retrieved (e.g.
2751 * - `injector()` - retrieves the injector of the current element or its parent.
2752 * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
2753 * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
2755 * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
2756 * current element. This getter should be used only on elements that contain a directive which starts a new isolate
2757 * scope. Calling `scope()` on this element always returns the original non-isolate scope.
2758 * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
2759 * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
2760 * parent element is reached.
2762 * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
2763 * @returns {Object} jQuery object.
2766 JQLite.expando = 'ng339';
2768 var jqCache = JQLite.cache = {},
2770 addEventListenerFn = function(element, type, fn) {
2771 element.addEventListener(type, fn, false);
2773 removeEventListenerFn = function(element, type, fn) {
2774 element.removeEventListener(type, fn, false);
2778 * !!! This is an undocumented "private" function !!!
2780 JQLite._data = function(node) {
2781 //jQuery always returns an object on cache miss
2782 return this.cache[node[this.expando]] || {};
2785 function jqNextId() { return ++jqId; }
2788 var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
2789 var MOZ_HACK_REGEXP = /^moz([A-Z])/;
2790 var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
2791 var jqLiteMinErr = minErr('jqLite');
2794 * Converts snake_case to camelCase.
2795 * Also there is special case for Moz prefix starting with upper case letter.
2796 * @param name Name to normalize
2798 function camelCase(name) {
2800 replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
2801 return offset ? letter.toUpperCase() : letter;
2803 replace(MOZ_HACK_REGEXP, 'Moz$1');
2806 var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
2807 var HTML_REGEXP = /<|&#?\w+;/;
2808 var TAG_NAME_REGEXP = /<([\w:-]+)/;
2809 var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
2812 'option': [1, '<select multiple="multiple">', '</select>'],
2814 'thead': [1, '<table>', '</table>'],
2815 'col': [2, '<table><colgroup>', '</colgroup></table>'],
2816 'tr': [2, '<table><tbody>', '</tbody></table>'],
2817 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
2818 '_default': [0, "", ""]
2821 wrapMap.optgroup = wrapMap.option;
2822 wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
2823 wrapMap.th = wrapMap.td;
2826 function jqLiteIsTextNode(html) {
2827 return !HTML_REGEXP.test(html);
2830 function jqLiteAcceptsData(node) {
2831 // The window object can accept data but has no nodeType
2832 // Otherwise we are only interested in elements (1) and documents (9)
2833 var nodeType = node.nodeType;
2834 return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
2837 function jqLiteHasData(node) {
2838 for (var key in jqCache[node.ng339]) {
2844 function jqLiteCleanData(nodes) {
2845 for (var i = 0, ii = nodes.length; i < ii; i++) {
2846 jqLiteRemoveData(nodes[i]);
2850 function jqLiteBuildFragment(html, context) {
2852 fragment = context.createDocumentFragment(),
2855 if (jqLiteIsTextNode(html)) {
2856 // Convert non-html into a text node
2857 nodes.push(context.createTextNode(html));
2859 // Convert html into DOM nodes
2860 tmp = tmp || fragment.appendChild(context.createElement("div"));
2861 tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
2862 wrap = wrapMap[tag] || wrapMap._default;
2863 tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
2865 // Descend through wrappers to the right content
2868 tmp = tmp.lastChild;
2871 nodes = concat(nodes, tmp.childNodes);
2873 tmp = fragment.firstChild;
2874 tmp.textContent = "";
2877 // Remove wrapper from fragment
2878 fragment.textContent = "";
2879 fragment.innerHTML = ""; // Clear inner HTML
2880 forEach(nodes, function(node) {
2881 fragment.appendChild(node);
2887 function jqLiteParseHTML(html, context) {
2888 context = context || document;
2891 if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
2892 return [context.createElement(parsed[1])];
2895 if ((parsed = jqLiteBuildFragment(html, context))) {
2896 return parsed.childNodes;
2903 // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
2904 var jqLiteContains = Node.prototype.contains || function(arg) {
2905 // jshint bitwise: false
2906 return !!(this.compareDocumentPosition(arg) & 16);
2907 // jshint bitwise: true
2910 /////////////////////////////////////////////
2911 function JQLite(element) {
2912 if (element instanceof JQLite) {
2918 if (isString(element)) {
2919 element = trim(element);
2922 if (!(this instanceof JQLite)) {
2923 if (argIsString && element.charAt(0) != '<') {
2924 throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
2926 return new JQLite(element);
2930 jqLiteAddNodes(this, jqLiteParseHTML(element));
2932 jqLiteAddNodes(this, element);
2936 function jqLiteClone(element) {
2937 return element.cloneNode(true);
2940 function jqLiteDealoc(element, onlyDescendants) {
2941 if (!onlyDescendants) jqLiteRemoveData(element);
2943 if (element.querySelectorAll) {
2944 var descendants = element.querySelectorAll('*');
2945 for (var i = 0, l = descendants.length; i < l; i++) {
2946 jqLiteRemoveData(descendants[i]);
2951 function jqLiteOff(element, type, fn, unsupported) {
2952 if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
2954 var expandoStore = jqLiteExpandoStore(element);
2955 var events = expandoStore && expandoStore.events;
2956 var handle = expandoStore && expandoStore.handle;
2958 if (!handle) return; //no listeners registered
2961 for (type in events) {
2962 if (type !== '$destroy') {
2963 removeEventListenerFn(element, type, handle);
2965 delete events[type];
2969 var removeHandler = function(type) {
2970 var listenerFns = events[type];
2971 if (isDefined(fn)) {
2972 arrayRemove(listenerFns || [], fn);
2974 if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
2975 removeEventListenerFn(element, type, handle);
2976 delete events[type];
2980 forEach(type.split(' '), function(type) {
2981 removeHandler(type);
2982 if (MOUSE_EVENT_MAP[type]) {
2983 removeHandler(MOUSE_EVENT_MAP[type]);
2989 function jqLiteRemoveData(element, name) {
2990 var expandoId = element.ng339;
2991 var expandoStore = expandoId && jqCache[expandoId];
2995 delete expandoStore.data[name];
2999 if (expandoStore.handle) {
3000 if (expandoStore.events.$destroy) {
3001 expandoStore.handle({}, '$destroy');
3005 delete jqCache[expandoId];
3006 element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
3011 function jqLiteExpandoStore(element, createIfNecessary) {
3012 var expandoId = element.ng339,
3013 expandoStore = expandoId && jqCache[expandoId];
3015 if (createIfNecessary && !expandoStore) {
3016 element.ng339 = expandoId = jqNextId();
3017 expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
3020 return expandoStore;
3024 function jqLiteData(element, key, value) {
3025 if (jqLiteAcceptsData(element)) {
3027 var isSimpleSetter = isDefined(value);
3028 var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
3029 var massGetter = !key;
3030 var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
3031 var data = expandoStore && expandoStore.data;
3033 if (isSimpleSetter) { // data('key', value)
3036 if (massGetter) { // data()
3039 if (isSimpleGetter) { // data('key')
3040 // don't force creation of expandoStore if it doesn't exist yet
3041 return data && data[key];
3042 } else { // mass-setter: data({key1: val1, key2: val2})
3050 function jqLiteHasClass(element, selector) {
3051 if (!element.getAttribute) return false;
3052 return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
3053 indexOf(" " + selector + " ") > -1);
3056 function jqLiteRemoveClass(element, cssClasses) {
3057 if (cssClasses && element.setAttribute) {
3058 forEach(cssClasses.split(' '), function(cssClass) {
3059 element.setAttribute('class', trim(
3060 (" " + (element.getAttribute('class') || '') + " ")
3061 .replace(/[\n\t]/g, " ")
3062 .replace(" " + trim(cssClass) + " ", " "))
3068 function jqLiteAddClass(element, cssClasses) {
3069 if (cssClasses && element.setAttribute) {
3070 var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
3071 .replace(/[\n\t]/g, " ");
3073 forEach(cssClasses.split(' '), function(cssClass) {
3074 cssClass = trim(cssClass);
3075 if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
3076 existingClasses += cssClass + ' ';
3080 element.setAttribute('class', trim(existingClasses));
3085 function jqLiteAddNodes(root, elements) {
3086 // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
3090 // if a Node (the most common case)
3091 if (elements.nodeType) {
3092 root[root.length++] = elements;
3094 var length = elements.length;
3096 // if an Array or NodeList and not a Window
3097 if (typeof length === 'number' && elements.window !== elements) {
3099 for (var i = 0; i < length; i++) {
3100 root[root.length++] = elements[i];
3104 root[root.length++] = elements;
3111 function jqLiteController(element, name) {
3112 return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
3115 function jqLiteInheritedData(element, name, value) {
3116 // if element is the document object work with the html element instead
3117 // this makes $(document).scope() possible
3118 if (element.nodeType == NODE_TYPE_DOCUMENT) {
3119 element = element.documentElement;
3121 var names = isArray(name) ? name : [name];
3124 for (var i = 0, ii = names.length; i < ii; i++) {
3125 if (isDefined(value = jqLite.data(element, names[i]))) return value;
3128 // If dealing with a document fragment node with a host element, and no parent, use the host
3129 // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
3130 // to lookup parent controllers.
3131 element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
3135 function jqLiteEmpty(element) {
3136 jqLiteDealoc(element, true);
3137 while (element.firstChild) {
3138 element.removeChild(element.firstChild);
3142 function jqLiteRemove(element, keepData) {
3143 if (!keepData) jqLiteDealoc(element);
3144 var parent = element.parentNode;
3145 if (parent) parent.removeChild(element);
3149 function jqLiteDocumentLoaded(action, win) {
3150 win = win || window;
3151 if (win.document.readyState === 'complete') {
3152 // Force the action to be run async for consistent behaviour
3153 // from the action's point of view
3154 // i.e. it will definitely not be in a $apply
3155 win.setTimeout(action);
3157 // No need to unbind this handler as load is only ever called once
3158 jqLite(win).on('load', action);
3162 //////////////////////////////////////////
3163 // Functions which are declared directly.
3164 //////////////////////////////////////////
3165 var JQLitePrototype = JQLite.prototype = {
3166 ready: function(fn) {
3169 function trigger() {
3175 // check if document is already loaded
3176 if (document.readyState === 'complete') {
3177 setTimeout(trigger);
3179 this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
3180 // we can not use jqLite since we are not done loading and jQuery could be loaded later.
3182 JQLite(window).on('load', trigger); // fallback to window.onload for others
3186 toString: function() {
3188 forEach(this, function(e) { value.push('' + e);});
3189 return '[' + value.join(', ') + ']';
3192 eq: function(index) {
3193 return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
3202 //////////////////////////////////////////
3203 // Functions iterating getter/setters.
3204 // these functions return self on setter and
3206 //////////////////////////////////////////
3207 var BOOLEAN_ATTR = {};
3208 forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
3209 BOOLEAN_ATTR[lowercase(value)] = value;
3211 var BOOLEAN_ELEMENTS = {};
3212 forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
3213 BOOLEAN_ELEMENTS[value] = true;
3215 var ALIASED_ATTR = {
3216 'ngMinlength': 'minlength',
3217 'ngMaxlength': 'maxlength',
3220 'ngPattern': 'pattern'
3223 function getBooleanAttrName(element, name) {
3224 // check dom last since we will most likely fail on name
3225 var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
3227 // booleanAttr is here twice to minimize DOM access
3228 return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
3231 function getAliasedAttrName(name) {
3232 return ALIASED_ATTR[name];
3237 removeData: jqLiteRemoveData,
3238 hasData: jqLiteHasData,
3239 cleanData: jqLiteCleanData
3240 }, function(fn, name) {
3246 inheritedData: jqLiteInheritedData,
3248 scope: function(element) {
3249 // Can't use jqLiteData here directly so we stay compatible with jQuery!
3250 return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
3253 isolateScope: function(element) {
3254 // Can't use jqLiteData here directly so we stay compatible with jQuery!
3255 return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
3258 controller: jqLiteController,
3260 injector: function(element) {
3261 return jqLiteInheritedData(element, '$injector');
3264 removeAttr: function(element, name) {
3265 element.removeAttribute(name);
3268 hasClass: jqLiteHasClass,
3270 css: function(element, name, value) {
3271 name = camelCase(name);
3273 if (isDefined(value)) {
3274 element.style[name] = value;
3276 return element.style[name];
3280 attr: function(element, name, value) {
3281 var nodeType = element.nodeType;
3282 if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
3285 var lowercasedName = lowercase(name);
3286 if (BOOLEAN_ATTR[lowercasedName]) {
3287 if (isDefined(value)) {
3289 element[name] = true;
3290 element.setAttribute(name, lowercasedName);
3292 element[name] = false;
3293 element.removeAttribute(lowercasedName);
3296 return (element[name] ||
3297 (element.attributes.getNamedItem(name) || noop).specified)
3301 } else if (isDefined(value)) {
3302 element.setAttribute(name, value);
3303 } else if (element.getAttribute) {
3304 // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
3305 // some elements (e.g. Document) don't have get attribute, so return undefined
3306 var ret = element.getAttribute(name, 2);
3307 // normalize non-existing attributes to undefined (as jQuery)
3308 return ret === null ? undefined : ret;
3312 prop: function(element, name, value) {
3313 if (isDefined(value)) {
3314 element[name] = value;
3316 return element[name];
3324 function getText(element, value) {
3325 if (isUndefined(value)) {
3326 var nodeType = element.nodeType;
3327 return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
3329 element.textContent = value;
3333 val: function(element, value) {
3334 if (isUndefined(value)) {
3335 if (element.multiple && nodeName_(element) === 'select') {
3337 forEach(element.options, function(option) {
3338 if (option.selected) {
3339 result.push(option.value || option.text);
3342 return result.length === 0 ? null : result;
3344 return element.value;
3346 element.value = value;
3349 html: function(element, value) {
3350 if (isUndefined(value)) {
3351 return element.innerHTML;
3353 jqLiteDealoc(element, true);
3354 element.innerHTML = value;
3358 }, function(fn, name) {
3360 * Properties: writes return selection, reads return first value
3362 JQLite.prototype[name] = function(arg1, arg2) {
3364 var nodeCount = this.length;
3366 // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
3367 // in a way that survives minification.
3368 // jqLiteEmpty takes no arguments but is a setter.
3369 if (fn !== jqLiteEmpty &&
3370 (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
3371 if (isObject(arg1)) {
3373 // we are a write, but the object properties are the key/values
3374 for (i = 0; i < nodeCount; i++) {
3375 if (fn === jqLiteData) {
3376 // data() takes the whole object in jQuery
3380 fn(this[i], key, arg1[key]);
3384 // return self for chaining
3387 // we are a read, so read the first child.
3388 // TODO: do we still need this?
3390 // Only if we have $dv do we iterate over all, otherwise it is just the first element.
3391 var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
3392 for (var j = 0; j < jj; j++) {
3393 var nodeValue = fn(this[j], arg1, arg2);
3394 value = value ? value + nodeValue : nodeValue;
3399 // we are a write, so apply to all children
3400 for (i = 0; i < nodeCount; i++) {
3401 fn(this[i], arg1, arg2);
3403 // return self for chaining
3409 function createEventHandler(element, events) {
3410 var eventHandler = function(event, type) {
3411 // jQuery specific api
3412 event.isDefaultPrevented = function() {
3413 return event.defaultPrevented;
3416 var eventFns = events[type || event.type];
3417 var eventFnsLength = eventFns ? eventFns.length : 0;
3419 if (!eventFnsLength) return;
3421 if (isUndefined(event.immediatePropagationStopped)) {
3422 var originalStopImmediatePropagation = event.stopImmediatePropagation;
3423 event.stopImmediatePropagation = function() {
3424 event.immediatePropagationStopped = true;
3426 if (event.stopPropagation) {
3427 event.stopPropagation();
3430 if (originalStopImmediatePropagation) {
3431 originalStopImmediatePropagation.call(event);
3436 event.isImmediatePropagationStopped = function() {
3437 return event.immediatePropagationStopped === true;
3440 // Some events have special handlers that wrap the real handler
3441 var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
3443 // Copy event handlers in case event handlers array is modified during execution.
3444 if ((eventFnsLength > 1)) {
3445 eventFns = shallowCopy(eventFns);
3448 for (var i = 0; i < eventFnsLength; i++) {
3449 if (!event.isImmediatePropagationStopped()) {
3450 handlerWrapper(element, event, eventFns[i]);
3455 // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
3456 // events on `element`
3457 eventHandler.elem = element;
3458 return eventHandler;
3461 function defaultHandlerWrapper(element, event, handler) {
3462 handler.call(element, event);
3465 function specialMouseHandlerWrapper(target, event, handler) {
3466 // Refer to jQuery's implementation of mouseenter & mouseleave
3467 // Read about mouseenter and mouseleave:
3468 // http://www.quirksmode.org/js/events_mouse.html#link8
3469 var related = event.relatedTarget;
3470 // For mousenter/leave call the handler if related is outside the target.
3471 // NB: No relatedTarget if the mouse left/entered the browser window
3472 if (!related || (related !== target && !jqLiteContains.call(target, related))) {
3473 handler.call(target, event);
3477 //////////////////////////////////////////
3478 // Functions iterating traversal.
3479 // These functions chain results into a single
3481 //////////////////////////////////////////
3483 removeData: jqLiteRemoveData,
3485 on: function jqLiteOn(element, type, fn, unsupported) {
3486 if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
3488 // Do not add event handlers to non-elements because they will not be cleaned up.
3489 if (!jqLiteAcceptsData(element)) {
3493 var expandoStore = jqLiteExpandoStore(element, true);
3494 var events = expandoStore.events;
3495 var handle = expandoStore.handle;
3498 handle = expandoStore.handle = createEventHandler(element, events);
3501 // http://jsperf.com/string-indexof-vs-split
3502 var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
3503 var i = types.length;
3505 var addHandler = function(type, specialHandlerWrapper, noEventListener) {
3506 var eventFns = events[type];
3509 eventFns = events[type] = [];
3510 eventFns.specialHandlerWrapper = specialHandlerWrapper;
3511 if (type !== '$destroy' && !noEventListener) {
3512 addEventListenerFn(element, type, handle);
3521 if (MOUSE_EVENT_MAP[type]) {
3522 addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
3523 addHandler(type, undefined, true);
3532 one: function(element, type, fn) {
3533 element = jqLite(element);
3535 //add the listener twice so that when it is called
3536 //you can remove the original function and still be
3537 //able to call element.off(ev, fn) normally
3538 element.on(type, function onFn() {
3539 element.off(type, fn);
3540 element.off(type, onFn);
3542 element.on(type, fn);
3545 replaceWith: function(element, replaceNode) {
3546 var index, parent = element.parentNode;
3547 jqLiteDealoc(element);
3548 forEach(new JQLite(replaceNode), function(node) {
3550 parent.insertBefore(node, index.nextSibling);
3552 parent.replaceChild(node, element);
3558 children: function(element) {
3560 forEach(element.childNodes, function(element) {
3561 if (element.nodeType === NODE_TYPE_ELEMENT) {
3562 children.push(element);
3568 contents: function(element) {
3569 return element.contentDocument || element.childNodes || [];
3572 append: function(element, node) {
3573 var nodeType = element.nodeType;
3574 if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
3576 node = new JQLite(node);
3578 for (var i = 0, ii = node.length; i < ii; i++) {
3579 var child = node[i];
3580 element.appendChild(child);
3584 prepend: function(element, node) {
3585 if (element.nodeType === NODE_TYPE_ELEMENT) {
3586 var index = element.firstChild;
3587 forEach(new JQLite(node), function(child) {
3588 element.insertBefore(child, index);
3593 wrap: function(element, wrapNode) {
3594 wrapNode = jqLite(wrapNode).eq(0).clone()[0];
3595 var parent = element.parentNode;
3597 parent.replaceChild(wrapNode, element);
3599 wrapNode.appendChild(element);
3602 remove: jqLiteRemove,
3604 detach: function(element) {
3605 jqLiteRemove(element, true);
3608 after: function(element, newElement) {
3609 var index = element, parent = element.parentNode;
3610 newElement = new JQLite(newElement);
3612 for (var i = 0, ii = newElement.length; i < ii; i++) {
3613 var node = newElement[i];
3614 parent.insertBefore(node, index.nextSibling);
3619 addClass: jqLiteAddClass,
3620 removeClass: jqLiteRemoveClass,
3622 toggleClass: function(element, selector, condition) {
3624 forEach(selector.split(' '), function(className) {
3625 var classCondition = condition;
3626 if (isUndefined(classCondition)) {
3627 classCondition = !jqLiteHasClass(element, className);
3629 (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
3634 parent: function(element) {
3635 var parent = element.parentNode;
3636 return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
3639 next: function(element) {
3640 return element.nextElementSibling;
3643 find: function(element, selector) {
3644 if (element.getElementsByTagName) {
3645 return element.getElementsByTagName(selector);
3653 triggerHandler: function(element, event, extraParameters) {
3655 var dummyEvent, eventFnsCopy, handlerArgs;
3656 var eventName = event.type || event;
3657 var expandoStore = jqLiteExpandoStore(element);
3658 var events = expandoStore && expandoStore.events;
3659 var eventFns = events && events[eventName];
3662 // Create a dummy event to pass to the handlers
3664 preventDefault: function() { this.defaultPrevented = true; },
3665 isDefaultPrevented: function() { return this.defaultPrevented === true; },
3666 stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
3667 isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
3668 stopPropagation: noop,
3673 // If a custom event was provided then extend our dummy event with it
3675 dummyEvent = extend(dummyEvent, event);
3678 // Copy event handlers in case event handlers array is modified during execution.
3679 eventFnsCopy = shallowCopy(eventFns);
3680 handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
3682 forEach(eventFnsCopy, function(fn) {
3683 if (!dummyEvent.isImmediatePropagationStopped()) {
3684 fn.apply(element, handlerArgs);
3689 }, function(fn, name) {
3691 * chaining functions
3693 JQLite.prototype[name] = function(arg1, arg2, arg3) {
3696 for (var i = 0, ii = this.length; i < ii; i++) {
3697 if (isUndefined(value)) {
3698 value = fn(this[i], arg1, arg2, arg3);
3699 if (isDefined(value)) {
3700 // any function which returns a value needs to be wrapped
3701 value = jqLite(value);
3704 jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
3707 return isDefined(value) ? value : this;
3710 // bind legacy bind/unbind to on/off
3711 JQLite.prototype.bind = JQLite.prototype.on;
3712 JQLite.prototype.unbind = JQLite.prototype.off;
3716 // Provider for private $$jqLite service
3717 function $$jqLiteProvider() {
3718 this.$get = function $$jqLite() {
3719 return extend(JQLite, {
3720 hasClass: function(node, classes) {
3721 if (node.attr) node = node[0];
3722 return jqLiteHasClass(node, classes);
3724 addClass: function(node, classes) {
3725 if (node.attr) node = node[0];
3726 return jqLiteAddClass(node, classes);
3728 removeClass: function(node, classes) {
3729 if (node.attr) node = node[0];
3730 return jqLiteRemoveClass(node, classes);
3737 * Computes a hash of an 'obj'.
3740 * number is number as string
3741 * object is either result of calling $$hashKey function on the object or uniquely generated id,
3742 * that is also assigned to the $$hashKey property of the object.
3745 * @returns {string} hash string such that the same input will have the same hash string.
3746 * The resulting string key is in 'type:hashKey' format.
3748 function hashKey(obj, nextUidFn) {
3749 var key = obj && obj.$$hashKey;
3752 if (typeof key === 'function') {
3753 key = obj.$$hashKey();
3758 var objType = typeof obj;
3759 if (objType == 'function' || (objType == 'object' && obj !== null)) {
3760 key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
3762 key = objType + ':' + obj;
3769 * HashMap which can use objects as keys
3771 function HashMap(array, isolatedUid) {
3774 this.nextUid = function() {
3778 forEach(array, this.put, this);
3780 HashMap.prototype = {
3782 * Store key value pair
3783 * @param key key to store can be any type
3784 * @param value value to store can be any type
3786 put: function(key, value) {
3787 this[hashKey(key, this.nextUid)] = value;
3792 * @returns {Object} the value for the key
3794 get: function(key) {
3795 return this[hashKey(key, this.nextUid)];
3799 * Remove the key/value pair
3802 remove: function(key) {
3803 var value = this[key = hashKey(key, this.nextUid)];
3809 var $$HashMapProvider = [function() {
3810 this.$get = [function() {
3818 * @name angular.injector
3822 * Creates an injector object that can be used for retrieving services as well as for
3823 * dependency injection (see {@link guide/di dependency injection}).
3825 * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
3826 * {@link angular.module}. The `ng` module must be explicitly added.
3827 * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
3828 * disallows argument name annotation inference.
3829 * @returns {injector} Injector object. See {@link auto.$injector $injector}.
3834 * // create an injector
3835 * var $injector = angular.injector(['ng']);
3837 * // use the injector to kick off your application
3838 * // use the type inference to auto inject arguments, or use implicit injection
3839 * $injector.invoke(function($rootScope, $compile, $document) {
3840 * $compile($document)($rootScope);
3841 * $rootScope.$digest();
3845 * Sometimes you want to get access to the injector of a currently running Angular app
3846 * from outside Angular. Perhaps, you want to inject and compile some markup after the
3847 * application has been bootstrapped. You can do this using the extra `injector()` added
3848 * to JQuery/jqLite elements. See {@link angular.element}.
3850 * *This is fairly rare but could be the case if a third party library is injecting the
3853 * In the following example a new block of HTML containing a `ng-controller`
3854 * directive is added to the end of the document body by JQuery. We then compile and link
3855 * it into the current AngularJS scope.
3858 * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
3859 * $(document.body).append($div);
3861 * angular.element(document).injector().invoke(function($compile) {
3862 * var scope = angular.element($div).scope();
3863 * $compile($div)(scope);
3874 * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
3877 var ARROW_ARG = /^([^\(]+?)=>/;
3878 var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
3879 var FN_ARG_SPLIT = /,/;
3880 var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
3881 var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
3882 var $injectorMinErr = minErr('$injector');
3884 function extractArgs(fn) {
3885 var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
3886 args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
3890 function anonFn(fn) {
3891 // For anonymous functions, showing at the very least the function signature can help in
3893 var args = extractArgs(fn);
3895 return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
3900 function annotate(fn, strictDi, name) {
3905 if (typeof fn === 'function') {
3906 if (!($inject = fn.$inject)) {
3910 if (!isString(name) || !name) {
3911 name = fn.name || anonFn(fn);
3913 throw $injectorMinErr('strictdi',
3914 '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
3916 argDecl = extractArgs(fn);
3917 forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
3918 arg.replace(FN_ARG, function(all, underscore, name) {
3923 fn.$inject = $inject;
3925 } else if (isArray(fn)) {
3926 last = fn.length - 1;
3927 assertArgFn(fn[last], 'fn');
3928 $inject = fn.slice(0, last);
3930 assertArgFn(fn, 'fn', true);
3935 ///////////////////////////////////////
3943 * `$injector` is used to retrieve object instances as defined by
3944 * {@link auto.$provide provider}, instantiate types, invoke methods,
3947 * The following always holds true:
3950 * var $injector = angular.injector();
3951 * expect($injector.get('$injector')).toBe($injector);
3952 * expect($injector.invoke(function($injector) {
3954 * })).toBe($injector);
3957 * # Injection Function Annotation
3959 * JavaScript does not have annotations, and annotations are needed for dependency injection. The
3960 * following are all valid ways of annotating function with injection arguments and are equivalent.
3963 * // inferred (only works if code not minified/obfuscated)
3964 * $injector.invoke(function(serviceA){});
3967 * function explicit(serviceA) {};
3968 * explicit.$inject = ['serviceA'];
3969 * $injector.invoke(explicit);
3972 * $injector.invoke(['serviceA', function(serviceA){}]);
3977 * In JavaScript calling `toString()` on a function returns the function definition. The definition
3978 * can then be parsed and the function arguments can be extracted. This method of discovering
3979 * annotations is disallowed when the injector is in strict mode.
3980 * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
3983 * ## `$inject` Annotation
3984 * By adding an `$inject` property onto a function the injection parameters can be specified.
3987 * As an array of injection names, where the last item in the array is the function to call.
3992 * @name $injector#get
3995 * Return an instance of the service.
3997 * @param {string} name The name of the instance to retrieve.
3998 * @param {string=} caller An optional string to provide the origin of the function call for error messages.
3999 * @return {*} The instance.
4004 * @name $injector#invoke
4007 * Invoke the method and supply the method arguments from the `$injector`.
4009 * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
4010 * injected according to the {@link guide/di $inject Annotation} rules.
4011 * @param {Object=} self The `this` for the invoked method.
4012 * @param {Object=} locals Optional object. If preset then any argument names are read from this
4013 * object first, before the `$injector` is consulted.
4014 * @returns {*} the value returned by the invoked `fn` function.
4019 * @name $injector#has
4022 * Allows the user to query if the particular service exists.
4024 * @param {string} name Name of the service to query.
4025 * @returns {boolean} `true` if injector has given service.
4030 * @name $injector#instantiate
4032 * Create a new instance of JS type. The method takes a constructor function, invokes the new
4033 * operator, and supplies all of the arguments to the constructor function as specified by the
4034 * constructor annotation.
4036 * @param {Function} Type Annotated constructor function.
4037 * @param {Object=} locals Optional object. If preset then any argument names are read from this
4038 * object first, before the `$injector` is consulted.
4039 * @returns {Object} new instance of `Type`.
4044 * @name $injector#annotate
4047 * Returns an array of service names which the function is requesting for injection. This API is
4048 * used by the injector to determine which services need to be injected into the function when the
4049 * function is invoked. There are three ways in which the function can be annotated with the needed
4054 * The simplest form is to extract the dependencies from the arguments of the function. This is done
4055 * by converting the function into a string using `toString()` method and extracting the argument
4059 * function MyController($scope, $route) {
4064 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
4067 * You can disallow this method by using strict injection mode.
4069 * This method does not work with code minification / obfuscation. For this reason the following
4070 * annotation strategies are supported.
4072 * # The `$inject` property
4074 * If a function has an `$inject` property and its value is an array of strings, then the strings
4075 * represent names of services to be injected into the function.
4078 * var MyController = function(obfuscatedScope, obfuscatedRoute) {
4081 * // Define function dependencies
4082 * MyController['$inject'] = ['$scope', '$route'];
4085 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
4088 * # The array notation
4090 * It is often desirable to inline Injected functions and that's when setting the `$inject` property
4091 * is very inconvenient. In these situations using the array notation to specify the dependencies in
4092 * a way that survives minification is a better choice:
4095 * // We wish to write this (not minification / obfuscation safe)
4096 * injector.invoke(function($compile, $rootScope) {
4100 * // We are forced to write break inlining
4101 * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
4104 * tmpFn.$inject = ['$compile', '$rootScope'];
4105 * injector.invoke(tmpFn);
4107 * // To better support inline function the inline annotation is supported
4108 * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
4113 * expect(injector.annotate(
4114 * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
4115 * ).toEqual(['$compile', '$rootScope']);
4118 * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
4119 * be retrieved as described above.
4121 * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
4123 * @returns {Array.<string>} The names of the services which the function requires.
4135 * The {@link auto.$provide $provide} service has a number of methods for registering components
4136 * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
4137 * {@link angular.Module}.
4139 * An Angular **service** is a singleton object created by a **service factory**. These **service
4140 * factories** are functions which, in turn, are created by a **service provider**.
4141 * The **service providers** are constructor functions. When instantiated they must contain a
4142 * property called `$get`, which holds the **service factory** function.
4144 * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
4145 * correct **service provider**, instantiating it and then calling its `$get` **service factory**
4146 * function to get the instance of the **service**.
4148 * Often services have no configuration options and there is no need to add methods to the service
4149 * provider. The provider will be no more than a constructor function with a `$get` property. For
4150 * these cases the {@link auto.$provide $provide} service has additional helper methods to register
4151 * services without specifying a provider.
4153 * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
4154 * {@link auto.$injector $injector}
4155 * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
4156 * providers and services.
4157 * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
4158 * services, not providers.
4159 * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
4160 * that will be wrapped in a **service provider** object, whose `$get` property will contain the
4161 * given factory function.
4162 * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
4163 * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
4164 * a new object using the given constructor function.
4166 * See the individual methods for more information and examples.
4171 * @name $provide#provider
4174 * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
4175 * are constructor functions, whose instances are responsible for "providing" a factory for a
4178 * Service provider names start with the name of the service they provide followed by `Provider`.
4179 * For example, the {@link ng.$log $log} service has a provider called
4180 * {@link ng.$logProvider $logProvider}.
4182 * Service provider objects can have additional methods which allow configuration of the provider
4183 * and its service. Importantly, you can configure what kind of service is created by the `$get`
4184 * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
4185 * method {@link ng.$logProvider#debugEnabled debugEnabled}
4186 * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
4189 * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
4191 * @param {(Object|function())} provider If the provider is:
4193 * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
4194 * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
4195 * - `Constructor`: a new instance of the provider will be created using
4196 * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
4198 * @returns {Object} registered provider instance
4202 * The following example shows how to create a simple event tracking service and register it using
4203 * {@link auto.$provide#provider $provide.provider()}.
4206 * // Define the eventTracker provider
4207 * function EventTrackerProvider() {
4208 * var trackingUrl = '/track';
4210 * // A provider method for configuring where the tracked events should been saved
4211 * this.setTrackingUrl = function(url) {
4212 * trackingUrl = url;
4215 * // The service factory function
4216 * this.$get = ['$http', function($http) {
4217 * var trackedEvents = {};
4219 * // Call this to track an event
4220 * event: function(event) {
4221 * var count = trackedEvents[event] || 0;
4223 * trackedEvents[event] = count;
4226 * // Call this to save the tracked events to the trackingUrl
4227 * save: function() {
4228 * $http.post(trackingUrl, trackedEvents);
4234 * describe('eventTracker', function() {
4237 * beforeEach(module(function($provide) {
4238 * // Register the eventTracker provider
4239 * $provide.provider('eventTracker', EventTrackerProvider);
4242 * beforeEach(module(function(eventTrackerProvider) {
4243 * // Configure eventTracker provider
4244 * eventTrackerProvider.setTrackingUrl('/custom-track');
4247 * it('tracks events', inject(function(eventTracker) {
4248 * expect(eventTracker.event('login')).toEqual(1);
4249 * expect(eventTracker.event('login')).toEqual(2);
4252 * it('saves to the tracking url', inject(function(eventTracker, $http) {
4253 * postSpy = spyOn($http, 'post');
4254 * eventTracker.event('login');
4255 * eventTracker.save();
4256 * expect(postSpy).toHaveBeenCalled();
4257 * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
4258 * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
4259 * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
4267 * @name $provide#factory
4270 * Register a **service factory**, which will be called to return the service instance.
4271 * This is short for registering a service where its provider consists of only a `$get` property,
4272 * which is the given service factory function.
4273 * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
4274 * configure your service in a provider.
4276 * @param {string} name The name of the instance.
4277 * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
4278 * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
4279 * @returns {Object} registered provider instance
4282 * Here is an example of registering a service
4284 * $provide.factory('ping', ['$http', function($http) {
4285 * return function ping() {
4286 * return $http.send('/ping');
4290 * You would then inject and use this service like this:
4292 * someModule.controller('Ctrl', ['ping', function(ping) {
4301 * @name $provide#service
4304 * Register a **service constructor**, which will be invoked with `new` to create the service
4306 * This is short for registering a service where its provider's `$get` property is the service
4307 * constructor function that will be used to instantiate the service instance.
4309 * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
4312 * @param {string} name The name of the instance.
4313 * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
4314 * that will be instantiated.
4315 * @returns {Object} registered provider instance
4318 * Here is an example of registering a service using
4319 * {@link auto.$provide#service $provide.service(class)}.
4321 * var Ping = function($http) {
4322 * this.$http = $http;
4325 * Ping.$inject = ['$http'];
4327 * Ping.prototype.send = function() {
4328 * return this.$http.get('/ping');
4330 * $provide.service('ping', Ping);
4332 * You would then inject and use this service like this:
4334 * someModule.controller('Ctrl', ['ping', function(ping) {
4343 * @name $provide#value
4346 * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
4347 * number, an array, an object or a function. This is short for registering a service where its
4348 * provider's `$get` property is a factory function that takes no arguments and returns the **value
4351 * Value services are similar to constant services, except that they cannot be injected into a
4352 * module configuration function (see {@link angular.Module#config}) but they can be overridden by
4354 * {@link auto.$provide#decorator decorator}.
4356 * @param {string} name The name of the instance.
4357 * @param {*} value The value.
4358 * @returns {Object} registered provider instance
4361 * Here are some examples of creating value services.
4363 * $provide.value('ADMIN_USER', 'admin');
4365 * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
4367 * $provide.value('halfOf', function(value) {
4376 * @name $provide#constant
4379 * Register a **constant service**, such as a string, a number, an array, an object or a function,
4380 * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
4381 * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
4382 * be overridden by an Angular {@link auto.$provide#decorator decorator}.
4384 * @param {string} name The name of the constant.
4385 * @param {*} value The constant value.
4386 * @returns {Object} registered instance
4389 * Here a some examples of creating constants:
4391 * $provide.constant('SHARD_HEIGHT', 306);
4393 * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
4395 * $provide.constant('double', function(value) {
4404 * @name $provide#decorator
4407 * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
4408 * intercepts the creation of a service, allowing it to override or modify the behaviour of the
4409 * service. The object returned by the decorator may be the original service, or a new service
4410 * object which replaces or wraps and delegates to the original service.
4412 * @param {string} name The name of the service to decorate.
4413 * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
4414 * instantiated and should return the decorated service instance. The function is called using
4415 * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
4416 * Local injection arguments:
4418 * * `$delegate` - The original service instance, which can be monkey patched, configured,
4419 * decorated or delegated to.
4422 * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
4423 * calls to {@link ng.$log#error $log.warn()}.
4425 * $provide.decorator('$log', ['$delegate', function($delegate) {
4426 * $delegate.warn = $delegate.error;
4433 function createInjector(modulesToLoad, strictDi) {
4434 strictDi = (strictDi === true);
4435 var INSTANTIATING = {},
4436 providerSuffix = 'Provider',
4438 loadedModules = new HashMap([], true),
4441 provider: supportObject(provider),
4442 factory: supportObject(factory),
4443 service: supportObject(service),
4444 value: supportObject(value),
4445 constant: supportObject(constant),
4446 decorator: decorator
4449 providerInjector = (providerCache.$injector =
4450 createInternalInjector(providerCache, function(serviceName, caller) {
4451 if (angular.isString(caller)) {
4454 throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
4457 protoInstanceInjector =
4458 createInternalInjector(instanceCache, function(serviceName, caller) {
4459 var provider = providerInjector.get(serviceName + providerSuffix, caller);
4460 return instanceInjector.invoke(
4461 provider.$get, provider, undefined, serviceName);
4463 instanceInjector = protoInstanceInjector;
4465 providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
4466 var runBlocks = loadModules(modulesToLoad);
4467 instanceInjector = protoInstanceInjector.get('$injector');
4468 instanceInjector.strictDi = strictDi;
4469 forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
4471 return instanceInjector;
4473 ////////////////////////////////////
4475 ////////////////////////////////////
4477 function supportObject(delegate) {
4478 return function(key, value) {
4479 if (isObject(key)) {
4480 forEach(key, reverseParams(delegate));
4482 return delegate(key, value);
4487 function provider(name, provider_) {
4488 assertNotHasOwnProperty(name, 'service');
4489 if (isFunction(provider_) || isArray(provider_)) {
4490 provider_ = providerInjector.instantiate(provider_);
4492 if (!provider_.$get) {
4493 throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
4495 return providerCache[name + providerSuffix] = provider_;
4498 function enforceReturnValue(name, factory) {
4499 return function enforcedReturnValue() {
4500 var result = instanceInjector.invoke(factory, this);
4501 if (isUndefined(result)) {
4502 throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
4508 function factory(name, factoryFn, enforce) {
4509 return provider(name, {
4510 $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
4514 function service(name, constructor) {
4515 return factory(name, ['$injector', function($injector) {
4516 return $injector.instantiate(constructor);
4520 function value(name, val) { return factory(name, valueFn(val), false); }
4522 function constant(name, value) {
4523 assertNotHasOwnProperty(name, 'constant');
4524 providerCache[name] = value;
4525 instanceCache[name] = value;
4528 function decorator(serviceName, decorFn) {
4529 var origProvider = providerInjector.get(serviceName + providerSuffix),
4530 orig$get = origProvider.$get;
4532 origProvider.$get = function() {
4533 var origInstance = instanceInjector.invoke(orig$get, origProvider);
4534 return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
4538 ////////////////////////////////////
4540 ////////////////////////////////////
4541 function loadModules(modulesToLoad) {
4542 assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
4543 var runBlocks = [], moduleFn;
4544 forEach(modulesToLoad, function(module) {
4545 if (loadedModules.get(module)) return;
4546 loadedModules.put(module, true);
4548 function runInvokeQueue(queue) {
4550 for (i = 0, ii = queue.length; i < ii; i++) {
4551 var invokeArgs = queue[i],
4552 provider = providerInjector.get(invokeArgs[0]);
4554 provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
4559 if (isString(module)) {
4560 moduleFn = angularModule(module);
4561 runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
4562 runInvokeQueue(moduleFn._invokeQueue);
4563 runInvokeQueue(moduleFn._configBlocks);
4564 } else if (isFunction(module)) {
4565 runBlocks.push(providerInjector.invoke(module));
4566 } else if (isArray(module)) {
4567 runBlocks.push(providerInjector.invoke(module));
4569 assertArgFn(module, 'module');
4572 if (isArray(module)) {
4573 module = module[module.length - 1];
4575 if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
4576 // Safari & FF's stack traces don't contain error.message content
4577 // unlike those of Chrome and IE
4578 // So if stack doesn't contain message, we create a new string that contains both.
4579 // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
4581 e = e.message + '\n' + e.stack;
4583 throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
4584 module, e.stack || e.message || e);
4590 ////////////////////////////////////
4591 // internal Injector
4592 ////////////////////////////////////
4594 function createInternalInjector(cache, factory) {
4596 function getService(serviceName, caller) {
4597 if (cache.hasOwnProperty(serviceName)) {
4598 if (cache[serviceName] === INSTANTIATING) {
4599 throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
4600 serviceName + ' <- ' + path.join(' <- '));
4602 return cache[serviceName];
4605 path.unshift(serviceName);
4606 cache[serviceName] = INSTANTIATING;
4607 return cache[serviceName] = factory(serviceName, caller);
4609 if (cache[serviceName] === INSTANTIATING) {
4610 delete cache[serviceName];
4619 function invoke(fn, self, locals, serviceName) {
4620 if (typeof locals === 'string') {
4621 serviceName = locals;
4626 $inject = createInjector.$$annotate(fn, strictDi, serviceName),
4630 for (i = 0, length = $inject.length; i < length; i++) {
4632 if (typeof key !== 'string') {
4633 throw $injectorMinErr('itkn',
4634 'Incorrect injection token! Expected service name as string, got {0}', key);
4637 locals && locals.hasOwnProperty(key)
4639 : getService(key, serviceName)
4646 // http://jsperf.com/angularjs-invoke-apply-vs-switch
4648 return fn.apply(self, args);
4651 function instantiate(Type, locals, serviceName) {
4652 // Check if Type is annotated and use just the given function at n-1 as parameter
4653 // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
4654 // Object creation: http://jsperf.com/create-constructor/2
4655 var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
4656 var returnedValue = invoke(Type, instance, locals, serviceName);
4658 return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
4663 instantiate: instantiate,
4665 annotate: createInjector.$$annotate,
4666 has: function(name) {
4667 return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
4673 createInjector.$$annotate = annotate;
4677 * @name $anchorScrollProvider
4680 * Use `$anchorScrollProvider` to disable automatic scrolling whenever
4681 * {@link ng.$location#hash $location.hash()} changes.
4683 function $AnchorScrollProvider() {
4685 var autoScrollingEnabled = true;
4689 * @name $anchorScrollProvider#disableAutoScrolling
4692 * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
4693 * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
4694 * Use this method to disable automatic scrolling.
4696 * If automatic scrolling is disabled, one must explicitly call
4697 * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
4700 this.disableAutoScrolling = function() {
4701 autoScrollingEnabled = false;
4706 * @name $anchorScroll
4709 * @requires $location
4710 * @requires $rootScope
4713 * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
4714 * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
4716 * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
4718 * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
4719 * match any anchor whenever it changes. This can be disabled by calling
4720 * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
4722 * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
4723 * vertical scroll-offset (either fixed or dynamic).
4725 * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
4726 * {@link ng.$location#hash $location.hash()} will be used.
4728 * @property {(number|function|jqLite)} yOffset
4729 * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
4730 * positioned elements at the top of the page, such as navbars, headers etc.
4732 * `yOffset` can be specified in various ways:
4733 * - **number**: A fixed number of pixels to be used as offset.<br /><br />
4734 * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
4735 * a number representing the offset (in pixels).<br /><br />
4736 * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
4737 * the top of the page to the element's bottom will be used as offset.<br />
4738 * **Note**: The element will be taken into account only as long as its `position` is set to
4739 * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
4740 * their height and/or positioning according to the viewport's size.
4743 * <div class="alert alert-warning">
4744 * In order for `yOffset` to work properly, scrolling should take place on the document's root and
4745 * not some child element.
4749 <example module="anchorScrollExample">
4750 <file name="index.html">
4751 <div id="scrollArea" ng-controller="ScrollController">
4752 <a ng-click="gotoBottom()">Go to bottom</a>
4753 <a id="bottom"></a> You're at the bottom!
4756 <file name="script.js">
4757 angular.module('anchorScrollExample', [])
4758 .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
4759 function ($scope, $location, $anchorScroll) {
4760 $scope.gotoBottom = function() {
4761 // set the location.hash to the id of
4762 // the element you wish to scroll to.
4763 $location.hash('bottom');
4765 // call $anchorScroll()
4770 <file name="style.css">
4784 * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
4785 * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
4788 <example module="anchorScrollOffsetExample">
4789 <file name="index.html">
4790 <div class="fixed-header" ng-controller="headerCtrl">
4791 <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
4795 <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
4799 <file name="script.js">
4800 angular.module('anchorScrollOffsetExample', [])
4801 .run(['$anchorScroll', function($anchorScroll) {
4802 $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
4804 .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
4805 function ($anchorScroll, $location, $scope) {
4806 $scope.gotoAnchor = function(x) {
4807 var newHash = 'anchor' + x;
4808 if ($location.hash() !== newHash) {
4809 // set the $location.hash to `newHash` and
4810 // $anchorScroll will automatically scroll to it
4811 $location.hash('anchor' + x);
4813 // call $anchorScroll() explicitly,
4814 // since $location.hash hasn't changed
4821 <file name="style.css">
4827 border: 2px dashed DarkOrchid;
4828 padding: 10px 10px 200px 10px;
4832 background-color: rgba(0, 0, 0, 0.2);
4835 top: 0; left: 0; right: 0;
4839 display: inline-block;
4845 this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
4846 var document = $window.document;
4848 // Helper function to get first anchor from a NodeList
4849 // (using `Array#some()` instead of `angular#forEach()` since it's more performant
4850 // and working in all supported browsers.)
4851 function getFirstAnchor(list) {
4853 Array.prototype.some.call(list, function(element) {
4854 if (nodeName_(element) === 'a') {
4862 function getYOffset() {
4864 var offset = scroll.yOffset;
4866 if (isFunction(offset)) {
4868 } else if (isElement(offset)) {
4869 var elem = offset[0];
4870 var style = $window.getComputedStyle(elem);
4871 if (style.position !== 'fixed') {
4874 offset = elem.getBoundingClientRect().bottom;
4876 } else if (!isNumber(offset)) {
4883 function scrollTo(elem) {
4885 elem.scrollIntoView();
4887 var offset = getYOffset();
4890 // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
4891 // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
4892 // top of the viewport.
4894 // IF the number of pixels from the top of `elem` to the end of the page's content is less
4895 // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
4896 // way down the page.
4898 // This is often the case for elements near the bottom of the page.
4900 // In such cases we do not need to scroll the whole `offset` up, just the difference between
4901 // the top of the element and the offset, which is enough to align the top of `elem` at the
4902 // desired position.
4903 var elemTop = elem.getBoundingClientRect().top;
4904 $window.scrollBy(0, elemTop - offset);
4907 $window.scrollTo(0, 0);
4911 function scroll(hash) {
4912 hash = isString(hash) ? hash : $location.hash();
4915 // empty hash, scroll to the top of the page
4916 if (!hash) scrollTo(null);
4918 // element with given id
4919 else if ((elm = document.getElementById(hash))) scrollTo(elm);
4921 // first anchor with given name :-D
4922 else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
4924 // no element and hash == 'top', scroll to the top of the page
4925 else if (hash === 'top') scrollTo(null);
4928 // does not scroll when user clicks on anchor link that is currently on
4929 // (no url change, no $location.hash() change), browser native does scroll
4930 if (autoScrollingEnabled) {
4931 $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
4932 function autoScrollWatchAction(newVal, oldVal) {
4933 // skip the initial scroll if $location.hash is empty
4934 if (newVal === oldVal && newVal === '') return;
4936 jqLiteDocumentLoaded(function() {
4937 $rootScope.$evalAsync(scroll);
4946 var $animateMinErr = minErr('$animate');
4947 var ELEMENT_NODE = 1;
4948 var NG_ANIMATE_CLASSNAME = 'ng-animate';
4950 function mergeClasses(a,b) {
4951 if (!a && !b) return '';
4954 if (isArray(a)) a = a.join(' ');
4955 if (isArray(b)) b = b.join(' ');
4959 function extractElementNode(element) {
4960 for (var i = 0; i < element.length; i++) {
4961 var elm = element[i];
4962 if (elm.nodeType === ELEMENT_NODE) {
4968 function splitClasses(classes) {
4969 if (isString(classes)) {
4970 classes = classes.split(' ');
4973 // Use createMap() to prevent class assumptions involving property names in
4975 var obj = createMap();
4976 forEach(classes, function(klass) {
4977 // sometimes the split leaves empty string values
4978 // incase extra spaces were applied to the options
4986 // if any other type of options value besides an Object value is
4987 // passed into the $animate.method() animation then this helper code
4988 // will be run which will ignore it. While this patch is not the
4989 // greatest solution to this, a lot of existing plugins depend on
4990 // $animate to either call the callback (< 1.2) or return a promise
4991 // that can be changed. This helper function ensures that the options
4992 // are wiped clean incase a callback function is provided.
4993 function prepareAnimateOptions(options) {
4994 return isObject(options)
4999 var $$CoreAnimateRunnerProvider = function() {
5000 this.$get = ['$q', '$$rAF', function($q, $$rAF) {
5001 function AnimateRunner() {}
5002 AnimateRunner.all = noop;
5003 AnimateRunner.chain = noop;
5004 AnimateRunner.prototype = {
5010 then: function(pass, fail) {
5011 return $q(function(resolve) {
5015 }).then(pass, fail);
5018 return AnimateRunner;
5022 // this is prefixed with Core since it conflicts with
5023 // the animateQueueProvider defined in ngAnimate/animateQueue.js
5024 var $$CoreAnimateQueueProvider = function() {
5025 var postDigestQueue = new HashMap();
5026 var postDigestElements = [];
5028 this.$get = ['$$AnimateRunner', '$rootScope',
5029 function($$AnimateRunner, $rootScope) {
5036 push: function(element, event, options, domOperation) {
5037 domOperation && domOperation();
5039 options = options || {};
5040 options.from && element.css(options.from);
5041 options.to && element.css(options.to);
5043 if (options.addClass || options.removeClass) {
5044 addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
5047 return new $$AnimateRunner(); // jshint ignore:line
5052 function updateData(data, classes, value) {
5053 var changed = false;
5055 classes = isString(classes) ? classes.split(' ') :
5056 isArray(classes) ? classes : [];
5057 forEach(classes, function(className) {
5060 data[className] = value;
5067 function handleCSSClassChanges() {
5068 forEach(postDigestElements, function(element) {
5069 var data = postDigestQueue.get(element);
5071 var existing = splitClasses(element.attr('class'));
5074 forEach(data, function(status, className) {
5075 var hasClass = !!existing[className];
5076 if (status !== hasClass) {
5078 toAdd += (toAdd.length ? ' ' : '') + className;
5080 toRemove += (toRemove.length ? ' ' : '') + className;
5085 forEach(element, function(elm) {
5086 toAdd && jqLiteAddClass(elm, toAdd);
5087 toRemove && jqLiteRemoveClass(elm, toRemove);
5089 postDigestQueue.remove(element);
5092 postDigestElements.length = 0;
5096 function addRemoveClassesPostDigest(element, add, remove) {
5097 var data = postDigestQueue.get(element) || {};
5099 var classesAdded = updateData(data, add, true);
5100 var classesRemoved = updateData(data, remove, false);
5102 if (classesAdded || classesRemoved) {
5104 postDigestQueue.put(element, data);
5105 postDigestElements.push(element);
5107 if (postDigestElements.length === 1) {
5108 $rootScope.$$postDigest(handleCSSClassChanges);
5117 * @name $animateProvider
5120 * Default implementation of $animate that doesn't perform any animations, instead just
5121 * synchronously performs DOM updates and resolves the returned runner promise.
5123 * In order to enable animations the `ngAnimate` module has to be loaded.
5125 * To see the functional implementation check out `src/ngAnimate/animate.js`.
5127 var $AnimateProvider = ['$provide', function($provide) {
5128 var provider = this;
5130 this.$$registeredAnimations = Object.create(null);
5134 * @name $animateProvider#register
5137 * Registers a new injectable animation factory function. The factory function produces the
5138 * animation object which contains callback functions for each event that is expected to be
5141 * * `eventFn`: `function(element, ... , doneFunction, options)`
5142 * The element to animate, the `doneFunction` and the options fed into the animation. Depending
5143 * on the type of animation additional arguments will be injected into the animation function. The
5144 * list below explains the function signatures for the different animation methods:
5146 * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
5147 * - addClass: function(element, addedClasses, doneFunction, options)
5148 * - removeClass: function(element, removedClasses, doneFunction, options)
5149 * - enter, leave, move: function(element, doneFunction, options)
5150 * - animate: function(element, fromStyles, toStyles, doneFunction, options)
5152 * Make sure to trigger the `doneFunction` once the animation is fully complete.
5156 * //enter, leave, move signature
5157 * eventFn : function(element, done, options) {
5158 * //code to run the animation
5159 * //once complete, then run done()
5160 * return function endFunction(wasCancelled) {
5161 * //code to cancel the animation
5167 * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
5168 * @param {Function} factory The factory function that will be executed to return the animation
5171 this.register = function(name, factory) {
5172 if (name && name.charAt(0) !== '.') {
5173 throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
5176 var key = name + '-animation';
5177 provider.$$registeredAnimations[name.substr(1)] = key;
5178 $provide.factory(key, factory);
5183 * @name $animateProvider#classNameFilter
5186 * Sets and/or returns the CSS class regular expression that is checked when performing
5187 * an animation. Upon bootstrap the classNameFilter value is not set at all and will
5188 * therefore enable $animate to attempt to perform an animation on any element that is triggered.
5189 * When setting the `classNameFilter` value, animations will only be performed on elements
5190 * that successfully match the filter expression. This in turn can boost performance
5191 * for low-powered devices as well as applications containing a lot of structural operations.
5192 * @param {RegExp=} expression The className expression which will be checked against all animations
5193 * @return {RegExp} The current CSS className expression value. If null then there is no expression value
5195 this.classNameFilter = function(expression) {
5196 if (arguments.length === 1) {
5197 this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
5198 if (this.$$classNameFilter) {
5199 var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
5200 if (reservedRegex.test(this.$$classNameFilter.toString())) {
5201 throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
5206 return this.$$classNameFilter;
5209 this.$get = ['$$animateQueue', function($$animateQueue) {
5210 function domInsert(element, parentElement, afterElement) {
5211 // if for some reason the previous element was removed
5212 // from the dom sometime before this code runs then let's
5213 // just stick to using the parent element as the anchor
5215 var afterNode = extractElementNode(afterElement);
5216 if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
5217 afterElement = null;
5220 afterElement ? afterElement.after(element) : parentElement.prepend(element);
5226 * @description The $animate service exposes a series of DOM utility methods that provide support
5227 * for animation hooks. The default behavior is the application of DOM operations, however,
5228 * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
5229 * to ensure that animation runs with the triggered DOM operation.
5231 * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
5232 * included and only when it is active then the animation hooks that `$animate` triggers will be
5233 * functional. Once active then all structural `ng-` directives will trigger animations as they perform
5234 * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
5235 * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
5237 * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
5239 * To learn more about enabling animation support, click here to visit the
5240 * {@link ngAnimate ngAnimate module page}.
5243 // we don't call it directly since non-existant arguments may
5244 // be interpreted as null within the sub enabled function
5251 * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
5252 * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
5253 * is fired with the following params:
5256 * $animate.on('enter', container,
5257 * function callback(element, phase) {
5258 * // cool we detected an enter animation within the container
5263 * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
5264 * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
5265 * as well as among its children
5266 * @param {Function} callback the callback function that will be fired when the listener is triggered
5268 * The arguments present in the callback function are:
5269 * * `element` - The captured DOM element that the animation was fired on.
5270 * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
5272 on: $$animateQueue.on,
5277 * @name $animate#off
5279 * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
5280 * can be used in three different ways depending on the arguments:
5283 * // remove all the animation event listeners listening for `enter`
5284 * $animate.off('enter');
5286 * // remove all the animation event listeners listening for `enter` on the given element and its children
5287 * $animate.off('enter', container);
5289 * // remove the event listener function provided by `listenerFn` that is set
5290 * // to listen for `enter` on the given `element` as well as its children
5291 * $animate.off('enter', container, callback);
5294 * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
5295 * @param {DOMElement=} container the container element the event listener was placed on
5296 * @param {Function=} callback the callback function that was registered as the listener
5298 off: $$animateQueue.off,
5302 * @name $animate#pin
5304 * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
5305 * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
5306 * element despite being outside the realm of the application or within another application. Say for example if the application
5307 * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
5308 * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
5309 * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
5311 * Note that this feature is only active when the `ngAnimate` module is used.
5313 * @param {DOMElement} element the external element that will be pinned
5314 * @param {DOMElement} parentElement the host parent element that will be associated with the external element
5316 pin: $$animateQueue.pin,
5321 * @name $animate#enabled
5323 * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
5324 * function can be called in four ways:
5327 * // returns true or false
5328 * $animate.enabled();
5330 * // changes the enabled state for all animations
5331 * $animate.enabled(false);
5332 * $animate.enabled(true);
5334 * // returns true or false if animations are enabled for an element
5335 * $animate.enabled(element);
5337 * // changes the enabled state for an element and its children
5338 * $animate.enabled(element, true);
5339 * $animate.enabled(element, false);
5342 * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
5343 * @param {boolean=} enabled whether or not the animations will be enabled for the element
5345 * @return {boolean} whether or not animations are enabled
5347 enabled: $$animateQueue.enabled,
5351 * @name $animate#cancel
5353 * @description Cancels the provided animation.
5355 * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
5357 cancel: function(runner) {
5358 runner.end && runner.end();
5364 * @name $animate#enter
5366 * @description Inserts the element into the DOM either after the `after` element (if provided) or
5367 * as the first child within the `parent` element and then triggers an animation.
5368 * A promise is returned that will be resolved during the next digest once the animation
5371 * @param {DOMElement} element the element which will be inserted into the DOM
5372 * @param {DOMElement} parent the parent element which will append the element as
5373 * a child (so long as the after element is not present)
5374 * @param {DOMElement=} after the sibling element after which the element will be appended
5375 * @param {object=} options an optional collection of options/styles that will be applied to the element
5377 * @return {Promise} the animation callback promise
5379 enter: function(element, parent, after, options) {
5380 parent = parent && jqLite(parent);
5381 after = after && jqLite(after);
5382 parent = parent || after.parent();
5383 domInsert(element, parent, after);
5384 return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
5390 * @name $animate#move
5392 * @description Inserts (moves) the element into its new position in the DOM either after
5393 * the `after` element (if provided) or as the first child within the `parent` element
5394 * and then triggers an animation. A promise is returned that will be resolved
5395 * during the next digest once the animation has completed.
5397 * @param {DOMElement} element the element which will be moved into the new DOM position
5398 * @param {DOMElement} parent the parent element which will append the element as
5399 * a child (so long as the after element is not present)
5400 * @param {DOMElement=} after the sibling element after which the element will be appended
5401 * @param {object=} options an optional collection of options/styles that will be applied to the element
5403 * @return {Promise} the animation callback promise
5405 move: function(element, parent, after, options) {
5406 parent = parent && jqLite(parent);
5407 after = after && jqLite(after);
5408 parent = parent || after.parent();
5409 domInsert(element, parent, after);
5410 return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
5415 * @name $animate#leave
5417 * @description Triggers an animation and then removes the element from the DOM.
5418 * When the function is called a promise is returned that will be resolved during the next
5419 * digest once the animation has completed.
5421 * @param {DOMElement} element the element which will be removed from the DOM
5422 * @param {object=} options an optional collection of options/styles that will be applied to the element
5424 * @return {Promise} the animation callback promise
5426 leave: function(element, options) {
5427 return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
5434 * @name $animate#addClass
5437 * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
5438 * execution, the addClass operation will only be handled after the next digest and it will not trigger an
5439 * animation if element already contains the CSS class or if the class is removed at a later step.
5440 * Note that class-based animations are treated differently compared to structural animations
5441 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5442 * depending if CSS or JavaScript animations are used.
5444 * @param {DOMElement} element the element which the CSS classes will be applied to
5445 * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
5446 * @param {object=} options an optional collection of options/styles that will be applied to the element
5448 * @return {Promise} the animation callback promise
5450 addClass: function(element, className, options) {
5451 options = prepareAnimateOptions(options);
5452 options.addClass = mergeClasses(options.addclass, className);
5453 return $$animateQueue.push(element, 'addClass', options);
5458 * @name $animate#removeClass
5461 * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
5462 * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
5463 * animation if element does not contain the CSS class or if the class is added at a later step.
5464 * Note that class-based animations are treated differently compared to structural animations
5465 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5466 * depending if CSS or JavaScript animations are used.
5468 * @param {DOMElement} element the element which the CSS classes will be applied to
5469 * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
5470 * @param {object=} options an optional collection of options/styles that will be applied to the element
5472 * @return {Promise} the animation callback promise
5474 removeClass: function(element, className, options) {
5475 options = prepareAnimateOptions(options);
5476 options.removeClass = mergeClasses(options.removeClass, className);
5477 return $$animateQueue.push(element, 'removeClass', options);
5482 * @name $animate#setClass
5485 * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
5486 * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
5487 * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
5488 * passed. Note that class-based animations are treated differently compared to structural animations
5489 * (like enter, move and leave) since the CSS classes may be added/removed at different points
5490 * depending if CSS or JavaScript animations are used.
5492 * @param {DOMElement} element the element which the CSS classes will be applied to
5493 * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
5494 * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
5495 * @param {object=} options an optional collection of options/styles that will be applied to the element
5497 * @return {Promise} the animation callback promise
5499 setClass: function(element, add, remove, options) {
5500 options = prepareAnimateOptions(options);
5501 options.addClass = mergeClasses(options.addClass, add);
5502 options.removeClass = mergeClasses(options.removeClass, remove);
5503 return $$animateQueue.push(element, 'setClass', options);
5508 * @name $animate#animate
5511 * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
5512 * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
5513 * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
5514 * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
5515 * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
5517 * @param {DOMElement} element the element which the CSS styles will be applied to
5518 * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
5519 * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
5520 * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
5521 * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
5522 * (Note that if no animation is detected then this value will not be appplied to the element.)
5523 * @param {object=} options an optional collection of options/styles that will be applied to the element
5525 * @return {Promise} the animation callback promise
5527 animate: function(element, from, to, className, options) {
5528 options = prepareAnimateOptions(options);
5529 options.from = options.from ? extend(options.from, from) : from;
5530 options.to = options.to ? extend(options.to, to) : to;
5532 className = className || 'ng-inline-animate';
5533 options.tempClasses = mergeClasses(options.tempClasses, className);
5534 return $$animateQueue.push(element, 'animate', options);
5546 * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
5547 * then the `$animateCss` service will actually perform animations.
5549 * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
5551 var $CoreAnimateCssProvider = function() {
5552 this.$get = ['$$rAF', '$q', function($$rAF, $q) {
5554 var RAFPromise = function() {};
5555 RAFPromise.prototype = {
5556 done: function(cancel) {
5557 this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
5562 cancel: function() {
5565 getPromise: function() {
5567 this.defer = $q.defer();
5569 return this.defer.promise;
5571 then: function(f1,f2) {
5572 return this.getPromise().then(f1,f2);
5574 'catch': function(f1) {
5575 return this.getPromise()['catch'](f1);
5577 'finally': function(f1) {
5578 return this.getPromise()['finally'](f1);
5582 return function(element, options) {
5583 // there is no point in applying the styles since
5584 // there is no animation that goes on at all in
5585 // this version of $animateCss.
5586 if (options.cleanupStyles) {
5587 options.from = options.to = null;
5591 element.css(options.from);
5592 options.from = null;
5595 var closed, runner = new RAFPromise();
5613 if (options.addClass) {
5614 element.addClass(options.addClass);
5615 options.addClass = null;
5617 if (options.removeClass) {
5618 element.removeClass(options.removeClass);
5619 options.removeClass = null;
5622 element.css(options.to);
5630 /* global stripHash: true */
5633 * ! This is a private undocumented service !
5638 * This object has two goals:
5640 * - hide all the global state in the browser caused by the window object
5641 * - abstract away all the browser specific features and inconsistencies
5643 * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
5644 * service, which can be used for convenient testing of the application without the interaction with
5645 * the real browser apis.
5648 * @param {object} window The global window object.
5649 * @param {object} document jQuery wrapped document.
5650 * @param {object} $log window.console or an object with the same interface.
5651 * @param {object} $sniffer $sniffer service
5653 function Browser(window, document, $log, $sniffer) {
5655 rawDocument = document[0],
5656 location = window.location,
5657 history = window.history,
5658 setTimeout = window.setTimeout,
5659 clearTimeout = window.clearTimeout,
5660 pendingDeferIds = {};
5662 self.isMock = false;
5664 var outstandingRequestCount = 0;
5665 var outstandingRequestCallbacks = [];
5667 // TODO(vojta): remove this temporary api
5668 self.$$completeOutstandingRequest = completeOutstandingRequest;
5669 self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
5672 * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
5673 * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
5675 function completeOutstandingRequest(fn) {
5677 fn.apply(null, sliceArgs(arguments, 1));
5679 outstandingRequestCount--;
5680 if (outstandingRequestCount === 0) {
5681 while (outstandingRequestCallbacks.length) {
5683 outstandingRequestCallbacks.pop()();
5692 function getHash(url) {
5693 var index = url.indexOf('#');
5694 return index === -1 ? '' : url.substr(index);
5699 * Note: this method is used only by scenario runner
5700 * TODO(vojta): prefix this method with $$ ?
5701 * @param {function()} callback Function that will be called when no outstanding request
5703 self.notifyWhenNoOutstandingRequests = function(callback) {
5704 if (outstandingRequestCount === 0) {
5707 outstandingRequestCallbacks.push(callback);
5711 //////////////////////////////////////////////////////////////
5713 //////////////////////////////////////////////////////////////
5715 var cachedState, lastHistoryState,
5716 lastBrowserUrl = location.href,
5717 baseElement = document.find('base'),
5718 pendingLocation = null;
5721 lastHistoryState = cachedState;
5724 * @name $browser#url
5728 * Without any argument, this method just returns current value of location.href.
5731 * With at least one argument, this method sets url to new value.
5732 * If html5 history api supported, pushState/replaceState is used, otherwise
5733 * location.href/location.replace is used.
5734 * Returns its own instance to allow chaining
5736 * NOTE: this api is intended for use only by the $location service. Please use the
5737 * {@link ng.$location $location service} to change url.
5739 * @param {string} url New url (when used as setter)
5740 * @param {boolean=} replace Should new url replace current history record?
5741 * @param {object=} state object to use with pushState/replaceState
5743 self.url = function(url, replace, state) {
5744 // In modern browsers `history.state` is `null` by default; treating it separately
5745 // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
5746 // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
5747 if (isUndefined(state)) {
5751 // Android Browser BFCache causes location, history reference to become stale.
5752 if (location !== window.location) location = window.location;
5753 if (history !== window.history) history = window.history;
5757 var sameState = lastHistoryState === state;
5759 // Don't change anything if previous and current URLs and states match. This also prevents
5760 // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
5761 // See https://github.com/angular/angular.js/commit/ffb2701
5762 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
5765 var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
5766 lastBrowserUrl = url;
5767 lastHistoryState = state;
5768 // Don't use history API if only the hash changed
5769 // due to a bug in IE10/IE11 which leads
5770 // to not firing a `hashchange` nor `popstate` event
5771 // in some cases (see #9143).
5772 if ($sniffer.history && (!sameBase || !sameState)) {
5773 history[replace ? 'replaceState' : 'pushState'](state, '', url);
5775 // Do the assignment again so that those two variables are referentially identical.
5776 lastHistoryState = cachedState;
5778 if (!sameBase || pendingLocation) {
5779 pendingLocation = url;
5782 location.replace(url);
5783 } else if (!sameBase) {
5784 location.href = url;
5786 location.hash = getHash(url);
5788 if (location.href !== url) {
5789 pendingLocation = url;
5795 // - pendingLocation is needed as browsers don't allow to read out
5796 // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
5797 // https://openradar.appspot.com/22186109).
5798 // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
5799 return pendingLocation || location.href.replace(/%27/g,"'");
5804 * @name $browser#state
5807 * This method is a getter.
5809 * Return history.state or null if history.state is undefined.
5811 * @returns {object} state
5813 self.state = function() {
5817 var urlChangeListeners = [],
5818 urlChangeInit = false;
5820 function cacheStateAndFireUrlChange() {
5821 pendingLocation = null;
5826 function getCurrentState() {
5828 return history.state;
5830 // MSIE can reportedly throw when there is no state (UNCONFIRMED).
5834 // This variable should be used *only* inside the cacheState function.
5835 var lastCachedState = null;
5836 function cacheState() {
5837 // This should be the only place in $browser where `history.state` is read.
5838 cachedState = getCurrentState();
5839 cachedState = isUndefined(cachedState) ? null : cachedState;
5841 // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
5842 if (equals(cachedState, lastCachedState)) {
5843 cachedState = lastCachedState;
5845 lastCachedState = cachedState;
5848 function fireUrlChange() {
5849 if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
5853 lastBrowserUrl = self.url();
5854 lastHistoryState = cachedState;
5855 forEach(urlChangeListeners, function(listener) {
5856 listener(self.url(), cachedState);
5861 * @name $browser#onUrlChange
5864 * Register callback function that will be called, when url changes.
5866 * It's only called when the url is changed from outside of angular:
5867 * - user types different url into address bar
5868 * - user clicks on history (forward/back) button
5869 * - user clicks on a link
5871 * It's not called when url is changed by $browser.url() method
5873 * The listener gets called with new url as parameter.
5875 * NOTE: this api is intended for use only by the $location service. Please use the
5876 * {@link ng.$location $location service} to monitor url changes in angular apps.
5878 * @param {function(string)} listener Listener function to be called when url changes.
5879 * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
5881 self.onUrlChange = function(callback) {
5882 // TODO(vojta): refactor to use node's syntax for events
5883 if (!urlChangeInit) {
5884 // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
5885 // don't fire popstate when user change the address bar and don't fire hashchange when url
5886 // changed by push/replaceState
5888 // html5 history api - popstate event
5889 if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
5891 jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
5893 urlChangeInit = true;
5896 urlChangeListeners.push(callback);
5902 * Remove popstate and hashchange handler from window.
5904 * NOTE: this api is intended for use only by $rootScope.
5906 self.$$applicationDestroyed = function() {
5907 jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
5911 * Checks whether the url has changed outside of Angular.
5912 * Needs to be exported to be able to check for changes that have been done in sync,
5913 * as hashchange/popstate events fire in async.
5915 self.$$checkUrlChange = fireUrlChange;
5917 //////////////////////////////////////////////////////////////
5919 //////////////////////////////////////////////////////////////
5922 * @name $browser#baseHref
5925 * Returns current <base href>
5926 * (always relative - without domain)
5928 * @returns {string} The current base href
5930 self.baseHref = function() {
5931 var href = baseElement.attr('href');
5932 return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
5936 * @name $browser#defer
5937 * @param {function()} fn A function, who's execution should be deferred.
5938 * @param {number=} [delay=0] of milliseconds to defer the function execution.
5939 * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
5942 * Executes a fn asynchronously via `setTimeout(fn, delay)`.
5944 * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
5945 * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
5946 * via `$browser.defer.flush()`.
5949 self.defer = function(fn, delay) {
5951 outstandingRequestCount++;
5952 timeoutId = setTimeout(function() {
5953 delete pendingDeferIds[timeoutId];
5954 completeOutstandingRequest(fn);
5956 pendingDeferIds[timeoutId] = true;
5962 * @name $browser#defer.cancel
5965 * Cancels a deferred task identified with `deferId`.
5967 * @param {*} deferId Token returned by the `$browser.defer` function.
5968 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
5971 self.defer.cancel = function(deferId) {
5972 if (pendingDeferIds[deferId]) {
5973 delete pendingDeferIds[deferId];
5974 clearTimeout(deferId);
5975 completeOutstandingRequest(noop);
5983 function $BrowserProvider() {
5984 this.$get = ['$window', '$log', '$sniffer', '$document',
5985 function($window, $log, $sniffer, $document) {
5986 return new Browser($window, $document, $log, $sniffer);
5992 * @name $cacheFactory
5995 * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
6000 * var cache = $cacheFactory('cacheId');
6001 * expect($cacheFactory.get('cacheId')).toBe(cache);
6002 * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
6004 * cache.put("key", "value");
6005 * cache.put("another key", "another value");
6007 * // We've specified no options on creation
6008 * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
6013 * @param {string} cacheId Name or id of the newly created cache.
6014 * @param {object=} options Options object that specifies the cache behavior. Properties:
6016 * - `{number=}` `capacity` — turns the cache into LRU cache.
6018 * @returns {object} Newly created cache object with the following set of methods:
6020 * - `{object}` `info()` — Returns id, size, and options of cache.
6021 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
6023 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
6024 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
6025 * - `{void}` `removeAll()` — Removes all cached values.
6026 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
6029 <example module="cacheExampleApp">
6030 <file name="index.html">
6031 <div ng-controller="CacheController">
6032 <input ng-model="newCacheKey" placeholder="Key">
6033 <input ng-model="newCacheValue" placeholder="Value">
6034 <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
6036 <p ng-if="keys.length">Cached Values</p>
6037 <div ng-repeat="key in keys">
6038 <span ng-bind="key"></span>
6040 <b ng-bind="cache.get(key)"></b>
6044 <div ng-repeat="(key, value) in cache.info()">
6045 <span ng-bind="key"></span>
6047 <b ng-bind="value"></b>
6051 <file name="script.js">
6052 angular.module('cacheExampleApp', []).
6053 controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
6055 $scope.cache = $cacheFactory('cacheId');
6056 $scope.put = function(key, value) {
6057 if (angular.isUndefined($scope.cache.get(key))) {
6058 $scope.keys.push(key);
6060 $scope.cache.put(key, angular.isUndefined(value) ? null : value);
6064 <file name="style.css">
6071 function $CacheFactoryProvider() {
6073 this.$get = function() {
6076 function cacheFactory(cacheId, options) {
6077 if (cacheId in caches) {
6078 throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
6082 stats = extend({}, options, {id: cacheId}),
6084 capacity = (options && options.capacity) || Number.MAX_VALUE,
6085 lruHash = createMap(),
6091 * @name $cacheFactory.Cache
6094 * A cache object used to store and retrieve data, primarily used by
6095 * {@link $http $http} and the {@link ng.directive:script script} directive to cache
6096 * templates and other data.
6099 * angular.module('superCache')
6100 * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
6101 * return $cacheFactory('super-cache');
6108 * it('should behave like a cache', inject(function(superCache) {
6109 * superCache.put('key', 'value');
6110 * superCache.put('another key', 'another value');
6112 * expect(superCache.info()).toEqual({
6113 * id: 'super-cache',
6117 * superCache.remove('another key');
6118 * expect(superCache.get('another key')).toBeUndefined();
6120 * superCache.removeAll();
6121 * expect(superCache.info()).toEqual({
6122 * id: 'super-cache',
6128 return caches[cacheId] = {
6132 * @name $cacheFactory.Cache#put
6136 * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
6137 * retrieved later, and incrementing the size of the cache if the key was not already
6138 * present in the cache. If behaving like an LRU cache, it will also remove stale
6139 * entries from the set.
6141 * It will not insert undefined values into the cache.
6143 * @param {string} key the key under which the cached data is stored.
6144 * @param {*} value the value to store alongside the key. If it is undefined, the key
6145 * will not be stored.
6146 * @returns {*} the value stored.
6148 put: function(key, value) {
6149 if (isUndefined(value)) return;
6150 if (capacity < Number.MAX_VALUE) {
6151 var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
6156 if (!(key in data)) size++;
6159 if (size > capacity) {
6160 this.remove(staleEnd.key);
6168 * @name $cacheFactory.Cache#get
6172 * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
6174 * @param {string} key the key of the data to be retrieved
6175 * @returns {*} the value stored.
6177 get: function(key) {
6178 if (capacity < Number.MAX_VALUE) {
6179 var lruEntry = lruHash[key];
6181 if (!lruEntry) return;
6192 * @name $cacheFactory.Cache#remove
6196 * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
6198 * @param {string} key the key of the entry to be removed
6200 remove: function(key) {
6201 if (capacity < Number.MAX_VALUE) {
6202 var lruEntry = lruHash[key];
6204 if (!lruEntry) return;
6206 if (lruEntry == freshEnd) freshEnd = lruEntry.p;
6207 if (lruEntry == staleEnd) staleEnd = lruEntry.n;
6208 link(lruEntry.n,lruEntry.p);
6210 delete lruHash[key];
6213 if (!(key in data)) return;
6222 * @name $cacheFactory.Cache#removeAll
6226 * Clears the cache object of any entries.
6228 removeAll: function() {
6231 lruHash = createMap();
6232 freshEnd = staleEnd = null;
6238 * @name $cacheFactory.Cache#destroy
6242 * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
6243 * removing it from the {@link $cacheFactory $cacheFactory} set.
6245 destroy: function() {
6249 delete caches[cacheId];
6255 * @name $cacheFactory.Cache#info
6259 * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
6261 * @returns {object} an object with the following properties:
6263 * <li>**id**: the id of the cache instance</li>
6264 * <li>**size**: the number of entries kept in the cache instance</li>
6265 * <li>**...**: any additional properties from the options object when creating the
6270 return extend({}, stats, {size: size});
6276 * makes the `entry` the freshEnd of the LRU linked list
6278 function refresh(entry) {
6279 if (entry != freshEnd) {
6282 } else if (staleEnd == entry) {
6286 link(entry.n, entry.p);
6287 link(entry, freshEnd);
6295 * bidirectionally links two entries of the LRU linked list
6297 function link(nextEntry, prevEntry) {
6298 if (nextEntry != prevEntry) {
6299 if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
6300 if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
6308 * @name $cacheFactory#info
6311 * Get information about all the caches that have been created
6313 * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
6315 cacheFactory.info = function() {
6317 forEach(caches, function(cache, cacheId) {
6318 info[cacheId] = cache.info();
6326 * @name $cacheFactory#get
6329 * Get access to a cache object by the `cacheId` used when it was created.
6331 * @param {string} cacheId Name or id of a cache to access.
6332 * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
6334 cacheFactory.get = function(cacheId) {
6335 return caches[cacheId];
6339 return cacheFactory;
6345 * @name $templateCache
6348 * The first time a template is used, it is loaded in the template cache for quick retrieval. You
6349 * can load templates directly into the cache in a `script` tag, or by consuming the
6350 * `$templateCache` service directly.
6352 * Adding via the `script` tag:
6355 * <script type="text/ng-template" id="templateId.html">
6356 * <p>This is the content of the template</p>
6360 * **Note:** the `script` tag containing the template does not need to be included in the `head` of
6361 * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
6362 * element with ng-app attribute), otherwise the template will be ignored.
6364 * Adding via the `$templateCache` service:
6367 * var myApp = angular.module('myApp', []);
6368 * myApp.run(function($templateCache) {
6369 * $templateCache.put('templateId.html', 'This is the content of the template');
6373 * To retrieve the template later, simply use it in your HTML:
6375 * <div ng-include=" 'templateId.html' "></div>
6378 * or get it via Javascript:
6380 * $templateCache.get('templateId.html')
6383 * See {@link ng.$cacheFactory $cacheFactory}.
6386 function $TemplateCacheProvider() {
6387 this.$get = ['$cacheFactory', function($cacheFactory) {
6388 return $cacheFactory('templates');
6392 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
6393 * Any commits to this file should be reviewed with security in mind. *
6394 * Changes to this file can potentially create security vulnerabilities. *
6395 * An approval from 2 Core members with history of modifying *
6396 * this file is required. *
6398 * Does the change somehow allow for arbitrary javascript to be executed? *
6399 * Or allows for someone to change the prototype of built-in objects? *
6400 * Or gives undesired access to variables likes document or window? *
6401 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
6403 /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
6405 * DOM-related variables:
6407 * - "node" - DOM Node
6408 * - "element" - DOM Element or Node
6409 * - "$node" or "$element" - jqLite-wrapped node or element
6412 * Compiler related stuff:
6414 * - "linkFn" - linking fn of a single directive
6415 * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
6416 * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
6417 * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
6427 * Compiles an HTML string or DOM into a template and produces a template function, which
6428 * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
6430 * The compilation is a process of walking the DOM tree and matching DOM elements to
6431 * {@link ng.$compileProvider#directive directives}.
6433 * <div class="alert alert-warning">
6434 * **Note:** This document is an in-depth reference of all directive options.
6435 * For a gentle introduction to directives with examples of common use cases,
6436 * see the {@link guide/directive directive guide}.
6439 * ## Comprehensive Directive API
6441 * There are many different options for a directive.
6443 * The difference resides in the return value of the factory function.
6444 * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
6445 * or just the `postLink` function (all other properties will have the default values).
6447 * <div class="alert alert-success">
6448 * **Best Practice:** It's recommended to use the "directive definition object" form.
6451 * Here's an example directive declared with a Directive Definition Object:
6454 * var myModule = angular.module(...);
6456 * myModule.directive('directiveName', function factory(injectables) {
6457 * var directiveDefinitionObject = {
6459 * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
6461 * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
6462 * transclude: false,
6464 * templateNamespace: 'html',
6466 * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
6467 * controllerAs: 'stringIdentifier',
6468 * bindToController: false,
6469 * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
6470 * compile: function compile(tElement, tAttrs, transclude) {
6472 * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
6473 * post: function postLink(scope, iElement, iAttrs, controller) { ... }
6476 * // return function postLink( ... ) { ... }
6480 * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
6481 * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
6484 * // link: function postLink( ... ) { ... }
6486 * return directiveDefinitionObject;
6490 * <div class="alert alert-warning">
6491 * **Note:** Any unspecified options will use the default value. You can see the default values below.
6494 * Therefore the above can be simplified as:
6497 * var myModule = angular.module(...);
6499 * myModule.directive('directiveName', function factory(injectables) {
6500 * var directiveDefinitionObject = {
6501 * link: function postLink(scope, iElement, iAttrs) { ... }
6503 * return directiveDefinitionObject;
6505 * // return function postLink(scope, iElement, iAttrs) { ... }
6511 * ### Directive Definition Object
6513 * The directive definition object provides instructions to the {@link ng.$compile
6514 * compiler}. The attributes are:
6516 * #### `multiElement`
6517 * When this property is set to true, the HTML compiler will collect DOM nodes between
6518 * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
6519 * together as the directive elements. It is recommended that this feature be used on directives
6520 * which are not strictly behavioural (such as {@link ngClick}), and which
6521 * do not manipulate or replace child nodes (such as {@link ngInclude}).
6524 * When there are multiple directives defined on a single DOM element, sometimes it
6525 * is necessary to specify the order in which the directives are applied. The `priority` is used
6526 * to sort the directives before their `compile` functions get called. Priority is defined as a
6527 * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
6528 * are also run in priority order, but post-link functions are run in reverse order. The order
6529 * of directives with the same priority is undefined. The default priority is `0`.
6532 * If set to true then the current `priority` will be the last set of directives
6533 * which will execute (any directives at the current priority will still execute
6534 * as the order of execution on same `priority` is undefined). Note that expressions
6535 * and other directives used in the directive's template will also be excluded from execution.
6538 * The scope property can be `true`, an object or a falsy value:
6540 * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
6542 * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
6543 * the directive's element. If multiple directives on the same element request a new scope,
6544 * only one new scope is created. The new scope rule does not apply for the root of the template
6545 * since the root of the template always gets a new scope.
6547 * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
6548 * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
6549 * scope. This is useful when creating reusable components, which should not accidentally read or modify
6550 * data in the parent scope.
6552 * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
6553 * directive's element. These local properties are useful for aliasing values for templates. The keys in
6554 * the object hash map to the name of the property on the isolate scope; the values define how the property
6555 * is bound to the parent scope, via matching attributes on the directive's element:
6557 * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
6558 * always a string since DOM attributes are strings. If no `attr` name is specified then the
6559 * attribute name is assumed to be the same as the local name.
6560 * Given `<widget my-attr="hello {{name}}">` and widget definition
6561 * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
6562 * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
6563 * `localName` property on the widget scope. The `name` is read from the parent scope (not
6566 * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
6567 * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
6568 * name is specified then the attribute name is assumed to be the same as the local name.
6569 * Given `<widget my-attr="parentModel">` and widget definition of
6570 * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
6571 * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
6572 * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
6573 * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
6574 * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
6575 * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
6576 * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
6578 * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
6579 * If no `attr` name is specified then the attribute name is assumed to be the same as the
6580 * local name. Given `<widget my-attr="count = count + value">` and widget definition of
6581 * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
6582 * a function wrapper for the `count = count + value` expression. Often it's desirable to
6583 * pass data from the isolated scope via an expression to the parent scope, this can be
6584 * done by passing a map of local variable names and values into the expression wrapper fn.
6585 * For example, if the expression is `increment(amount)` then we can specify the amount value
6586 * by calling the `localFn` as `localFn({amount: 22})`.
6588 * In general it's possible to apply more than one directive to one element, but there might be limitations
6589 * depending on the type of scope required by the directives. The following points will help explain these limitations.
6590 * For simplicity only two directives are taken into account, but it is also applicable for several directives:
6592 * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
6593 * * **child scope** + **no scope** => Both directives will share one single child scope
6594 * * **child scope** + **child scope** => Both directives will share one single child scope
6595 * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
6596 * its parent's scope
6597 * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
6598 * be applied to the same element.
6599 * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
6600 * cannot be applied to the same element.
6603 * #### `bindToController`
6604 * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
6605 * allow a component to have its properties bound to the controller, rather than to scope. When the controller
6606 * is instantiated, the initial values of the isolate scope bindings are already available.
6609 * Controller constructor function. The controller is instantiated before the
6610 * pre-linking phase and can be accessed by other directives (see
6611 * `require` attribute). This allows the directives to communicate with each other and augment
6612 * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
6614 * * `$scope` - Current scope associated with the element
6615 * * `$element` - Current element
6616 * * `$attrs` - Current attributes object for the element
6617 * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
6618 * `function([scope], cloneLinkingFn, futureParentElement)`.
6619 * * `scope`: optional argument to override the scope.
6620 * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
6621 * * `futureParentElement`:
6622 * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
6623 * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
6624 * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
6625 * and when the `cloneLinkinFn` is passed,
6626 * as those elements need to created and cloned in a special way when they are defined outside their
6627 * usual containers (e.g. like `<svg>`).
6628 * * See also the `directive.templateNamespace` property.
6632 * Require another directive and inject its controller as the fourth argument to the linking function. The
6633 * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
6634 * injected argument will be an array in corresponding order. If no such directive can be
6635 * found, or if the directive does not have a controller, then an error is raised (unless no link function
6636 * is specified, in which case error checking is skipped). The name can be prefixed with:
6638 * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
6639 * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
6640 * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
6641 * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
6642 * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
6643 * `null` to the `link` fn if not found.
6644 * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
6645 * `null` to the `link` fn if not found.
6648 * #### `controllerAs`
6649 * Identifier name for a reference to the controller in the directive's scope.
6650 * This allows the controller to be referenced from the directive template. This is especially
6651 * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
6652 * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
6653 * `controllerAs` reference might overwrite a property that already exists on the parent scope.
6657 * String of subset of `EACM` which restricts the directive to a specific directive
6658 * declaration style. If omitted, the defaults (elements and attributes) are used.
6660 * * `E` - Element name (default): `<my-directive></my-directive>`
6661 * * `A` - Attribute (default): `<div my-directive="exp"></div>`
6662 * * `C` - Class: `<div class="my-directive: exp;"></div>`
6663 * * `M` - Comment: `<!-- directive: my-directive exp -->`
6666 * #### `templateNamespace`
6667 * String representing the document type used by the markup in the template.
6668 * AngularJS needs this information as those elements need to be created and cloned
6669 * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
6671 * * `html` - All root nodes in the template are HTML. Root nodes may also be
6672 * top-level elements such as `<svg>` or `<math>`.
6673 * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
6674 * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
6676 * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
6679 * HTML markup that may:
6680 * * Replace the contents of the directive's element (default).
6681 * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
6682 * * Wrap the contents of the directive's element (if `transclude` is true).
6686 * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
6687 * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
6688 * function api below) and returns a string value.
6691 * #### `templateUrl`
6692 * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
6694 * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
6695 * for later when the template has been resolved. In the meantime it will continue to compile and link
6696 * sibling and parent elements as though this element had not contained any directives.
6698 * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
6699 * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
6700 * case when only one deeply nested directive has `templateUrl`.
6702 * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
6704 * You can specify `templateUrl` as a string representing the URL or as a function which takes two
6705 * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
6706 * a string value representing the url. In either case, the template URL is passed through {@link
6707 * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
6710 * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
6711 * specify what the template should replace. Defaults to `false`.
6713 * * `true` - the template will replace the directive's element.
6714 * * `false` - the template will replace the contents of the directive's element.
6716 * The replacement process migrates all of the attributes / classes from the old element to the new
6717 * one. See the {@link guide/directive#template-expanding-directive
6718 * Directives Guide} for an example.
6720 * There are very few scenarios where element replacement is required for the application function,
6721 * the main one being reusable custom components that are used within SVG contexts
6722 * (because SVG doesn't work with custom elements in the DOM tree).
6725 * Extract the contents of the element where the directive appears and make it available to the directive.
6726 * The contents are compiled and provided to the directive as a **transclusion function**. See the
6727 * {@link $compile#transclusion Transclusion} section below.
6729 * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
6730 * directive's element or the entire element:
6732 * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
6733 * * `'element'` - transclude the whole of the directive's element including any directives on this
6734 * element that defined at a lower priority than this directive. When used, the `template`
6735 * property is ignored.
6741 * function compile(tElement, tAttrs, transclude) { ... }
6744 * The compile function deals with transforming the template DOM. Since most directives do not do
6745 * template transformation, it is not used often. The compile function takes the following arguments:
6747 * * `tElement` - template element - The element where the directive has been declared. It is
6748 * safe to do template transformation on the element and child elements only.
6750 * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
6751 * between all directive compile functions.
6753 * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
6755 * <div class="alert alert-warning">
6756 * **Note:** The template instance and the link instance may be different objects if the template has
6757 * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
6758 * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
6759 * should be done in a linking function rather than in a compile function.
6762 * <div class="alert alert-warning">
6763 * **Note:** The compile function cannot handle directives that recursively use themselves in their
6764 * own templates or compile functions. Compiling these directives results in an infinite loop and a
6765 * stack overflow errors.
6767 * This can be avoided by manually using $compile in the postLink function to imperatively compile
6768 * a directive's template instead of relying on automatic template compilation via `template` or
6769 * `templateUrl` declaration or manual compilation inside the compile function.
6772 * <div class="alert alert-danger">
6773 * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
6774 * e.g. does not know about the right outer scope. Please use the transclude function that is passed
6775 * to the link function instead.
6778 * A compile function can have a return value which can be either a function or an object.
6780 * * returning a (post-link) function - is equivalent to registering the linking function via the
6781 * `link` property of the config object when the compile function is empty.
6783 * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
6784 * control when a linking function should be called during the linking phase. See info about
6785 * pre-linking and post-linking functions below.
6789 * This property is used only if the `compile` property is not defined.
6792 * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
6795 * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
6796 * executed after the template has been cloned. This is where most of the directive logic will be
6799 * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
6800 * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
6802 * * `iElement` - instance element - The element where the directive is to be used. It is safe to
6803 * manipulate the children of the element only in `postLink` function since the children have
6804 * already been linked.
6806 * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
6807 * between all directive linking functions.
6809 * * `controller` - the directive's required controller instance(s) - Instances are shared
6810 * among all directives, which allows the directives to use the controllers as a communication
6811 * channel. The exact value depends on the directive's `require` property:
6812 * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
6813 * * `string`: the controller instance
6814 * * `array`: array of controller instances
6816 * If a required controller cannot be found, and it is optional, the instance is `null`,
6817 * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
6819 * Note that you can also require the directive's own controller - it will be made available like
6820 * any other controller.
6822 * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
6823 * This is the same as the `$transclude`
6824 * parameter of directive controllers, see there for details.
6825 * `function([scope], cloneLinkingFn, futureParentElement)`.
6827 * #### Pre-linking function
6829 * Executed before the child elements are linked. Not safe to do DOM transformation since the
6830 * compiler linking function will fail to locate the correct elements for linking.
6832 * #### Post-linking function
6834 * Executed after the child elements are linked.
6836 * Note that child elements that contain `templateUrl` directives will not have been compiled
6837 * and linked since they are waiting for their template to load asynchronously and their own
6838 * compilation and linking has been suspended until that occurs.
6840 * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
6841 * for their async templates to be resolved.
6846 * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
6847 * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
6848 * scope from where they were taken.
6850 * Transclusion is used (often with {@link ngTransclude}) to insert the
6851 * original contents of a directive's element into a specified place in the template of the directive.
6852 * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
6853 * content has access to the properties on the scope from which it was taken, even if the directive
6854 * has isolated scope.
6855 * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
6857 * This makes it possible for the widget to have private state for its template, while the transcluded
6858 * content has access to its originating scope.
6860 * <div class="alert alert-warning">
6861 * **Note:** When testing an element transclude directive you must not place the directive at the root of the
6862 * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
6863 * Testing Transclusion Directives}.
6866 * #### Transclusion Functions
6868 * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
6869 * function** to the directive's `link` function and `controller`. This transclusion function is a special
6870 * **linking function** that will return the compiled contents linked to a new transclusion scope.
6872 * <div class="alert alert-info">
6873 * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
6874 * ngTransclude will deal with it for us.
6877 * If you want to manually control the insertion and removal of the transcluded content in your directive
6878 * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
6879 * object that contains the compiled DOM, which is linked to the correct transclusion scope.
6881 * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
6882 * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
6883 * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
6885 * <div class="alert alert-info">
6886 * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
6887 * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
6890 * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
6891 * attach function**:
6894 * var transcludedContent, transclusionScope;
6896 * $transclude(function(clone, scope) {
6897 * element.append(clone);
6898 * transcludedContent = clone;
6899 * transclusionScope = scope;
6903 * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
6904 * associated transclusion scope:
6907 * transcludedContent.remove();
6908 * transclusionScope.$destroy();
6911 * <div class="alert alert-info">
6912 * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
6913 * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
6914 * then you are also responsible for calling `$destroy` on the transclusion scope.
6917 * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
6918 * automatically destroy their transluded clones as necessary so you do not need to worry about this if
6919 * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
6922 * #### Transclusion Scopes
6924 * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
6925 * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
6926 * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
6929 * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
6935 * <div transclusion>
6941 * The `$parent` scope hierarchy will look like this:
6949 * but the scopes will inherit prototypically from different scopes to their `$parent`.
6960 * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
6961 * `link()` or `compile()` functions. It has a variety of uses.
6963 * accessing *Normalized attribute names:*
6964 * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
6965 * the attributes object allows for normalized access to
6968 * * *Directive inter-communication:* All directives share the same instance of the attributes
6969 * object which allows the directives to use the attributes object as inter directive
6972 * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
6973 * allowing other directives to read the interpolated value.
6975 * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
6976 * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
6977 * the only way to easily get the actual value because during the linking phase the interpolation
6978 * hasn't been evaluated yet and so the value is at this time set to `undefined`.
6981 * function linkingFn(scope, elm, attrs, ctrl) {
6982 * // get the attribute value
6983 * console.log(attrs.ngModel);
6985 * // change the attribute
6986 * attrs.$set('ngModel', 'new value');
6988 * // observe changes to interpolated attribute
6989 * attrs.$observe('ngModel', function(value) {
6990 * console.log('ngModel has changed value to ' + value);
6997 * <div class="alert alert-warning">
6998 * **Note**: Typically directives are registered with `module.directive`. The example below is
6999 * to illustrate how `$compile` works.
7002 <example module="compileExample">
7003 <file name="index.html">
7005 angular.module('compileExample', [], function($compileProvider) {
7006 // configure new 'compile' directive by passing a directive
7007 // factory function. The factory function injects the '$compile'
7008 $compileProvider.directive('compile', function($compile) {
7009 // directive factory creates a link function
7010 return function(scope, element, attrs) {
7013 // watch the 'compile' expression for changes
7014 return scope.$eval(attrs.compile);
7017 // when the 'compile' expression changes
7018 // assign it into the current DOM
7019 element.html(value);
7021 // compile the new DOM and link it to the current
7023 // NOTE: we only compile .childNodes so that
7024 // we don't get into infinite loop compiling ourselves
7025 $compile(element.contents())(scope);
7031 .controller('GreeterController', ['$scope', function($scope) {
7032 $scope.name = 'Angular';
7033 $scope.html = 'Hello {{name}}';
7036 <div ng-controller="GreeterController">
7037 <input ng-model="name"> <br/>
7038 <textarea ng-model="html"></textarea> <br/>
7039 <div compile="html"></div>
7042 <file name="protractor.js" type="protractor">
7043 it('should auto compile', function() {
7044 var textarea = $('textarea');
7045 var output = $('div[compile]');
7046 // The initial state reads 'Hello Angular'.
7047 expect(output.getText()).toBe('Hello Angular');
7049 textarea.sendKeys('{{name}}!');
7050 expect(output.getText()).toBe('Angular!');
7057 * @param {string|DOMElement} element Element or HTML string to compile into a template function.
7058 * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
7060 * <div class="alert alert-danger">
7061 * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
7062 * e.g. will not use the right outer scope. Please pass the transclude function as a
7063 * `parentBoundTranscludeFn` to the link function instead.
7066 * @param {number} maxPriority only apply directives lower than given priority (Only effects the
7067 * root element(s), not their children)
7068 * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
7069 * (a DOM element/tree) to a scope. Where:
7071 * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
7072 * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
7073 * `template` and call the `cloneAttachFn` function allowing the caller to attach the
7074 * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
7075 * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
7077 * * `clonedElement` - is a clone of the original `element` passed into the compiler.
7078 * * `scope` - is the current scope with which the linking function is working with.
7080 * * `options` - An optional object hash with linking options. If `options` is provided, then the following
7081 * keys may be used to control linking behavior:
7083 * * `parentBoundTranscludeFn` - the transclude function made available to
7084 * directives; if given, it will be passed through to the link functions of
7085 * directives found in `element` during compilation.
7086 * * `transcludeControllers` - an object hash with keys that map controller names
7087 * to controller instances; if given, it will make the controllers
7088 * available to directives.
7089 * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
7090 * the cloned elements; only needed for transcludes that are allowed to contain non html
7091 * elements (e.g. SVG elements). See also the directive.controller property.
7093 * Calling the linking function returns the element of the template. It is either the original
7094 * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
7096 * After linking the view is not updated until after a call to $digest which typically is done by
7097 * Angular automatically.
7099 * If you need access to the bound view, there are two ways to do it:
7101 * - If you are not asking the linking function to clone the template, create the DOM element(s)
7102 * before you send them to the compiler and keep this reference around.
7104 * var element = $compile('<p>{{total}}</p>')(scope);
7107 * - if on the other hand, you need the element to be cloned, the view reference from the original
7108 * example would not point to the clone, but rather to the original template that was cloned. In
7109 * this case, you can access the clone via the cloneAttachFn:
7111 * var templateElement = angular.element('<p>{{total}}</p>'),
7114 * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
7115 * //attach the clone to DOM document at the right place
7118 * //now we have reference to the cloned DOM via `clonedElement`
7122 * For information on how the compiler works, see the
7123 * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
7126 var $compileMinErr = minErr('$compile');
7130 * @name $compileProvider
7134 $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
7135 function $CompileProvider($provide, $$sanitizeUriProvider) {
7136 var hasDirectives = {},
7137 Suffix = 'Directive',
7138 COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
7139 CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
7140 ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
7141 REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
7143 // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
7144 // The assumption is that future DOM event attribute names will begin with
7145 // 'on' and be composed of only English letters.
7146 var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
7148 function parseIsolateBindings(scope, directiveName, isController) {
7149 var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
7153 forEach(scope, function(definition, scopeName) {
7154 var match = definition.match(LOCAL_REGEXP);
7157 throw $compileMinErr('iscp',
7158 "Invalid {3} for directive '{0}'." +
7159 " Definition: {... {1}: '{2}' ...}",
7160 directiveName, scopeName, definition,
7161 (isController ? "controller bindings definition" :
7162 "isolate scope definition"));
7165 bindings[scopeName] = {
7167 collection: match[2] === '*',
7168 optional: match[3] === '?',
7169 attrName: match[4] || scopeName
7176 function parseDirectiveBindings(directive, directiveName) {
7179 bindToController: null
7181 if (isObject(directive.scope)) {
7182 if (directive.bindToController === true) {
7183 bindings.bindToController = parseIsolateBindings(directive.scope,
7184 directiveName, true);
7185 bindings.isolateScope = {};
7187 bindings.isolateScope = parseIsolateBindings(directive.scope,
7188 directiveName, false);
7191 if (isObject(directive.bindToController)) {
7192 bindings.bindToController =
7193 parseIsolateBindings(directive.bindToController, directiveName, true);
7195 if (isObject(bindings.bindToController)) {
7196 var controller = directive.controller;
7197 var controllerAs = directive.controllerAs;
7199 // There is no controller, there may or may not be a controllerAs property
7200 throw $compileMinErr('noctrl',
7201 "Cannot bind to controller without directive '{0}'s controller.",
7203 } else if (!identifierForController(controller, controllerAs)) {
7204 // There is a controller, but no identifier or controllerAs property
7205 throw $compileMinErr('noident',
7206 "Cannot bind to controller without identifier for directive '{0}'.",
7213 function assertValidDirectiveName(name) {
7214 var letter = name.charAt(0);
7215 if (!letter || letter !== lowercase(letter)) {
7216 throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
7218 if (name !== name.trim()) {
7219 throw $compileMinErr('baddir',
7220 "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
7227 * @name $compileProvider#directive
7231 * Register a new directive with the compiler.
7233 * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
7234 * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
7235 * names and the values are the factories.
7236 * @param {Function|Array} directiveFactory An injectable directive factory function. See
7237 * {@link guide/directive} for more info.
7238 * @returns {ng.$compileProvider} Self for chaining.
7240 this.directive = function registerDirective(name, directiveFactory) {
7241 assertNotHasOwnProperty(name, 'directive');
7242 if (isString(name)) {
7243 assertValidDirectiveName(name);
7244 assertArg(directiveFactory, 'directiveFactory');
7245 if (!hasDirectives.hasOwnProperty(name)) {
7246 hasDirectives[name] = [];
7247 $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
7248 function($injector, $exceptionHandler) {
7249 var directives = [];
7250 forEach(hasDirectives[name], function(directiveFactory, index) {
7252 var directive = $injector.invoke(directiveFactory);
7253 if (isFunction(directive)) {
7254 directive = { compile: valueFn(directive) };
7255 } else if (!directive.compile && directive.link) {
7256 directive.compile = valueFn(directive.link);
7258 directive.priority = directive.priority || 0;
7259 directive.index = index;
7260 directive.name = directive.name || name;
7261 directive.require = directive.require || (directive.controller && directive.name);
7262 directive.restrict = directive.restrict || 'EA';
7263 var bindings = directive.$$bindings =
7264 parseDirectiveBindings(directive, directive.name);
7265 if (isObject(bindings.isolateScope)) {
7266 directive.$$isolateBindings = bindings.isolateScope;
7268 directive.$$moduleName = directiveFactory.$$moduleName;
7269 directives.push(directive);
7271 $exceptionHandler(e);
7277 hasDirectives[name].push(directiveFactory);
7279 forEach(name, reverseParams(registerDirective));
7287 * @name $compileProvider#aHrefSanitizationWhitelist
7291 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
7292 * urls during a[href] sanitization.
7294 * The sanitization is a security measure aimed at preventing XSS attacks via html links.
7296 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
7297 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
7298 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
7299 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
7301 * @param {RegExp=} regexp New regexp to whitelist urls with.
7302 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
7303 * chaining otherwise.
7305 this.aHrefSanitizationWhitelist = function(regexp) {
7306 if (isDefined(regexp)) {
7307 $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
7310 return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
7317 * @name $compileProvider#imgSrcSanitizationWhitelist
7321 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
7322 * urls during img[src] sanitization.
7324 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
7326 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
7327 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
7328 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
7329 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
7331 * @param {RegExp=} regexp New regexp to whitelist urls with.
7332 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
7333 * chaining otherwise.
7335 this.imgSrcSanitizationWhitelist = function(regexp) {
7336 if (isDefined(regexp)) {
7337 $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
7340 return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
7346 * @name $compileProvider#debugInfoEnabled
7348 * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
7349 * current debugInfoEnabled state
7350 * @returns {*} current value if used as getter or itself (chaining) if used as setter
7355 * Call this method to enable/disable various debug runtime information in the compiler such as adding
7356 * binding information and a reference to the current scope on to DOM elements.
7357 * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
7358 * * `ng-binding` CSS class
7359 * * `$binding` data property containing an array of the binding expressions
7361 * You may want to disable this in production for a significant performance boost. See
7362 * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
7364 * The default value is true.
7366 var debugInfoEnabled = true;
7367 this.debugInfoEnabled = function(enabled) {
7368 if (isDefined(enabled)) {
7369 debugInfoEnabled = enabled;
7372 return debugInfoEnabled;
7376 '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
7377 '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
7378 function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
7379 $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
7381 var Attributes = function(element, attributesToCopy) {
7382 if (attributesToCopy) {
7383 var keys = Object.keys(attributesToCopy);
7386 for (i = 0, l = keys.length; i < l; i++) {
7388 this[key] = attributesToCopy[key];
7394 this.$$element = element;
7397 Attributes.prototype = {
7400 * @name $compile.directive.Attributes#$normalize
7404 * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
7405 * `data-`) to its normalized, camelCase form.
7407 * Also there is special case for Moz prefix starting with upper case letter.
7409 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
7411 * @param {string} name Name to normalize
7413 $normalize: directiveNormalize,
7418 * @name $compile.directive.Attributes#$addClass
7422 * Adds the CSS class value specified by the classVal parameter to the element. If animations
7423 * are enabled then an animation will be triggered for the class addition.
7425 * @param {string} classVal The className value that will be added to the element
7427 $addClass: function(classVal) {
7428 if (classVal && classVal.length > 0) {
7429 $animate.addClass(this.$$element, classVal);
7435 * @name $compile.directive.Attributes#$removeClass
7439 * Removes the CSS class value specified by the classVal parameter from the element. If
7440 * animations are enabled then an animation will be triggered for the class removal.
7442 * @param {string} classVal The className value that will be removed from the element
7444 $removeClass: function(classVal) {
7445 if (classVal && classVal.length > 0) {
7446 $animate.removeClass(this.$$element, classVal);
7452 * @name $compile.directive.Attributes#$updateClass
7456 * Adds and removes the appropriate CSS class values to the element based on the difference
7457 * between the new and old CSS class values (specified as newClasses and oldClasses).
7459 * @param {string} newClasses The current CSS className value
7460 * @param {string} oldClasses The former CSS className value
7462 $updateClass: function(newClasses, oldClasses) {
7463 var toAdd = tokenDifference(newClasses, oldClasses);
7464 if (toAdd && toAdd.length) {
7465 $animate.addClass(this.$$element, toAdd);
7468 var toRemove = tokenDifference(oldClasses, newClasses);
7469 if (toRemove && toRemove.length) {
7470 $animate.removeClass(this.$$element, toRemove);
7475 * Set a normalized attribute on the element in a way such that all directives
7476 * can share the attribute. This function properly handles boolean attributes.
7477 * @param {string} key Normalized key. (ie ngAttribute)
7478 * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
7479 * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
7481 * @param {string=} attrName Optional none normalized name. Defaults to key.
7483 $set: function(key, value, writeAttr, attrName) {
7484 // TODO: decide whether or not to throw an error if "class"
7485 //is set through this function since it may cause $updateClass to
7488 var node = this.$$element[0],
7489 booleanKey = getBooleanAttrName(node, key),
7490 aliasedKey = getAliasedAttrName(key),
7495 this.$$element.prop(key, value);
7496 attrName = booleanKey;
7497 } else if (aliasedKey) {
7498 this[aliasedKey] = value;
7499 observer = aliasedKey;
7504 // translate normalized key to actual key
7506 this.$attr[key] = attrName;
7508 attrName = this.$attr[key];
7510 this.$attr[key] = attrName = snake_case(key, '-');
7514 nodeName = nodeName_(this.$$element);
7516 if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
7517 (nodeName === 'img' && key === 'src')) {
7518 // sanitize a[href] and img[src] values
7519 this[key] = value = $$sanitizeUri(value, key === 'src');
7520 } else if (nodeName === 'img' && key === 'srcset') {
7521 // sanitize img[srcset] values
7524 // first check if there are spaces because it's not the same pattern
7525 var trimmedSrcset = trim(value);
7526 // ( 999x ,| 999w ,| ,|, )
7527 var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
7528 var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
7530 // split srcset into tuple of uri and descriptor except for the last item
7531 var rawUris = trimmedSrcset.split(pattern);
7534 var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
7535 for (var i = 0; i < nbrUrisWith2parts; i++) {
7536 var innerIdx = i * 2;
7538 result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
7539 // add the descriptor
7540 result += (" " + trim(rawUris[innerIdx + 1]));
7543 // split the last item into uri and descriptor
7544 var lastTuple = trim(rawUris[i * 2]).split(/\s/);
7546 // sanitize the last uri
7547 result += $$sanitizeUri(trim(lastTuple[0]), true);
7549 // and add the last descriptor if any
7550 if (lastTuple.length === 2) {
7551 result += (" " + trim(lastTuple[1]));
7553 this[key] = value = result;
7556 if (writeAttr !== false) {
7557 if (value === null || isUndefined(value)) {
7558 this.$$element.removeAttr(attrName);
7560 this.$$element.attr(attrName, value);
7565 var $$observers = this.$$observers;
7566 $$observers && forEach($$observers[observer], function(fn) {
7570 $exceptionHandler(e);
7578 * @name $compile.directive.Attributes#$observe
7582 * Observes an interpolated attribute.
7584 * The observer function will be invoked once during the next `$digest` following
7585 * compilation. The observer is then invoked whenever the interpolated value
7588 * @param {string} key Normalized key. (ie ngAttribute) .
7589 * @param {function(interpolatedValue)} fn Function that will be called whenever
7590 the interpolated value of the attribute changes.
7591 * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
7592 * @returns {function()} Returns a deregistration function for this observer.
7594 $observe: function(key, fn) {
7596 $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
7597 listeners = ($$observers[key] || ($$observers[key] = []));
7600 $rootScope.$evalAsync(function() {
7601 if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
7602 // no one registered attribute interpolation function, so lets call it manually
7608 arrayRemove(listeners, fn);
7614 function safeAddClass($element, className) {
7616 $element.addClass(className);
7618 // ignore, since it means that we are trying to set class on
7619 // SVG element, where class name is read-only.
7624 var startSymbol = $interpolate.startSymbol(),
7625 endSymbol = $interpolate.endSymbol(),
7626 denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
7628 : function denormalizeTemplate(template) {
7629 return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
7631 NG_ATTR_BINDING = /^ngAttr[A-Z]/;
7632 var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
7634 compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
7635 var bindings = $element.data('$binding') || [];
7637 if (isArray(binding)) {
7638 bindings = bindings.concat(binding);
7640 bindings.push(binding);
7643 $element.data('$binding', bindings);
7646 compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
7647 safeAddClass($element, 'ng-binding');
7650 compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
7651 var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
7652 $element.data(dataName, scope);
7655 compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
7656 safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
7661 //================================
7663 function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
7664 previousCompileContext) {
7665 if (!($compileNodes instanceof jqLite)) {
7666 // jquery always rewraps, whereas we need to preserve the original selector so that we can
7668 $compileNodes = jqLite($compileNodes);
7670 // We can not compile top level text elements since text nodes can be merged and we will
7671 // not be able to attach scope data to them, so we will wrap them in <span>
7672 forEach($compileNodes, function(node, index) {
7673 if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */) {
7674 $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
7677 var compositeLinkFn =
7678 compileNodes($compileNodes, transcludeFn, $compileNodes,
7679 maxPriority, ignoreDirective, previousCompileContext);
7680 compile.$$addScopeClass($compileNodes);
7681 var namespace = null;
7682 return function publicLinkFn(scope, cloneConnectFn, options) {
7683 assertArg(scope, 'scope');
7685 if (previousCompileContext && previousCompileContext.needsNewScope) {
7686 // A parent directive did a replace and a directive on this element asked
7687 // for transclusion, which caused us to lose a layer of element on which
7688 // we could hold the new transclusion scope, so we will create it manually
7690 scope = scope.$parent.$new();
7693 options = options || {};
7694 var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
7695 transcludeControllers = options.transcludeControllers,
7696 futureParentElement = options.futureParentElement;
7698 // When `parentBoundTranscludeFn` is passed, it is a
7699 // `controllersBoundTransclude` function (it was previously passed
7700 // as `transclude` to directive.link) so we must unwrap it to get
7701 // its `boundTranscludeFn`
7702 if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
7703 parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
7707 namespace = detectNamespaceForChildElements(futureParentElement);
7710 if (namespace !== 'html') {
7711 // When using a directive with replace:true and templateUrl the $compileNodes
7712 // (or a child element inside of them)
7713 // might change, so we need to recreate the namespace adapted compileNodes
7714 // for call to the link function.
7715 // Note: This will already clone the nodes...
7717 wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
7719 } else if (cloneConnectFn) {
7720 // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
7721 // and sometimes changes the structure of the DOM.
7722 $linkNode = JQLitePrototype.clone.call($compileNodes);
7724 $linkNode = $compileNodes;
7727 if (transcludeControllers) {
7728 for (var controllerName in transcludeControllers) {
7729 $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
7733 compile.$$addScopeInfo($linkNode, scope);
7735 if (cloneConnectFn) cloneConnectFn($linkNode, scope);
7736 if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
7741 function detectNamespaceForChildElements(parentElement) {
7742 // TODO: Make this detect MathML as well...
7743 var node = parentElement && parentElement[0];
7747 return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
7752 * Compile function matches each node in nodeList against the directives. Once all directives
7753 * for a particular node are collected their compile functions are executed. The compile
7754 * functions return values - the linking functions - are combined into a composite linking
7755 * function, which is the a linking function for the node.
7757 * @param {NodeList} nodeList an array of nodes or NodeList to compile
7758 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
7759 * scope argument is auto-generated to the new child of the transcluded parent scope.
7760 * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
7761 * the rootElement must be set the jqLite collection of the compile root. This is
7762 * needed so that the jqLite collection items can be replaced with widgets.
7763 * @param {number=} maxPriority Max directive priority.
7764 * @returns {Function} A composite linking function of all of the matched directives or null.
7766 function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
7767 previousCompileContext) {
7769 attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
7771 for (var i = 0; i < nodeList.length; i++) {
7772 attrs = new Attributes();
7774 // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
7775 directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
7778 nodeLinkFn = (directives.length)
7779 ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
7780 null, [], [], previousCompileContext)
7783 if (nodeLinkFn && nodeLinkFn.scope) {
7784 compile.$$addScopeClass(attrs.$$element);
7787 childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
7788 !(childNodes = nodeList[i].childNodes) ||
7791 : compileNodes(childNodes,
7793 (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
7794 && nodeLinkFn.transclude) : transcludeFn);
7796 if (nodeLinkFn || childLinkFn) {
7797 linkFns.push(i, nodeLinkFn, childLinkFn);
7799 nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
7802 //use the previous context only for the first element in the virtual group
7803 previousCompileContext = null;
7806 // return a linking function if we have found anything, null otherwise
7807 return linkFnFound ? compositeLinkFn : null;
7809 function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
7810 var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
7814 if (nodeLinkFnFound) {
7815 // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
7816 // offsets don't get screwed up
7817 var nodeListLength = nodeList.length;
7818 stableNodeList = new Array(nodeListLength);
7820 // create a sparse array by only copying the elements which have a linkFn
7821 for (i = 0; i < linkFns.length; i+=3) {
7823 stableNodeList[idx] = nodeList[idx];
7826 stableNodeList = nodeList;
7829 for (i = 0, ii = linkFns.length; i < ii;) {
7830 node = stableNodeList[linkFns[i++]];
7831 nodeLinkFn = linkFns[i++];
7832 childLinkFn = linkFns[i++];
7835 if (nodeLinkFn.scope) {
7836 childScope = scope.$new();
7837 compile.$$addScopeInfo(jqLite(node), childScope);
7842 if (nodeLinkFn.transcludeOnThisElement) {
7843 childBoundTranscludeFn = createBoundTranscludeFn(
7844 scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
7846 } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
7847 childBoundTranscludeFn = parentBoundTranscludeFn;
7849 } else if (!parentBoundTranscludeFn && transcludeFn) {
7850 childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
7853 childBoundTranscludeFn = null;
7856 nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
7858 } else if (childLinkFn) {
7859 childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
7865 function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
7867 var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
7869 if (!transcludedScope) {
7870 transcludedScope = scope.$new(false, containingScope);
7871 transcludedScope.$$transcluded = true;
7874 return transcludeFn(transcludedScope, cloneFn, {
7875 parentBoundTranscludeFn: previousBoundTranscludeFn,
7876 transcludeControllers: controllers,
7877 futureParentElement: futureParentElement
7881 // We need to attach the transclusion slots onto the `boundTranscludeFn`
7882 // so that they are available inside the `controllersBoundTransclude` function
7883 var boundSlots = boundTranscludeFn.$$slots = createMap();
7884 for (var slotName in transcludeFn.$$slots) {
7885 boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
7888 return boundTranscludeFn;
7892 * Looks for directives on the given node and adds them to the directive collection which is
7895 * @param node Node to search.
7896 * @param directives An array to which the directives are added to. This array is sorted before
7897 * the function returns.
7898 * @param attrs The shared attrs object which is used to populate the normalized attributes.
7899 * @param {number=} maxPriority Max directive priority.
7901 function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
7902 var nodeType = node.nodeType,
7903 attrsMap = attrs.$attr,
7908 case NODE_TYPE_ELEMENT: /* Element */
7909 // use the node name: <directive>
7910 addDirective(directives,
7911 directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
7913 // iterate over the attributes
7914 for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
7915 j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
7916 var attrStartName = false;
7917 var attrEndName = false;
7921 value = trim(attr.value);
7923 // support ngAttr attribute binding
7924 ngAttrName = directiveNormalize(name);
7925 if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
7926 name = name.replace(PREFIX_REGEXP, '')
7927 .substr(8).replace(/_(.)/g, function(match, letter) {
7928 return letter.toUpperCase();
7932 var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
7933 if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
7934 attrStartName = name;
7935 attrEndName = name.substr(0, name.length - 5) + 'end';
7936 name = name.substr(0, name.length - 6);
7939 nName = directiveNormalize(name.toLowerCase());
7940 attrsMap[nName] = name;
7941 if (isNgAttr || !attrs.hasOwnProperty(nName)) {
7942 attrs[nName] = value;
7943 if (getBooleanAttrName(node, nName)) {
7944 attrs[nName] = true; // presence means true
7947 addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
7948 addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
7952 // use class as directive
7953 className = node.className;
7954 if (isObject(className)) {
7955 // Maybe SVGAnimatedString
7956 className = className.animVal;
7958 if (isString(className) && className !== '') {
7959 while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
7960 nName = directiveNormalize(match[2]);
7961 if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
7962 attrs[nName] = trim(match[3]);
7964 className = className.substr(match.index + match[0].length);
7968 case NODE_TYPE_TEXT: /* Text Node */
7970 // Workaround for #11781
7971 while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
7972 node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
7973 node.parentNode.removeChild(node.nextSibling);
7976 addTextInterpolateDirective(directives, node.nodeValue);
7978 case NODE_TYPE_COMMENT: /* Comment */
7980 match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
7982 nName = directiveNormalize(match[1]);
7983 if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
7984 attrs[nName] = trim(match[2]);
7988 // turns out that under some circumstances IE9 throws errors when one attempts to read
7989 // comment's node value.
7990 // Just ignore it and continue. (Can't seem to reproduce in test case.)
7995 directives.sort(byPriority);
8000 * Given a node with an directive-start it collects all of the siblings until it finds
8007 function groupScan(node, attrStart, attrEnd) {
8010 if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
8013 throw $compileMinErr('uterdir',
8014 "Unterminated attribute, found '{0}' but no matching '{1}' found.",
8015 attrStart, attrEnd);
8017 if (node.nodeType == NODE_TYPE_ELEMENT) {
8018 if (node.hasAttribute(attrStart)) depth++;
8019 if (node.hasAttribute(attrEnd)) depth--;
8022 node = node.nextSibling;
8023 } while (depth > 0);
8028 return jqLite(nodes);
8032 * Wrapper for linking function which converts normal linking function into a grouped
8037 * @returns {Function}
8039 function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
8040 return function(scope, element, attrs, controllers, transcludeFn) {
8041 element = groupScan(element[0], attrStart, attrEnd);
8042 return linkFn(scope, element, attrs, controllers, transcludeFn);
8047 * A function generator that is used to support both eager and lazy compilation
8050 * @param $compileNodes
8051 * @param transcludeFn
8052 * @param maxPriority
8053 * @param ignoreDirective
8054 * @param previousCompileContext
8055 * @returns {Function}
8057 function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
8059 return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
8066 compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
8068 // Null out all of these references in order to make them eligible for garbage collection
8069 // since this is a potentially long lived closure
8070 $compileNodes = transcludeFn = previousCompileContext = null;
8073 return compiled.apply(this, arguments);
8078 * Once the directives have been collected, their compile functions are executed. This method
8079 * is responsible for inlining directive templates as well as terminating the application
8080 * of the directives if the terminal directive has been reached.
8082 * @param {Array} directives Array of collected directives to execute their compile function.
8083 * this needs to be pre-sorted by priority order.
8084 * @param {Node} compileNode The raw DOM node to apply the compile functions to
8085 * @param {Object} templateAttrs The shared attribute function
8086 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
8087 * scope argument is auto-generated to the new
8088 * child of the transcluded parent scope.
8089 * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
8090 * argument has the root jqLite array so that we can replace nodes
8092 * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
8093 * compiling the transclusion.
8094 * @param {Array.<Function>} preLinkFns
8095 * @param {Array.<Function>} postLinkFns
8096 * @param {Object} previousCompileContext Context used for previous compilation of the current
8098 * @returns {Function} linkFn
8100 function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
8101 jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
8102 previousCompileContext) {
8103 previousCompileContext = previousCompileContext || {};
8105 var terminalPriority = -Number.MAX_VALUE,
8106 newScopeDirective = previousCompileContext.newScopeDirective,
8107 controllerDirectives = previousCompileContext.controllerDirectives,
8108 newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
8109 templateDirective = previousCompileContext.templateDirective,
8110 nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
8111 hasTranscludeDirective = false,
8112 hasTemplate = false,
8113 hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
8114 $compileNode = templateAttrs.$$element = jqLite(compileNode),
8118 replaceDirective = originalReplaceDirective,
8119 childTranscludeFn = transcludeFn,
8121 didScanForMultipleTransclusion = false,
8122 mightHaveMultipleTransclusionError = false,
8125 // executes all directives on the current element
8126 for (var i = 0, ii = directives.length; i < ii; i++) {
8127 directive = directives[i];
8128 var attrStart = directive.$$start;
8129 var attrEnd = directive.$$end;
8131 // collect multiblock sections
8133 $compileNode = groupScan(compileNode, attrStart, attrEnd);
8135 $template = undefined;
8137 if (terminalPriority > directive.priority) {
8138 break; // prevent further processing of directives
8141 if (directiveValue = directive.scope) {
8143 // skip the check for directives with async templates, we'll check the derived sync
8144 // directive when the template arrives
8145 if (!directive.templateUrl) {
8146 if (isObject(directiveValue)) {
8147 // This directive is trying to add an isolated scope.
8148 // Check that there is no scope of any kind already
8149 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
8150 directive, $compileNode);
8151 newIsolateScopeDirective = directive;
8153 // This directive is trying to add a child scope.
8154 // Check that there is no isolated scope already
8155 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
8160 newScopeDirective = newScopeDirective || directive;
8163 directiveName = directive.name;
8165 // If we encounter a condition that can result in transclusion on the directive,
8166 // then scan ahead in the remaining directives for others that may cause a multiple
8167 // transclusion error to be thrown during the compilation process. If a matching directive
8168 // is found, then we know that when we encounter a transcluded directive, we need to eagerly
8169 // compile the `transclude` function rather than doing it lazily in order to throw
8170 // exceptions at the correct time
8171 if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
8172 || (directive.transclude && !directive.$$tlb))) {
8173 var candidateDirective;
8175 for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
8176 if ((candidateDirective.transclude && !candidateDirective.$$tlb)
8177 || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
8178 mightHaveMultipleTransclusionError = true;
8183 didScanForMultipleTransclusion = true;
8186 if (!directive.templateUrl && directive.controller) {
8187 directiveValue = directive.controller;
8188 controllerDirectives = controllerDirectives || createMap();
8189 assertNoDuplicate("'" + directiveName + "' controller",
8190 controllerDirectives[directiveName], directive, $compileNode);
8191 controllerDirectives[directiveName] = directive;
8194 if (directiveValue = directive.transclude) {
8195 hasTranscludeDirective = true;
8197 // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
8198 // This option should only be used by directives that know how to safely handle element transclusion,
8199 // where the transcluded nodes are added or replaced after linking.
8200 if (!directive.$$tlb) {
8201 assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
8202 nonTlbTranscludeDirective = directive;
8205 if (directiveValue == 'element') {
8206 hasElementTranscludeDirective = true;
8207 terminalPriority = directive.priority;
8208 $template = $compileNode;
8209 $compileNode = templateAttrs.$$element =
8210 jqLite(document.createComment(' ' + directiveName + ': ' +
8211 templateAttrs[directiveName] + ' '));
8212 compileNode = $compileNode[0];
8213 replaceWith(jqCollection, sliceArgs($template), compileNode);
8215 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
8216 replaceDirective && replaceDirective.name, {
8218 // - controllerDirectives - otherwise we'll create duplicates controllers
8219 // - newIsolateScopeDirective or templateDirective - combining templates with
8220 // element transclusion doesn't make sense.
8222 // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
8223 // on the same element more than once.
8224 nonTlbTranscludeDirective: nonTlbTranscludeDirective
8228 var slots = createMap();
8229 $template = jqLite(jqLiteClone(compileNode)).contents();
8231 if (isObject(directiveValue)) {
8233 // We have transclusion slots - collect them up and compile them and store their
8234 // transclusion functions
8236 var slotNames = createMap();
8237 var filledSlots = createMap();
8239 // Parse the slot names: if they start with a ? then they are optional
8240 forEach(directiveValue, function(slotName, key) {
8241 var optional = (slotName.charAt(0) === '?');
8242 slotName = optional ? slotName.substring(1) : slotName;
8243 slotNames[key] = slotName;
8244 slots[slotName] = [];
8245 // filledSlots contains `true` for all slots that are either optional or have been
8246 // filled. This is used to check that we have not missed any required slots
8247 filledSlots[slotName] = optional;
8250 // Add the matching elements into their slot
8251 forEach($compileNode.children(), function(node) {
8252 var slotName = slotNames[directiveNormalize(nodeName_(node))];
8254 filledSlots[slotName] = true;
8255 slots[slotName].push(node);
8257 $template.push(node);
8261 // Check for required slots that were not filled
8262 forEach(filledSlots, function(filled, slotName) {
8264 throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
8268 forEach(Object.keys(slots), function(slotName) {
8269 slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
8273 $compileNode.empty(); // clear contents
8274 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
8275 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
8276 childTranscludeFn.$$slots = slots;
8280 if (directive.template) {
8282 assertNoDuplicate('template', templateDirective, directive, $compileNode);
8283 templateDirective = directive;
8285 directiveValue = (isFunction(directive.template))
8286 ? directive.template($compileNode, templateAttrs)
8287 : directive.template;
8289 directiveValue = denormalizeTemplate(directiveValue);
8291 if (directive.replace) {
8292 replaceDirective = directive;
8293 if (jqLiteIsTextNode(directiveValue)) {
8296 $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
8298 compileNode = $template[0];
8300 if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
8301 throw $compileMinErr('tplrt',
8302 "Template for directive '{0}' must have exactly one root element. {1}",
8306 replaceWith(jqCollection, $compileNode, compileNode);
8308 var newTemplateAttrs = {$attr: {}};
8310 // combine directives from the original node and from the template:
8311 // - take the array of directives for this element
8312 // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
8313 // - collect directives from the template and sort them by priority
8314 // - combine directives as: processed + template + unprocessed
8315 var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
8316 var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
8318 if (newIsolateScopeDirective || newScopeDirective) {
8319 // The original directive caused the current element to be replaced but this element
8320 // also needs to have a new scope, so we need to tell the template directives
8321 // that they would need to get their scope from further up, if they require transclusion
8322 markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
8324 directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
8325 mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
8327 ii = directives.length;
8329 $compileNode.html(directiveValue);
8333 if (directive.templateUrl) {
8335 assertNoDuplicate('template', templateDirective, directive, $compileNode);
8336 templateDirective = directive;
8338 if (directive.replace) {
8339 replaceDirective = directive;
8342 nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
8343 templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
8344 controllerDirectives: controllerDirectives,
8345 newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
8346 newIsolateScopeDirective: newIsolateScopeDirective,
8347 templateDirective: templateDirective,
8348 nonTlbTranscludeDirective: nonTlbTranscludeDirective
8350 ii = directives.length;
8351 } else if (directive.compile) {
8353 linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
8354 if (isFunction(linkFn)) {
8355 addLinkFns(null, linkFn, attrStart, attrEnd);
8356 } else if (linkFn) {
8357 addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
8360 $exceptionHandler(e, startingTag($compileNode));
8364 if (directive.terminal) {
8365 nodeLinkFn.terminal = true;
8366 terminalPriority = Math.max(terminalPriority, directive.priority);
8371 nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
8372 nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
8373 nodeLinkFn.templateOnThisElement = hasTemplate;
8374 nodeLinkFn.transclude = childTranscludeFn;
8376 previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
8378 // might be normal or delayed nodeLinkFn depending on if templateUrl is present
8381 ////////////////////
8383 function addLinkFns(pre, post, attrStart, attrEnd) {
8385 if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
8386 pre.require = directive.require;
8387 pre.directiveName = directiveName;
8388 if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
8389 pre = cloneAndAnnotateFn(pre, {isolateScope: true});
8391 preLinkFns.push(pre);
8394 if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
8395 post.require = directive.require;
8396 post.directiveName = directiveName;
8397 if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
8398 post = cloneAndAnnotateFn(post, {isolateScope: true});
8400 postLinkFns.push(post);
8405 function getControllers(directiveName, require, $element, elementControllers) {
8408 if (isString(require)) {
8409 var match = require.match(REQUIRE_PREFIX_REGEXP);
8410 var name = require.substring(match[0].length);
8411 var inheritType = match[1] || match[3];
8412 var optional = match[2] === '?';
8414 //If only parents then start at the parent element
8415 if (inheritType === '^^') {
8416 $element = $element.parent();
8417 //Otherwise attempt getting the controller from elementControllers in case
8418 //the element is transcluded (and has no data) and to avoid .data if possible
8420 value = elementControllers && elementControllers[name];
8421 value = value && value.instance;
8425 var dataName = '$' + name + 'Controller';
8426 value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
8429 if (!value && !optional) {
8430 throw $compileMinErr('ctreq',
8431 "Controller '{0}', required by directive '{1}', can't be found!",
8432 name, directiveName);
8434 } else if (isArray(require)) {
8436 for (var i = 0, ii = require.length; i < ii; i++) {
8437 value[i] = getControllers(directiveName, require[i], $element, elementControllers);
8441 return value || null;
8444 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
8445 var elementControllers = createMap();
8446 for (var controllerKey in controllerDirectives) {
8447 var directive = controllerDirectives[controllerKey];
8449 $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
8452 $transclude: transcludeFn
8455 var controller = directive.controller;
8456 if (controller == '@') {
8457 controller = attrs[directive.name];
8460 var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
8462 // For directives with element transclusion the element is a comment,
8463 // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
8464 // clean up (http://bugs.jquery.com/ticket/8335).
8465 // Instead, we save the controllers for the element in a local hash and attach to .data
8466 // later, once we have the actual element.
8467 elementControllers[directive.name] = controllerInstance;
8468 if (!hasElementTranscludeDirective) {
8469 $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
8472 return elementControllers;
8475 function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
8476 var linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
8477 attrs, removeScopeBindingWatches, removeControllerBindingWatches;
8479 if (compileNode === linkNode) {
8480 attrs = templateAttrs;
8481 $element = templateAttrs.$$element;
8483 $element = jqLite(linkNode);
8484 attrs = new Attributes($element, templateAttrs);
8487 controllerScope = scope;
8488 if (newIsolateScopeDirective) {
8489 isolateScope = scope.$new(true);
8490 } else if (newScopeDirective) {
8491 controllerScope = scope.$parent;
8494 if (boundTranscludeFn) {
8495 // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
8496 // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
8497 transcludeFn = controllersBoundTransclude;
8498 transcludeFn.$$boundTransclude = boundTranscludeFn;
8501 if (controllerDirectives) {
8502 elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
8505 if (newIsolateScopeDirective) {
8506 // Initialize isolate scope bindings for new isolate scope directive.
8507 compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
8508 templateDirective === newIsolateScopeDirective.$$originalDirective)));
8509 compile.$$addScopeClass($element, true);
8510 isolateScope.$$isolateBindings =
8511 newIsolateScopeDirective.$$isolateBindings;
8512 removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
8513 isolateScope.$$isolateBindings,
8514 newIsolateScopeDirective);
8515 if (removeScopeBindingWatches) {
8516 isolateScope.$on('$destroy', removeScopeBindingWatches);
8520 // Initialize bindToController bindings
8521 for (var name in elementControllers) {
8522 var controllerDirective = controllerDirectives[name];
8523 var controller = elementControllers[name];
8524 var bindings = controllerDirective.$$bindings.bindToController;
8526 if (controller.identifier && bindings) {
8527 removeControllerBindingWatches =
8528 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
8531 var controllerResult = controller();
8532 if (controllerResult !== controller.instance) {
8533 // If the controller constructor has a return value, overwrite the instance
8534 // from setupControllers
8535 controller.instance = controllerResult;
8536 $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
8537 removeControllerBindingWatches && removeControllerBindingWatches();
8538 removeControllerBindingWatches =
8539 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
8544 for (i = 0, ii = preLinkFns.length; i < ii; i++) {
8545 linkFn = preLinkFns[i];
8546 invokeLinkFn(linkFn,
8547 linkFn.isolateScope ? isolateScope : scope,
8550 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
8556 // We only pass the isolate scope, if the isolate directive has a template,
8557 // otherwise the child elements do not belong to the isolate directive.
8558 var scopeToChild = scope;
8559 if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
8560 scopeToChild = isolateScope;
8562 childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
8565 for (i = postLinkFns.length - 1; i >= 0; i--) {
8566 linkFn = postLinkFns[i];
8567 invokeLinkFn(linkFn,
8568 linkFn.isolateScope ? isolateScope : scope,
8571 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
8576 // This is the function that is injected as `$transclude`.
8577 // Note: all arguments are optional!
8578 function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
8579 var transcludeControllers;
8580 // No scope passed in:
8581 if (!isScope(scope)) {
8582 slotName = futureParentElement;
8583 futureParentElement = cloneAttachFn;
8584 cloneAttachFn = scope;
8588 if (hasElementTranscludeDirective) {
8589 transcludeControllers = elementControllers;
8591 if (!futureParentElement) {
8592 futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
8595 var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
8596 if (!slotTranscludeFn) {
8597 throw $compileMinErr('noslot',
8598 'No parent directive that requires a transclusion with slot name "{0}". ' +
8600 slotName, startingTag($element));
8602 return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
8604 return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
8609 // Depending upon the context in which a directive finds itself it might need to have a new isolated
8610 // or child scope created. For instance:
8611 // * if the directive has been pulled into a template because another directive with a higher priority
8612 // asked for element transclusion
8613 // * if the directive itself asks for transclusion but it is at the root of a template and the original
8614 // element was replaced. See https://github.com/angular/angular.js/issues/12936
8615 function markDirectiveScope(directives, isolateScope, newScope) {
8616 for (var j = 0, jj = directives.length; j < jj; j++) {
8617 directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
8622 * looks up the directive and decorates it with exception handling and proper parameters. We
8623 * call this the boundDirective.
8625 * @param {string} name name of the directive to look up.
8626 * @param {string} location The directive must be found in specific format.
8627 * String containing any of theses characters:
8629 * * `E`: element name
8633 * @returns {boolean} true if directive was added.
8635 function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
8637 if (name === ignoreDirective) return null;
8639 if (hasDirectives.hasOwnProperty(name)) {
8640 for (var directive, directives = $injector.get(name + Suffix),
8641 i = 0, ii = directives.length; i < ii; i++) {
8643 directive = directives[i];
8644 if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
8645 directive.restrict.indexOf(location) != -1) {
8646 if (startAttrName) {
8647 directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
8649 tDirectives.push(directive);
8652 } catch (e) { $exceptionHandler(e); }
8660 * looks up the directive and returns true if it is a multi-element directive,
8661 * and therefore requires DOM nodes between -start and -end markers to be grouped
8664 * @param {string} name name of the directive to look up.
8665 * @returns true if directive was registered as multi-element.
8667 function directiveIsMultiElement(name) {
8668 if (hasDirectives.hasOwnProperty(name)) {
8669 for (var directive, directives = $injector.get(name + Suffix),
8670 i = 0, ii = directives.length; i < ii; i++) {
8671 directive = directives[i];
8672 if (directive.multiElement) {
8681 * When the element is replaced with HTML template then the new attributes
8682 * on the template need to be merged with the existing attributes in the DOM.
8683 * The desired effect is to have both of the attributes present.
8685 * @param {object} dst destination attributes (original DOM)
8686 * @param {object} src source attributes (from the directive template)
8688 function mergeTemplateAttributes(dst, src) {
8689 var srcAttr = src.$attr,
8690 dstAttr = dst.$attr,
8691 $element = dst.$$element;
8693 // reapply the old attributes to the new element
8694 forEach(dst, function(value, key) {
8695 if (key.charAt(0) != '$') {
8696 if (src[key] && src[key] !== value) {
8697 value += (key === 'style' ? ';' : ' ') + src[key];
8699 dst.$set(key, value, true, srcAttr[key]);
8703 // copy the new attributes on the old attrs object
8704 forEach(src, function(value, key) {
8705 if (key == 'class') {
8706 safeAddClass($element, value);
8707 dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
8708 } else if (key == 'style') {
8709 $element.attr('style', $element.attr('style') + ';' + value);
8710 dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
8711 // `dst` will never contain hasOwnProperty as DOM parser won't let it.
8712 // You will get an "InvalidCharacterError: DOM Exception 5" error if you
8713 // have an attribute like "has-own-property" or "data-has-own-property", etc.
8714 } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
8716 dstAttr[key] = srcAttr[key];
8722 function compileTemplateUrl(directives, $compileNode, tAttrs,
8723 $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
8725 afterTemplateNodeLinkFn,
8726 afterTemplateChildLinkFn,
8727 beforeTemplateCompileNode = $compileNode[0],
8728 origAsyncDirective = directives.shift(),
8729 derivedSyncDirective = inherit(origAsyncDirective, {
8730 templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
8732 templateUrl = (isFunction(origAsyncDirective.templateUrl))
8733 ? origAsyncDirective.templateUrl($compileNode, tAttrs)
8734 : origAsyncDirective.templateUrl,
8735 templateNamespace = origAsyncDirective.templateNamespace;
8737 $compileNode.empty();
8739 $templateRequest(templateUrl)
8740 .then(function(content) {
8741 var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
8743 content = denormalizeTemplate(content);
8745 if (origAsyncDirective.replace) {
8746 if (jqLiteIsTextNode(content)) {
8749 $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
8751 compileNode = $template[0];
8753 if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
8754 throw $compileMinErr('tplrt',
8755 "Template for directive '{0}' must have exactly one root element. {1}",
8756 origAsyncDirective.name, templateUrl);
8759 tempTemplateAttrs = {$attr: {}};
8760 replaceWith($rootElement, $compileNode, compileNode);
8761 var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
8763 if (isObject(origAsyncDirective.scope)) {
8764 // the original directive that caused the template to be loaded async required
8766 markDirectiveScope(templateDirectives, true);
8768 directives = templateDirectives.concat(directives);
8769 mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
8771 compileNode = beforeTemplateCompileNode;
8772 $compileNode.html(content);
8775 directives.unshift(derivedSyncDirective);
8777 afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
8778 childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
8779 previousCompileContext);
8780 forEach($rootElement, function(node, i) {
8781 if (node == compileNode) {
8782 $rootElement[i] = $compileNode[0];
8785 afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
8787 while (linkQueue.length) {
8788 var scope = linkQueue.shift(),
8789 beforeTemplateLinkNode = linkQueue.shift(),
8790 linkRootElement = linkQueue.shift(),
8791 boundTranscludeFn = linkQueue.shift(),
8792 linkNode = $compileNode[0];
8794 if (scope.$$destroyed) continue;
8796 if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
8797 var oldClasses = beforeTemplateLinkNode.className;
8799 if (!(previousCompileContext.hasElementTranscludeDirective &&
8800 origAsyncDirective.replace)) {
8801 // it was cloned therefore we have to clone as well.
8802 linkNode = jqLiteClone(compileNode);
8804 replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
8806 // Copy in CSS classes from original node
8807 safeAddClass(jqLite(linkNode), oldClasses);
8809 if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
8810 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
8812 childBoundTranscludeFn = boundTranscludeFn;
8814 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
8815 childBoundTranscludeFn);
8820 return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
8821 var childBoundTranscludeFn = boundTranscludeFn;
8822 if (scope.$$destroyed) return;
8824 linkQueue.push(scope,
8827 childBoundTranscludeFn);
8829 if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
8830 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
8832 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
8839 * Sorting function for bound directives.
8841 function byPriority(a, b) {
8842 var diff = b.priority - a.priority;
8843 if (diff !== 0) return diff;
8844 if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
8845 return a.index - b.index;
8848 function assertNoDuplicate(what, previousDirective, directive, element) {
8850 function wrapModuleNameIfDefined(moduleName) {
8852 (' (module: ' + moduleName + ')') :
8856 if (previousDirective) {
8857 throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
8858 previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
8859 directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
8864 function addTextInterpolateDirective(directives, text) {
8865 var interpolateFn = $interpolate(text, true);
8866 if (interpolateFn) {
8869 compile: function textInterpolateCompileFn(templateNode) {
8870 var templateNodeParent = templateNode.parent(),
8871 hasCompileParent = !!templateNodeParent.length;
8873 // When transcluding a template that has bindings in the root
8874 // we don't have a parent and thus need to add the class during linking fn.
8875 if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
8877 return function textInterpolateLinkFn(scope, node) {
8878 var parent = node.parent();
8879 if (!hasCompileParent) compile.$$addBindingClass(parent);
8880 compile.$$addBindingInfo(parent, interpolateFn.expressions);
8881 scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
8882 node[0].nodeValue = value;
8891 function wrapTemplate(type, template) {
8892 type = lowercase(type || 'html');
8896 var wrapper = document.createElement('div');
8897 wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
8898 return wrapper.childNodes[0].childNodes;
8905 function getTrustedContext(node, attrNormalizedName) {
8906 if (attrNormalizedName == "srcdoc") {
8909 var tag = nodeName_(node);
8910 // maction[xlink:href] can source SVG. It's not limited to <maction>.
8911 if (attrNormalizedName == "xlinkHref" ||
8912 (tag == "form" && attrNormalizedName == "action") ||
8913 (tag != "img" && (attrNormalizedName == "src" ||
8914 attrNormalizedName == "ngSrc"))) {
8915 return $sce.RESOURCE_URL;
8920 function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
8921 var trustedContext = getTrustedContext(node, name);
8922 allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
8924 var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
8926 // no interpolation found -> ignore
8927 if (!interpolateFn) return;
8930 if (name === "multiple" && nodeName_(node) === "select") {
8931 throw $compileMinErr("selmulti",
8932 "Binding to the 'multiple' attribute is not supported. Element: {0}",
8938 compile: function() {
8940 pre: function attrInterpolatePreLinkFn(scope, element, attr) {
8941 var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
8943 if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
8944 throw $compileMinErr('nodomevents',
8945 "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
8946 "ng- versions (such as ng-click instead of onclick) instead.");
8949 // If the attribute has changed since last $interpolate()ed
8950 var newValue = attr[name];
8951 if (newValue !== value) {
8952 // we need to interpolate again since the attribute value has been updated
8953 // (e.g. by another directive's compile function)
8954 // ensure unset/empty values make interpolateFn falsy
8955 interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
8959 // if attribute was updated so that there is no interpolation going on we don't want to
8960 // register any observers
8961 if (!interpolateFn) return;
8963 // initialize attr object so that it's ready in case we need the value for isolate
8964 // scope initialization, otherwise the value would not be available from isolate
8965 // directive's linking fn during linking phase
8966 attr[name] = interpolateFn(scope);
8968 ($$observers[name] || ($$observers[name] = [])).$$inter = true;
8969 (attr.$$observers && attr.$$observers[name].$$scope || scope).
8970 $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
8971 //special case for class attribute addition + removal
8972 //so that class changes can tap into the animation
8973 //hooks provided by the $animate service. Be sure to
8974 //skip animations when the first digest occurs (when
8975 //both the new and the old values are the same) since
8976 //the CSS classes are the non-interpolated values
8977 if (name === 'class' && newValue != oldValue) {
8978 attr.$updateClass(newValue, oldValue);
8980 attr.$set(name, newValue);
8991 * This is a special jqLite.replaceWith, which can replace items which
8992 * have no parents, provided that the containing jqLite collection is provided.
8994 * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
8995 * in the root of the tree.
8996 * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
8997 * the shell, but replace its DOM node reference.
8998 * @param {Node} newNode The new DOM node.
9000 function replaceWith($rootElement, elementsToRemove, newNode) {
9001 var firstElementToRemove = elementsToRemove[0],
9002 removeCount = elementsToRemove.length,
9003 parent = firstElementToRemove.parentNode,
9007 for (i = 0, ii = $rootElement.length; i < ii; i++) {
9008 if ($rootElement[i] == firstElementToRemove) {
9009 $rootElement[i++] = newNode;
9010 for (var j = i, j2 = j + removeCount - 1,
9011 jj = $rootElement.length;
9012 j < jj; j++, j2++) {
9014 $rootElement[j] = $rootElement[j2];
9016 delete $rootElement[j];
9019 $rootElement.length -= removeCount - 1;
9021 // If the replaced element is also the jQuery .context then replace it
9022 // .context is a deprecated jQuery api, so we should set it only when jQuery set it
9023 // http://api.jquery.com/context/
9024 if ($rootElement.context === firstElementToRemove) {
9025 $rootElement.context = newNode;
9033 parent.replaceChild(newNode, firstElementToRemove);
9036 // Append all the `elementsToRemove` to a fragment. This will...
9037 // - remove them from the DOM
9038 // - allow them to still be traversed with .nextSibling
9039 // - allow a single fragment.qSA to fetch all elements being removed
9040 var fragment = document.createDocumentFragment();
9041 for (i = 0; i < removeCount; i++) {
9042 fragment.appendChild(elementsToRemove[i]);
9045 if (jqLite.hasData(firstElementToRemove)) {
9046 // Copy over user data (that includes Angular's $scope etc.). Don't copy private
9047 // data here because there's no public interface in jQuery to do that and copying over
9048 // event listeners (which is the main use of private data) wouldn't work anyway.
9049 jqLite.data(newNode, jqLite.data(firstElementToRemove));
9051 // Remove $destroy event listeners from `firstElementToRemove`
9052 jqLite(firstElementToRemove).off('$destroy');
9055 // Cleanup any data/listeners on the elements and children.
9056 // This includes invoking the $destroy event on any elements with listeners.
9057 jqLite.cleanData(fragment.querySelectorAll('*'));
9059 // Update the jqLite collection to only contain the `newNode`
9060 for (i = 1; i < removeCount; i++) {
9061 delete elementsToRemove[i];
9063 elementsToRemove[0] = newNode;
9064 elementsToRemove.length = 1;
9068 function cloneAndAnnotateFn(fn, annotation) {
9069 return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
9073 function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
9075 linkFn(scope, $element, attrs, controllers, transcludeFn);
9077 $exceptionHandler(e, startingTag($element));
9082 // Set up $watches for isolate scope and controller bindings. This process
9083 // only occurs for isolate scopes and new scopes with controllerAs.
9084 function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
9085 var removeWatchCollection = [];
9086 forEach(bindings, function(definition, scopeName) {
9087 var attrName = definition.attrName,
9088 optional = definition.optional,
9089 mode = definition.mode, // @, =, or &
9091 parentGet, parentSet, compare;
9096 if (!optional && !hasOwnProperty.call(attrs, attrName)) {
9097 destination[scopeName] = attrs[attrName] = void 0;
9099 attrs.$observe(attrName, function(value) {
9100 if (isString(value)) {
9101 destination[scopeName] = value;
9104 attrs.$$observers[attrName].$$scope = scope;
9105 if (isString(attrs[attrName])) {
9106 // If the attribute has been provided then we trigger an interpolation to ensure
9107 // the value is there for use in the link fn
9108 destination[scopeName] = $interpolate(attrs[attrName])(scope);
9113 if (!hasOwnProperty.call(attrs, attrName)) {
9114 if (optional) break;
9115 attrs[attrName] = void 0;
9117 if (optional && !attrs[attrName]) break;
9119 parentGet = $parse(attrs[attrName]);
9120 if (parentGet.literal) {
9123 compare = function(a, b) { return a === b || (a !== a && b !== b); };
9125 parentSet = parentGet.assign || function() {
9126 // reset the change, or we will throw this exception on every $digest
9127 lastValue = destination[scopeName] = parentGet(scope);
9128 throw $compileMinErr('nonassign',
9129 "Expression '{0}' used with directive '{1}' is non-assignable!",
9130 attrs[attrName], directive.name);
9132 lastValue = destination[scopeName] = parentGet(scope);
9133 var parentValueWatch = function parentValueWatch(parentValue) {
9134 if (!compare(parentValue, destination[scopeName])) {
9135 // we are out of sync and need to copy
9136 if (!compare(parentValue, lastValue)) {
9137 // parent changed and it has precedence
9138 destination[scopeName] = parentValue;
9140 // if the parent can be assigned then do so
9141 parentSet(scope, parentValue = destination[scopeName]);
9144 return lastValue = parentValue;
9146 parentValueWatch.$stateful = true;
9148 if (definition.collection) {
9149 removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
9151 removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
9153 removeWatchCollection.push(removeWatch);
9157 // Don't assign Object.prototype method to scope
9158 parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
9160 // Don't assign noop to destination if expression is not valid
9161 if (parentGet === noop && optional) break;
9163 destination[scopeName] = function(locals) {
9164 return parentGet(scope, locals);
9170 return removeWatchCollection.length && function removeWatches() {
9171 for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
9172 removeWatchCollection[i]();
9179 var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
9181 * Converts all accepted directives format into proper directive name.
9182 * @param name Name to normalize
9184 function directiveNormalize(name) {
9185 return camelCase(name.replace(PREFIX_REGEXP, ''));
9190 * @name $compile.directive.Attributes
9193 * A shared object between directive compile / linking functions which contains normalized DOM
9194 * element attributes. The values reflect current binding state `{{ }}`. The normalization is
9195 * needed since all of these are treated as equivalent in Angular:
9198 * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
9204 * @name $compile.directive.Attributes#$attr
9207 * A map of DOM element attribute names to the normalized name. This is
9208 * needed to do reverse lookup from normalized name back to actual name.
9214 * @name $compile.directive.Attributes#$set
9218 * Set DOM element attribute value.
9221 * @param {string} name Normalized element attribute name of the property to modify. The name is
9222 * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
9223 * property to the original name.
9224 * @param {string} value Value to set the attribute to. The value can be an interpolated string.
9230 * Closure compiler type information
9233 function nodesetLinkingFn(
9234 /* angular.Scope */ scope,
9235 /* NodeList */ nodeList,
9236 /* Element */ rootElement,
9237 /* function(Function) */ boundTranscludeFn
9240 function directiveLinkingFn(
9241 /* nodesetLinkingFn */ nodesetLinkingFn,
9242 /* angular.Scope */ scope,
9244 /* Element */ rootElement,
9245 /* function(Function) */ boundTranscludeFn
9248 function tokenDifference(str1, str2) {
9250 tokens1 = str1.split(/\s+/),
9251 tokens2 = str2.split(/\s+/);
9254 for (var i = 0; i < tokens1.length; i++) {
9255 var token = tokens1[i];
9256 for (var j = 0; j < tokens2.length; j++) {
9257 if (token == tokens2[j]) continue outer;
9259 values += (values.length > 0 ? ' ' : '') + token;
9264 function removeComments(jqNodes) {
9265 jqNodes = jqLite(jqNodes);
9266 var i = jqNodes.length;
9273 var node = jqNodes[i];
9274 if (node.nodeType === NODE_TYPE_COMMENT) {
9275 splice.call(jqNodes, i, 1);
9281 var $controllerMinErr = minErr('$controller');
9284 var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
9285 function identifierForController(controller, ident) {
9286 if (ident && isString(ident)) return ident;
9287 if (isString(controller)) {
9288 var match = CNTRL_REG.exec(controller);
9289 if (match) return match[3];
9296 * @name $controllerProvider
9298 * The {@link ng.$controller $controller service} is used by Angular to create new
9301 * This provider allows controller registration via the
9302 * {@link ng.$controllerProvider#register register} method.
9304 function $ControllerProvider() {
9305 var controllers = {},
9310 * @name $controllerProvider#register
9311 * @param {string|Object} name Controller name, or an object map of controllers where the keys are
9312 * the names and the values are the constructors.
9313 * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
9314 * annotations in the array notation).
9316 this.register = function(name, constructor) {
9317 assertNotHasOwnProperty(name, 'controller');
9318 if (isObject(name)) {
9319 extend(controllers, name);
9321 controllers[name] = constructor;
9327 * @name $controllerProvider#allowGlobals
9328 * @description If called, allows `$controller` to find controller constructors on `window`
9330 this.allowGlobals = function() {
9335 this.$get = ['$injector', '$window', function($injector, $window) {
9340 * @requires $injector
9342 * @param {Function|string} constructor If called with a function then it's considered to be the
9343 * controller constructor function. Otherwise it's considered to be a string which is used
9344 * to retrieve the controller constructor using the following steps:
9346 * * check if a controller with given name is registered via `$controllerProvider`
9347 * * check if evaluating the string on the current scope returns a constructor
9348 * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
9349 * `window` object (not recommended)
9351 * The string can use the `controller as property` syntax, where the controller instance is published
9352 * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
9353 * to work correctly.
9355 * @param {Object} locals Injection locals for Controller.
9356 * @return {Object} Instance of given controller.
9359 * `$controller` service is responsible for instantiating controllers.
9361 * It's just a simple call to {@link auto.$injector $injector}, but extracted into
9362 * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
9364 return function(expression, locals, later, ident) {
9366 // param `later` --- indicates that the controller's constructor is invoked at a later time.
9367 // If true, $controller will allocate the object with the correct
9368 // prototype chain, but will not invoke the controller until a returned
9369 // callback is invoked.
9370 // param `ident` --- An optional label which overrides the label parsed from the controller
9371 // expression, if any.
9372 var instance, match, constructor, identifier;
9373 later = later === true;
9374 if (ident && isString(ident)) {
9378 if (isString(expression)) {
9379 match = expression.match(CNTRL_REG);
9381 throw $controllerMinErr('ctrlfmt',
9382 "Badly formed controller string '{0}'. " +
9383 "Must match `__name__ as __id__` or `__name__`.", expression);
9385 constructor = match[1],
9386 identifier = identifier || match[3];
9387 expression = controllers.hasOwnProperty(constructor)
9388 ? controllers[constructor]
9389 : getter(locals.$scope, constructor, true) ||
9390 (globals ? getter($window, constructor, true) : undefined);
9392 assertArgFn(expression, constructor, true);
9396 // Instantiate controller later:
9397 // This machinery is used to create an instance of the object before calling the
9398 // controller's constructor itself.
9400 // This allows properties to be added to the controller before the constructor is
9401 // invoked. Primarily, this is used for isolate scope bindings in $compile.
9403 // This feature is not intended for use by applications, and is thus not documented
9405 // Object creation: http://jsperf.com/create-constructor/2
9406 var controllerPrototype = (isArray(expression) ?
9407 expression[expression.length - 1] : expression).prototype;
9408 instance = Object.create(controllerPrototype || null);
9411 addIdentifier(locals, identifier, instance, constructor || expression.name);
9415 return instantiate = extend(function() {
9416 var result = $injector.invoke(expression, instance, locals, constructor);
9417 if (result !== instance && (isObject(result) || isFunction(result))) {
9420 // If result changed, re-assign controllerAs value to scope.
9421 addIdentifier(locals, identifier, instance, constructor || expression.name);
9427 identifier: identifier
9431 instance = $injector.instantiate(expression, locals, constructor);
9434 addIdentifier(locals, identifier, instance, constructor || expression.name);
9440 function addIdentifier(locals, identifier, instance, name) {
9441 if (!(locals && isObject(locals.$scope))) {
9442 throw minErr('$controller')('noscp',
9443 "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
9447 locals.$scope[identifier] = instance;
9458 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
9461 <example module="documentExample">
9462 <file name="index.html">
9463 <div ng-controller="ExampleController">
9464 <p>$document title: <b ng-bind="title"></b></p>
9465 <p>window.document title: <b ng-bind="windowTitle"></b></p>
9468 <file name="script.js">
9469 angular.module('documentExample', [])
9470 .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
9471 $scope.title = $document[0].title;
9472 $scope.windowTitle = angular.element(window.document)[0].title;
9477 function $DocumentProvider() {
9478 this.$get = ['$window', function(window) {
9479 return jqLite(window.document);
9485 * @name $exceptionHandler
9489 * Any uncaught exception in angular expressions is delegated to this service.
9490 * The default implementation simply delegates to `$log.error` which logs it into
9491 * the browser console.
9493 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
9494 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
9499 * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
9500 * return function(exception, cause) {
9501 * exception.message += ' (caused by "' + cause + '")';
9507 * This example will override the normal action of `$exceptionHandler`, to make angular
9508 * exceptions fail hard when they happen, instead of just logging to the console.
9511 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
9512 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
9513 * (unless executed during a digest).
9515 * If you wish, you can manually delegate exceptions, e.g.
9516 * `try { ... } catch(e) { $exceptionHandler(e); }`
9518 * @param {Error} exception Exception associated with the error.
9519 * @param {string=} cause optional information about the context in which
9520 * the error was thrown.
9523 function $ExceptionHandlerProvider() {
9524 this.$get = ['$log', function($log) {
9525 return function(exception, cause) {
9526 $log.error.apply($log, arguments);
9531 var $$ForceReflowProvider = function() {
9532 this.$get = ['$document', function($document) {
9533 return function(domNode) {
9534 //the line below will force the browser to perform a repaint so
9535 //that all the animated elements within the animation frame will
9536 //be properly updated and drawn on screen. This is required to
9537 //ensure that the preparation animation is properly flushed so that
9538 //the active state picks up from there. DO NOT REMOVE THIS LINE.
9539 //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
9540 //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
9541 //WILL TAKE YEARS AWAY FROM YOUR LIFE.
9543 if (!domNode.nodeType && domNode instanceof jqLite) {
9544 domNode = domNode[0];
9547 domNode = $document[0].body;
9549 return domNode.offsetWidth + 1;
9554 var APPLICATION_JSON = 'application/json';
9555 var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
9556 var JSON_START = /^\[|^\{(?!\{)/;
9561 var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
9562 var $httpMinErr = minErr('$http');
9563 var $httpMinErrLegacyFn = function(method) {
9565 throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
9569 function serializeValue(v) {
9571 return isDate(v) ? v.toISOString() : toJson(v);
9577 function $HttpParamSerializerProvider() {
9580 * @name $httpParamSerializer
9583 * Default {@link $http `$http`} params serializer that converts objects to strings
9584 * according to the following rules:
9586 * * `{'foo': 'bar'}` results in `foo=bar`
9587 * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
9588 * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
9589 * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
9591 * Note that serializer will sort the request parameters alphabetically.
9594 this.$get = function() {
9595 return function ngParamSerializer(params) {
9596 if (!params) return '';
9598 forEachSorted(params, function(value, key) {
9599 if (value === null || isUndefined(value)) return;
9600 if (isArray(value)) {
9601 forEach(value, function(v, k) {
9602 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
9605 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
9609 return parts.join('&');
9614 function $HttpParamSerializerJQLikeProvider() {
9617 * @name $httpParamSerializerJQLike
9620 * Alternative {@link $http `$http`} params serializer that follows
9621 * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
9622 * The serializer will also sort the params alphabetically.
9624 * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
9631 * paramSerializer: '$httpParamSerializerJQLike'
9635 * It is also possible to set it as the default `paramSerializer` in the
9636 * {@link $httpProvider#defaults `$httpProvider`}.
9638 * Additionally, you can inject the serializer and use it explicitly, for example to serialize
9639 * form data for submission:
9642 * .controller(function($http, $httpParamSerializerJQLike) {
9648 * data: $httpParamSerializerJQLike(myData),
9650 * 'Content-Type': 'application/x-www-form-urlencoded'
9658 this.$get = function() {
9659 return function jQueryLikeParamSerializer(params) {
9660 if (!params) return '';
9662 serialize(params, '', true);
9663 return parts.join('&');
9665 function serialize(toSerialize, prefix, topLevel) {
9666 if (toSerialize === null || isUndefined(toSerialize)) return;
9667 if (isArray(toSerialize)) {
9668 forEach(toSerialize, function(value, index) {
9669 serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
9671 } else if (isObject(toSerialize) && !isDate(toSerialize)) {
9672 forEachSorted(toSerialize, function(value, key) {
9673 serialize(value, prefix +
9674 (topLevel ? '' : '[') +
9676 (topLevel ? '' : ']'));
9679 parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
9686 function defaultHttpResponseTransform(data, headers) {
9687 if (isString(data)) {
9688 // Strip json vulnerability protection prefix and trim whitespace
9689 var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
9692 var contentType = headers('Content-Type');
9693 if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
9694 data = fromJson(tempData);
9702 function isJsonLike(str) {
9703 var jsonStart = str.match(JSON_START);
9704 return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
9708 * Parse headers into key value object
9710 * @param {string} headers Raw headers as a string
9711 * @returns {Object} Parsed headers as key value object
9713 function parseHeaders(headers) {
9714 var parsed = createMap(), i;
9716 function fillInParsed(key, val) {
9718 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
9722 if (isString(headers)) {
9723 forEach(headers.split('\n'), function(line) {
9724 i = line.indexOf(':');
9725 fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
9727 } else if (isObject(headers)) {
9728 forEach(headers, function(headerVal, headerKey) {
9729 fillInParsed(lowercase(headerKey), trim(headerVal));
9738 * Returns a function that provides access to parsed headers.
9740 * Headers are lazy parsed when first requested.
9743 * @param {(string|Object)} headers Headers to provide access to.
9744 * @returns {function(string=)} Returns a getter function which if called with:
9746 * - if called with single an argument returns a single header value or null
9747 * - if called with no arguments returns an object containing all headers.
9749 function headersGetter(headers) {
9752 return function(name) {
9753 if (!headersObj) headersObj = parseHeaders(headers);
9756 var value = headersObj[lowercase(name)];
9757 if (value === void 0) {
9769 * Chain all given functions
9771 * This function is used for both request and response transforming
9773 * @param {*} data Data to transform.
9774 * @param {function(string=)} headers HTTP headers getter fn.
9775 * @param {number} status HTTP status code of the response.
9776 * @param {(Function|Array.<Function>)} fns Function or an array of functions.
9777 * @returns {*} Transformed data.
9779 function transformData(data, headers, status, fns) {
9780 if (isFunction(fns)) {
9781 return fns(data, headers, status);
9784 forEach(fns, function(fn) {
9785 data = fn(data, headers, status);
9792 function isSuccess(status) {
9793 return 200 <= status && status < 300;
9799 * @name $httpProvider
9801 * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
9803 function $HttpProvider() {
9806 * @name $httpProvider#defaults
9809 * Object containing default values for all {@link ng.$http $http} requests.
9811 * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
9812 * that will provide the cache for all requests who set their `cache` property to `true`.
9813 * If you set the `defaults.cache = false` then only requests that specify their own custom
9814 * cache object will be cached. See {@link $http#caching $http Caching} for more information.
9816 * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
9817 * Defaults value is `'XSRF-TOKEN'`.
9819 * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
9820 * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
9822 * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
9823 * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
9824 * setting default headers.
9825 * - **`defaults.headers.common`**
9826 * - **`defaults.headers.post`**
9827 * - **`defaults.headers.put`**
9828 * - **`defaults.headers.patch`**
9831 * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
9832 * used to the prepare string representation of request parameters (specified as an object).
9833 * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
9834 * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
9837 var defaults = this.defaults = {
9838 // transform incoming response data
9839 transformResponse: [defaultHttpResponseTransform],
9841 // transform outgoing request data
9842 transformRequest: [function(d) {
9843 return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
9849 'Accept': 'application/json, text/plain, */*'
9851 post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
9852 put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
9853 patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
9856 xsrfCookieName: 'XSRF-TOKEN',
9857 xsrfHeaderName: 'X-XSRF-TOKEN',
9859 paramSerializer: '$httpParamSerializer'
9862 var useApplyAsync = false;
9865 * @name $httpProvider#useApplyAsync
9868 * Configure $http service to combine processing of multiple http responses received at around
9869 * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
9870 * significant performance improvement for bigger applications that make many HTTP requests
9871 * concurrently (common during application bootstrap).
9873 * Defaults to false. If no value is specified, returns the current configured value.
9875 * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
9876 * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
9877 * to load and share the same digest cycle.
9879 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
9880 * otherwise, returns the current configured value.
9882 this.useApplyAsync = function(value) {
9883 if (isDefined(value)) {
9884 useApplyAsync = !!value;
9887 return useApplyAsync;
9890 var useLegacyPromise = true;
9893 * @name $httpProvider#useLegacyPromiseExtensions
9896 * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
9897 * This should be used to make sure that applications work without these methods.
9899 * Defaults to true. If no value is specified, returns the current configured value.
9901 * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
9903 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
9904 * otherwise, returns the current configured value.
9906 this.useLegacyPromiseExtensions = function(value) {
9907 if (isDefined(value)) {
9908 useLegacyPromise = !!value;
9911 return useLegacyPromise;
9916 * @name $httpProvider#interceptors
9919 * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
9920 * pre-processing of request or postprocessing of responses.
9922 * These service factories are ordered by request, i.e. they are applied in the same order as the
9923 * array, on request, but reverse order, on response.
9925 * {@link ng.$http#interceptors Interceptors detailed info}
9927 var interceptorFactories = this.interceptors = [];
9929 this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
9930 function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
9932 var defaultCache = $cacheFactory('$http');
9935 * Make sure that default param serializer is exposed as a function
9937 defaults.paramSerializer = isString(defaults.paramSerializer) ?
9938 $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
9941 * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
9942 * The reversal is needed so that we can build up the interception chain around the
9945 var reversedInterceptors = [];
9947 forEach(interceptorFactories, function(interceptorFactory) {
9948 reversedInterceptors.unshift(isString(interceptorFactory)
9949 ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
9956 * @requires ng.$httpBackend
9957 * @requires $cacheFactory
9958 * @requires $rootScope
9960 * @requires $injector
9963 * The `$http` service is a core Angular service that facilitates communication with the remote
9964 * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
9965 * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
9967 * For unit testing applications that use `$http` service, see
9968 * {@link ngMock.$httpBackend $httpBackend mock}.
9970 * For a higher level of abstraction, please check out the {@link ngResource.$resource
9971 * $resource} service.
9973 * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
9974 * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
9975 * it is important to familiarize yourself with these APIs and the guarantees they provide.
9979 * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
9980 * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
9983 * // Simple GET request example:
9987 * }).then(function successCallback(response) {
9988 * // this callback will be called asynchronously
9989 * // when the response is available
9990 * }, function errorCallback(response) {
9991 * // called asynchronously if an error occurs
9992 * // or server returns response with an error status.
9996 * The response object has these properties:
9998 * - **data** – `{string|Object}` – The response body transformed with the transform
10000 * - **status** – `{number}` – HTTP status code of the response.
10001 * - **headers** – `{function([headerName])}` – Header getter function.
10002 * - **config** – `{Object}` – The configuration object that was used to generate the request.
10003 * - **statusText** – `{string}` – HTTP status text of the response.
10005 * A response status code between 200 and 299 is considered a success status and
10006 * will result in the success callback being called. Note that if the response is a redirect,
10007 * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
10008 * called for such responses.
10011 * ## Shortcut methods
10013 * Shortcut methods are also available. All shortcut methods require passing in the URL, and
10014 * request data must be passed in for POST/PUT requests. An optional config can be passed as the
10018 * $http.get('/someUrl', config).then(successCallback, errorCallback);
10019 * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
10022 * Complete list of shortcut methods:
10024 * - {@link ng.$http#get $http.get}
10025 * - {@link ng.$http#head $http.head}
10026 * - {@link ng.$http#post $http.post}
10027 * - {@link ng.$http#put $http.put}
10028 * - {@link ng.$http#delete $http.delete}
10029 * - {@link ng.$http#jsonp $http.jsonp}
10030 * - {@link ng.$http#patch $http.patch}
10033 * ## Writing Unit Tests that use $http
10034 * When unit testing (using {@link ngMock ngMock}), it is necessary to call
10035 * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
10036 * request using trained responses.
10039 * $httpBackend.expectGET(...);
10041 * $httpBackend.flush();
10044 * ## Deprecation Notice
10045 * <div class="alert alert-danger">
10046 * The `$http` legacy promise methods `success` and `error` have been deprecated.
10047 * Use the standard `then` method instead.
10048 * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
10049 * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
10052 * ## Setting HTTP Headers
10054 * The $http service will automatically add certain HTTP headers to all requests. These defaults
10055 * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
10056 * object, which currently contains this default configuration:
10058 * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
10059 * - `Accept: application/json, text/plain, * / *`
10060 * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
10061 * - `Content-Type: application/json`
10062 * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
10063 * - `Content-Type: application/json`
10065 * To add or overwrite these defaults, simply add or remove a property from these configuration
10066 * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
10067 * with the lowercased HTTP method name as the key, e.g.
10068 * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
10070 * The defaults can also be set at runtime via the `$http.defaults` object in the same
10071 * fashion. For example:
10074 * module.run(function($http) {
10075 * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
10079 * In addition, you can supply a `headers` property in the config object passed when
10080 * calling `$http(config)`, which overrides the defaults without changing them globally.
10082 * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
10083 * Use the `headers` property, setting the desired header to `undefined`. For example:
10088 * url: 'http://example.com',
10090 * 'Content-Type': undefined
10092 * data: { test: 'test' }
10095 * $http(req).then(function(){...}, function(){...});
10098 * ## Transforming Requests and Responses
10100 * Both requests and responses can be transformed using transformation functions: `transformRequest`
10101 * and `transformResponse`. These properties can be a single function that returns
10102 * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
10103 * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
10105 * ### Default Transformations
10107 * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
10108 * `defaults.transformResponse` properties. If a request does not provide its own transformations
10109 * then these will be applied.
10111 * You can augment or replace the default transformations by modifying these properties by adding to or
10112 * replacing the array.
10114 * Angular provides the following default transformations:
10116 * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
10118 * - If the `data` property of the request configuration object contains an object, serialize it
10119 * into JSON format.
10121 * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
10123 * - If XSRF prefix is detected, strip it (see Security Considerations section below).
10124 * - If JSON response is detected, deserialize it using a JSON parser.
10127 * ### Overriding the Default Transformations Per Request
10129 * If you wish override the request/response transformations only for a single request then provide
10130 * `transformRequest` and/or `transformResponse` properties on the configuration object passed
10133 * Note that if you provide these properties on the config object the default transformations will be
10134 * overwritten. If you wish to augment the default transformations then you must include them in your
10135 * local transformation array.
10137 * The following code demonstrates adding a new response transformation to be run after the default response
10138 * transformations have been run.
10141 * function appendTransform(defaults, transform) {
10143 * // We can't guarantee that the default transformation is an array
10144 * defaults = angular.isArray(defaults) ? defaults : [defaults];
10146 * // Append the new transformation to the defaults
10147 * return defaults.concat(transform);
10153 * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
10154 * return doTransform(value);
10162 * To enable caching, set the request configuration `cache` property to `true` (to use default
10163 * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
10164 * When the cache is enabled, `$http` stores the response from the server in the specified
10165 * cache. The next time the same request is made, the response is served from the cache without
10166 * sending a request to the server.
10168 * Note that even if the response is served from cache, delivery of the data is asynchronous in
10169 * the same way that real requests are.
10171 * If there are multiple GET requests for the same URL that should be cached using the same
10172 * cache, but the cache is not populated yet, only one request to the server will be made and
10173 * the remaining requests will be fulfilled using the response from the first request.
10175 * You can change the default cache to a new object (built with
10176 * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
10177 * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
10178 * their `cache` property to `true` will now use this cache object.
10180 * If you set the default cache to `false` then only requests that specify their own custom
10181 * cache object will be cached.
10185 * Before you start creating interceptors, be sure to understand the
10186 * {@link ng.$q $q and deferred/promise APIs}.
10188 * For purposes of global error handling, authentication, or any kind of synchronous or
10189 * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
10190 * able to intercept requests before they are handed to the server and
10191 * responses before they are handed over to the application code that
10192 * initiated these requests. The interceptors leverage the {@link ng.$q
10193 * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
10195 * The interceptors are service factories that are registered with the `$httpProvider` by
10196 * adding them to the `$httpProvider.interceptors` array. The factory is called and
10197 * injected with dependencies (if specified) and returns the interceptor.
10199 * There are two kinds of interceptors (and two kinds of rejection interceptors):
10201 * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
10202 * modify the `config` object or create a new one. The function needs to return the `config`
10203 * object directly, or a promise containing the `config` or a new `config` object.
10204 * * `requestError`: interceptor gets called when a previous interceptor threw an error or
10205 * resolved with a rejection.
10206 * * `response`: interceptors get called with http `response` object. The function is free to
10207 * modify the `response` object or create a new one. The function needs to return the `response`
10208 * object directly, or as a promise containing the `response` or a new `response` object.
10209 * * `responseError`: interceptor gets called when a previous interceptor threw an error or
10210 * resolved with a rejection.
10214 * // register the interceptor as a service
10215 * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
10217 * // optional method
10218 * 'request': function(config) {
10219 * // do something on success
10223 * // optional method
10224 * 'requestError': function(rejection) {
10225 * // do something on error
10226 * if (canRecover(rejection)) {
10227 * return responseOrNewPromise
10229 * return $q.reject(rejection);
10234 * // optional method
10235 * 'response': function(response) {
10236 * // do something on success
10240 * // optional method
10241 * 'responseError': function(rejection) {
10242 * // do something on error
10243 * if (canRecover(rejection)) {
10244 * return responseOrNewPromise
10246 * return $q.reject(rejection);
10251 * $httpProvider.interceptors.push('myHttpInterceptor');
10254 * // alternatively, register the interceptor via an anonymous factory
10255 * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
10257 * 'request': function(config) {
10261 * 'response': function(response) {
10268 * ## Security Considerations
10270 * When designing web applications, consider security threats from:
10272 * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
10273 * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
10275 * Both server and the client must cooperate in order to eliminate these threats. Angular comes
10276 * pre-configured with strategies that address these issues, but for this to work backend server
10277 * cooperation is required.
10279 * ### JSON Vulnerability Protection
10281 * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
10282 * allows third party website to turn your JSON resource URL into
10283 * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
10284 * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
10285 * Angular will automatically strip the prefix before processing it as JSON.
10287 * For example if your server needs to return:
10292 * which is vulnerable to attack, your server can return:
10298 * Angular will strip the prefix, before processing the JSON.
10301 * ### Cross Site Request Forgery (XSRF) Protection
10303 * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
10304 * an unauthorized site can gain your user's private data. Angular provides a mechanism
10305 * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
10306 * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
10307 * JavaScript that runs on your domain could read the cookie, your server can be assured that
10308 * the XHR came from JavaScript running on your domain. The header will not be set for
10309 * cross-domain requests.
10311 * To take advantage of this, your server needs to set a token in a JavaScript readable session
10312 * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
10313 * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
10314 * that only JavaScript running on your domain could have sent the request. The token must be
10315 * unique for each user and must be verifiable by the server (to prevent the JavaScript from
10316 * making up its own tokens). We recommend that the token is a digest of your site's
10317 * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
10318 * for added security.
10320 * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
10321 * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
10322 * or the per-request config object.
10324 * In order to prevent collisions in environments where multiple Angular apps share the
10325 * same domain or subdomain, we recommend that each application uses unique cookie name.
10327 * @param {object} config Object describing the request to be made and how it should be
10328 * processed. The object has following properties:
10330 * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
10331 * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
10332 * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
10333 * with the `paramSerializer` and appended as GET parameters.
10334 * - **data** – `{string|Object}` – Data to be sent as the request message data.
10335 * - **headers** – `{Object}` – Map of strings or functions which return strings representing
10336 * HTTP headers to send to the server. If the return value of a function is null, the
10337 * header will not be sent. Functions accept a config object as an argument.
10338 * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
10339 * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
10340 * - **transformRequest** –
10341 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
10342 * transform function or an array of such functions. The transform function takes the http
10343 * request body and headers and returns its transformed (typically serialized) version.
10344 * See {@link ng.$http#overriding-the-default-transformations-per-request
10345 * Overriding the Default Transformations}
10346 * - **transformResponse** –
10347 * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
10348 * transform function or an array of such functions. The transform function takes the http
10349 * response body, headers and status and returns its transformed (typically deserialized) version.
10350 * See {@link ng.$http#overriding-the-default-transformations-per-request
10351 * Overriding the Default TransformationjqLiks}
10352 * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
10353 * prepare the string representation of request parameters (specified as an object).
10354 * If specified as string, it is interpreted as function registered with the
10355 * {@link $injector $injector}, which means you can create your own serializer
10356 * by registering it as a {@link auto.$provide#service service}.
10357 * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
10358 * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
10359 * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
10360 * GET request, otherwise if a cache instance built with
10361 * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
10363 * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
10364 * that should abort the request when resolved.
10365 * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
10366 * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
10367 * for more information.
10368 * - **responseType** - `{string}` - see
10369 * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
10371 * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
10372 * when the request succeeds or fails.
10375 * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
10376 * requests. This is primarily meant to be used for debugging purposes.
10380 <example module="httpExample">
10381 <file name="index.html">
10382 <div ng-controller="FetchController">
10383 <select ng-model="method" aria-label="Request method">
10384 <option>GET</option>
10385 <option>JSONP</option>
10387 <input type="text" ng-model="url" size="80" aria-label="URL" />
10388 <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
10389 <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
10390 <button id="samplejsonpbtn"
10391 ng-click="updateModel('JSONP',
10392 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
10395 <button id="invalidjsonpbtn"
10396 ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
10399 <pre>http status code: {{status}}</pre>
10400 <pre>http response data: {{data}}</pre>
10403 <file name="script.js">
10404 angular.module('httpExample', [])
10405 .controller('FetchController', ['$scope', '$http', '$templateCache',
10406 function($scope, $http, $templateCache) {
10407 $scope.method = 'GET';
10408 $scope.url = 'http-hello.html';
10410 $scope.fetch = function() {
10411 $scope.code = null;
10412 $scope.response = null;
10414 $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
10415 then(function(response) {
10416 $scope.status = response.status;
10417 $scope.data = response.data;
10418 }, function(response) {
10419 $scope.data = response.data || "Request failed";
10420 $scope.status = response.status;
10424 $scope.updateModel = function(method, url) {
10425 $scope.method = method;
10430 <file name="http-hello.html">
10433 <file name="protractor.js" type="protractor">
10434 var status = element(by.binding('status'));
10435 var data = element(by.binding('data'));
10436 var fetchBtn = element(by.id('fetchbtn'));
10437 var sampleGetBtn = element(by.id('samplegetbtn'));
10438 var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
10439 var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
10441 it('should make an xhr GET request', function() {
10442 sampleGetBtn.click();
10444 expect(status.getText()).toMatch('200');
10445 expect(data.getText()).toMatch(/Hello, \$http!/);
10448 // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
10449 // it('should make a JSONP request to angularjs.org', function() {
10450 // sampleJsonpBtn.click();
10451 // fetchBtn.click();
10452 // expect(status.getText()).toMatch('200');
10453 // expect(data.getText()).toMatch(/Super Hero!/);
10456 it('should make JSONP request to invalid URL and invoke the error handler',
10458 invalidJsonpBtn.click();
10460 expect(status.getText()).toMatch('0');
10461 expect(data.getText()).toMatch('Request failed');
10466 function $http(requestConfig) {
10468 if (!isObject(requestConfig)) {
10469 throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
10472 var config = extend({
10474 transformRequest: defaults.transformRequest,
10475 transformResponse: defaults.transformResponse,
10476 paramSerializer: defaults.paramSerializer
10479 config.headers = mergeHeaders(requestConfig);
10480 config.method = uppercase(config.method);
10481 config.paramSerializer = isString(config.paramSerializer) ?
10482 $injector.get(config.paramSerializer) : config.paramSerializer;
10484 var serverRequest = function(config) {
10485 var headers = config.headers;
10486 var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
10488 // strip content-type if data is undefined
10489 if (isUndefined(reqData)) {
10490 forEach(headers, function(value, header) {
10491 if (lowercase(header) === 'content-type') {
10492 delete headers[header];
10497 if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
10498 config.withCredentials = defaults.withCredentials;
10502 return sendReq(config, reqData).then(transformResponse, transformResponse);
10505 var chain = [serverRequest, undefined];
10506 var promise = $q.when(config);
10508 // apply interceptors
10509 forEach(reversedInterceptors, function(interceptor) {
10510 if (interceptor.request || interceptor.requestError) {
10511 chain.unshift(interceptor.request, interceptor.requestError);
10513 if (interceptor.response || interceptor.responseError) {
10514 chain.push(interceptor.response, interceptor.responseError);
10518 while (chain.length) {
10519 var thenFn = chain.shift();
10520 var rejectFn = chain.shift();
10522 promise = promise.then(thenFn, rejectFn);
10525 if (useLegacyPromise) {
10526 promise.success = function(fn) {
10527 assertArgFn(fn, 'fn');
10529 promise.then(function(response) {
10530 fn(response.data, response.status, response.headers, config);
10535 promise.error = function(fn) {
10536 assertArgFn(fn, 'fn');
10538 promise.then(null, function(response) {
10539 fn(response.data, response.status, response.headers, config);
10544 promise.success = $httpMinErrLegacyFn('success');
10545 promise.error = $httpMinErrLegacyFn('error');
10550 function transformResponse(response) {
10551 // make a copy since the response must be cacheable
10552 var resp = extend({}, response);
10553 resp.data = transformData(response.data, response.headers, response.status,
10554 config.transformResponse);
10555 return (isSuccess(response.status))
10560 function executeHeaderFns(headers, config) {
10561 var headerContent, processedHeaders = {};
10563 forEach(headers, function(headerFn, header) {
10564 if (isFunction(headerFn)) {
10565 headerContent = headerFn(config);
10566 if (headerContent != null) {
10567 processedHeaders[header] = headerContent;
10570 processedHeaders[header] = headerFn;
10574 return processedHeaders;
10577 function mergeHeaders(config) {
10578 var defHeaders = defaults.headers,
10579 reqHeaders = extend({}, config.headers),
10580 defHeaderName, lowercaseDefHeaderName, reqHeaderName;
10582 defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
10584 // using for-in instead of forEach to avoid unecessary iteration after header has been found
10585 defaultHeadersIteration:
10586 for (defHeaderName in defHeaders) {
10587 lowercaseDefHeaderName = lowercase(defHeaderName);
10589 for (reqHeaderName in reqHeaders) {
10590 if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
10591 continue defaultHeadersIteration;
10595 reqHeaders[defHeaderName] = defHeaders[defHeaderName];
10598 // execute if header value is a function for merged headers
10599 return executeHeaderFns(reqHeaders, shallowCopy(config));
10603 $http.pendingRequests = [];
10610 * Shortcut method to perform `GET` request.
10612 * @param {string} url Relative or absolute URL specifying the destination of the request
10613 * @param {Object=} config Optional configuration object
10614 * @returns {HttpPromise} Future object
10619 * @name $http#delete
10622 * Shortcut method to perform `DELETE` request.
10624 * @param {string} url Relative or absolute URL specifying the destination of the request
10625 * @param {Object=} config Optional configuration object
10626 * @returns {HttpPromise} Future object
10634 * Shortcut method to perform `HEAD` request.
10636 * @param {string} url Relative or absolute URL specifying the destination of the request
10637 * @param {Object=} config Optional configuration object
10638 * @returns {HttpPromise} Future object
10643 * @name $http#jsonp
10646 * Shortcut method to perform `JSONP` request.
10648 * @param {string} url Relative or absolute URL specifying the destination of the request.
10649 * The name of the callback should be the string `JSON_CALLBACK`.
10650 * @param {Object=} config Optional configuration object
10651 * @returns {HttpPromise} Future object
10653 createShortMethods('get', 'delete', 'head', 'jsonp');
10660 * Shortcut method to perform `POST` request.
10662 * @param {string} url Relative or absolute URL specifying the destination of the request
10663 * @param {*} data Request content
10664 * @param {Object=} config Optional configuration object
10665 * @returns {HttpPromise} Future object
10673 * Shortcut method to perform `PUT` request.
10675 * @param {string} url Relative or absolute URL specifying the destination of the request
10676 * @param {*} data Request content
10677 * @param {Object=} config Optional configuration object
10678 * @returns {HttpPromise} Future object
10683 * @name $http#patch
10686 * Shortcut method to perform `PATCH` request.
10688 * @param {string} url Relative or absolute URL specifying the destination of the request
10689 * @param {*} data Request content
10690 * @param {Object=} config Optional configuration object
10691 * @returns {HttpPromise} Future object
10693 createShortMethodsWithData('post', 'put', 'patch');
10697 * @name $http#defaults
10700 * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
10701 * default headers, withCredentials as well as request and response transformations.
10703 * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
10705 $http.defaults = defaults;
10711 function createShortMethods(names) {
10712 forEach(arguments, function(name) {
10713 $http[name] = function(url, config) {
10714 return $http(extend({}, config || {}, {
10723 function createShortMethodsWithData(name) {
10724 forEach(arguments, function(name) {
10725 $http[name] = function(url, data, config) {
10726 return $http(extend({}, config || {}, {
10737 * Makes the request.
10739 * !!! ACCESSES CLOSURE VARS:
10740 * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
10742 function sendReq(config, reqData) {
10743 var deferred = $q.defer(),
10744 promise = deferred.promise,
10747 reqHeaders = config.headers,
10748 url = buildUrl(config.url, config.paramSerializer(config.params));
10750 $http.pendingRequests.push(config);
10751 promise.then(removePendingReq, removePendingReq);
10754 if ((config.cache || defaults.cache) && config.cache !== false &&
10755 (config.method === 'GET' || config.method === 'JSONP')) {
10756 cache = isObject(config.cache) ? config.cache
10757 : isObject(defaults.cache) ? defaults.cache
10762 cachedResp = cache.get(url);
10763 if (isDefined(cachedResp)) {
10764 if (isPromiseLike(cachedResp)) {
10765 // cached request has already been sent, but there is no response yet
10766 cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
10768 // serving from cache
10769 if (isArray(cachedResp)) {
10770 resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
10772 resolvePromise(cachedResp, 200, {}, 'OK');
10776 // put the promise for the non-transformed response into cache as a placeholder
10777 cache.put(url, promise);
10782 // if we won't have the response in cache, set the xsrf headers and
10783 // send the request to the backend
10784 if (isUndefined(cachedResp)) {
10785 var xsrfValue = urlIsSameOrigin(config.url)
10786 ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
10789 reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
10792 $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
10793 config.withCredentials, config.responseType);
10800 * Callback registered to $httpBackend():
10801 * - caches the response if desired
10802 * - resolves the raw $http promise
10805 function done(status, response, headersString, statusText) {
10807 if (isSuccess(status)) {
10808 cache.put(url, [status, response, parseHeaders(headersString), statusText]);
10810 // remove promise from the cache
10815 function resolveHttpPromise() {
10816 resolvePromise(response, status, headersString, statusText);
10819 if (useApplyAsync) {
10820 $rootScope.$applyAsync(resolveHttpPromise);
10822 resolveHttpPromise();
10823 if (!$rootScope.$$phase) $rootScope.$apply();
10829 * Resolves the raw $http promise.
10831 function resolvePromise(response, status, headers, statusText) {
10832 //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
10833 status = status >= -1 ? status : 0;
10835 (isSuccess(status) ? deferred.resolve : deferred.reject)({
10838 headers: headersGetter(headers),
10840 statusText: statusText
10844 function resolvePromiseWithResult(result) {
10845 resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
10848 function removePendingReq() {
10849 var idx = $http.pendingRequests.indexOf(config);
10850 if (idx !== -1) $http.pendingRequests.splice(idx, 1);
10855 function buildUrl(url, serializedParams) {
10856 if (serializedParams.length > 0) {
10857 url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
10866 * @name $xhrFactory
10869 * Factory function used to create XMLHttpRequest objects.
10871 * Replace or decorate this service to create your own custom XMLHttpRequest objects.
10874 * angular.module('myApp', [])
10875 * .factory('$xhrFactory', function() {
10876 * return function createXhr(method, url) {
10877 * return new window.XMLHttpRequest({mozSystem: true});
10882 * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
10883 * @param {string} url URL of the request.
10885 function $xhrFactoryProvider() {
10886 this.$get = function() {
10887 return function createXhr() {
10888 return new window.XMLHttpRequest();
10895 * @name $httpBackend
10896 * @requires $window
10897 * @requires $document
10898 * @requires $xhrFactory
10901 * HTTP backend used by the {@link ng.$http service} that delegates to
10902 * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
10904 * You should never need to use this service directly, instead use the higher-level abstractions:
10905 * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
10907 * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
10908 * $httpBackend} which can be trained with responses.
10910 function $HttpBackendProvider() {
10911 this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
10912 return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
10916 function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
10917 // TODO(vojta): fix the signature
10918 return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
10919 $browser.$$incOutstandingRequestCount();
10920 url = url || $browser.url();
10922 if (lowercase(method) == 'jsonp') {
10923 var callbackId = '_' + (callbacks.counter++).toString(36);
10924 callbacks[callbackId] = function(data) {
10925 callbacks[callbackId].data = data;
10926 callbacks[callbackId].called = true;
10929 var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
10930 callbackId, function(status, text) {
10931 completeRequest(callback, status, callbacks[callbackId].data, "", text);
10932 callbacks[callbackId] = noop;
10936 var xhr = createXhr(method, url);
10938 xhr.open(method, url, true);
10939 forEach(headers, function(value, key) {
10940 if (isDefined(value)) {
10941 xhr.setRequestHeader(key, value);
10945 xhr.onload = function requestLoaded() {
10946 var statusText = xhr.statusText || '';
10948 // responseText is the old-school way of retrieving response (supported by IE9)
10949 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
10950 var response = ('response' in xhr) ? xhr.response : xhr.responseText;
10952 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
10953 var status = xhr.status === 1223 ? 204 : xhr.status;
10955 // fix status code when it is 0 (0 status is undocumented).
10956 // Occurs when accessing file resources or on Android 4.1 stock browser
10957 // while retrieving files from application cache.
10958 if (status === 0) {
10959 status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
10962 completeRequest(callback,
10965 xhr.getAllResponseHeaders(),
10969 var requestError = function() {
10970 // The response is always empty
10971 // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
10972 completeRequest(callback, -1, null, null, '');
10975 xhr.onerror = requestError;
10976 xhr.onabort = requestError;
10978 if (withCredentials) {
10979 xhr.withCredentials = true;
10982 if (responseType) {
10984 xhr.responseType = responseType;
10986 // WebKit added support for the json responseType value on 09/03/2013
10987 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
10988 // known to throw when setting the value "json" as the response type. Other older
10989 // browsers implementing the responseType
10991 // The json response type can be ignored if not supported, because JSON payloads are
10992 // parsed on the client-side regardless.
10993 if (responseType !== 'json') {
10999 xhr.send(isUndefined(post) ? null : post);
11003 var timeoutId = $browserDefer(timeoutRequest, timeout);
11004 } else if (isPromiseLike(timeout)) {
11005 timeout.then(timeoutRequest);
11009 function timeoutRequest() {
11010 jsonpDone && jsonpDone();
11011 xhr && xhr.abort();
11014 function completeRequest(callback, status, response, headersString, statusText) {
11015 // cancel timeout and subsequent timeout promise resolution
11016 if (isDefined(timeoutId)) {
11017 $browserDefer.cancel(timeoutId);
11019 jsonpDone = xhr = null;
11021 callback(status, response, headersString, statusText);
11022 $browser.$$completeOutstandingRequest(noop);
11026 function jsonpReq(url, callbackId, done) {
11027 // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
11028 // - fetches local scripts via XHR and evals them
11029 // - adds and immediately removes script elements from the document
11030 var script = rawDocument.createElement('script'), callback = null;
11031 script.type = "text/javascript";
11033 script.async = true;
11035 callback = function(event) {
11036 removeEventListenerFn(script, "load", callback);
11037 removeEventListenerFn(script, "error", callback);
11038 rawDocument.body.removeChild(script);
11041 var text = "unknown";
11044 if (event.type === "load" && !callbacks[callbackId].called) {
11045 event = { type: "error" };
11048 status = event.type === "error" ? 404 : 200;
11052 done(status, text);
11056 addEventListenerFn(script, "load", callback);
11057 addEventListenerFn(script, "error", callback);
11058 rawDocument.body.appendChild(script);
11063 var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
11064 $interpolateMinErr.throwNoconcat = function(text) {
11065 throw $interpolateMinErr('noconcat',
11066 "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
11067 "interpolations that concatenate multiple expressions when a trusted value is " +
11068 "required. See http://docs.angularjs.org/api/ng.$sce", text);
11071 $interpolateMinErr.interr = function(text, err) {
11072 return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
11077 * @name $interpolateProvider
11081 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
11083 * <div class="alert alert-danger">
11084 * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
11085 * template within a Python Jinja template (or any other template language). Mixing templating
11086 * languages is **very dangerous**. The embedding template language will not safely escape Angular
11087 * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
11092 <example module="customInterpolationApp">
11093 <file name="index.html">
11095 var customInterpolationApp = angular.module('customInterpolationApp', []);
11097 customInterpolationApp.config(function($interpolateProvider) {
11098 $interpolateProvider.startSymbol('//');
11099 $interpolateProvider.endSymbol('//');
11103 customInterpolationApp.controller('DemoController', function() {
11104 this.label = "This binding is brought you by // interpolation symbols.";
11107 <div ng-app="App" ng-controller="DemoController as demo">
11111 <file name="protractor.js" type="protractor">
11112 it('should interpolate binding with custom symbols', function() {
11113 expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
11118 function $InterpolateProvider() {
11119 var startSymbol = '{{';
11120 var endSymbol = '}}';
11124 * @name $interpolateProvider#startSymbol
11126 * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
11128 * @param {string=} value new value to set the starting symbol to.
11129 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
11131 this.startSymbol = function(value) {
11133 startSymbol = value;
11136 return startSymbol;
11142 * @name $interpolateProvider#endSymbol
11144 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
11146 * @param {string=} value new value to set the ending symbol to.
11147 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
11149 this.endSymbol = function(value) {
11159 this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
11160 var startSymbolLength = startSymbol.length,
11161 endSymbolLength = endSymbol.length,
11162 escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
11163 escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
11165 function escape(ch) {
11166 return '\\\\\\' + ch;
11169 function unescapeText(text) {
11170 return text.replace(escapedStartRegexp, startSymbol).
11171 replace(escapedEndRegexp, endSymbol);
11174 function stringify(value) {
11175 if (value == null) { // null || undefined
11178 switch (typeof value) {
11182 value = '' + value;
11185 value = toJson(value);
11191 //TODO: this is the same as the constantWatchDelegate in parse.js
11192 function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
11194 return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
11196 return constantInterp(scope);
11197 }, listener, objectEquality);
11202 * @name $interpolate
11210 * Compiles a string with markup into an interpolation function. This service is used by the
11211 * HTML {@link ng.$compile $compile} service for data binding. See
11212 * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
11213 * interpolation markup.
11217 * var $interpolate = ...; // injected
11218 * var exp = $interpolate('Hello {{name | uppercase}}!');
11219 * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
11222 * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
11223 * `true`, the interpolation function will return `undefined` unless all embedded expressions
11224 * evaluate to a value other than `undefined`.
11227 * var $interpolate = ...; // injected
11228 * var context = {greeting: 'Hello', name: undefined };
11230 * // default "forgiving" mode
11231 * var exp = $interpolate('{{greeting}} {{name}}!');
11232 * expect(exp(context)).toEqual('Hello !');
11234 * // "allOrNothing" mode
11235 * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
11236 * expect(exp(context)).toBeUndefined();
11237 * context.name = 'Angular';
11238 * expect(exp(context)).toEqual('Hello Angular!');
11241 * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
11243 * ####Escaped Interpolation
11244 * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
11245 * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
11246 * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
11249 * This enables web-servers to prevent script injection attacks and defacing attacks, to some
11250 * degree, while also enabling code examples to work without relying on the
11251 * {@link ng.directive:ngNonBindable ngNonBindable} directive.
11253 * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
11254 * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all
11255 * interpolation start/end markers with their escaped counterparts.**
11257 * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
11258 * output when the $interpolate service processes the text. So, for HTML elements interpolated
11259 * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
11260 * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
11261 * this is typically useful only when user-data is used in rendering a template from the server, or
11262 * when otherwise untrusted data is used by a directive.
11265 * <file name="index.html">
11266 * <div ng-init="username='A user'">
11267 * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
11269 * <p><strong>{{username}}</strong> attempts to inject code which will deface the
11270 * application, but fails to accomplish their task, because the server has correctly
11271 * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
11273 * <p>Instead, the result of the attempted script injection is visible, and can be removed
11274 * from the database by an administrator.</p>
11279 * @param {string} text The text with markup to interpolate.
11280 * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
11281 * embedded expression in order to return an interpolation function. Strings with no
11282 * embedded expression will return null for the interpolation function.
11283 * @param {string=} trustedContext when provided, the returned function passes the interpolated
11284 * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
11285 * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
11286 * provides Strict Contextual Escaping for details.
11287 * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
11288 * unless all embedded expressions evaluate to a value other than `undefined`.
11289 * @returns {function(context)} an interpolation function which is used to compute the
11290 * interpolated string. The function has these parameters:
11292 * - `context`: evaluation context for all expressions embedded in the interpolated text
11294 function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
11295 // Provide a quick exit and simplified result function for text with no interpolation
11296 if (!text.length || text.indexOf(startSymbol) === -1) {
11297 var constantInterp;
11298 if (!mustHaveExpression) {
11299 var unescapedText = unescapeText(text);
11300 constantInterp = valueFn(unescapedText);
11301 constantInterp.exp = text;
11302 constantInterp.expressions = [];
11303 constantInterp.$$watchDelegate = constantWatchDelegate;
11305 return constantInterp;
11308 allOrNothing = !!allOrNothing;
11314 textLength = text.length,
11317 expressionPositions = [];
11319 while (index < textLength) {
11320 if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
11321 ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
11322 if (index !== startIndex) {
11323 concat.push(unescapeText(text.substring(index, startIndex)));
11325 exp = text.substring(startIndex + startSymbolLength, endIndex);
11326 expressions.push(exp);
11327 parseFns.push($parse(exp, parseStringifyInterceptor));
11328 index = endIndex + endSymbolLength;
11329 expressionPositions.push(concat.length);
11332 // we did not find an interpolation, so we have to add the remainder to the separators array
11333 if (index !== textLength) {
11334 concat.push(unescapeText(text.substring(index)));
11340 // Concatenating expressions makes it hard to reason about whether some combination of
11341 // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
11342 // single expression be used for iframe[src], object[src], etc., we ensure that the value
11343 // that's used is assigned or constructed by some JS code somewhere that is more testable or
11344 // make it obvious that you bound the value to some user controlled value. This helps reduce
11345 // the load when auditing for XSS issues.
11346 if (trustedContext && concat.length > 1) {
11347 $interpolateMinErr.throwNoconcat(text);
11350 if (!mustHaveExpression || expressions.length) {
11351 var compute = function(values) {
11352 for (var i = 0, ii = expressions.length; i < ii; i++) {
11353 if (allOrNothing && isUndefined(values[i])) return;
11354 concat[expressionPositions[i]] = values[i];
11356 return concat.join('');
11359 var getValue = function(value) {
11360 return trustedContext ?
11361 $sce.getTrusted(trustedContext, value) :
11362 $sce.valueOf(value);
11365 return extend(function interpolationFn(context) {
11367 var ii = expressions.length;
11368 var values = new Array(ii);
11371 for (; i < ii; i++) {
11372 values[i] = parseFns[i](context);
11375 return compute(values);
11377 $exceptionHandler($interpolateMinErr.interr(text, err));
11381 // all of these properties are undocumented for now
11382 exp: text, //just for compatibility with regular watchers created via $watch
11383 expressions: expressions,
11384 $$watchDelegate: function(scope, listener) {
11386 return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
11387 var currValue = compute(values);
11388 if (isFunction(listener)) {
11389 listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
11391 lastValue = currValue;
11397 function parseStringifyInterceptor(value) {
11399 value = getValue(value);
11400 return allOrNothing && !isDefined(value) ? value : stringify(value);
11402 $exceptionHandler($interpolateMinErr.interr(text, err));
11410 * @name $interpolate#startSymbol
11412 * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
11414 * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
11417 * @returns {string} start symbol.
11419 $interpolate.startSymbol = function() {
11420 return startSymbol;
11426 * @name $interpolate#endSymbol
11428 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
11430 * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
11433 * @returns {string} end symbol.
11435 $interpolate.endSymbol = function() {
11439 return $interpolate;
11443 function $IntervalProvider() {
11444 this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
11445 function($rootScope, $window, $q, $$q, $browser) {
11446 var intervals = {};
11454 * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
11457 * The return value of registering an interval function is a promise. This promise will be
11458 * notified upon each tick of the interval, and will be resolved after `count` iterations, or
11459 * run indefinitely if `count` is not defined. The value of the notification will be the
11460 * number of iterations that have run.
11461 * To cancel an interval, call `$interval.cancel(promise)`.
11463 * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
11464 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
11467 * <div class="alert alert-warning">
11468 * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
11469 * with them. In particular they are not automatically destroyed when a controller's scope or a
11470 * directive's element are destroyed.
11471 * You should take this into consideration and make sure to always cancel the interval at the
11472 * appropriate moment. See the example below for more details on how and when to do this.
11475 * @param {function()} fn A function that should be called repeatedly.
11476 * @param {number} delay Number of milliseconds between each function call.
11477 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
11479 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
11480 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
11481 * @param {...*=} Pass additional parameters to the executed function.
11482 * @returns {promise} A promise which will be notified on each iteration.
11485 * <example module="intervalExample">
11486 * <file name="index.html">
11488 * angular.module('intervalExample', [])
11489 * .controller('ExampleController', ['$scope', '$interval',
11490 * function($scope, $interval) {
11491 * $scope.format = 'M/d/yy h:mm:ss a';
11492 * $scope.blood_1 = 100;
11493 * $scope.blood_2 = 120;
11496 * $scope.fight = function() {
11497 * // Don't start a new fight if we are already fighting
11498 * if ( angular.isDefined(stop) ) return;
11500 * stop = $interval(function() {
11501 * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
11502 * $scope.blood_1 = $scope.blood_1 - 3;
11503 * $scope.blood_2 = $scope.blood_2 - 4;
11505 * $scope.stopFight();
11510 * $scope.stopFight = function() {
11511 * if (angular.isDefined(stop)) {
11512 * $interval.cancel(stop);
11513 * stop = undefined;
11517 * $scope.resetFight = function() {
11518 * $scope.blood_1 = 100;
11519 * $scope.blood_2 = 120;
11522 * $scope.$on('$destroy', function() {
11523 * // Make sure that the interval is destroyed too
11524 * $scope.stopFight();
11527 * // Register the 'myCurrentTime' directive factory method.
11528 * // We inject $interval and dateFilter service since the factory method is DI.
11529 * .directive('myCurrentTime', ['$interval', 'dateFilter',
11530 * function($interval, dateFilter) {
11531 * // return the directive link function. (compile function not needed)
11532 * return function(scope, element, attrs) {
11533 * var format, // date format
11534 * stopTime; // so that we can cancel the time updates
11536 * // used to update the UI
11537 * function updateTime() {
11538 * element.text(dateFilter(new Date(), format));
11541 * // watch the expression, and update the UI on change.
11542 * scope.$watch(attrs.myCurrentTime, function(value) {
11547 * stopTime = $interval(updateTime, 1000);
11549 * // listen on DOM destroy (removal) event, and cancel the next UI update
11550 * // to prevent updating time after the DOM element was removed.
11551 * element.on('$destroy', function() {
11552 * $interval.cancel(stopTime);
11559 * <div ng-controller="ExampleController">
11560 * <label>Date format: <input ng-model="format"></label> <hr/>
11561 * Current time is: <span my-current-time="format"></span>
11563 * Blood 1 : <font color='red'>{{blood_1}}</font>
11564 * Blood 2 : <font color='red'>{{blood_2}}</font>
11565 * <button type="button" data-ng-click="fight()">Fight</button>
11566 * <button type="button" data-ng-click="stopFight()">StopFight</button>
11567 * <button type="button" data-ng-click="resetFight()">resetFight</button>
11574 function interval(fn, delay, count, invokeApply) {
11575 var hasParams = arguments.length > 4,
11576 args = hasParams ? sliceArgs(arguments, 4) : [],
11577 setInterval = $window.setInterval,
11578 clearInterval = $window.clearInterval,
11580 skipApply = (isDefined(invokeApply) && !invokeApply),
11581 deferred = (skipApply ? $$q : $q).defer(),
11582 promise = deferred.promise;
11584 count = isDefined(count) ? count : 0;
11586 promise.$$intervalId = setInterval(function tick() {
11588 $browser.defer(callback);
11590 $rootScope.$evalAsync(callback);
11592 deferred.notify(iteration++);
11594 if (count > 0 && iteration >= count) {
11595 deferred.resolve(iteration);
11596 clearInterval(promise.$$intervalId);
11597 delete intervals[promise.$$intervalId];
11600 if (!skipApply) $rootScope.$apply();
11604 intervals[promise.$$intervalId] = deferred;
11608 function callback() {
11612 fn.apply(null, args);
11620 * @name $interval#cancel
11623 * Cancels a task associated with the `promise`.
11625 * @param {Promise=} promise returned by the `$interval` function.
11626 * @returns {boolean} Returns `true` if the task was successfully canceled.
11628 interval.cancel = function(promise) {
11629 if (promise && promise.$$intervalId in intervals) {
11630 intervals[promise.$$intervalId].reject('canceled');
11631 $window.clearInterval(promise.$$intervalId);
11632 delete intervals[promise.$$intervalId];
11647 * $locale service provides localization rules for various Angular components. As of right now the
11648 * only public api is:
11650 * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
11653 var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
11654 DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
11655 var $locationMinErr = minErr('$location');
11659 * Encode path using encodeUriSegment, ignoring forward slashes
11661 * @param {string} path Path to encode
11662 * @returns {string}
11664 function encodePath(path) {
11665 var segments = path.split('/'),
11666 i = segments.length;
11669 segments[i] = encodeUriSegment(segments[i]);
11672 return segments.join('/');
11675 function parseAbsoluteUrl(absoluteUrl, locationObj) {
11676 var parsedUrl = urlResolve(absoluteUrl);
11678 locationObj.$$protocol = parsedUrl.protocol;
11679 locationObj.$$host = parsedUrl.hostname;
11680 locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
11684 function parseAppUrl(relativeUrl, locationObj) {
11685 var prefixed = (relativeUrl.charAt(0) !== '/');
11687 relativeUrl = '/' + relativeUrl;
11689 var match = urlResolve(relativeUrl);
11690 locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
11691 match.pathname.substring(1) : match.pathname);
11692 locationObj.$$search = parseKeyValue(match.search);
11693 locationObj.$$hash = decodeURIComponent(match.hash);
11695 // make sure path starts with '/';
11696 if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
11697 locationObj.$$path = '/' + locationObj.$$path;
11704 * @param {string} begin
11705 * @param {string} whole
11706 * @returns {string} returns text from whole after begin or undefined if it does not begin with
11709 function beginsWith(begin, whole) {
11710 if (whole.indexOf(begin) === 0) {
11711 return whole.substr(begin.length);
11716 function stripHash(url) {
11717 var index = url.indexOf('#');
11718 return index == -1 ? url : url.substr(0, index);
11721 function trimEmptyHash(url) {
11722 return url.replace(/(#.+)|#$/, '$1');
11726 function stripFile(url) {
11727 return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
11730 /* return the server only (scheme://host:port) */
11731 function serverBase(url) {
11732 return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
11737 * LocationHtml5Url represents an url
11738 * This object is exposed as $location service when HTML5 mode is enabled and supported
11741 * @param {string} appBase application base URL
11742 * @param {string} appBaseNoFile application base URL stripped of any filename
11743 * @param {string} basePrefix url path prefix
11745 function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
11746 this.$$html5 = true;
11747 basePrefix = basePrefix || '';
11748 parseAbsoluteUrl(appBase, this);
11752 * Parse given html5 (regular) url string into properties
11753 * @param {string} url HTML5 url
11756 this.$$parse = function(url) {
11757 var pathUrl = beginsWith(appBaseNoFile, url);
11758 if (!isString(pathUrl)) {
11759 throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
11763 parseAppUrl(pathUrl, this);
11765 if (!this.$$path) {
11773 * Compose url and update `absUrl` property
11776 this.$$compose = function() {
11777 var search = toKeyValue(this.$$search),
11778 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
11780 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
11781 this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
11784 this.$$parseLinkUrl = function(url, relHref) {
11785 if (relHref && relHref[0] === '#') {
11786 // special case for links to hash fragments:
11787 // keep the old url and only replace the hash fragment
11788 this.hash(relHref.slice(1));
11791 var appUrl, prevAppUrl;
11794 if (isDefined(appUrl = beginsWith(appBase, url))) {
11795 prevAppUrl = appUrl;
11796 if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
11797 rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
11799 rewrittenUrl = appBase + prevAppUrl;
11801 } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
11802 rewrittenUrl = appBaseNoFile + appUrl;
11803 } else if (appBaseNoFile == url + '/') {
11804 rewrittenUrl = appBaseNoFile;
11806 if (rewrittenUrl) {
11807 this.$$parse(rewrittenUrl);
11809 return !!rewrittenUrl;
11815 * LocationHashbangUrl represents url
11816 * This object is exposed as $location service when developer doesn't opt into html5 mode.
11817 * It also serves as the base class for html5 mode fallback on legacy browsers.
11820 * @param {string} appBase application base URL
11821 * @param {string} appBaseNoFile application base URL stripped of any filename
11822 * @param {string} hashPrefix hashbang prefix
11824 function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
11826 parseAbsoluteUrl(appBase, this);
11830 * Parse given hashbang url into properties
11831 * @param {string} url Hashbang url
11834 this.$$parse = function(url) {
11835 var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
11836 var withoutHashUrl;
11838 if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
11840 // The rest of the url starts with a hash so we have
11841 // got either a hashbang path or a plain hash fragment
11842 withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
11843 if (isUndefined(withoutHashUrl)) {
11844 // There was no hashbang prefix so we just have a hash fragment
11845 withoutHashUrl = withoutBaseUrl;
11849 // There was no hashbang path nor hash fragment:
11850 // If we are in HTML5 mode we use what is left as the path;
11851 // Otherwise we ignore what is left
11852 if (this.$$html5) {
11853 withoutHashUrl = withoutBaseUrl;
11855 withoutHashUrl = '';
11856 if (isUndefined(withoutBaseUrl)) {
11863 parseAppUrl(withoutHashUrl, this);
11865 this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
11870 * In Windows, on an anchor node on documents loaded from
11871 * the filesystem, the browser will return a pathname
11872 * prefixed with the drive name ('/C:/path') when a
11873 * pathname without a drive is set:
11874 * * a.setAttribute('href', '/foo')
11875 * * a.pathname === '/C:/foo' //true
11877 * Inside of Angular, we're always using pathnames that
11878 * do not include drive names for routing.
11880 function removeWindowsDriveName(path, url, base) {
11882 Matches paths for file protocol on windows,
11883 such as /C:/foo/bar, and captures only /foo/bar.
11885 var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
11887 var firstPathSegmentMatch;
11889 //Get the relative path from the input URL.
11890 if (url.indexOf(base) === 0) {
11891 url = url.replace(base, '');
11894 // The input URL intentionally contains a first path segment that ends with a colon.
11895 if (windowsFilePathExp.exec(url)) {
11899 firstPathSegmentMatch = windowsFilePathExp.exec(path);
11900 return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
11905 * Compose hashbang url and update `absUrl` property
11908 this.$$compose = function() {
11909 var search = toKeyValue(this.$$search),
11910 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
11912 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
11913 this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
11916 this.$$parseLinkUrl = function(url, relHref) {
11917 if (stripHash(appBase) == stripHash(url)) {
11927 * LocationHashbangUrl represents url
11928 * This object is exposed as $location service when html5 history api is enabled but the browser
11929 * does not support it.
11932 * @param {string} appBase application base URL
11933 * @param {string} appBaseNoFile application base URL stripped of any filename
11934 * @param {string} hashPrefix hashbang prefix
11936 function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
11937 this.$$html5 = true;
11938 LocationHashbangUrl.apply(this, arguments);
11940 this.$$parseLinkUrl = function(url, relHref) {
11941 if (relHref && relHref[0] === '#') {
11942 // special case for links to hash fragments:
11943 // keep the old url and only replace the hash fragment
11944 this.hash(relHref.slice(1));
11951 if (appBase == stripHash(url)) {
11952 rewrittenUrl = url;
11953 } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
11954 rewrittenUrl = appBase + hashPrefix + appUrl;
11955 } else if (appBaseNoFile === url + '/') {
11956 rewrittenUrl = appBaseNoFile;
11958 if (rewrittenUrl) {
11959 this.$$parse(rewrittenUrl);
11961 return !!rewrittenUrl;
11964 this.$$compose = function() {
11965 var search = toKeyValue(this.$$search),
11966 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
11968 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
11969 // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
11970 this.$$absUrl = appBase + hashPrefix + this.$$url;
11976 var locationPrototype = {
11979 * Are we in html5 mode?
11985 * Has any change been replacing?
11992 * @name $location#absUrl
11995 * This method is getter only.
11997 * Return full url representation with all segments encoded according to rules specified in
11998 * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
12002 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12003 * var absUrl = $location.absUrl();
12004 * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
12007 * @return {string} full url
12009 absUrl: locationGetter('$$absUrl'),
12013 * @name $location#url
12016 * This method is getter / setter.
12018 * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
12020 * Change path, search and hash, when called with parameter and return `$location`.
12024 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12025 * var url = $location.url();
12026 * // => "/some/path?foo=bar&baz=xoxo"
12029 * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
12030 * @return {string} url
12032 url: function(url) {
12033 if (isUndefined(url)) {
12037 var match = PATH_MATCH.exec(url);
12038 if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
12039 if (match[2] || match[1] || url === '') this.search(match[3] || '');
12040 this.hash(match[5] || '');
12047 * @name $location#protocol
12050 * This method is getter only.
12052 * Return protocol of current url.
12056 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12057 * var protocol = $location.protocol();
12061 * @return {string} protocol of current url
12063 protocol: locationGetter('$$protocol'),
12067 * @name $location#host
12070 * This method is getter only.
12072 * Return host of current url.
12074 * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
12078 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12079 * var host = $location.host();
12080 * // => "example.com"
12082 * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
12083 * host = $location.host();
12084 * // => "example.com"
12085 * host = location.host;
12086 * // => "example.com:8080"
12089 * @return {string} host of current url.
12091 host: locationGetter('$$host'),
12095 * @name $location#port
12098 * This method is getter only.
12100 * Return port of current url.
12104 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12105 * var port = $location.port();
12109 * @return {Number} port
12111 port: locationGetter('$$port'),
12115 * @name $location#path
12118 * This method is getter / setter.
12120 * Return path of current url when called without any parameter.
12122 * Change path when called with parameter and return `$location`.
12124 * Note: Path should always begin with forward slash (/), this method will add the forward slash
12125 * if it is missing.
12129 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12130 * var path = $location.path();
12131 * // => "/some/path"
12134 * @param {(string|number)=} path New path
12135 * @return {string} path
12137 path: locationGetterSetter('$$path', function(path) {
12138 path = path !== null ? path.toString() : '';
12139 return path.charAt(0) == '/' ? path : '/' + path;
12144 * @name $location#search
12147 * This method is getter / setter.
12149 * Return search part (as object) of current url when called without any parameter.
12151 * Change search part when called with parameter and return `$location`.
12155 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
12156 * var searchObject = $location.search();
12157 * // => {foo: 'bar', baz: 'xoxo'}
12159 * // set foo to 'yipee'
12160 * $location.search('foo', 'yipee');
12161 * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
12164 * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
12167 * When called with a single argument the method acts as a setter, setting the `search` component
12168 * of `$location` to the specified value.
12170 * If the argument is a hash object containing an array of values, these values will be encoded
12171 * as duplicate search parameters in the url.
12173 * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
12174 * will override only a single search property.
12176 * If `paramValue` is an array, it will override the property of the `search` component of
12177 * `$location` specified via the first argument.
12179 * If `paramValue` is `null`, the property specified via the first argument will be deleted.
12181 * If `paramValue` is `true`, the property specified via the first argument will be added with no
12182 * value nor trailing equal sign.
12184 * @return {Object} If called with no arguments returns the parsed `search` object. If called with
12185 * one or more arguments returns `$location` object itself.
12187 search: function(search, paramValue) {
12188 switch (arguments.length) {
12190 return this.$$search;
12192 if (isString(search) || isNumber(search)) {
12193 search = search.toString();
12194 this.$$search = parseKeyValue(search);
12195 } else if (isObject(search)) {
12196 search = copy(search, {});
12197 // remove object undefined or null properties
12198 forEach(search, function(value, key) {
12199 if (value == null) delete search[key];
12202 this.$$search = search;
12204 throw $locationMinErr('isrcharg',
12205 'The first argument of the `$location#search()` call must be a string or an object.');
12209 if (isUndefined(paramValue) || paramValue === null) {
12210 delete this.$$search[search];
12212 this.$$search[search] = paramValue;
12222 * @name $location#hash
12225 * This method is getter / setter.
12227 * Returns the hash fragment when called without any parameters.
12229 * Changes the hash fragment when called with a parameter and returns `$location`.
12233 * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
12234 * var hash = $location.hash();
12235 * // => "hashValue"
12238 * @param {(string|number)=} hash New hash fragment
12239 * @return {string} hash
12241 hash: locationGetterSetter('$$hash', function(hash) {
12242 return hash !== null ? hash.toString() : '';
12247 * @name $location#replace
12250 * If called, all changes to $location during the current `$digest` will replace the current history
12251 * record, instead of adding a new one.
12253 replace: function() {
12254 this.$$replace = true;
12259 forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
12260 Location.prototype = Object.create(locationPrototype);
12264 * @name $location#state
12267 * This method is getter / setter.
12269 * Return the history state object when called without any parameter.
12271 * Change the history state object when called with one parameter and return `$location`.
12272 * The state object is later passed to `pushState` or `replaceState`.
12274 * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
12275 * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
12276 * older browsers (like IE9 or Android < 4.0), don't use this method.
12278 * @param {object=} state State object for pushState or replaceState
12279 * @return {object} state
12281 Location.prototype.state = function(state) {
12282 if (!arguments.length) {
12283 return this.$$state;
12286 if (Location !== LocationHtml5Url || !this.$$html5) {
12287 throw $locationMinErr('nostate', 'History API state support is available only ' +
12288 'in HTML5 mode and only in browsers supporting HTML5 History API');
12290 // The user might modify `stateObject` after invoking `$location.state(stateObject)`
12291 // but we're changing the $$state reference to $browser.state() during the $digest
12292 // so the modification window is narrow.
12293 this.$$state = isUndefined(state) ? null : state;
12300 function locationGetter(property) {
12301 return function() {
12302 return this[property];
12307 function locationGetterSetter(property, preprocess) {
12308 return function(value) {
12309 if (isUndefined(value)) {
12310 return this[property];
12313 this[property] = preprocess(value);
12325 * @requires $rootElement
12328 * The $location service parses the URL in the browser address bar (based on the
12329 * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
12330 * available to your application. Changes to the URL in the address bar are reflected into
12331 * $location service and changes to $location are reflected into the browser address bar.
12333 * **The $location service:**
12335 * - Exposes the current URL in the browser address bar, so you can
12336 * - Watch and observe the URL.
12337 * - Change the URL.
12338 * - Synchronizes the URL with the browser when the user
12339 * - Changes the address bar.
12340 * - Clicks the back or forward button (or clicks a History link).
12341 * - Clicks on a link.
12342 * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
12344 * For more information see {@link guide/$location Developer Guide: Using $location}
12349 * @name $locationProvider
12351 * Use the `$locationProvider` to configure how the application deep linking paths are stored.
12353 function $LocationProvider() {
12354 var hashPrefix = '',
12363 * @name $locationProvider#hashPrefix
12365 * @param {string=} prefix Prefix for hash part (containing path and search)
12366 * @returns {*} current value if used as getter or itself (chaining) if used as setter
12368 this.hashPrefix = function(prefix) {
12369 if (isDefined(prefix)) {
12370 hashPrefix = prefix;
12379 * @name $locationProvider#html5Mode
12381 * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
12382 * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
12384 * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
12385 * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
12386 * support `pushState`.
12387 * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
12388 * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
12389 * true, and a base tag is not present, an error will be thrown when `$location` is injected.
12390 * See the {@link guide/$location $location guide for more information}
12391 * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
12392 * enables/disables url rewriting for relative links.
12394 * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
12396 this.html5Mode = function(mode) {
12397 if (isBoolean(mode)) {
12398 html5Mode.enabled = mode;
12400 } else if (isObject(mode)) {
12402 if (isBoolean(mode.enabled)) {
12403 html5Mode.enabled = mode.enabled;
12406 if (isBoolean(mode.requireBase)) {
12407 html5Mode.requireBase = mode.requireBase;
12410 if (isBoolean(mode.rewriteLinks)) {
12411 html5Mode.rewriteLinks = mode.rewriteLinks;
12422 * @name $location#$locationChangeStart
12423 * @eventType broadcast on root scope
12425 * Broadcasted before a URL will change.
12427 * This change can be prevented by calling
12428 * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
12429 * details about event object. Upon successful change
12430 * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
12432 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
12433 * the browser supports the HTML5 History API.
12435 * @param {Object} angularEvent Synthetic event object.
12436 * @param {string} newUrl New URL
12437 * @param {string=} oldUrl URL that was before it was changed.
12438 * @param {string=} newState New history state object
12439 * @param {string=} oldState History state object that was before it was changed.
12444 * @name $location#$locationChangeSuccess
12445 * @eventType broadcast on root scope
12447 * Broadcasted after a URL was changed.
12449 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
12450 * the browser supports the HTML5 History API.
12452 * @param {Object} angularEvent Synthetic event object.
12453 * @param {string} newUrl New URL
12454 * @param {string=} oldUrl URL that was before it was changed.
12455 * @param {string=} newState New history state object
12456 * @param {string=} oldState History state object that was before it was changed.
12459 this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
12460 function($rootScope, $browser, $sniffer, $rootElement, $window) {
12463 baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
12464 initialUrl = $browser.url(),
12467 if (html5Mode.enabled) {
12468 if (!baseHref && html5Mode.requireBase) {
12469 throw $locationMinErr('nobase',
12470 "$location in HTML5 mode requires a <base> tag to be present!");
12472 appBase = serverBase(initialUrl) + (baseHref || '/');
12473 LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
12475 appBase = stripHash(initialUrl);
12476 LocationMode = LocationHashbangUrl;
12478 var appBaseNoFile = stripFile(appBase);
12480 $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
12481 $location.$$parseLinkUrl(initialUrl, initialUrl);
12483 $location.$$state = $browser.state();
12485 var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
12487 function setBrowserUrlWithFallback(url, replace, state) {
12488 var oldUrl = $location.url();
12489 var oldState = $location.$$state;
12491 $browser.url(url, replace, state);
12493 // Make sure $location.state() returns referentially identical (not just deeply equal)
12494 // state object; this makes possible quick checking if the state changed in the digest
12495 // loop. Checking deep equality would be too expensive.
12496 $location.$$state = $browser.state();
12498 // Restore old values if pushState fails
12499 $location.url(oldUrl);
12500 $location.$$state = oldState;
12506 $rootElement.on('click', function(event) {
12507 // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
12508 // currently we open nice url link and redirect then
12510 if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
12512 var elm = jqLite(event.target);
12514 // traverse the DOM up to find first A tag
12515 while (nodeName_(elm[0]) !== 'a') {
12516 // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
12517 if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
12520 var absHref = elm.prop('href');
12521 // get the actual href attribute - see
12522 // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
12523 var relHref = elm.attr('href') || elm.attr('xlink:href');
12525 if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
12526 // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
12528 absHref = urlResolve(absHref.animVal).href;
12531 // Ignore when url is started with javascript: or mailto:
12532 if (IGNORE_URI_REGEXP.test(absHref)) return;
12534 if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
12535 if ($location.$$parseLinkUrl(absHref, relHref)) {
12536 // We do a preventDefault for all urls that are part of the angular application,
12537 // in html5mode and also without, so that we are able to abort navigation without
12538 // getting double entries in the location history.
12539 event.preventDefault();
12540 // update location manually
12541 if ($location.absUrl() != $browser.url()) {
12542 $rootScope.$apply();
12543 // hack to work around FF6 bug 684208 when scenario runner clicks on links
12544 $window.angular['ff-684208-preventDefault'] = true;
12551 // rewrite hashbang url <> html5 url
12552 if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
12553 $browser.url($location.absUrl(), true);
12556 var initializing = true;
12558 // update $location when $browser url changes
12559 $browser.onUrlChange(function(newUrl, newState) {
12561 if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
12562 // If we are navigating outside of the app then force a reload
12563 $window.location.href = newUrl;
12567 $rootScope.$evalAsync(function() {
12568 var oldUrl = $location.absUrl();
12569 var oldState = $location.$$state;
12570 var defaultPrevented;
12571 newUrl = trimEmptyHash(newUrl);
12572 $location.$$parse(newUrl);
12573 $location.$$state = newState;
12575 defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
12576 newState, oldState).defaultPrevented;
12578 // if the location was changed by a `$locationChangeStart` handler then stop
12579 // processing this location change
12580 if ($location.absUrl() !== newUrl) return;
12582 if (defaultPrevented) {
12583 $location.$$parse(oldUrl);
12584 $location.$$state = oldState;
12585 setBrowserUrlWithFallback(oldUrl, false, oldState);
12587 initializing = false;
12588 afterLocationChange(oldUrl, oldState);
12591 if (!$rootScope.$$phase) $rootScope.$digest();
12595 $rootScope.$watch(function $locationWatch() {
12596 var oldUrl = trimEmptyHash($browser.url());
12597 var newUrl = trimEmptyHash($location.absUrl());
12598 var oldState = $browser.state();
12599 var currentReplace = $location.$$replace;
12600 var urlOrStateChanged = oldUrl !== newUrl ||
12601 ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
12603 if (initializing || urlOrStateChanged) {
12604 initializing = false;
12606 $rootScope.$evalAsync(function() {
12607 var newUrl = $location.absUrl();
12608 var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
12609 $location.$$state, oldState).defaultPrevented;
12611 // if the location was changed by a `$locationChangeStart` handler then stop
12612 // processing this location change
12613 if ($location.absUrl() !== newUrl) return;
12615 if (defaultPrevented) {
12616 $location.$$parse(oldUrl);
12617 $location.$$state = oldState;
12619 if (urlOrStateChanged) {
12620 setBrowserUrlWithFallback(newUrl, currentReplace,
12621 oldState === $location.$$state ? null : $location.$$state);
12623 afterLocationChange(oldUrl, oldState);
12628 $location.$$replace = false;
12630 // we don't need to return anything because $evalAsync will make the digest loop dirty when
12631 // there is a change
12636 function afterLocationChange(oldUrl, oldState) {
12637 $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
12638 $location.$$state, oldState);
12646 * @requires $window
12649 * Simple service for logging. Default implementation safely writes the message
12650 * into the browser's console (if present).
12652 * The main purpose of this service is to simplify debugging and troubleshooting.
12654 * The default is to log `debug` messages. You can use
12655 * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
12658 <example module="logExample">
12659 <file name="script.js">
12660 angular.module('logExample', [])
12661 .controller('LogController', ['$scope', '$log', function($scope, $log) {
12662 $scope.$log = $log;
12663 $scope.message = 'Hello World!';
12666 <file name="index.html">
12667 <div ng-controller="LogController">
12668 <p>Reload this page with open console, enter text and hit the log button...</p>
12670 <input type="text" ng-model="message" /></label>
12671 <button ng-click="$log.log(message)">log</button>
12672 <button ng-click="$log.warn(message)">warn</button>
12673 <button ng-click="$log.info(message)">info</button>
12674 <button ng-click="$log.error(message)">error</button>
12675 <button ng-click="$log.debug(message)">debug</button>
12683 * @name $logProvider
12685 * Use the `$logProvider` to configure how the application logs messages
12687 function $LogProvider() {
12693 * @name $logProvider#debugEnabled
12695 * @param {boolean=} flag enable or disable debug level messages
12696 * @returns {*} current value if used as getter or itself (chaining) if used as setter
12698 this.debugEnabled = function(flag) {
12699 if (isDefined(flag)) {
12707 this.$get = ['$window', function($window) {
12714 * Write a log message
12716 log: consoleLog('log'),
12723 * Write an information message
12725 info: consoleLog('info'),
12732 * Write a warning message
12734 warn: consoleLog('warn'),
12741 * Write an error message
12743 error: consoleLog('error'),
12750 * Write a debug message
12752 debug: (function() {
12753 var fn = consoleLog('debug');
12755 return function() {
12757 fn.apply(self, arguments);
12763 function formatError(arg) {
12764 if (arg instanceof Error) {
12766 arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
12767 ? 'Error: ' + arg.message + '\n' + arg.stack
12769 } else if (arg.sourceURL) {
12770 arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
12776 function consoleLog(type) {
12777 var console = $window.console || {},
12778 logFn = console[type] || console.log || noop,
12781 // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
12782 // The reason behind this is that console.log has type "object" in IE8...
12784 hasApply = !!logFn.apply;
12788 return function() {
12790 forEach(arguments, function(arg) {
12791 args.push(formatError(arg));
12793 return logFn.apply(console, args);
12797 // we are IE which either doesn't have window.console => this is noop and we do nothing,
12798 // or we are IE where console.log doesn't have apply so we log at least first 2 args
12799 return function(arg1, arg2) {
12800 logFn(arg1, arg2 == null ? '' : arg2);
12806 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
12807 * Any commits to this file should be reviewed with security in mind. *
12808 * Changes to this file can potentially create security vulnerabilities. *
12809 * An approval from 2 Core members with history of modifying *
12810 * this file is required. *
12812 * Does the change somehow allow for arbitrary javascript to be executed? *
12813 * Or allows for someone to change the prototype of built-in objects? *
12814 * Or gives undesired access to variables likes document or window? *
12815 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
12817 var $parseMinErr = minErr('$parse');
12819 // Sandboxing Angular Expressions
12820 // ------------------------------
12821 // Angular expressions are generally considered safe because these expressions only have direct
12822 // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
12823 // obtaining a reference to native JS functions such as the Function constructor.
12825 // As an example, consider the following Angular expression:
12827 // {}.toString.constructor('alert("evil JS code")')
12829 // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
12830 // against the expression language, but not to prevent exploits that were enabled by exposing
12831 // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
12832 // practice and therefore we are not even trying to protect against interaction with an object
12833 // explicitly exposed in this way.
12835 // In general, it is not possible to access a Window object from an angular expression unless a
12836 // window or some DOM object that has a reference to window is published onto a Scope.
12837 // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
12840 // See https://docs.angularjs.org/guide/security
12843 function ensureSafeMemberName(name, fullExpression) {
12844 if (name === "__defineGetter__" || name === "__defineSetter__"
12845 || name === "__lookupGetter__" || name === "__lookupSetter__"
12846 || name === "__proto__") {
12847 throw $parseMinErr('isecfld',
12848 'Attempting to access a disallowed field in Angular expressions! '
12849 + 'Expression: {0}', fullExpression);
12854 function getStringValue(name, fullExpression) {
12855 // From the JavaScript docs:
12856 // Property names must be strings. This means that non-string objects cannot be used
12857 // as keys in an object. Any non-string object, including a number, is typecasted
12858 // into a string via the toString method.
12860 // So, to ensure that we are checking the same `name` that JavaScript would use,
12861 // we cast it to a string, if possible.
12862 // Doing `name + ''` can cause a repl error if the result to `toString` is not a string,
12863 // this is, this will handle objects that misbehave.
12865 if (!isString(name)) {
12866 throw $parseMinErr('iseccst',
12867 'Cannot convert object to primitive value! '
12868 + 'Expression: {0}', fullExpression);
12873 function ensureSafeObject(obj, fullExpression) {
12874 // nifty check if obj is Function that is fast and works across iframes and other contexts
12876 if (obj.constructor === obj) {
12877 throw $parseMinErr('isecfn',
12878 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
12880 } else if (// isWindow(obj)
12881 obj.window === obj) {
12882 throw $parseMinErr('isecwindow',
12883 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
12885 } else if (// isElement(obj)
12886 obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
12887 throw $parseMinErr('isecdom',
12888 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
12890 } else if (// block Object so that we can't get hold of dangerous Object.* methods
12892 throw $parseMinErr('isecobj',
12893 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
12900 var CALL = Function.prototype.call;
12901 var APPLY = Function.prototype.apply;
12902 var BIND = Function.prototype.bind;
12904 function ensureSafeFunction(obj, fullExpression) {
12906 if (obj.constructor === obj) {
12907 throw $parseMinErr('isecfn',
12908 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
12910 } else if (obj === CALL || obj === APPLY || obj === BIND) {
12911 throw $parseMinErr('isecff',
12912 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
12918 function ensureSafeAssignContext(obj, fullExpression) {
12920 if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
12921 obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
12922 throw $parseMinErr('isecaf',
12923 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
12928 var OPERATORS = createMap();
12929 forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
12930 var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
12933 /////////////////////////////////////////
12939 var Lexer = function(options) {
12940 this.options = options;
12943 Lexer.prototype = {
12944 constructor: Lexer,
12946 lex: function(text) {
12951 while (this.index < this.text.length) {
12952 var ch = this.text.charAt(this.index);
12953 if (ch === '"' || ch === "'") {
12954 this.readString(ch);
12955 } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
12957 } else if (this.isIdent(ch)) {
12959 } else if (this.is(ch, '(){}[].,;:?')) {
12960 this.tokens.push({index: this.index, text: ch});
12962 } else if (this.isWhitespace(ch)) {
12965 var ch2 = ch + this.peek();
12966 var ch3 = ch2 + this.peek(2);
12967 var op1 = OPERATORS[ch];
12968 var op2 = OPERATORS[ch2];
12969 var op3 = OPERATORS[ch3];
12970 if (op1 || op2 || op3) {
12971 var token = op3 ? ch3 : (op2 ? ch2 : ch);
12972 this.tokens.push({index: this.index, text: token, operator: true});
12973 this.index += token.length;
12975 this.throwError('Unexpected next character ', this.index, this.index + 1);
12979 return this.tokens;
12982 is: function(ch, chars) {
12983 return chars.indexOf(ch) !== -1;
12986 peek: function(i) {
12988 return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
12991 isNumber: function(ch) {
12992 return ('0' <= ch && ch <= '9') && typeof ch === "string";
12995 isWhitespace: function(ch) {
12996 // IE treats non-breaking space as \u00A0
12997 return (ch === ' ' || ch === '\r' || ch === '\t' ||
12998 ch === '\n' || ch === '\v' || ch === '\u00A0');
13001 isIdent: function(ch) {
13002 return ('a' <= ch && ch <= 'z' ||
13003 'A' <= ch && ch <= 'Z' ||
13004 '_' === ch || ch === '$');
13007 isExpOperator: function(ch) {
13008 return (ch === '-' || ch === '+' || this.isNumber(ch));
13011 throwError: function(error, start, end) {
13012 end = end || this.index;
13013 var colStr = (isDefined(start)
13014 ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
13016 throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
13017 error, colStr, this.text);
13020 readNumber: function() {
13022 var start = this.index;
13023 while (this.index < this.text.length) {
13024 var ch = lowercase(this.text.charAt(this.index));
13025 if (ch == '.' || this.isNumber(ch)) {
13028 var peekCh = this.peek();
13029 if (ch == 'e' && this.isExpOperator(peekCh)) {
13031 } else if (this.isExpOperator(ch) &&
13032 peekCh && this.isNumber(peekCh) &&
13033 number.charAt(number.length - 1) == 'e') {
13035 } else if (this.isExpOperator(ch) &&
13036 (!peekCh || !this.isNumber(peekCh)) &&
13037 number.charAt(number.length - 1) == 'e') {
13038 this.throwError('Invalid exponent');
13049 value: Number(number)
13053 readIdent: function() {
13054 var start = this.index;
13055 while (this.index < this.text.length) {
13056 var ch = this.text.charAt(this.index);
13057 if (!(this.isIdent(ch) || this.isNumber(ch))) {
13064 text: this.text.slice(start, this.index),
13069 readString: function(quote) {
13070 var start = this.index;
13073 var rawString = quote;
13074 var escape = false;
13075 while (this.index < this.text.length) {
13076 var ch = this.text.charAt(this.index);
13080 var hex = this.text.substring(this.index + 1, this.index + 5);
13081 if (!hex.match(/[\da-f]{4}/i)) {
13082 this.throwError('Invalid unicode escape [\\u' + hex + ']');
13085 string += String.fromCharCode(parseInt(hex, 16));
13087 var rep = ESCAPE[ch];
13088 string = string + (rep || ch);
13091 } else if (ch === '\\') {
13093 } else if (ch === quote) {
13107 this.throwError('Unterminated quote', start);
13111 var AST = function(lexer, options) {
13112 this.lexer = lexer;
13113 this.options = options;
13116 AST.Program = 'Program';
13117 AST.ExpressionStatement = 'ExpressionStatement';
13118 AST.AssignmentExpression = 'AssignmentExpression';
13119 AST.ConditionalExpression = 'ConditionalExpression';
13120 AST.LogicalExpression = 'LogicalExpression';
13121 AST.BinaryExpression = 'BinaryExpression';
13122 AST.UnaryExpression = 'UnaryExpression';
13123 AST.CallExpression = 'CallExpression';
13124 AST.MemberExpression = 'MemberExpression';
13125 AST.Identifier = 'Identifier';
13126 AST.Literal = 'Literal';
13127 AST.ArrayExpression = 'ArrayExpression';
13128 AST.Property = 'Property';
13129 AST.ObjectExpression = 'ObjectExpression';
13130 AST.ThisExpression = 'ThisExpression';
13132 // Internal use only
13133 AST.NGValueParameter = 'NGValueParameter';
13136 ast: function(text) {
13138 this.tokens = this.lexer.lex(text);
13140 var value = this.program();
13142 if (this.tokens.length !== 0) {
13143 this.throwError('is an unexpected token', this.tokens[0]);
13149 program: function() {
13152 if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
13153 body.push(this.expressionStatement());
13154 if (!this.expect(';')) {
13155 return { type: AST.Program, body: body};
13160 expressionStatement: function() {
13161 return { type: AST.ExpressionStatement, expression: this.filterChain() };
13164 filterChain: function() {
13165 var left = this.expression();
13167 while ((token = this.expect('|'))) {
13168 left = this.filter(left);
13173 expression: function() {
13174 return this.assignment();
13177 assignment: function() {
13178 var result = this.ternary();
13179 if (this.expect('=')) {
13180 result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
13185 ternary: function() {
13186 var test = this.logicalOR();
13189 if (this.expect('?')) {
13190 alternate = this.expression();
13191 if (this.consume(':')) {
13192 consequent = this.expression();
13193 return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
13199 logicalOR: function() {
13200 var left = this.logicalAND();
13201 while (this.expect('||')) {
13202 left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
13207 logicalAND: function() {
13208 var left = this.equality();
13209 while (this.expect('&&')) {
13210 left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
13215 equality: function() {
13216 var left = this.relational();
13218 while ((token = this.expect('==','!=','===','!=='))) {
13219 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
13224 relational: function() {
13225 var left = this.additive();
13227 while ((token = this.expect('<', '>', '<=', '>='))) {
13228 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
13233 additive: function() {
13234 var left = this.multiplicative();
13236 while ((token = this.expect('+','-'))) {
13237 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
13242 multiplicative: function() {
13243 var left = this.unary();
13245 while ((token = this.expect('*','/','%'))) {
13246 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
13251 unary: function() {
13253 if ((token = this.expect('+', '-', '!'))) {
13254 return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
13256 return this.primary();
13260 primary: function() {
13262 if (this.expect('(')) {
13263 primary = this.filterChain();
13265 } else if (this.expect('[')) {
13266 primary = this.arrayDeclaration();
13267 } else if (this.expect('{')) {
13268 primary = this.object();
13269 } else if (this.constants.hasOwnProperty(this.peek().text)) {
13270 primary = copy(this.constants[this.consume().text]);
13271 } else if (this.peek().identifier) {
13272 primary = this.identifier();
13273 } else if (this.peek().constant) {
13274 primary = this.constant();
13276 this.throwError('not a primary expression', this.peek());
13280 while ((next = this.expect('(', '[', '.'))) {
13281 if (next.text === '(') {
13282 primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
13284 } else if (next.text === '[') {
13285 primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
13287 } else if (next.text === '.') {
13288 primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
13290 this.throwError('IMPOSSIBLE');
13296 filter: function(baseExpression) {
13297 var args = [baseExpression];
13298 var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
13300 while (this.expect(':')) {
13301 args.push(this.expression());
13307 parseArguments: function() {
13309 if (this.peekToken().text !== ')') {
13311 args.push(this.expression());
13312 } while (this.expect(','));
13317 identifier: function() {
13318 var token = this.consume();
13319 if (!token.identifier) {
13320 this.throwError('is not a valid identifier', token);
13322 return { type: AST.Identifier, name: token.text };
13325 constant: function() {
13326 // TODO check that it is a constant
13327 return { type: AST.Literal, value: this.consume().value };
13330 arrayDeclaration: function() {
13332 if (this.peekToken().text !== ']') {
13334 if (this.peek(']')) {
13335 // Support trailing commas per ES5.1.
13338 elements.push(this.expression());
13339 } while (this.expect(','));
13343 return { type: AST.ArrayExpression, elements: elements };
13346 object: function() {
13347 var properties = [], property;
13348 if (this.peekToken().text !== '}') {
13350 if (this.peek('}')) {
13351 // Support trailing commas per ES5.1.
13354 property = {type: AST.Property, kind: 'init'};
13355 if (this.peek().constant) {
13356 property.key = this.constant();
13357 } else if (this.peek().identifier) {
13358 property.key = this.identifier();
13360 this.throwError("invalid key", this.peek());
13363 property.value = this.expression();
13364 properties.push(property);
13365 } while (this.expect(','));
13369 return {type: AST.ObjectExpression, properties: properties };
13372 throwError: function(msg, token) {
13373 throw $parseMinErr('syntax',
13374 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
13375 token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
13378 consume: function(e1) {
13379 if (this.tokens.length === 0) {
13380 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
13383 var token = this.expect(e1);
13385 this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
13390 peekToken: function() {
13391 if (this.tokens.length === 0) {
13392 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
13394 return this.tokens[0];
13397 peek: function(e1, e2, e3, e4) {
13398 return this.peekAhead(0, e1, e2, e3, e4);
13401 peekAhead: function(i, e1, e2, e3, e4) {
13402 if (this.tokens.length > i) {
13403 var token = this.tokens[i];
13404 var t = token.text;
13405 if (t === e1 || t === e2 || t === e3 || t === e4 ||
13406 (!e1 && !e2 && !e3 && !e4)) {
13413 expect: function(e1, e2, e3, e4) {
13414 var token = this.peek(e1, e2, e3, e4);
13416 this.tokens.shift();
13423 /* `undefined` is not a constant, it is an identifier,
13424 * but using it as an identifier is not supported
13427 'true': { type: AST.Literal, value: true },
13428 'false': { type: AST.Literal, value: false },
13429 'null': { type: AST.Literal, value: null },
13430 'undefined': {type: AST.Literal, value: undefined },
13431 'this': {type: AST.ThisExpression }
13435 function ifDefined(v, d) {
13436 return typeof v !== 'undefined' ? v : d;
13439 function plusFn(l, r) {
13440 if (typeof l === 'undefined') return r;
13441 if (typeof r === 'undefined') return l;
13445 function isStateless($filter, filterName) {
13446 var fn = $filter(filterName);
13447 return !fn.$stateful;
13450 function findConstantAndWatchExpressions(ast, $filter) {
13453 switch (ast.type) {
13455 allConstants = true;
13456 forEach(ast.body, function(expr) {
13457 findConstantAndWatchExpressions(expr.expression, $filter);
13458 allConstants = allConstants && expr.expression.constant;
13460 ast.constant = allConstants;
13463 ast.constant = true;
13466 case AST.UnaryExpression:
13467 findConstantAndWatchExpressions(ast.argument, $filter);
13468 ast.constant = ast.argument.constant;
13469 ast.toWatch = ast.argument.toWatch;
13471 case AST.BinaryExpression:
13472 findConstantAndWatchExpressions(ast.left, $filter);
13473 findConstantAndWatchExpressions(ast.right, $filter);
13474 ast.constant = ast.left.constant && ast.right.constant;
13475 ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
13477 case AST.LogicalExpression:
13478 findConstantAndWatchExpressions(ast.left, $filter);
13479 findConstantAndWatchExpressions(ast.right, $filter);
13480 ast.constant = ast.left.constant && ast.right.constant;
13481 ast.toWatch = ast.constant ? [] : [ast];
13483 case AST.ConditionalExpression:
13484 findConstantAndWatchExpressions(ast.test, $filter);
13485 findConstantAndWatchExpressions(ast.alternate, $filter);
13486 findConstantAndWatchExpressions(ast.consequent, $filter);
13487 ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
13488 ast.toWatch = ast.constant ? [] : [ast];
13490 case AST.Identifier:
13491 ast.constant = false;
13492 ast.toWatch = [ast];
13494 case AST.MemberExpression:
13495 findConstantAndWatchExpressions(ast.object, $filter);
13496 if (ast.computed) {
13497 findConstantAndWatchExpressions(ast.property, $filter);
13499 ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
13500 ast.toWatch = [ast];
13502 case AST.CallExpression:
13503 allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
13505 forEach(ast.arguments, function(expr) {
13506 findConstantAndWatchExpressions(expr, $filter);
13507 allConstants = allConstants && expr.constant;
13508 if (!expr.constant) {
13509 argsToWatch.push.apply(argsToWatch, expr.toWatch);
13512 ast.constant = allConstants;
13513 ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
13515 case AST.AssignmentExpression:
13516 findConstantAndWatchExpressions(ast.left, $filter);
13517 findConstantAndWatchExpressions(ast.right, $filter);
13518 ast.constant = ast.left.constant && ast.right.constant;
13519 ast.toWatch = [ast];
13521 case AST.ArrayExpression:
13522 allConstants = true;
13524 forEach(ast.elements, function(expr) {
13525 findConstantAndWatchExpressions(expr, $filter);
13526 allConstants = allConstants && expr.constant;
13527 if (!expr.constant) {
13528 argsToWatch.push.apply(argsToWatch, expr.toWatch);
13531 ast.constant = allConstants;
13532 ast.toWatch = argsToWatch;
13534 case AST.ObjectExpression:
13535 allConstants = true;
13537 forEach(ast.properties, function(property) {
13538 findConstantAndWatchExpressions(property.value, $filter);
13539 allConstants = allConstants && property.value.constant;
13540 if (!property.value.constant) {
13541 argsToWatch.push.apply(argsToWatch, property.value.toWatch);
13544 ast.constant = allConstants;
13545 ast.toWatch = argsToWatch;
13547 case AST.ThisExpression:
13548 ast.constant = false;
13554 function getInputs(body) {
13555 if (body.length != 1) return;
13556 var lastExpression = body[0].expression;
13557 var candidate = lastExpression.toWatch;
13558 if (candidate.length !== 1) return candidate;
13559 return candidate[0] !== lastExpression ? candidate : undefined;
13562 function isAssignable(ast) {
13563 return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
13566 function assignableAST(ast) {
13567 if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
13568 return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
13572 function isLiteral(ast) {
13573 return ast.body.length === 0 ||
13574 ast.body.length === 1 && (
13575 ast.body[0].expression.type === AST.Literal ||
13576 ast.body[0].expression.type === AST.ArrayExpression ||
13577 ast.body[0].expression.type === AST.ObjectExpression);
13580 function isConstant(ast) {
13581 return ast.constant;
13584 function ASTCompiler(astBuilder, $filter) {
13585 this.astBuilder = astBuilder;
13586 this.$filter = $filter;
13589 ASTCompiler.prototype = {
13590 compile: function(expression, expensiveChecks) {
13592 var ast = this.astBuilder.ast(expression);
13596 expensiveChecks: expensiveChecks,
13597 fn: {vars: [], body: [], own: {}},
13598 assign: {vars: [], body: [], own: {}},
13601 findConstantAndWatchExpressions(ast, self.$filter);
13604 this.stage = 'assign';
13605 if ((assignable = assignableAST(ast))) {
13606 this.state.computing = 'assign';
13607 var result = this.nextId();
13608 this.recurse(assignable, result);
13609 this.return_(result);
13610 extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
13612 var toWatch = getInputs(ast.body);
13613 self.stage = 'inputs';
13614 forEach(toWatch, function(watch, key) {
13615 var fnKey = 'fn' + key;
13616 self.state[fnKey] = {vars: [], body: [], own: {}};
13617 self.state.computing = fnKey;
13618 var intoId = self.nextId();
13619 self.recurse(watch, intoId);
13620 self.return_(intoId);
13621 self.state.inputs.push(fnKey);
13622 watch.watchId = key;
13624 this.state.computing = 'fn';
13625 this.stage = 'main';
13628 // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
13629 // This is a workaround for this until we do a better job at only removing the prefix only when we should.
13630 '"' + this.USE + ' ' + this.STRICT + '";\n' +
13631 this.filterPrefix() +
13632 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
13638 var fn = (new Function('$filter',
13639 'ensureSafeMemberName',
13640 'ensureSafeObject',
13641 'ensureSafeFunction',
13643 'ensureSafeAssignContext',
13649 ensureSafeMemberName,
13651 ensureSafeFunction,
13653 ensureSafeAssignContext,
13658 this.state = this.stage = undefined;
13659 fn.literal = isLiteral(ast);
13660 fn.constant = isConstant(ast);
13668 watchFns: function() {
13670 var fns = this.state.inputs;
13672 forEach(fns, function(name) {
13673 result.push('var ' + name + '=' + self.generateFunction(name, 's'));
13676 result.push('fn.inputs=[' + fns.join(',') + '];');
13678 return result.join('');
13681 generateFunction: function(name, params) {
13682 return 'function(' + params + '){' +
13683 this.varsPrefix(name) +
13688 filterPrefix: function() {
13691 forEach(this.state.filters, function(id, filter) {
13692 parts.push(id + '=$filter(' + self.escape(filter) + ')');
13694 if (parts.length) return 'var ' + parts.join(',') + ';';
13698 varsPrefix: function(section) {
13699 return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
13702 body: function(section) {
13703 return this.state[section].body.join('');
13706 recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
13707 var left, right, self = this, args, expression;
13708 recursionFn = recursionFn || noop;
13709 if (!skipWatchIdCheck && isDefined(ast.watchId)) {
13710 intoId = intoId || this.nextId();
13712 this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
13713 this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
13717 switch (ast.type) {
13719 forEach(ast.body, function(expression, pos) {
13720 self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
13721 if (pos !== ast.body.length - 1) {
13722 self.current().body.push(right, ';');
13724 self.return_(right);
13729 expression = this.escape(ast.value);
13730 this.assign(intoId, expression);
13731 recursionFn(expression);
13733 case AST.UnaryExpression:
13734 this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
13735 expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
13736 this.assign(intoId, expression);
13737 recursionFn(expression);
13739 case AST.BinaryExpression:
13740 this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
13741 this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
13742 if (ast.operator === '+') {
13743 expression = this.plus(left, right);
13744 } else if (ast.operator === '-') {
13745 expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
13747 expression = '(' + left + ')' + ast.operator + '(' + right + ')';
13749 this.assign(intoId, expression);
13750 recursionFn(expression);
13752 case AST.LogicalExpression:
13753 intoId = intoId || this.nextId();
13754 self.recurse(ast.left, intoId);
13755 self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
13756 recursionFn(intoId);
13758 case AST.ConditionalExpression:
13759 intoId = intoId || this.nextId();
13760 self.recurse(ast.test, intoId);
13761 self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
13762 recursionFn(intoId);
13764 case AST.Identifier:
13765 intoId = intoId || this.nextId();
13767 nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
13768 nameId.computed = false;
13769 nameId.name = ast.name;
13771 ensureSafeMemberName(ast.name);
13772 self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
13774 self.if_(self.stage === 'inputs' || 's', function() {
13775 if (create && create !== 1) {
13777 self.not(self.nonComputedMember('s', ast.name)),
13778 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
13780 self.assign(intoId, self.nonComputedMember('s', ast.name));
13782 }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
13784 if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
13785 self.addEnsureSafeObject(intoId);
13787 recursionFn(intoId);
13789 case AST.MemberExpression:
13790 left = nameId && (nameId.context = this.nextId()) || this.nextId();
13791 intoId = intoId || this.nextId();
13792 self.recurse(ast.object, left, undefined, function() {
13793 self.if_(self.notNull(left), function() {
13794 if (ast.computed) {
13795 right = self.nextId();
13796 self.recurse(ast.property, right);
13797 self.getStringValue(right);
13798 self.addEnsureSafeMemberName(right);
13799 if (create && create !== 1) {
13800 self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
13802 expression = self.ensureSafeObject(self.computedMember(left, right));
13803 self.assign(intoId, expression);
13805 nameId.computed = true;
13806 nameId.name = right;
13809 ensureSafeMemberName(ast.property.name);
13810 if (create && create !== 1) {
13811 self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
13813 expression = self.nonComputedMember(left, ast.property.name);
13814 if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
13815 expression = self.ensureSafeObject(expression);
13817 self.assign(intoId, expression);
13819 nameId.computed = false;
13820 nameId.name = ast.property.name;
13824 self.assign(intoId, 'undefined');
13826 recursionFn(intoId);
13829 case AST.CallExpression:
13830 intoId = intoId || this.nextId();
13832 right = self.filter(ast.callee.name);
13834 forEach(ast.arguments, function(expr) {
13835 var argument = self.nextId();
13836 self.recurse(expr, argument);
13837 args.push(argument);
13839 expression = right + '(' + args.join(',') + ')';
13840 self.assign(intoId, expression);
13841 recursionFn(intoId);
13843 right = self.nextId();
13846 self.recurse(ast.callee, right, left, function() {
13847 self.if_(self.notNull(right), function() {
13848 self.addEnsureSafeFunction(right);
13849 forEach(ast.arguments, function(expr) {
13850 self.recurse(expr, self.nextId(), undefined, function(argument) {
13851 args.push(self.ensureSafeObject(argument));
13855 if (!self.state.expensiveChecks) {
13856 self.addEnsureSafeObject(left.context);
13858 expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
13860 expression = right + '(' + args.join(',') + ')';
13862 expression = self.ensureSafeObject(expression);
13863 self.assign(intoId, expression);
13865 self.assign(intoId, 'undefined');
13867 recursionFn(intoId);
13871 case AST.AssignmentExpression:
13872 right = this.nextId();
13874 if (!isAssignable(ast.left)) {
13875 throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
13877 this.recurse(ast.left, undefined, left, function() {
13878 self.if_(self.notNull(left.context), function() {
13879 self.recurse(ast.right, right);
13880 self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
13881 self.addEnsureSafeAssignContext(left.context);
13882 expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
13883 self.assign(intoId, expression);
13884 recursionFn(intoId || expression);
13888 case AST.ArrayExpression:
13890 forEach(ast.elements, function(expr) {
13891 self.recurse(expr, self.nextId(), undefined, function(argument) {
13892 args.push(argument);
13895 expression = '[' + args.join(',') + ']';
13896 this.assign(intoId, expression);
13897 recursionFn(expression);
13899 case AST.ObjectExpression:
13901 forEach(ast.properties, function(property) {
13902 self.recurse(property.value, self.nextId(), undefined, function(expr) {
13903 args.push(self.escape(
13904 property.key.type === AST.Identifier ? property.key.name :
13905 ('' + property.key.value)) +
13909 expression = '{' + args.join(',') + '}';
13910 this.assign(intoId, expression);
13911 recursionFn(expression);
13913 case AST.ThisExpression:
13914 this.assign(intoId, 's');
13917 case AST.NGValueParameter:
13918 this.assign(intoId, 'v');
13924 getHasOwnProperty: function(element, property) {
13925 var key = element + '.' + property;
13926 var own = this.current().own;
13927 if (!own.hasOwnProperty(key)) {
13928 own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
13933 assign: function(id, value) {
13935 this.current().body.push(id, '=', value, ';');
13939 filter: function(filterName) {
13940 if (!this.state.filters.hasOwnProperty(filterName)) {
13941 this.state.filters[filterName] = this.nextId(true);
13943 return this.state.filters[filterName];
13946 ifDefined: function(id, defaultValue) {
13947 return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
13950 plus: function(left, right) {
13951 return 'plus(' + left + ',' + right + ')';
13954 return_: function(id) {
13955 this.current().body.push('return ', id, ';');
13958 if_: function(test, alternate, consequent) {
13959 if (test === true) {
13962 var body = this.current().body;
13963 body.push('if(', test, '){');
13967 body.push('else{');
13974 not: function(expression) {
13975 return '!(' + expression + ')';
13978 notNull: function(expression) {
13979 return expression + '!=null';
13982 nonComputedMember: function(left, right) {
13983 return left + '.' + right;
13986 computedMember: function(left, right) {
13987 return left + '[' + right + ']';
13990 member: function(left, right, computed) {
13991 if (computed) return this.computedMember(left, right);
13992 return this.nonComputedMember(left, right);
13995 addEnsureSafeObject: function(item) {
13996 this.current().body.push(this.ensureSafeObject(item), ';');
13999 addEnsureSafeMemberName: function(item) {
14000 this.current().body.push(this.ensureSafeMemberName(item), ';');
14003 addEnsureSafeFunction: function(item) {
14004 this.current().body.push(this.ensureSafeFunction(item), ';');
14007 addEnsureSafeAssignContext: function(item) {
14008 this.current().body.push(this.ensureSafeAssignContext(item), ';');
14011 ensureSafeObject: function(item) {
14012 return 'ensureSafeObject(' + item + ',text)';
14015 ensureSafeMemberName: function(item) {
14016 return 'ensureSafeMemberName(' + item + ',text)';
14019 ensureSafeFunction: function(item) {
14020 return 'ensureSafeFunction(' + item + ',text)';
14023 getStringValue: function(item) {
14024 this.assign(item, 'getStringValue(' + item + ',text)');
14027 ensureSafeAssignContext: function(item) {
14028 return 'ensureSafeAssignContext(' + item + ',text)';
14031 lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
14033 return function() {
14034 self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
14038 lazyAssign: function(id, value) {
14040 return function() {
14041 self.assign(id, value);
14045 stringEscapeRegex: /[^ a-zA-Z0-9]/g,
14047 stringEscapeFn: function(c) {
14048 return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
14051 escape: function(value) {
14052 if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
14053 if (isNumber(value)) return value.toString();
14054 if (value === true) return 'true';
14055 if (value === false) return 'false';
14056 if (value === null) return 'null';
14057 if (typeof value === 'undefined') return 'undefined';
14059 throw $parseMinErr('esc', 'IMPOSSIBLE');
14062 nextId: function(skip, init) {
14063 var id = 'v' + (this.state.nextId++);
14065 this.current().vars.push(id + (init ? '=' + init : ''));
14070 current: function() {
14071 return this.state[this.state.computing];
14076 function ASTInterpreter(astBuilder, $filter) {
14077 this.astBuilder = astBuilder;
14078 this.$filter = $filter;
14081 ASTInterpreter.prototype = {
14082 compile: function(expression, expensiveChecks) {
14084 var ast = this.astBuilder.ast(expression);
14085 this.expression = expression;
14086 this.expensiveChecks = expensiveChecks;
14087 findConstantAndWatchExpressions(ast, self.$filter);
14090 if ((assignable = assignableAST(ast))) {
14091 assign = this.recurse(assignable);
14093 var toWatch = getInputs(ast.body);
14097 forEach(toWatch, function(watch, key) {
14098 var input = self.recurse(watch);
14099 watch.input = input;
14100 inputs.push(input);
14101 watch.watchId = key;
14104 var expressions = [];
14105 forEach(ast.body, function(expression) {
14106 expressions.push(self.recurse(expression.expression));
14108 var fn = ast.body.length === 0 ? function() {} :
14109 ast.body.length === 1 ? expressions[0] :
14110 function(scope, locals) {
14112 forEach(expressions, function(exp) {
14113 lastValue = exp(scope, locals);
14118 fn.assign = function(scope, value, locals) {
14119 return assign(scope, locals, value);
14123 fn.inputs = inputs;
14125 fn.literal = isLiteral(ast);
14126 fn.constant = isConstant(ast);
14130 recurse: function(ast, context, create) {
14131 var left, right, self = this, args, expression;
14133 return this.inputs(ast.input, ast.watchId);
14135 switch (ast.type) {
14137 return this.value(ast.value, context);
14138 case AST.UnaryExpression:
14139 right = this.recurse(ast.argument);
14140 return this['unary' + ast.operator](right, context);
14141 case AST.BinaryExpression:
14142 left = this.recurse(ast.left);
14143 right = this.recurse(ast.right);
14144 return this['binary' + ast.operator](left, right, context);
14145 case AST.LogicalExpression:
14146 left = this.recurse(ast.left);
14147 right = this.recurse(ast.right);
14148 return this['binary' + ast.operator](left, right, context);
14149 case AST.ConditionalExpression:
14150 return this['ternary?:'](
14151 this.recurse(ast.test),
14152 this.recurse(ast.alternate),
14153 this.recurse(ast.consequent),
14156 case AST.Identifier:
14157 ensureSafeMemberName(ast.name, self.expression);
14158 return self.identifier(ast.name,
14159 self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
14160 context, create, self.expression);
14161 case AST.MemberExpression:
14162 left = this.recurse(ast.object, false, !!create);
14163 if (!ast.computed) {
14164 ensureSafeMemberName(ast.property.name, self.expression);
14165 right = ast.property.name;
14167 if (ast.computed) right = this.recurse(ast.property);
14168 return ast.computed ?
14169 this.computedMember(left, right, context, create, self.expression) :
14170 this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
14171 case AST.CallExpression:
14173 forEach(ast.arguments, function(expr) {
14174 args.push(self.recurse(expr));
14176 if (ast.filter) right = this.$filter(ast.callee.name);
14177 if (!ast.filter) right = this.recurse(ast.callee, true);
14178 return ast.filter ?
14179 function(scope, locals, assign, inputs) {
14181 for (var i = 0; i < args.length; ++i) {
14182 values.push(args[i](scope, locals, assign, inputs));
14184 var value = right.apply(undefined, values, inputs);
14185 return context ? {context: undefined, name: undefined, value: value} : value;
14187 function(scope, locals, assign, inputs) {
14188 var rhs = right(scope, locals, assign, inputs);
14190 if (rhs.value != null) {
14191 ensureSafeObject(rhs.context, self.expression);
14192 ensureSafeFunction(rhs.value, self.expression);
14194 for (var i = 0; i < args.length; ++i) {
14195 values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
14197 value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
14199 return context ? {value: value} : value;
14201 case AST.AssignmentExpression:
14202 left = this.recurse(ast.left, true, 1);
14203 right = this.recurse(ast.right);
14204 return function(scope, locals, assign, inputs) {
14205 var lhs = left(scope, locals, assign, inputs);
14206 var rhs = right(scope, locals, assign, inputs);
14207 ensureSafeObject(lhs.value, self.expression);
14208 ensureSafeAssignContext(lhs.context);
14209 lhs.context[lhs.name] = rhs;
14210 return context ? {value: rhs} : rhs;
14212 case AST.ArrayExpression:
14214 forEach(ast.elements, function(expr) {
14215 args.push(self.recurse(expr));
14217 return function(scope, locals, assign, inputs) {
14219 for (var i = 0; i < args.length; ++i) {
14220 value.push(args[i](scope, locals, assign, inputs));
14222 return context ? {value: value} : value;
14224 case AST.ObjectExpression:
14226 forEach(ast.properties, function(property) {
14227 args.push({key: property.key.type === AST.Identifier ?
14228 property.key.name :
14229 ('' + property.key.value),
14230 value: self.recurse(property.value)
14233 return function(scope, locals, assign, inputs) {
14235 for (var i = 0; i < args.length; ++i) {
14236 value[args[i].key] = args[i].value(scope, locals, assign, inputs);
14238 return context ? {value: value} : value;
14240 case AST.ThisExpression:
14241 return function(scope) {
14242 return context ? {value: scope} : scope;
14244 case AST.NGValueParameter:
14245 return function(scope, locals, assign, inputs) {
14246 return context ? {value: assign} : assign;
14251 'unary+': function(argument, context) {
14252 return function(scope, locals, assign, inputs) {
14253 var arg = argument(scope, locals, assign, inputs);
14254 if (isDefined(arg)) {
14259 return context ? {value: arg} : arg;
14262 'unary-': function(argument, context) {
14263 return function(scope, locals, assign, inputs) {
14264 var arg = argument(scope, locals, assign, inputs);
14265 if (isDefined(arg)) {
14270 return context ? {value: arg} : arg;
14273 'unary!': function(argument, context) {
14274 return function(scope, locals, assign, inputs) {
14275 var arg = !argument(scope, locals, assign, inputs);
14276 return context ? {value: arg} : arg;
14279 'binary+': function(left, right, context) {
14280 return function(scope, locals, assign, inputs) {
14281 var lhs = left(scope, locals, assign, inputs);
14282 var rhs = right(scope, locals, assign, inputs);
14283 var arg = plusFn(lhs, rhs);
14284 return context ? {value: arg} : arg;
14287 'binary-': function(left, right, context) {
14288 return function(scope, locals, assign, inputs) {
14289 var lhs = left(scope, locals, assign, inputs);
14290 var rhs = right(scope, locals, assign, inputs);
14291 var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
14292 return context ? {value: arg} : arg;
14295 'binary*': function(left, right, context) {
14296 return function(scope, locals, assign, inputs) {
14297 var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
14298 return context ? {value: arg} : arg;
14301 'binary/': function(left, right, context) {
14302 return function(scope, locals, assign, inputs) {
14303 var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
14304 return context ? {value: arg} : arg;
14307 'binary%': function(left, right, context) {
14308 return function(scope, locals, assign, inputs) {
14309 var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
14310 return context ? {value: arg} : arg;
14313 'binary===': function(left, right, context) {
14314 return function(scope, locals, assign, inputs) {
14315 var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
14316 return context ? {value: arg} : arg;
14319 'binary!==': function(left, right, context) {
14320 return function(scope, locals, assign, inputs) {
14321 var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
14322 return context ? {value: arg} : arg;
14325 'binary==': function(left, right, context) {
14326 return function(scope, locals, assign, inputs) {
14327 var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
14328 return context ? {value: arg} : arg;
14331 'binary!=': function(left, right, context) {
14332 return function(scope, locals, assign, inputs) {
14333 var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
14334 return context ? {value: arg} : arg;
14337 'binary<': function(left, right, context) {
14338 return function(scope, locals, assign, inputs) {
14339 var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
14340 return context ? {value: arg} : arg;
14343 'binary>': function(left, right, context) {
14344 return function(scope, locals, assign, inputs) {
14345 var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
14346 return context ? {value: arg} : arg;
14349 'binary<=': function(left, right, context) {
14350 return function(scope, locals, assign, inputs) {
14351 var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
14352 return context ? {value: arg} : arg;
14355 'binary>=': function(left, right, context) {
14356 return function(scope, locals, assign, inputs) {
14357 var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
14358 return context ? {value: arg} : arg;
14361 'binary&&': function(left, right, context) {
14362 return function(scope, locals, assign, inputs) {
14363 var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
14364 return context ? {value: arg} : arg;
14367 'binary||': function(left, right, context) {
14368 return function(scope, locals, assign, inputs) {
14369 var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
14370 return context ? {value: arg} : arg;
14373 'ternary?:': function(test, alternate, consequent, context) {
14374 return function(scope, locals, assign, inputs) {
14375 var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
14376 return context ? {value: arg} : arg;
14379 value: function(value, context) {
14380 return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
14382 identifier: function(name, expensiveChecks, context, create, expression) {
14383 return function(scope, locals, assign, inputs) {
14384 var base = locals && (name in locals) ? locals : scope;
14385 if (create && create !== 1 && base && !(base[name])) {
14388 var value = base ? base[name] : undefined;
14389 if (expensiveChecks) {
14390 ensureSafeObject(value, expression);
14393 return {context: base, name: name, value: value};
14399 computedMember: function(left, right, context, create, expression) {
14400 return function(scope, locals, assign, inputs) {
14401 var lhs = left(scope, locals, assign, inputs);
14405 rhs = right(scope, locals, assign, inputs);
14406 rhs = getStringValue(rhs);
14407 ensureSafeMemberName(rhs, expression);
14408 if (create && create !== 1 && lhs && !(lhs[rhs])) {
14412 ensureSafeObject(value, expression);
14415 return {context: lhs, name: rhs, value: value};
14421 nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
14422 return function(scope, locals, assign, inputs) {
14423 var lhs = left(scope, locals, assign, inputs);
14424 if (create && create !== 1 && lhs && !(lhs[right])) {
14427 var value = lhs != null ? lhs[right] : undefined;
14428 if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
14429 ensureSafeObject(value, expression);
14432 return {context: lhs, name: right, value: value};
14438 inputs: function(input, watchId) {
14439 return function(scope, value, locals, inputs) {
14440 if (inputs) return inputs[watchId];
14441 return input(scope, value, locals);
14449 var Parser = function(lexer, $filter, options) {
14450 this.lexer = lexer;
14451 this.$filter = $filter;
14452 this.options = options;
14453 this.ast = new AST(this.lexer);
14454 this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
14455 new ASTCompiler(this.ast, $filter);
14458 Parser.prototype = {
14459 constructor: Parser,
14461 parse: function(text) {
14462 return this.astCompiler.compile(text, this.options.expensiveChecks);
14466 var getterFnCacheDefault = createMap();
14467 var getterFnCacheExpensive = createMap();
14469 function isPossiblyDangerousMemberName(name) {
14470 return name == 'constructor';
14473 var objectValueOf = Object.prototype.valueOf;
14475 function getValueOf(value) {
14476 return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
14479 ///////////////////////////////////
14488 * Converts Angular {@link guide/expression expression} into a function.
14491 * var getter = $parse('user.name');
14492 * var setter = getter.assign;
14493 * var context = {user:{name:'angular'}};
14494 * var locals = {user:{name:'local'}};
14496 * expect(getter(context)).toEqual('angular');
14497 * setter(context, 'newValue');
14498 * expect(context.user.name).toEqual('newValue');
14499 * expect(getter(context, locals)).toEqual('local');
14503 * @param {string} expression String expression to compile.
14504 * @returns {function(context, locals)} a function which represents the compiled expression:
14506 * * `context` – `{object}` – an object against which any expressions embedded in the strings
14507 * are evaluated against (typically a scope object).
14508 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
14511 * The returned function also has the following properties:
14512 * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
14514 * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
14515 * constant literals.
14516 * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
14517 * set to a function to change its value on the given context.
14524 * @name $parseProvider
14527 * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
14530 function $ParseProvider() {
14531 var cacheDefault = createMap();
14532 var cacheExpensive = createMap();
14534 this.$get = ['$filter', function($filter) {
14535 var noUnsafeEval = csp().noUnsafeEval;
14536 var $parseOptions = {
14538 expensiveChecks: false
14540 $parseOptionsExpensive = {
14542 expensiveChecks: true
14545 return function $parse(exp, interceptorFn, expensiveChecks) {
14546 var parsedExpression, oneTime, cacheKey;
14548 switch (typeof exp) {
14553 var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
14554 parsedExpression = cache[cacheKey];
14556 if (!parsedExpression) {
14557 if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
14559 exp = exp.substring(2);
14561 var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
14562 var lexer = new Lexer(parseOptions);
14563 var parser = new Parser(lexer, $filter, parseOptions);
14564 parsedExpression = parser.parse(exp);
14565 if (parsedExpression.constant) {
14566 parsedExpression.$$watchDelegate = constantWatchDelegate;
14567 } else if (oneTime) {
14568 parsedExpression.$$watchDelegate = parsedExpression.literal ?
14569 oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
14570 } else if (parsedExpression.inputs) {
14571 parsedExpression.$$watchDelegate = inputsWatchDelegate;
14573 cache[cacheKey] = parsedExpression;
14575 return addInterceptor(parsedExpression, interceptorFn);
14578 return addInterceptor(exp, interceptorFn);
14585 function expressionInputDirtyCheck(newValue, oldValueOfValue) {
14587 if (newValue == null || oldValueOfValue == null) { // null/undefined
14588 return newValue === oldValueOfValue;
14591 if (typeof newValue === 'object') {
14593 // attempt to convert the value to a primitive type
14594 // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
14595 // be cheaply dirty-checked
14596 newValue = getValueOf(newValue);
14598 if (typeof newValue === 'object') {
14599 // objects/arrays are not supported - deep-watching them would be too expensive
14603 // fall-through to the primitive equality check
14607 return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
14610 function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
14611 var inputExpressions = parsedExpression.inputs;
14614 if (inputExpressions.length === 1) {
14615 var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
14616 inputExpressions = inputExpressions[0];
14617 return scope.$watch(function expressionInputWatch(scope) {
14618 var newInputValue = inputExpressions(scope);
14619 if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
14620 lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
14621 oldInputValueOf = newInputValue && getValueOf(newInputValue);
14624 }, listener, objectEquality, prettyPrintExpression);
14627 var oldInputValueOfValues = [];
14628 var oldInputValues = [];
14629 for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
14630 oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
14631 oldInputValues[i] = null;
14634 return scope.$watch(function expressionInputsWatch(scope) {
14635 var changed = false;
14637 for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
14638 var newInputValue = inputExpressions[i](scope);
14639 if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
14640 oldInputValues[i] = newInputValue;
14641 oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
14646 lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
14650 }, listener, objectEquality, prettyPrintExpression);
14653 function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
14654 var unwatch, lastValue;
14655 return unwatch = scope.$watch(function oneTimeWatch(scope) {
14656 return parsedExpression(scope);
14657 }, function oneTimeListener(value, old, scope) {
14659 if (isFunction(listener)) {
14660 listener.apply(this, arguments);
14662 if (isDefined(value)) {
14663 scope.$$postDigest(function() {
14664 if (isDefined(lastValue)) {
14669 }, objectEquality);
14672 function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
14673 var unwatch, lastValue;
14674 return unwatch = scope.$watch(function oneTimeWatch(scope) {
14675 return parsedExpression(scope);
14676 }, function oneTimeListener(value, old, scope) {
14678 if (isFunction(listener)) {
14679 listener.call(this, value, old, scope);
14681 if (isAllDefined(value)) {
14682 scope.$$postDigest(function() {
14683 if (isAllDefined(lastValue)) unwatch();
14686 }, objectEquality);
14688 function isAllDefined(value) {
14689 var allDefined = true;
14690 forEach(value, function(val) {
14691 if (!isDefined(val)) allDefined = false;
14697 function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
14699 return unwatch = scope.$watch(function constantWatch(scope) {
14701 return parsedExpression(scope);
14702 }, listener, objectEquality);
14705 function addInterceptor(parsedExpression, interceptorFn) {
14706 if (!interceptorFn) return parsedExpression;
14707 var watchDelegate = parsedExpression.$$watchDelegate;
14708 var useInputs = false;
14711 watchDelegate !== oneTimeLiteralWatchDelegate &&
14712 watchDelegate !== oneTimeWatchDelegate;
14714 var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
14715 var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
14716 return interceptorFn(value, scope, locals);
14717 } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
14718 var value = parsedExpression(scope, locals, assign, inputs);
14719 var result = interceptorFn(value, scope, locals);
14720 // we only return the interceptor's result if the
14721 // initial value is defined (for bind-once)
14722 return isDefined(value) ? result : value;
14725 // Propagate $$watchDelegates other then inputsWatchDelegate
14726 if (parsedExpression.$$watchDelegate &&
14727 parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
14728 fn.$$watchDelegate = parsedExpression.$$watchDelegate;
14729 } else if (!interceptorFn.$stateful) {
14730 // If there is an interceptor, but no watchDelegate then treat the interceptor like
14731 // we treat filters - it is assumed to be a pure function unless flagged with $stateful
14732 fn.$$watchDelegate = inputsWatchDelegate;
14733 useInputs = !parsedExpression.inputs;
14734 fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
14745 * @requires $rootScope
14748 * A service that helps you run functions asynchronously, and use their return values (or exceptions)
14749 * when they are done processing.
14751 * This is an implementation of promises/deferred objects inspired by
14752 * [Kris Kowal's Q](https://github.com/kriskowal/q).
14754 * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
14755 * implementations, and the other which resembles ES6 promises to some degree.
14759 * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
14760 * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
14761 * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
14763 * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
14766 * It can be used like so:
14769 * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
14770 * // are available in the current lexical scope (they could have been injected or passed in).
14772 * function asyncGreet(name) {
14773 * // perform some asynchronous operation, resolve or reject the promise when appropriate.
14774 * return $q(function(resolve, reject) {
14775 * setTimeout(function() {
14776 * if (okToGreet(name)) {
14777 * resolve('Hello, ' + name + '!');
14779 * reject('Greeting ' + name + ' is not allowed.');
14785 * var promise = asyncGreet('Robin Hood');
14786 * promise.then(function(greeting) {
14787 * alert('Success: ' + greeting);
14788 * }, function(reason) {
14789 * alert('Failed: ' + reason);
14793 * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
14795 * Note: unlike ES6 behaviour, an exception thrown in the constructor function will NOT implicitly reject the promise.
14797 * However, the more traditional CommonJS-style usage is still available, and documented below.
14799 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
14800 * interface for interacting with an object that represents the result of an action that is
14801 * performed asynchronously, and may or may not be finished at any given point in time.
14803 * From the perspective of dealing with error handling, deferred and promise APIs are to
14804 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
14807 * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
14808 * // are available in the current lexical scope (they could have been injected or passed in).
14810 * function asyncGreet(name) {
14811 * var deferred = $q.defer();
14813 * setTimeout(function() {
14814 * deferred.notify('About to greet ' + name + '.');
14816 * if (okToGreet(name)) {
14817 * deferred.resolve('Hello, ' + name + '!');
14819 * deferred.reject('Greeting ' + name + ' is not allowed.');
14823 * return deferred.promise;
14826 * var promise = asyncGreet('Robin Hood');
14827 * promise.then(function(greeting) {
14828 * alert('Success: ' + greeting);
14829 * }, function(reason) {
14830 * alert('Failed: ' + reason);
14831 * }, function(update) {
14832 * alert('Got notification: ' + update);
14836 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
14837 * comes in the way of guarantees that promise and deferred APIs make, see
14838 * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
14840 * Additionally the promise api allows for composition that is very hard to do with the
14841 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
14842 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
14843 * section on serial or parallel joining of promises.
14845 * # The Deferred API
14847 * A new instance of deferred is constructed by calling `$q.defer()`.
14849 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
14850 * that can be used for signaling the successful or unsuccessful completion, as well as the status
14855 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
14856 * constructed via `$q.reject`, the promise will be rejected instead.
14857 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
14858 * resolving it with a rejection constructed via `$q.reject`.
14859 * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
14860 * multiple times before the promise is either resolved or rejected.
14864 * - promise – `{Promise}` – promise object associated with this deferred.
14867 * # The Promise API
14869 * A new promise instance is created when a deferred instance is created and can be retrieved by
14870 * calling `deferred.promise`.
14872 * The purpose of the promise object is to allow for interested parties to get access to the result
14873 * of the deferred task when it completes.
14877 * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
14878 * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
14879 * as soon as the result is available. The callbacks are called with a single argument: the result
14880 * or rejection reason. Additionally, the notify callback may be called zero or more times to
14881 * provide a progress indication, before the promise is resolved or rejected.
14883 * This method *returns a new promise* which is resolved or rejected via the return value of the
14884 * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
14885 * with the value which is resolved in that promise using
14886 * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
14887 * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
14888 * resolved or rejected from the notifyCallback method.
14890 * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
14892 * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
14893 * but to do so without modifying the final value. This is useful to release resources or do some
14894 * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
14895 * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
14896 * more information.
14898 * # Chaining promises
14900 * Because calling the `then` method of a promise returns a new derived promise, it is easily
14901 * possible to create a chain of promises:
14904 * promiseB = promiseA.then(function(result) {
14905 * return result + 1;
14908 * // promiseB will be resolved immediately after promiseA is resolved and its value
14909 * // will be the result of promiseA incremented by 1
14912 * It is possible to create chains of any length and since a promise can be resolved with another
14913 * promise (which will defer its resolution further), it is possible to pause/defer resolution of
14914 * the promises at any point in the chain. This makes it possible to implement powerful APIs like
14915 * $http's response interceptors.
14918 * # Differences between Kris Kowal's Q and $q
14920 * There are two main differences:
14922 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
14923 * mechanism in angular, which means faster propagation of resolution or rejection into your
14924 * models and avoiding unnecessary browser repaints, which would result in flickering UI.
14925 * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
14926 * all the important functionality needed for common async tasks.
14931 * it('should simulate promise', inject(function($q, $rootScope) {
14932 * var deferred = $q.defer();
14933 * var promise = deferred.promise;
14934 * var resolvedValue;
14936 * promise.then(function(value) { resolvedValue = value; });
14937 * expect(resolvedValue).toBeUndefined();
14939 * // Simulate resolving of promise
14940 * deferred.resolve(123);
14941 * // Note that the 'then' function does not get called synchronously.
14942 * // This is because we want the promise API to always be async, whether or not
14943 * // it got called synchronously or asynchronously.
14944 * expect(resolvedValue).toBeUndefined();
14946 * // Propagate promise resolution to 'then' functions using $apply().
14947 * $rootScope.$apply();
14948 * expect(resolvedValue).toEqual(123);
14952 * @param {function(function, function)} resolver Function which is responsible for resolving or
14953 * rejecting the newly created promise. The first parameter is a function which resolves the
14954 * promise, the second parameter is a function which rejects the promise.
14956 * @returns {Promise} The newly created promise.
14958 function $QProvider() {
14960 this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
14961 return qFactory(function(callback) {
14962 $rootScope.$evalAsync(callback);
14963 }, $exceptionHandler);
14967 function $$QProvider() {
14968 this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
14969 return qFactory(function(callback) {
14970 $browser.defer(callback);
14971 }, $exceptionHandler);
14976 * Constructs a promise manager.
14978 * @param {function(function)} nextTick Function for executing functions in the next turn.
14979 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
14980 * debugging purposes.
14981 * @returns {object} Promise manager.
14983 function qFactory(nextTick, exceptionHandler) {
14984 var $qMinErr = minErr('$q', TypeError);
14988 * @name ng.$q#defer
14992 * Creates a `Deferred` object which represents a task which will finish in the future.
14994 * @returns {Deferred} Returns a new instance of deferred.
14996 var defer = function() {
14997 var d = new Deferred();
14998 //Necessary to support unbound execution :/
14999 d.resolve = simpleBind(d, d.resolve);
15000 d.reject = simpleBind(d, d.reject);
15001 d.notify = simpleBind(d, d.notify);
15005 function Promise() {
15006 this.$$state = { status: 0 };
15009 extend(Promise.prototype, {
15010 then: function(onFulfilled, onRejected, progressBack) {
15011 if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
15014 var result = new Deferred();
15016 this.$$state.pending = this.$$state.pending || [];
15017 this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
15018 if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
15020 return result.promise;
15023 "catch": function(callback) {
15024 return this.then(null, callback);
15027 "finally": function(callback, progressBack) {
15028 return this.then(function(value) {
15029 return handleCallback(value, true, callback);
15030 }, function(error) {
15031 return handleCallback(error, false, callback);
15036 //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
15037 function simpleBind(context, fn) {
15038 return function(value) {
15039 fn.call(context, value);
15043 function processQueue(state) {
15044 var fn, deferred, pending;
15046 pending = state.pending;
15047 state.processScheduled = false;
15048 state.pending = undefined;
15049 for (var i = 0, ii = pending.length; i < ii; ++i) {
15050 deferred = pending[i][0];
15051 fn = pending[i][state.status];
15053 if (isFunction(fn)) {
15054 deferred.resolve(fn(state.value));
15055 } else if (state.status === 1) {
15056 deferred.resolve(state.value);
15058 deferred.reject(state.value);
15061 deferred.reject(e);
15062 exceptionHandler(e);
15067 function scheduleProcessQueue(state) {
15068 if (state.processScheduled || !state.pending) return;
15069 state.processScheduled = true;
15070 nextTick(function() { processQueue(state); });
15073 function Deferred() {
15074 this.promise = new Promise();
15077 extend(Deferred.prototype, {
15078 resolve: function(val) {
15079 if (this.promise.$$state.status) return;
15080 if (val === this.promise) {
15081 this.$$reject($qMinErr(
15083 "Expected promise to be resolved with value other than itself '{0}'",
15086 this.$$resolve(val);
15091 $$resolve: function(val) {
15096 if ((isObject(val) || isFunction(val))) then = val && val.then;
15097 if (isFunction(then)) {
15098 this.promise.$$state.status = -1;
15099 then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
15101 this.promise.$$state.value = val;
15102 this.promise.$$state.status = 1;
15103 scheduleProcessQueue(this.promise.$$state);
15107 exceptionHandler(e);
15110 function resolvePromise(val) {
15113 that.$$resolve(val);
15115 function rejectPromise(val) {
15118 that.$$reject(val);
15122 reject: function(reason) {
15123 if (this.promise.$$state.status) return;
15124 this.$$reject(reason);
15127 $$reject: function(reason) {
15128 this.promise.$$state.value = reason;
15129 this.promise.$$state.status = 2;
15130 scheduleProcessQueue(this.promise.$$state);
15133 notify: function(progress) {
15134 var callbacks = this.promise.$$state.pending;
15136 if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
15137 nextTick(function() {
15138 var callback, result;
15139 for (var i = 0, ii = callbacks.length; i < ii; i++) {
15140 result = callbacks[i][0];
15141 callback = callbacks[i][3];
15143 result.notify(isFunction(callback) ? callback(progress) : progress);
15145 exceptionHandler(e);
15159 * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
15160 * used to forward rejection in a chain of promises. If you are dealing with the last promise in
15161 * a promise chain, you don't need to worry about it.
15163 * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
15164 * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
15165 * a promise error callback and you want to forward the error to the promise derived from the
15166 * current promise, you have to "rethrow" the error by returning a rejection constructed via
15170 * promiseB = promiseA.then(function(result) {
15171 * // success: do something and resolve promiseB
15172 * // with the old or a new result
15174 * }, function(reason) {
15175 * // error: handle the error if possible and
15176 * // resolve promiseB with newPromiseOrValue,
15177 * // otherwise forward the rejection to promiseB
15178 * if (canHandle(reason)) {
15179 * // handle the error and recover
15180 * return newPromiseOrValue;
15182 * return $q.reject(reason);
15186 * @param {*} reason Constant, message, exception or an object representing the rejection reason.
15187 * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
15189 var reject = function(reason) {
15190 var result = new Deferred();
15191 result.reject(reason);
15192 return result.promise;
15195 var makePromise = function makePromise(value, resolved) {
15196 var result = new Deferred();
15198 result.resolve(value);
15200 result.reject(value);
15202 return result.promise;
15205 var handleCallback = function handleCallback(value, isResolved, callback) {
15206 var callbackOutput = null;
15208 if (isFunction(callback)) callbackOutput = callback();
15210 return makePromise(e, false);
15212 if (isPromiseLike(callbackOutput)) {
15213 return callbackOutput.then(function() {
15214 return makePromise(value, isResolved);
15215 }, function(error) {
15216 return makePromise(error, false);
15219 return makePromise(value, isResolved);
15229 * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
15230 * This is useful when you are dealing with an object that might or might not be a promise, or if
15231 * the promise comes from a source that can't be trusted.
15233 * @param {*} value Value or a promise
15234 * @param {Function=} successCallback
15235 * @param {Function=} errorCallback
15236 * @param {Function=} progressCallback
15237 * @returns {Promise} Returns a promise of the passed value or promise
15241 var when = function(value, callback, errback, progressBack) {
15242 var result = new Deferred();
15243 result.resolve(value);
15244 return result.promise.then(callback, errback, progressBack);
15253 * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
15255 * @param {*} value Value or a promise
15256 * @param {Function=} successCallback
15257 * @param {Function=} errorCallback
15258 * @param {Function=} progressCallback
15259 * @returns {Promise} Returns a promise of the passed value or promise
15261 var resolve = when;
15269 * Combines multiple promises into a single promise that is resolved when all of the input
15270 * promises are resolved.
15272 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
15273 * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
15274 * each value corresponding to the promise at the same index/key in the `promises` array/hash.
15275 * If any of the promises is resolved with a rejection, this resulting promise will be rejected
15276 * with the same rejection value.
15279 function all(promises) {
15280 var deferred = new Deferred(),
15282 results = isArray(promises) ? [] : {};
15284 forEach(promises, function(promise, key) {
15286 when(promise).then(function(value) {
15287 if (results.hasOwnProperty(key)) return;
15288 results[key] = value;
15289 if (!(--counter)) deferred.resolve(results);
15290 }, function(reason) {
15291 if (results.hasOwnProperty(key)) return;
15292 deferred.reject(reason);
15296 if (counter === 0) {
15297 deferred.resolve(results);
15300 return deferred.promise;
15303 var $Q = function Q(resolver) {
15304 if (!isFunction(resolver)) {
15305 throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
15308 if (!(this instanceof Q)) {
15309 // More useful when $Q is the Promise itself.
15310 return new Q(resolver);
15313 var deferred = new Deferred();
15315 function resolveFn(value) {
15316 deferred.resolve(value);
15319 function rejectFn(reason) {
15320 deferred.reject(reason);
15323 resolver(resolveFn, rejectFn);
15325 return deferred.promise;
15329 $Q.reject = reject;
15331 $Q.resolve = resolve;
15337 function $$RAFProvider() { //rAF
15338 this.$get = ['$window', '$timeout', function($window, $timeout) {
15339 var requestAnimationFrame = $window.requestAnimationFrame ||
15340 $window.webkitRequestAnimationFrame;
15342 var cancelAnimationFrame = $window.cancelAnimationFrame ||
15343 $window.webkitCancelAnimationFrame ||
15344 $window.webkitCancelRequestAnimationFrame;
15346 var rafSupported = !!requestAnimationFrame;
15347 var raf = rafSupported
15349 var id = requestAnimationFrame(fn);
15350 return function() {
15351 cancelAnimationFrame(id);
15355 var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
15356 return function() {
15357 $timeout.cancel(timer);
15361 raf.supported = rafSupported;
15370 * The design decisions behind the scope are heavily favored for speed and memory consumption.
15372 * The typical use of scope is to watch the expressions, which most of the time return the same
15373 * value as last time so we optimize the operation.
15375 * Closures construction is expensive in terms of speed as well as memory:
15376 * - No closures, instead use prototypical inheritance for API
15377 * - Internal state needs to be stored on scope directly, which means that private state is
15378 * exposed as $$____ properties
15380 * Loop operations are optimized by using while(count--) { ... }
15381 * - This means that in order to keep the same order of execution as addition we have to add
15382 * items to the array at the beginning (unshift) instead of at the end (push)
15384 * Child scopes are created and removed often
15385 * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
15387 * There are fewer watches than observers. This is why you don't want the observer to be implemented
15388 * in the same way as watch. Watch requires return of the initialization function which is expensive
15395 * @name $rootScopeProvider
15398 * Provider for the $rootScope service.
15403 * @name $rootScopeProvider#digestTtl
15406 * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
15407 * assuming that the model is unstable.
15409 * The current default is 10 iterations.
15411 * In complex applications it's possible that the dependencies between `$watch`s will result in
15412 * several digest iterations. However if an application needs more than the default 10 digest
15413 * iterations for its model to stabilize then you should investigate what is causing the model to
15414 * continuously change during the digest.
15416 * Increasing the TTL could have performance implications, so you should not change it without
15417 * proper justification.
15419 * @param {number} limit The number of digest iterations.
15428 * Every application has a single root {@link ng.$rootScope.Scope scope}.
15429 * All other scopes are descendant scopes of the root scope. Scopes provide separation
15430 * between the model and the view, via a mechanism for watching the model for changes.
15431 * They also provide event emission/broadcast and subscription facility. See the
15432 * {@link guide/scope developer guide on scopes}.
15434 function $RootScopeProvider() {
15436 var $rootScopeMinErr = minErr('$rootScope');
15437 var lastDirtyWatch = null;
15438 var applyAsyncId = null;
15440 this.digestTtl = function(value) {
15441 if (arguments.length) {
15447 function createChildScopeClass(parent) {
15448 function ChildScope() {
15449 this.$$watchers = this.$$nextSibling =
15450 this.$$childHead = this.$$childTail = null;
15451 this.$$listeners = {};
15452 this.$$listenerCount = {};
15453 this.$$watchersCount = 0;
15454 this.$id = nextUid();
15455 this.$$ChildScope = null;
15457 ChildScope.prototype = parent;
15461 this.$get = ['$exceptionHandler', '$parse', '$browser',
15462 function($exceptionHandler, $parse, $browser) {
15464 function destroyChildScope($event) {
15465 $event.currentScope.$$destroyed = true;
15468 function cleanUpScope($scope) {
15471 // There is a memory leak in IE9 if all child scopes are not disconnected
15472 // completely when a scope is destroyed. So this code will recurse up through
15473 // all this scopes children
15475 // See issue https://github.com/angular/angular.js/issues/10706
15476 $scope.$$childHead && cleanUpScope($scope.$$childHead);
15477 $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
15480 // The code below works around IE9 and V8's memory leaks
15483 // - https://code.google.com/p/v8/issues/detail?id=2073#c26
15484 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
15485 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
15487 $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
15488 $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
15493 * @name $rootScope.Scope
15496 * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
15497 * {@link auto.$injector $injector}. Child scopes are created using the
15498 * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
15499 * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
15500 * an in-depth introduction and usage examples.
15504 * A scope can inherit from a parent scope, as in this example:
15506 var parent = $rootScope;
15507 var child = parent.$new();
15509 parent.salutation = "Hello";
15510 expect(child.salutation).toEqual('Hello');
15512 child.salutation = "Welcome";
15513 expect(child.salutation).toEqual('Welcome');
15514 expect(parent.salutation).toEqual('Hello');
15517 * When interacting with `Scope` in tests, additional helper methods are available on the
15518 * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
15522 * @param {Object.<string, function()>=} providers Map of service factory which need to be
15523 * provided for the current scope. Defaults to {@link ng}.
15524 * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
15525 * append/override services provided by `providers`. This is handy
15526 * when unit-testing and having the need to override a default
15528 * @returns {Object} Newly created scope.
15532 this.$id = nextUid();
15533 this.$$phase = this.$parent = this.$$watchers =
15534 this.$$nextSibling = this.$$prevSibling =
15535 this.$$childHead = this.$$childTail = null;
15537 this.$$destroyed = false;
15538 this.$$listeners = {};
15539 this.$$listenerCount = {};
15540 this.$$watchersCount = 0;
15541 this.$$isolateBindings = null;
15546 * @name $rootScope.Scope#$id
15549 * Unique scope ID (monotonically increasing) useful for debugging.
15554 * @name $rootScope.Scope#$parent
15557 * Reference to the parent scope.
15562 * @name $rootScope.Scope#$root
15565 * Reference to the root scope.
15568 Scope.prototype = {
15569 constructor: Scope,
15572 * @name $rootScope.Scope#$new
15576 * Creates a new child {@link ng.$rootScope.Scope scope}.
15578 * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
15579 * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
15581 * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
15582 * desired for the scope and its child scopes to be permanently detached from the parent and
15583 * thus stop participating in model change detection and listener notification by invoking.
15585 * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
15586 * parent scope. The scope is isolated, as it can not see parent scope properties.
15587 * When creating widgets, it is useful for the widget to not accidentally read parent
15590 * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
15591 * of the newly created scope. Defaults to `this` scope if not provided.
15592 * This is used when creating a transclude scope to correctly place it
15593 * in the scope hierarchy while maintaining the correct prototypical
15596 * @returns {Object} The newly created child scope.
15599 $new: function(isolate, parent) {
15602 parent = parent || this;
15605 child = new Scope();
15606 child.$root = this.$root;
15608 // Only create a child scope class if somebody asks for one,
15609 // but cache it to allow the VM to optimize lookups.
15610 if (!this.$$ChildScope) {
15611 this.$$ChildScope = createChildScopeClass(this);
15613 child = new this.$$ChildScope();
15615 child.$parent = parent;
15616 child.$$prevSibling = parent.$$childTail;
15617 if (parent.$$childHead) {
15618 parent.$$childTail.$$nextSibling = child;
15619 parent.$$childTail = child;
15621 parent.$$childHead = parent.$$childTail = child;
15624 // When the new scope is not isolated or we inherit from `this`, and
15625 // the parent scope is destroyed, the property `$$destroyed` is inherited
15626 // prototypically. In all other cases, this property needs to be set
15627 // when the parent scope is destroyed.
15628 // The listener needs to be added after the parent is set
15629 if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
15636 * @name $rootScope.Scope#$watch
15640 * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
15642 * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
15643 * $digest()} and should return the value that will be watched. (`watchExpression` should not change
15644 * its value when executed multiple times with the same input because it may be executed multiple
15645 * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
15646 * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
15647 * - The `listener` is called only when the value from the current `watchExpression` and the
15648 * previous call to `watchExpression` are not equal (with the exception of the initial run,
15649 * see below). Inequality is determined according to reference inequality,
15650 * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
15651 * via the `!==` Javascript operator, unless `objectEquality == true`
15653 * - When `objectEquality == true`, inequality of the `watchExpression` is determined
15654 * according to the {@link angular.equals} function. To save the value of the object for
15655 * later comparison, the {@link angular.copy} function is used. This therefore means that
15656 * watching complex objects will have adverse memory and performance implications.
15657 * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
15658 * This is achieved by rerunning the watchers until no changes are detected. The rerun
15659 * iteration limit is 10 to prevent an infinite loop deadlock.
15662 * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
15663 * you can register a `watchExpression` function with no `listener`. (Be prepared for
15664 * multiple calls to your `watchExpression` because it will execute multiple times in a
15665 * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
15667 * After a watcher is registered with the scope, the `listener` fn is called asynchronously
15668 * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
15669 * watcher. In rare cases, this is undesirable because the listener is called when the result
15670 * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
15671 * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
15672 * listener was called due to initialization.
15678 // let's assume that scope was dependency injected as the $rootScope
15679 var scope = $rootScope;
15680 scope.name = 'misko';
15683 expect(scope.counter).toEqual(0);
15684 scope.$watch('name', function(newValue, oldValue) {
15685 scope.counter = scope.counter + 1;
15687 expect(scope.counter).toEqual(0);
15690 // the listener is always called during the first $digest loop after it was registered
15691 expect(scope.counter).toEqual(1);
15694 // but now it will not be called unless the value changes
15695 expect(scope.counter).toEqual(1);
15697 scope.name = 'adam';
15699 expect(scope.counter).toEqual(2);
15703 // Using a function as a watchExpression
15705 scope.foodCounter = 0;
15706 expect(scope.foodCounter).toEqual(0);
15708 // This function returns the value being watched. It is called for each turn of the $digest loop
15709 function() { return food; },
15710 // This is the change listener, called when the value returned from the above function changes
15711 function(newValue, oldValue) {
15712 if ( newValue !== oldValue ) {
15713 // Only increment the counter if the value changed
15714 scope.foodCounter = scope.foodCounter + 1;
15718 // No digest has been run so the counter will be zero
15719 expect(scope.foodCounter).toEqual(0);
15721 // Run the digest but since food has not changed count will still be zero
15723 expect(scope.foodCounter).toEqual(0);
15725 // Update food and run digest. Now the counter will increment
15726 food = 'cheeseburger';
15728 expect(scope.foodCounter).toEqual(1);
15734 * @param {(function()|string)} watchExpression Expression that is evaluated on each
15735 * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
15736 * a call to the `listener`.
15738 * - `string`: Evaluated as {@link guide/expression expression}
15739 * - `function(scope)`: called with current `scope` as a parameter.
15740 * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
15741 * of `watchExpression` changes.
15743 * - `newVal` contains the current value of the `watchExpression`
15744 * - `oldVal` contains the previous value of the `watchExpression`
15745 * - `scope` refers to the current scope
15746 * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
15747 * comparing for reference equality.
15748 * @returns {function()} Returns a deregistration function for this listener.
15750 $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
15751 var get = $parse(watchExp);
15753 if (get.$$watchDelegate) {
15754 return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
15757 array = scope.$$watchers,
15760 last: initWatchVal,
15762 exp: prettyPrintExpression || watchExp,
15763 eq: !!objectEquality
15766 lastDirtyWatch = null;
15768 if (!isFunction(listener)) {
15773 array = scope.$$watchers = [];
15775 // we use unshift since we use a while loop in $digest for speed.
15776 // the while loop reads in reverse order.
15777 array.unshift(watcher);
15778 incrementWatchersCount(this, 1);
15780 return function deregisterWatch() {
15781 if (arrayRemove(array, watcher) >= 0) {
15782 incrementWatchersCount(scope, -1);
15784 lastDirtyWatch = null;
15790 * @name $rootScope.Scope#$watchGroup
15794 * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
15795 * If any one expression in the collection changes the `listener` is executed.
15797 * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
15798 * call to $digest() to see if any items changes.
15799 * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
15801 * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
15802 * watched using {@link ng.$rootScope.Scope#$watch $watch()}
15804 * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
15805 * expression in `watchExpressions` changes
15806 * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
15807 * those of `watchExpression`
15808 * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
15809 * those of `watchExpression`
15810 * The `scope` refers to the current scope.
15811 * @returns {function()} Returns a de-registration function for all listeners.
15813 $watchGroup: function(watchExpressions, listener) {
15814 var oldValues = new Array(watchExpressions.length);
15815 var newValues = new Array(watchExpressions.length);
15816 var deregisterFns = [];
15818 var changeReactionScheduled = false;
15819 var firstRun = true;
15821 if (!watchExpressions.length) {
15822 // No expressions means we call the listener ASAP
15823 var shouldCall = true;
15824 self.$evalAsync(function() {
15825 if (shouldCall) listener(newValues, newValues, self);
15827 return function deregisterWatchGroup() {
15828 shouldCall = false;
15832 if (watchExpressions.length === 1) {
15833 // Special case size of one
15834 return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
15835 newValues[0] = value;
15836 oldValues[0] = oldValue;
15837 listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
15841 forEach(watchExpressions, function(expr, i) {
15842 var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
15843 newValues[i] = value;
15844 oldValues[i] = oldValue;
15845 if (!changeReactionScheduled) {
15846 changeReactionScheduled = true;
15847 self.$evalAsync(watchGroupAction);
15850 deregisterFns.push(unwatchFn);
15853 function watchGroupAction() {
15854 changeReactionScheduled = false;
15858 listener(newValues, newValues, self);
15860 listener(newValues, oldValues, self);
15864 return function deregisterWatchGroup() {
15865 while (deregisterFns.length) {
15866 deregisterFns.shift()();
15874 * @name $rootScope.Scope#$watchCollection
15878 * Shallow watches the properties of an object and fires whenever any of the properties change
15879 * (for arrays, this implies watching the array items; for object maps, this implies watching
15880 * the properties). If a change is detected, the `listener` callback is fired.
15882 * - The `obj` collection is observed via standard $watch operation and is examined on every
15883 * call to $digest() to see if any items have been added, removed, or moved.
15884 * - The `listener` is called whenever anything within the `obj` has changed. Examples include
15885 * adding, removing, and moving items belonging to an object or array.
15890 $scope.names = ['igor', 'matias', 'misko', 'james'];
15891 $scope.dataCount = 4;
15893 $scope.$watchCollection('names', function(newNames, oldNames) {
15894 $scope.dataCount = newNames.length;
15897 expect($scope.dataCount).toEqual(4);
15900 //still at 4 ... no changes
15901 expect($scope.dataCount).toEqual(4);
15903 $scope.names.pop();
15906 //now there's been a change
15907 expect($scope.dataCount).toEqual(3);
15911 * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
15912 * expression value should evaluate to an object or an array which is observed on each
15913 * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
15914 * collection will trigger a call to the `listener`.
15916 * @param {function(newCollection, oldCollection, scope)} listener a callback function called
15917 * when a change is detected.
15918 * - The `newCollection` object is the newly modified data obtained from the `obj` expression
15919 * - The `oldCollection` object is a copy of the former collection data.
15920 * Due to performance considerations, the`oldCollection` value is computed only if the
15921 * `listener` function declares two or more arguments.
15922 * - The `scope` argument refers to the current scope.
15924 * @returns {function()} Returns a de-registration function for this listener. When the
15925 * de-registration function is executed, the internal watch operation is terminated.
15927 $watchCollection: function(obj, listener) {
15928 $watchCollectionInterceptor.$stateful = true;
15931 // the current value, updated on each dirty-check run
15933 // a shallow copy of the newValue from the last dirty-check run,
15934 // updated to match newValue during dirty-check run
15936 // a shallow copy of the newValue from when the last change happened
15938 // only track veryOldValue if the listener is asking for it
15939 var trackVeryOldValue = (listener.length > 1);
15940 var changeDetected = 0;
15941 var changeDetector = $parse(obj, $watchCollectionInterceptor);
15942 var internalArray = [];
15943 var internalObject = {};
15944 var initRun = true;
15947 function $watchCollectionInterceptor(_value) {
15949 var newLength, key, bothNaN, newItem, oldItem;
15951 // If the new value is undefined, then return undefined as the watch may be a one-time watch
15952 if (isUndefined(newValue)) return;
15954 if (!isObject(newValue)) { // if primitive
15955 if (oldValue !== newValue) {
15956 oldValue = newValue;
15959 } else if (isArrayLike(newValue)) {
15960 if (oldValue !== internalArray) {
15961 // we are transitioning from something which was not an array into array.
15962 oldValue = internalArray;
15963 oldLength = oldValue.length = 0;
15967 newLength = newValue.length;
15969 if (oldLength !== newLength) {
15970 // if lengths do not match we need to trigger change notification
15972 oldValue.length = oldLength = newLength;
15974 // copy the items to oldValue and look for changes.
15975 for (var i = 0; i < newLength; i++) {
15976 oldItem = oldValue[i];
15977 newItem = newValue[i];
15979 bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
15980 if (!bothNaN && (oldItem !== newItem)) {
15982 oldValue[i] = newItem;
15986 if (oldValue !== internalObject) {
15987 // we are transitioning from something which was not an object into object.
15988 oldValue = internalObject = {};
15992 // copy the items to oldValue and look for changes.
15994 for (key in newValue) {
15995 if (hasOwnProperty.call(newValue, key)) {
15997 newItem = newValue[key];
15998 oldItem = oldValue[key];
16000 if (key in oldValue) {
16001 bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
16002 if (!bothNaN && (oldItem !== newItem)) {
16004 oldValue[key] = newItem;
16008 oldValue[key] = newItem;
16013 if (oldLength > newLength) {
16014 // we used to have more keys, need to find them and destroy them.
16016 for (key in oldValue) {
16017 if (!hasOwnProperty.call(newValue, key)) {
16019 delete oldValue[key];
16024 return changeDetected;
16027 function $watchCollectionAction() {
16030 listener(newValue, newValue, self);
16032 listener(newValue, veryOldValue, self);
16035 // make a copy for the next time a collection is changed
16036 if (trackVeryOldValue) {
16037 if (!isObject(newValue)) {
16039 veryOldValue = newValue;
16040 } else if (isArrayLike(newValue)) {
16041 veryOldValue = new Array(newValue.length);
16042 for (var i = 0; i < newValue.length; i++) {
16043 veryOldValue[i] = newValue[i];
16045 } else { // if object
16047 for (var key in newValue) {
16048 if (hasOwnProperty.call(newValue, key)) {
16049 veryOldValue[key] = newValue[key];
16056 return this.$watch(changeDetector, $watchCollectionAction);
16061 * @name $rootScope.Scope#$digest
16065 * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
16066 * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
16067 * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
16068 * until no more listeners are firing. This means that it is possible to get into an infinite
16069 * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
16070 * iterations exceeds 10.
16072 * Usually, you don't call `$digest()` directly in
16073 * {@link ng.directive:ngController controllers} or in
16074 * {@link ng.$compileProvider#directive directives}.
16075 * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
16076 * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
16078 * If you want to be notified whenever `$digest()` is called,
16079 * you can register a `watchExpression` function with
16080 * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
16082 * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
16087 scope.name = 'misko';
16090 expect(scope.counter).toEqual(0);
16091 scope.$watch('name', function(newValue, oldValue) {
16092 scope.counter = scope.counter + 1;
16094 expect(scope.counter).toEqual(0);
16097 // the listener is always called during the first $digest loop after it was registered
16098 expect(scope.counter).toEqual(1);
16101 // but now it will not be called unless the value changes
16102 expect(scope.counter).toEqual(1);
16104 scope.name = 'adam';
16106 expect(scope.counter).toEqual(2);
16110 $digest: function() {
16111 var watch, value, last,
16115 next, current, target = this,
16117 logIdx, logMsg, asyncTask;
16119 beginPhase('$digest');
16120 // Check for changes to browser url that happened in sync before the call to $digest
16121 $browser.$$checkUrlChange();
16123 if (this === $rootScope && applyAsyncId !== null) {
16124 // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
16125 // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
16126 $browser.defer.cancel(applyAsyncId);
16130 lastDirtyWatch = null;
16132 do { // "while dirty" loop
16136 while (asyncQueue.length) {
16138 asyncTask = asyncQueue.shift();
16139 asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
16141 $exceptionHandler(e);
16143 lastDirtyWatch = null;
16146 traverseScopesLoop:
16147 do { // "traverse the scopes" loop
16148 if ((watchers = current.$$watchers)) {
16149 // process our watches
16150 length = watchers.length;
16153 watch = watchers[length];
16154 // Most common watches are on primitives, in which case we can short
16155 // circuit it with === operator, only when === fails do we use .equals
16157 if ((value = watch.get(current)) !== (last = watch.last) &&
16159 ? equals(value, last)
16160 : (typeof value === 'number' && typeof last === 'number'
16161 && isNaN(value) && isNaN(last)))) {
16163 lastDirtyWatch = watch;
16164 watch.last = watch.eq ? copy(value, null) : value;
16165 watch.fn(value, ((last === initWatchVal) ? value : last), current);
16168 if (!watchLog[logIdx]) watchLog[logIdx] = [];
16169 watchLog[logIdx].push({
16170 msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
16175 } else if (watch === lastDirtyWatch) {
16176 // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
16177 // have already been tested.
16179 break traverseScopesLoop;
16183 $exceptionHandler(e);
16188 // Insanity Warning: scope depth-first traversal
16189 // yes, this code is a bit crazy, but it works and we have tests to prove it!
16190 // this piece should be kept in sync with the traversal in $broadcast
16191 if (!(next = ((current.$$watchersCount && current.$$childHead) ||
16192 (current !== target && current.$$nextSibling)))) {
16193 while (current !== target && !(next = current.$$nextSibling)) {
16194 current = current.$parent;
16197 } while ((current = next));
16199 // `break traverseScopesLoop;` takes us to here
16201 if ((dirty || asyncQueue.length) && !(ttl--)) {
16203 throw $rootScopeMinErr('infdig',
16204 '{0} $digest() iterations reached. Aborting!\n' +
16205 'Watchers fired in the last 5 iterations: {1}',
16209 } while (dirty || asyncQueue.length);
16213 while (postDigestQueue.length) {
16215 postDigestQueue.shift()();
16217 $exceptionHandler(e);
16225 * @name $rootScope.Scope#$destroy
16226 * @eventType broadcast on scope being destroyed
16229 * Broadcasted when a scope and its children are being destroyed.
16231 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
16232 * clean up DOM bindings before an element is removed from the DOM.
16237 * @name $rootScope.Scope#$destroy
16241 * Removes the current scope (and all of its children) from the parent scope. Removal implies
16242 * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
16243 * propagate to the current scope and its children. Removal also implies that the current
16244 * scope is eligible for garbage collection.
16246 * The `$destroy()` is usually used by directives such as
16247 * {@link ng.directive:ngRepeat ngRepeat} for managing the
16248 * unrolling of the loop.
16250 * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
16251 * Application code can register a `$destroy` event handler that will give it a chance to
16252 * perform any necessary cleanup.
16254 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
16255 * clean up DOM bindings before an element is removed from the DOM.
16257 $destroy: function() {
16258 // We can't destroy a scope that has been already destroyed.
16259 if (this.$$destroyed) return;
16260 var parent = this.$parent;
16262 this.$broadcast('$destroy');
16263 this.$$destroyed = true;
16265 if (this === $rootScope) {
16266 //Remove handlers attached to window when $rootScope is removed
16267 $browser.$$applicationDestroyed();
16270 incrementWatchersCount(this, -this.$$watchersCount);
16271 for (var eventName in this.$$listenerCount) {
16272 decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
16275 // sever all the references to parent scopes (after this cleanup, the current scope should
16276 // not be retained by any of our references and should be eligible for garbage collection)
16277 if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
16278 if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
16279 if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
16280 if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
16282 // Disable listeners, watchers and apply/digest methods
16283 this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
16284 this.$on = this.$watch = this.$watchGroup = function() { return noop; };
16285 this.$$listeners = {};
16287 // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
16288 this.$$nextSibling = null;
16289 cleanUpScope(this);
16294 * @name $rootScope.Scope#$eval
16298 * Executes the `expression` on the current scope and returns the result. Any exceptions in
16299 * the expression are propagated (uncaught). This is useful when evaluating Angular
16304 var scope = ng.$rootScope.Scope();
16308 expect(scope.$eval('a+b')).toEqual(3);
16309 expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
16312 * @param {(string|function())=} expression An angular expression to be executed.
16314 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
16315 * - `function(scope)`: execute the function with the current `scope` parameter.
16317 * @param {(object)=} locals Local variables object, useful for overriding values in scope.
16318 * @returns {*} The result of evaluating the expression.
16320 $eval: function(expr, locals) {
16321 return $parse(expr)(this, locals);
16326 * @name $rootScope.Scope#$evalAsync
16330 * Executes the expression on the current scope at a later point in time.
16332 * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
16335 * - it will execute after the function that scheduled the evaluation (preferably before DOM
16337 * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
16338 * `expression` execution.
16340 * Any exceptions from the execution of the expression are forwarded to the
16341 * {@link ng.$exceptionHandler $exceptionHandler} service.
16343 * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
16344 * will be scheduled. However, it is encouraged to always call code that changes the model
16345 * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
16347 * @param {(string|function())=} expression An angular expression to be executed.
16349 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
16350 * - `function(scope)`: execute the function with the current `scope` parameter.
16352 * @param {(object)=} locals Local variables object, useful for overriding values in scope.
16354 $evalAsync: function(expr, locals) {
16355 // if we are outside of an $digest loop and this is the first time we are scheduling async
16356 // task also schedule async auto-flush
16357 if (!$rootScope.$$phase && !asyncQueue.length) {
16358 $browser.defer(function() {
16359 if (asyncQueue.length) {
16360 $rootScope.$digest();
16365 asyncQueue.push({scope: this, expression: expr, locals: locals});
16368 $$postDigest: function(fn) {
16369 postDigestQueue.push(fn);
16374 * @name $rootScope.Scope#$apply
16378 * `$apply()` is used to execute an expression in angular from outside of the angular
16379 * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
16380 * Because we are calling into the angular framework we need to perform proper scope life
16381 * cycle of {@link ng.$exceptionHandler exception handling},
16382 * {@link ng.$rootScope.Scope#$digest executing watches}.
16386 * # Pseudo-Code of `$apply()`
16388 function $apply(expr) {
16390 return $eval(expr);
16392 $exceptionHandler(e);
16400 * Scope's `$apply()` method transitions through the following stages:
16402 * 1. The {@link guide/expression expression} is executed using the
16403 * {@link ng.$rootScope.Scope#$eval $eval()} method.
16404 * 2. Any exceptions from the execution of the expression are forwarded to the
16405 * {@link ng.$exceptionHandler $exceptionHandler} service.
16406 * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
16407 * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
16410 * @param {(string|function())=} exp An angular expression to be executed.
16412 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
16413 * - `function(scope)`: execute the function with current `scope` parameter.
16415 * @returns {*} The result of evaluating the expression.
16417 $apply: function(expr) {
16419 beginPhase('$apply');
16421 return this.$eval(expr);
16426 $exceptionHandler(e);
16429 $rootScope.$digest();
16431 $exceptionHandler(e);
16439 * @name $rootScope.Scope#$applyAsync
16443 * Schedule the invocation of $apply to occur at a later time. The actual time difference
16444 * varies across browsers, but is typically around ~10 milliseconds.
16446 * This can be used to queue up multiple expressions which need to be evaluated in the same
16449 * @param {(string|function())=} exp An angular expression to be executed.
16451 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
16452 * - `function(scope)`: execute the function with current `scope` parameter.
16454 $applyAsync: function(expr) {
16456 expr && applyAsyncQueue.push($applyAsyncExpression);
16457 scheduleApplyAsync();
16459 function $applyAsyncExpression() {
16466 * @name $rootScope.Scope#$on
16470 * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
16471 * discussion of event life cycle.
16473 * The event listener function format is: `function(event, args...)`. The `event` object
16474 * passed into the listener has the following attributes:
16476 * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
16478 * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
16479 * event propagates through the scope hierarchy, this property is set to null.
16480 * - `name` - `{string}`: name of the event.
16481 * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
16482 * further event propagation (available only for events that were `$emit`-ed).
16483 * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
16485 * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
16487 * @param {string} name Event name to listen on.
16488 * @param {function(event, ...args)} listener Function to call when the event is emitted.
16489 * @returns {function()} Returns a deregistration function for this listener.
16491 $on: function(name, listener) {
16492 var namedListeners = this.$$listeners[name];
16493 if (!namedListeners) {
16494 this.$$listeners[name] = namedListeners = [];
16496 namedListeners.push(listener);
16498 var current = this;
16500 if (!current.$$listenerCount[name]) {
16501 current.$$listenerCount[name] = 0;
16503 current.$$listenerCount[name]++;
16504 } while ((current = current.$parent));
16507 return function() {
16508 var indexOfListener = namedListeners.indexOf(listener);
16509 if (indexOfListener !== -1) {
16510 namedListeners[indexOfListener] = null;
16511 decrementListenerCount(self, 1, name);
16519 * @name $rootScope.Scope#$emit
16523 * Dispatches an event `name` upwards through the scope hierarchy notifying the
16524 * registered {@link ng.$rootScope.Scope#$on} listeners.
16526 * The event life cycle starts at the scope on which `$emit` was called. All
16527 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
16528 * notified. Afterwards, the event traverses upwards toward the root scope and calls all
16529 * registered listeners along the way. The event will stop propagating if one of the listeners
16532 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
16533 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
16535 * @param {string} name Event name to emit.
16536 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
16537 * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
16539 $emit: function(name, args) {
16543 stopPropagation = false,
16546 targetScope: scope,
16547 stopPropagation: function() {stopPropagation = true;},
16548 preventDefault: function() {
16549 event.defaultPrevented = true;
16551 defaultPrevented: false
16553 listenerArgs = concat([event], arguments, 1),
16557 namedListeners = scope.$$listeners[name] || empty;
16558 event.currentScope = scope;
16559 for (i = 0, length = namedListeners.length; i < length; i++) {
16561 // if listeners were deregistered, defragment the array
16562 if (!namedListeners[i]) {
16563 namedListeners.splice(i, 1);
16569 //allow all listeners attached to the current scope to run
16570 namedListeners[i].apply(null, listenerArgs);
16572 $exceptionHandler(e);
16575 //if any listener on the current scope stops propagation, prevent bubbling
16576 if (stopPropagation) {
16577 event.currentScope = null;
16581 scope = scope.$parent;
16584 event.currentScope = null;
16592 * @name $rootScope.Scope#$broadcast
16596 * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
16597 * registered {@link ng.$rootScope.Scope#$on} listeners.
16599 * The event life cycle starts at the scope on which `$broadcast` was called. All
16600 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
16601 * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
16602 * scope and calls all registered listeners along the way. The event cannot be canceled.
16604 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
16605 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
16607 * @param {string} name Event name to broadcast.
16608 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
16609 * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
16611 $broadcast: function(name, args) {
16617 targetScope: target,
16618 preventDefault: function() {
16619 event.defaultPrevented = true;
16621 defaultPrevented: false
16624 if (!target.$$listenerCount[name]) return event;
16626 var listenerArgs = concat([event], arguments, 1),
16627 listeners, i, length;
16629 //down while you can, then up and next sibling or up and next sibling until back at root
16630 while ((current = next)) {
16631 event.currentScope = current;
16632 listeners = current.$$listeners[name] || [];
16633 for (i = 0, length = listeners.length; i < length; i++) {
16634 // if listeners were deregistered, defragment the array
16635 if (!listeners[i]) {
16636 listeners.splice(i, 1);
16643 listeners[i].apply(null, listenerArgs);
16645 $exceptionHandler(e);
16649 // Insanity Warning: scope depth-first traversal
16650 // yes, this code is a bit crazy, but it works and we have tests to prove it!
16651 // this piece should be kept in sync with the traversal in $digest
16652 // (though it differs due to having the extra check for $$listenerCount)
16653 if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
16654 (current !== target && current.$$nextSibling)))) {
16655 while (current !== target && !(next = current.$$nextSibling)) {
16656 current = current.$parent;
16661 event.currentScope = null;
16666 var $rootScope = new Scope();
16668 //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
16669 var asyncQueue = $rootScope.$$asyncQueue = [];
16670 var postDigestQueue = $rootScope.$$postDigestQueue = [];
16671 var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
16676 function beginPhase(phase) {
16677 if ($rootScope.$$phase) {
16678 throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
16681 $rootScope.$$phase = phase;
16684 function clearPhase() {
16685 $rootScope.$$phase = null;
16688 function incrementWatchersCount(current, count) {
16690 current.$$watchersCount += count;
16691 } while ((current = current.$parent));
16694 function decrementListenerCount(current, count, name) {
16696 current.$$listenerCount[name] -= count;
16698 if (current.$$listenerCount[name] === 0) {
16699 delete current.$$listenerCount[name];
16701 } while ((current = current.$parent));
16705 * function used as an initial value for watchers.
16706 * because it's unique we can easily tell it apart from other values
16708 function initWatchVal() {}
16710 function flushApplyAsync() {
16711 while (applyAsyncQueue.length) {
16713 applyAsyncQueue.shift()();
16715 $exceptionHandler(e);
16718 applyAsyncId = null;
16721 function scheduleApplyAsync() {
16722 if (applyAsyncId === null) {
16723 applyAsyncId = $browser.defer(function() {
16724 $rootScope.$apply(flushApplyAsync);
16733 * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
16735 function $$SanitizeUriProvider() {
16736 var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
16737 imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
16741 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
16742 * urls during a[href] sanitization.
16744 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
16746 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
16747 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
16748 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
16749 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
16751 * @param {RegExp=} regexp New regexp to whitelist urls with.
16752 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
16753 * chaining otherwise.
16755 this.aHrefSanitizationWhitelist = function(regexp) {
16756 if (isDefined(regexp)) {
16757 aHrefSanitizationWhitelist = regexp;
16760 return aHrefSanitizationWhitelist;
16766 * Retrieves or overrides the default regular expression that is used for whitelisting of safe
16767 * urls during img[src] sanitization.
16769 * The sanitization is a security measure aimed at prevent XSS attacks via html links.
16771 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
16772 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
16773 * regular expression. If a match is found, the original url is written into the dom. Otherwise,
16774 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
16776 * @param {RegExp=} regexp New regexp to whitelist urls with.
16777 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
16778 * chaining otherwise.
16780 this.imgSrcSanitizationWhitelist = function(regexp) {
16781 if (isDefined(regexp)) {
16782 imgSrcSanitizationWhitelist = regexp;
16785 return imgSrcSanitizationWhitelist;
16788 this.$get = function() {
16789 return function sanitizeUri(uri, isImage) {
16790 var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
16792 normalizedVal = urlResolve(uri).href;
16793 if (normalizedVal !== '' && !normalizedVal.match(regex)) {
16794 return 'unsafe:' + normalizedVal;
16801 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
16802 * Any commits to this file should be reviewed with security in mind. *
16803 * Changes to this file can potentially create security vulnerabilities. *
16804 * An approval from 2 Core members with history of modifying *
16805 * this file is required. *
16807 * Does the change somehow allow for arbitrary javascript to be executed? *
16808 * Or allows for someone to change the prototype of built-in objects? *
16809 * Or gives undesired access to variables likes document or window? *
16810 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
16812 var $sceMinErr = minErr('$sce');
16814 var SCE_CONTEXTS = {
16818 // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
16819 // url. (e.g. ng-include, script src, templateUrl)
16820 RESOURCE_URL: 'resourceUrl',
16824 // Helper functions follow.
16826 function adjustMatcher(matcher) {
16827 if (matcher === 'self') {
16829 } else if (isString(matcher)) {
16830 // Strings match exactly except for 2 wildcards - '*' and '**'.
16831 // '*' matches any character except those from the set ':/.?&'.
16832 // '**' matches any character (like .* in a RegExp).
16833 // More than 2 *'s raises an error as it's ill defined.
16834 if (matcher.indexOf('***') > -1) {
16835 throw $sceMinErr('iwcard',
16836 'Illegal sequence *** in string matcher. String: {0}', matcher);
16838 matcher = escapeForRegexp(matcher).
16839 replace('\\*\\*', '.*').
16840 replace('\\*', '[^:/.?&;]*');
16841 return new RegExp('^' + matcher + '$');
16842 } else if (isRegExp(matcher)) {
16843 // The only other type of matcher allowed is a Regexp.
16844 // Match entire URL / disallow partial matches.
16845 // Flags are reset (i.e. no global, ignoreCase or multiline)
16846 return new RegExp('^' + matcher.source + '$');
16848 throw $sceMinErr('imatcher',
16849 'Matchers may only be "self", string patterns or RegExp objects');
16854 function adjustMatchers(matchers) {
16855 var adjustedMatchers = [];
16856 if (isDefined(matchers)) {
16857 forEach(matchers, function(matcher) {
16858 adjustedMatchers.push(adjustMatcher(matcher));
16861 return adjustedMatchers;
16867 * @name $sceDelegate
16872 * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
16873 * Contextual Escaping (SCE)} services to AngularJS.
16875 * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
16876 * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
16877 * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
16878 * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
16879 * work because `$sce` delegates to `$sceDelegate` for these operations.
16881 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
16883 * The default instance of `$sceDelegate` should work out of the box with little pain. While you
16884 * can override it completely to change the behavior of `$sce`, the common case would
16885 * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
16886 * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
16887 * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
16888 * $sceDelegateProvider.resourceUrlWhitelist} and {@link
16889 * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
16894 * @name $sceDelegateProvider
16897 * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
16898 * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
16899 * that the URLs used for sourcing Angular templates are safe. Refer {@link
16900 * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
16901 * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
16903 * For the general details about this service in Angular, read the main page for {@link ng.$sce
16904 * Strict Contextual Escaping (SCE)}.
16906 * **Example**: Consider the following case. <a name="example"></a>
16908 * - your app is hosted at url `http://myapp.example.com/`
16909 * - but some of your templates are hosted on other domains you control such as
16910 * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
16911 * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
16913 * Here is what a secure configuration for this scenario might look like:
16916 * angular.module('myApp', []).config(function($sceDelegateProvider) {
16917 * $sceDelegateProvider.resourceUrlWhitelist([
16918 * // Allow same origin resource loads.
16920 * // Allow loading from our assets domain. Notice the difference between * and **.
16921 * 'http://srv*.assets.example.com/**'
16924 * // The blacklist overrides the whitelist so the open redirect here is blocked.
16925 * $sceDelegateProvider.resourceUrlBlacklist([
16926 * 'http://myapp.example.com/clickThru**'
16932 function $SceDelegateProvider() {
16933 this.SCE_CONTEXTS = SCE_CONTEXTS;
16935 // Resource URLs can also be trusted by policy.
16936 var resourceUrlWhitelist = ['self'],
16937 resourceUrlBlacklist = [];
16941 * @name $sceDelegateProvider#resourceUrlWhitelist
16944 * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
16945 * provided. This must be an array or null. A snapshot of this array is used so further
16946 * changes to the array are ignored.
16948 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
16949 * allowed in this array.
16951 * Note: **an empty whitelist array will block all URLs**!
16953 * @return {Array} the currently set whitelist array.
16955 * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
16956 * same origin resource requests.
16959 * Sets/Gets the whitelist of trusted resource URLs.
16961 this.resourceUrlWhitelist = function(value) {
16962 if (arguments.length) {
16963 resourceUrlWhitelist = adjustMatchers(value);
16965 return resourceUrlWhitelist;
16970 * @name $sceDelegateProvider#resourceUrlBlacklist
16973 * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
16974 * provided. This must be an array or null. A snapshot of this array is used so further
16975 * changes to the array are ignored.
16977 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
16978 * allowed in this array.
16980 * The typical usage for the blacklist is to **block
16981 * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
16982 * these would otherwise be trusted but actually return content from the redirected domain.
16984 * Finally, **the blacklist overrides the whitelist** and has the final say.
16986 * @return {Array} the currently set blacklist array.
16988 * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
16989 * is no blacklist.)
16992 * Sets/Gets the blacklist of trusted resource URLs.
16995 this.resourceUrlBlacklist = function(value) {
16996 if (arguments.length) {
16997 resourceUrlBlacklist = adjustMatchers(value);
16999 return resourceUrlBlacklist;
17002 this.$get = ['$injector', function($injector) {
17004 var htmlSanitizer = function htmlSanitizer(html) {
17005 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
17008 if ($injector.has('$sanitize')) {
17009 htmlSanitizer = $injector.get('$sanitize');
17013 function matchUrl(matcher, parsedUrl) {
17014 if (matcher === 'self') {
17015 return urlIsSameOrigin(parsedUrl);
17017 // definitely a regex. See adjustMatchers()
17018 return !!matcher.exec(parsedUrl.href);
17022 function isResourceUrlAllowedByPolicy(url) {
17023 var parsedUrl = urlResolve(url.toString());
17024 var i, n, allowed = false;
17025 // Ensure that at least one item from the whitelist allows this url.
17026 for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
17027 if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
17033 // Ensure that no item from the blacklist blocked this url.
17034 for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
17035 if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
17044 function generateHolderType(Base) {
17045 var holderType = function TrustedValueHolderType(trustedValue) {
17046 this.$$unwrapTrustedValue = function() {
17047 return trustedValue;
17051 holderType.prototype = new Base();
17053 holderType.prototype.valueOf = function sceValueOf() {
17054 return this.$$unwrapTrustedValue();
17056 holderType.prototype.toString = function sceToString() {
17057 return this.$$unwrapTrustedValue().toString();
17062 var trustedValueHolderBase = generateHolderType(),
17065 byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
17066 byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
17067 byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
17068 byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
17069 byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
17073 * @name $sceDelegate#trustAs
17076 * Returns an object that is trusted by angular for use in specified strict
17077 * contextual escaping contexts (such as ng-bind-html, ng-include, any src
17078 * attribute interpolation, any dom event binding attribute interpolation
17079 * such as for onclick, etc.) that uses the provided value.
17080 * See {@link ng.$sce $sce} for enabling strict contextual escaping.
17082 * @param {string} type The kind of context in which this value is safe for use. e.g. url,
17083 * resourceUrl, html, js and css.
17084 * @param {*} value The value that that should be considered trusted/safe.
17085 * @returns {*} A value that can be used to stand in for the provided `value` in places
17086 * where Angular expects a $sce.trustAs() return value.
17088 function trustAs(type, trustedValue) {
17089 var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
17090 if (!Constructor) {
17091 throw $sceMinErr('icontext',
17092 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
17093 type, trustedValue);
17095 if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
17096 return trustedValue;
17098 // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
17099 // mutable objects, we ensure here that the value passed in is actually a string.
17100 if (typeof trustedValue !== 'string') {
17101 throw $sceMinErr('itype',
17102 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
17105 return new Constructor(trustedValue);
17110 * @name $sceDelegate#valueOf
17113 * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
17114 * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
17115 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
17117 * If the passed parameter is not a value that had been returned by {@link
17118 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
17120 * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
17121 * call or anything else.
17122 * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
17123 * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
17124 * `value` unchanged.
17126 function valueOf(maybeTrusted) {
17127 if (maybeTrusted instanceof trustedValueHolderBase) {
17128 return maybeTrusted.$$unwrapTrustedValue();
17130 return maybeTrusted;
17136 * @name $sceDelegate#getTrusted
17139 * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
17140 * returns the originally supplied value if the queried context type is a supertype of the
17141 * created type. If this condition isn't satisfied, throws an exception.
17143 * <div class="alert alert-danger">
17144 * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
17145 * (XSS) vulnerability in your application.
17148 * @param {string} type The kind of context in which this value is to be used.
17149 * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
17150 * `$sceDelegate.trustAs`} call.
17151 * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
17152 * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
17154 function getTrusted(type, maybeTrusted) {
17155 if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
17156 return maybeTrusted;
17158 var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
17159 if (constructor && maybeTrusted instanceof constructor) {
17160 return maybeTrusted.$$unwrapTrustedValue();
17162 // If we get here, then we may only take one of two actions.
17163 // 1. sanitize the value for the requested type, or
17164 // 2. throw an exception.
17165 if (type === SCE_CONTEXTS.RESOURCE_URL) {
17166 if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
17167 return maybeTrusted;
17169 throw $sceMinErr('insecurl',
17170 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
17171 maybeTrusted.toString());
17173 } else if (type === SCE_CONTEXTS.HTML) {
17174 return htmlSanitizer(maybeTrusted);
17176 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
17179 return { trustAs: trustAs,
17180 getTrusted: getTrusted,
17181 valueOf: valueOf };
17188 * @name $sceProvider
17191 * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
17192 * - enable/disable Strict Contextual Escaping (SCE) in a module
17193 * - override the default implementation with a custom delegate
17195 * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
17198 /* jshint maxlen: false*/
17207 * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
17209 * # Strict Contextual Escaping
17211 * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
17212 * contexts to result in a value that is marked as safe to use for that context. One example of
17213 * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
17214 * to these contexts as privileged or SCE contexts.
17216 * As of version 1.2, Angular ships with SCE enabled by default.
17218 * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
17219 * one to execute arbitrary javascript by the use of the expression() syntax. Refer
17220 * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
17221 * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
17222 * to the top of your HTML document.
17224 * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
17225 * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
17227 * Here's an example of a binding in a privileged context:
17230 * <input ng-model="userHtml" aria-label="User input">
17231 * <div ng-bind-html="userHtml"></div>
17234 * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
17235 * disabled, this application allows the user to render arbitrary HTML into the DIV.
17236 * In a more realistic example, one may be rendering user comments, blog articles, etc. via
17237 * bindings. (HTML is just one example of a context where rendering user controlled input creates
17238 * security vulnerabilities.)
17240 * For the case of HTML, you might use a library, either on the client side, or on the server side,
17241 * to sanitize unsafe HTML before binding to the value and rendering it in the document.
17243 * How would you ensure that every place that used these types of bindings was bound to a value that
17244 * was sanitized by your library (or returned as safe for rendering by your server?) How can you
17245 * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
17246 * properties/fields and forgot to update the binding to the sanitized value?
17248 * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
17249 * determine that something explicitly says it's safe to use a value for binding in that
17250 * context. You can then audit your code (a simple grep would do) to ensure that this is only done
17251 * for those values that you can easily tell are safe - because they were received from your server,
17252 * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
17253 * allowing only the files in a specific directory to do this. Ensuring that the internal API
17254 * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
17256 * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
17257 * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
17258 * obtain values that will be accepted by SCE / privileged contexts.
17261 * ## How does it work?
17263 * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
17264 * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
17265 * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
17266 * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
17268 * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
17269 * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
17273 * var ngBindHtmlDirective = ['$sce', function($sce) {
17274 * return function(scope, element, attr) {
17275 * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
17276 * element.html(value || '');
17282 * ## Impact on loading templates
17284 * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
17285 * `templateUrl`'s specified by {@link guide/directive directives}.
17287 * By default, Angular only loads templates from the same domain and protocol as the application
17288 * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
17289 * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
17290 * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
17291 * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
17295 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
17296 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
17297 * policy apply in addition to this and may further restrict whether the template is successfully
17298 * loaded. This means that without the right CORS policy, loading templates from a different domain
17299 * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
17302 * ## This feels like too much overhead
17304 * It's important to remember that SCE only applies to interpolation expressions.
17306 * If your expressions are constant literals, they're automatically trusted and you don't need to
17307 * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
17308 * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
17310 * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
17311 * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
17313 * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
17314 * templates in `ng-include` from your application's domain without having to even know about SCE.
17315 * It blocks loading templates from other domains or loading templates over http from an https
17316 * served document. You can change these by setting your own custom {@link
17317 * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
17318 * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
17320 * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
17321 * application that's secure and can be audited to verify that with much more ease than bolting
17322 * security onto an application later.
17324 * <a name="contexts"></a>
17325 * ## What trusted context types are supported?
17327 * | Context | Notes |
17328 * |---------------------|----------------|
17329 * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
17330 * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
17331 * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
17332 * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
17333 * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
17335 * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
17337 * Each element in these arrays must be one of the following:
17340 * - The special **string**, `'self'`, can be used to match against all URLs of the **same
17341 * domain** as the application document using the **same protocol**.
17342 * - **String** (except the special value `'self'`)
17343 * - The string is matched against the full *normalized / absolute URL* of the resource
17344 * being tested (substring matches are not good enough.)
17345 * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
17346 * match themselves.
17347 * - `*`: matches zero or more occurrences of any character other than one of the following 6
17348 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
17350 * - `**`: matches zero or more occurrences of *any* character. As such, it's not
17351 * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
17352 * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
17353 * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
17354 * http://foo.example.com/templates/**).
17355 * - **RegExp** (*see caveat below*)
17356 * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
17357 * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
17358 * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
17359 * have good test coverage). For instance, the use of `.` in the regex is correct only in a
17360 * small number of cases. A `.` character in the regex used when matching the scheme or a
17361 * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
17362 * is highly recommended to use the string patterns and only fall back to regular expressions
17363 * as a last resort.
17364 * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
17365 * matched against the **entire** *normalized / absolute URL* of the resource being tested
17366 * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
17367 * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
17368 * - If you are generating your JavaScript from some other templating engine (not
17369 * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
17370 * remember to escape your regular expression (and be aware that you might need more than
17371 * one level of escaping depending on your templating engine and the way you interpolated
17372 * the value.) Do make use of your platform's escaping mechanism as it might be good
17373 * enough before coding your own. E.g. Ruby has
17374 * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
17375 * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
17376 * Javascript lacks a similar built in function for escaping. Take a look at Google
17377 * Closure library's [goog.string.regExpEscape(s)](
17378 * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
17380 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
17382 * ## Show me an example using SCE.
17384 * <example module="mySceApp" deps="angular-sanitize.js">
17385 * <file name="index.html">
17386 * <div ng-controller="AppController as myCtrl">
17387 * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
17388 * <b>User comments</b><br>
17389 * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
17390 * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
17392 * <div class="well">
17393 * <div ng-repeat="userComment in myCtrl.userComments">
17394 * <b>{{userComment.name}}</b>:
17395 * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
17402 * <file name="script.js">
17403 * angular.module('mySceApp', ['ngSanitize'])
17404 * .controller('AppController', ['$http', '$templateCache', '$sce',
17405 * function($http, $templateCache, $sce) {
17407 * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
17408 * self.userComments = userComments;
17410 * self.explicitlyTrustedHtml = $sce.trustAsHtml(
17411 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
17412 * 'sanitization."">Hover over this text.</span>');
17416 * <file name="test_data.json">
17418 * { "name": "Alice",
17420 * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
17423 * "htmlComment": "<i>Yes!</i> Am I the only other one?"
17428 * <file name="protractor.js" type="protractor">
17429 * describe('SCE doc demo', function() {
17430 * it('should sanitize untrusted values', function() {
17431 * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
17432 * .toBe('<span>Is <i>anyone</i> reading this?</span>');
17435 * it('should NOT sanitize explicitly trusted values', function() {
17436 * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
17437 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
17438 * 'sanitization."">Hover over this text.</span>');
17446 * ## Can I disable SCE completely?
17448 * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
17449 * for little coding overhead. It will be much harder to take an SCE disabled application and
17450 * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
17451 * for cases where you have a lot of existing code that was written before SCE was introduced and
17452 * you're migrating them a module at a time.
17454 * That said, here's how you can completely disable SCE:
17457 * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
17458 * // Completely disable SCE. For demonstration purposes only!
17459 * // Do not use in new projects.
17460 * $sceProvider.enabled(false);
17465 /* jshint maxlen: 100 */
17467 function $SceProvider() {
17468 var enabled = true;
17472 * @name $sceProvider#enabled
17475 * @param {boolean=} value If provided, then enables/disables SCE.
17476 * @return {boolean} true if SCE is enabled, false otherwise.
17479 * Enables/disables SCE and returns the current value.
17481 this.enabled = function(value) {
17482 if (arguments.length) {
17489 /* Design notes on the default implementation for SCE.
17491 * The API contract for the SCE delegate
17492 * -------------------------------------
17493 * The SCE delegate object must provide the following 3 methods:
17495 * - trustAs(contextEnum, value)
17496 * This method is used to tell the SCE service that the provided value is OK to use in the
17497 * contexts specified by contextEnum. It must return an object that will be accepted by
17498 * getTrusted() for a compatible contextEnum and return this value.
17501 * For values that were not produced by trustAs(), return them as is. For values that were
17502 * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
17503 * trustAs is wrapping the given values into some type, this operation unwraps it when given
17506 * - getTrusted(contextEnum, value)
17507 * This function should return the a value that is safe to use in the context specified by
17508 * contextEnum or throw and exception otherwise.
17510 * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
17511 * opaque or wrapped in some holder object. That happens to be an implementation detail. For
17512 * instance, an implementation could maintain a registry of all trusted objects by context. In
17513 * such a case, trustAs() would return the same object that was passed in. getTrusted() would
17514 * return the same object passed in if it was found in the registry under a compatible context or
17515 * throw an exception otherwise. An implementation might only wrap values some of the time based
17516 * on some criteria. getTrusted() might return a value and not throw an exception for special
17517 * constants or objects even if not wrapped. All such implementations fulfill this contract.
17520 * A note on the inheritance model for SCE contexts
17521 * ------------------------------------------------
17522 * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
17523 * is purely an implementation details.
17525 * The contract is simply this:
17527 * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
17528 * will also succeed.
17530 * Inheritance happens to capture this in a natural way. In some future, we
17531 * may not use inheritance anymore. That is OK because no code outside of
17532 * sce.js and sceSpecs.js would need to be aware of this detail.
17535 this.$get = ['$parse', '$sceDelegate', function(
17536 $parse, $sceDelegate) {
17537 // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
17538 // the "expression(javascript expression)" syntax which is insecure.
17539 if (enabled && msie < 8) {
17540 throw $sceMinErr('iequirks',
17541 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
17542 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
17543 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
17546 var sce = shallowCopy(SCE_CONTEXTS);
17550 * @name $sce#isEnabled
17553 * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
17554 * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
17557 * Returns a boolean indicating if SCE is enabled.
17559 sce.isEnabled = function() {
17562 sce.trustAs = $sceDelegate.trustAs;
17563 sce.getTrusted = $sceDelegate.getTrusted;
17564 sce.valueOf = $sceDelegate.valueOf;
17567 sce.trustAs = sce.getTrusted = function(type, value) { return value; };
17568 sce.valueOf = identity;
17573 * @name $sce#parseAs
17576 * Converts Angular {@link guide/expression expression} into a function. This is like {@link
17577 * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
17578 * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
17581 * @param {string} type The kind of SCE context in which this result will be used.
17582 * @param {string} expression String expression to compile.
17583 * @returns {function(context, locals)} a function which represents the compiled expression:
17585 * * `context` – `{object}` – an object against which any expressions embedded in the strings
17586 * are evaluated against (typically a scope object).
17587 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
17590 sce.parseAs = function sceParseAs(type, expr) {
17591 var parsed = $parse(expr);
17592 if (parsed.literal && parsed.constant) {
17595 return $parse(expr, function(value) {
17596 return sce.getTrusted(type, value);
17603 * @name $sce#trustAs
17606 * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
17607 * returns an object that is trusted by angular for use in specified strict contextual
17608 * escaping contexts (such as ng-bind-html, ng-include, any src attribute
17609 * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
17610 * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
17613 * @param {string} type The kind of context in which this value is safe for use. e.g. url,
17614 * resourceUrl, html, js and css.
17615 * @param {*} value The value that that should be considered trusted/safe.
17616 * @returns {*} A value that can be used to stand in for the provided `value` in places
17617 * where Angular expects a $sce.trustAs() return value.
17622 * @name $sce#trustAsHtml
17625 * Shorthand method. `$sce.trustAsHtml(value)` →
17626 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
17628 * @param {*} value The value to trustAs.
17629 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
17630 * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
17631 * only accept expressions that are either literal constants or are the
17632 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
17637 * @name $sce#trustAsUrl
17640 * Shorthand method. `$sce.trustAsUrl(value)` →
17641 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
17643 * @param {*} value The value to trustAs.
17644 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
17645 * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
17646 * only accept expressions that are either literal constants or are the
17647 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
17652 * @name $sce#trustAsResourceUrl
17655 * Shorthand method. `$sce.trustAsResourceUrl(value)` →
17656 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
17658 * @param {*} value The value to trustAs.
17659 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
17660 * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
17661 * only accept expressions that are either literal constants or are the return
17662 * value of {@link ng.$sce#trustAs $sce.trustAs}.)
17667 * @name $sce#trustAsJs
17670 * Shorthand method. `$sce.trustAsJs(value)` →
17671 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
17673 * @param {*} value The value to trustAs.
17674 * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
17675 * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
17676 * only accept expressions that are either literal constants or are the
17677 * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
17682 * @name $sce#getTrusted
17685 * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
17686 * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
17687 * originally supplied value if the queried context type is a supertype of the created type.
17688 * If this condition isn't satisfied, throws an exception.
17690 * @param {string} type The kind of context in which this value is to be used.
17691 * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
17693 * @returns {*} The value the was originally provided to
17694 * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
17695 * Otherwise, throws an exception.
17700 * @name $sce#getTrustedHtml
17703 * Shorthand method. `$sce.getTrustedHtml(value)` →
17704 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
17706 * @param {*} value The value to pass to `$sce.getTrusted`.
17707 * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
17712 * @name $sce#getTrustedCss
17715 * Shorthand method. `$sce.getTrustedCss(value)` →
17716 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
17718 * @param {*} value The value to pass to `$sce.getTrusted`.
17719 * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
17724 * @name $sce#getTrustedUrl
17727 * Shorthand method. `$sce.getTrustedUrl(value)` →
17728 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
17730 * @param {*} value The value to pass to `$sce.getTrusted`.
17731 * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
17736 * @name $sce#getTrustedResourceUrl
17739 * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
17740 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
17742 * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
17743 * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
17748 * @name $sce#getTrustedJs
17751 * Shorthand method. `$sce.getTrustedJs(value)` →
17752 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
17754 * @param {*} value The value to pass to `$sce.getTrusted`.
17755 * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
17760 * @name $sce#parseAsHtml
17763 * Shorthand method. `$sce.parseAsHtml(expression string)` →
17764 * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
17766 * @param {string} expression String expression to compile.
17767 * @returns {function(context, locals)} a function which represents the compiled expression:
17769 * * `context` – `{object}` – an object against which any expressions embedded in the strings
17770 * are evaluated against (typically a scope object).
17771 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
17777 * @name $sce#parseAsCss
17780 * Shorthand method. `$sce.parseAsCss(value)` →
17781 * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
17783 * @param {string} expression String expression to compile.
17784 * @returns {function(context, locals)} a function which represents the compiled expression:
17786 * * `context` – `{object}` – an object against which any expressions embedded in the strings
17787 * are evaluated against (typically a scope object).
17788 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
17794 * @name $sce#parseAsUrl
17797 * Shorthand method. `$sce.parseAsUrl(value)` →
17798 * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
17800 * @param {string} expression String expression to compile.
17801 * @returns {function(context, locals)} a function which represents the compiled expression:
17803 * * `context` – `{object}` – an object against which any expressions embedded in the strings
17804 * are evaluated against (typically a scope object).
17805 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
17811 * @name $sce#parseAsResourceUrl
17814 * Shorthand method. `$sce.parseAsResourceUrl(value)` →
17815 * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
17817 * @param {string} expression String expression to compile.
17818 * @returns {function(context, locals)} a function which represents the compiled expression:
17820 * * `context` – `{object}` – an object against which any expressions embedded in the strings
17821 * are evaluated against (typically a scope object).
17822 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
17828 * @name $sce#parseAsJs
17831 * Shorthand method. `$sce.parseAsJs(value)` →
17832 * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
17834 * @param {string} expression String expression to compile.
17835 * @returns {function(context, locals)} a function which represents the compiled expression:
17837 * * `context` – `{object}` – an object against which any expressions embedded in the strings
17838 * are evaluated against (typically a scope object).
17839 * * `locals` – `{object=}` – local variables context object, useful for overriding values in
17843 // Shorthand delegations.
17844 var parse = sce.parseAs,
17845 getTrusted = sce.getTrusted,
17846 trustAs = sce.trustAs;
17848 forEach(SCE_CONTEXTS, function(enumValue, name) {
17849 var lName = lowercase(name);
17850 sce[camelCase("parse_as_" + lName)] = function(expr) {
17851 return parse(enumValue, expr);
17853 sce[camelCase("get_trusted_" + lName)] = function(value) {
17854 return getTrusted(enumValue, value);
17856 sce[camelCase("trust_as_" + lName)] = function(value) {
17857 return trustAs(enumValue, value);
17866 * !!! This is an undocumented "private" service !!!
17869 * @requires $window
17870 * @requires $document
17872 * @property {boolean} history Does the browser support html5 history api ?
17873 * @property {boolean} transitions Does the browser support CSS transition events ?
17874 * @property {boolean} animations Does the browser support CSS animation events ?
17877 * This is very simple implementation of testing browser's features.
17879 function $SnifferProvider() {
17880 this.$get = ['$window', '$document', function($window, $document) {
17881 var eventSupport = {},
17883 toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
17884 boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
17885 document = $document[0] || {},
17887 vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
17888 bodyStyle = document.body && document.body.style,
17889 transitions = false,
17890 animations = false,
17894 for (var prop in bodyStyle) {
17895 if (match = vendorRegex.exec(prop)) {
17896 vendorPrefix = match[0];
17897 vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
17902 if (!vendorPrefix) {
17903 vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
17906 transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
17907 animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
17909 if (android && (!transitions || !animations)) {
17910 transitions = isString(bodyStyle.webkitTransition);
17911 animations = isString(bodyStyle.webkitAnimation);
17917 // Android has history.pushState, but it does not update location correctly
17918 // so let's not use the history API at all.
17919 // http://code.google.com/p/android/issues/detail?id=17471
17920 // https://github.com/angular/angular.js/issues/904
17922 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
17923 // so let's not use the history API also
17924 // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
17926 history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
17928 hasEvent: function(event) {
17929 // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
17930 // it. In particular the event is not fired when backspace or delete key are pressed or
17931 // when cut operation is performed.
17932 // IE10+ implements 'input' event but it erroneously fires under various situations,
17933 // e.g. when placeholder changes, or a form is focused.
17934 if (event === 'input' && msie <= 11) return false;
17936 if (isUndefined(eventSupport[event])) {
17937 var divElm = document.createElement('div');
17938 eventSupport[event] = 'on' + event in divElm;
17941 return eventSupport[event];
17944 vendorPrefix: vendorPrefix,
17945 transitions: transitions,
17946 animations: animations,
17952 var $compileMinErr = minErr('$compile');
17956 * @name $templateRequestProvider
17958 * Used to configure the options passed to the {@link $http} service when making a template request.
17960 * For example, it can be used for specifying the "Accept" header that is sent to the server, when
17961 * requesting a template.
17963 function $TemplateRequestProvider() {
17969 * @name $templateRequestProvider#httpOptions
17971 * The options to be passed to the {@link $http} service when making the request.
17972 * You can use this to override options such as the "Accept" header for template requests.
17974 * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
17975 * options if not overridden here.
17977 * @param {string=} value new value for the {@link $http} options.
17978 * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
17980 this.httpOptions = function(val) {
17985 return httpOptions;
17990 * @name $templateRequest
17993 * The `$templateRequest` service runs security checks then downloads the provided template using
17994 * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
17995 * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
17996 * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
17997 * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
17998 * when `tpl` is of type string and `$templateCache` has the matching entry.
18000 * If you want to pass custom options to the `$http` service, such as setting the Accept header you
18001 * can configure this via {@link $templateRequestProvider#httpOptions}.
18003 * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
18004 * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
18006 * @return {Promise} a promise for the HTTP response data of the given URL.
18008 * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
18010 this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
18012 function handleRequestFn(tpl, ignoreRequestError) {
18013 handleRequestFn.totalPendingRequests++;
18015 // We consider the template cache holds only trusted templates, so
18016 // there's no need to go through whitelisting again for keys that already
18017 // are included in there. This also makes Angular accept any script
18018 // directive, no matter its name. However, we still need to unwrap trusted
18020 if (!isString(tpl) || !$templateCache.get(tpl)) {
18021 tpl = $sce.getTrustedResourceUrl(tpl);
18024 var transformResponse = $http.defaults && $http.defaults.transformResponse;
18026 if (isArray(transformResponse)) {
18027 transformResponse = transformResponse.filter(function(transformer) {
18028 return transformer !== defaultHttpResponseTransform;
18030 } else if (transformResponse === defaultHttpResponseTransform) {
18031 transformResponse = null;
18034 return $http.get(tpl, extend({
18035 cache: $templateCache,
18036 transformResponse: transformResponse
18038 ['finally'](function() {
18039 handleRequestFn.totalPendingRequests--;
18041 .then(function(response) {
18042 $templateCache.put(tpl, response.data);
18043 return response.data;
18046 function handleError(resp) {
18047 if (!ignoreRequestError) {
18048 throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
18049 tpl, resp.status, resp.statusText);
18051 return $q.reject(resp);
18055 handleRequestFn.totalPendingRequests = 0;
18057 return handleRequestFn;
18061 function $$TestabilityProvider() {
18062 this.$get = ['$rootScope', '$browser', '$location',
18063 function($rootScope, $browser, $location) {
18066 * @name $testability
18069 * The private $$testability service provides a collection of methods for use when debugging
18070 * or by automated test and debugging tools.
18072 var testability = {};
18075 * @name $$testability#findBindings
18078 * Returns an array of elements that are bound (via ng-bind or {{}})
18079 * to expressions matching the input.
18081 * @param {Element} element The element root to search from.
18082 * @param {string} expression The binding expression to match.
18083 * @param {boolean} opt_exactMatch If true, only returns exact matches
18084 * for the expression. Filters and whitespace are ignored.
18086 testability.findBindings = function(element, expression, opt_exactMatch) {
18087 var bindings = element.getElementsByClassName('ng-binding');
18089 forEach(bindings, function(binding) {
18090 var dataBinding = angular.element(binding).data('$binding');
18092 forEach(dataBinding, function(bindingName) {
18093 if (opt_exactMatch) {
18094 var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
18095 if (matcher.test(bindingName)) {
18096 matches.push(binding);
18099 if (bindingName.indexOf(expression) != -1) {
18100 matches.push(binding);
18110 * @name $$testability#findModels
18113 * Returns an array of elements that are two-way found via ng-model to
18114 * expressions matching the input.
18116 * @param {Element} element The element root to search from.
18117 * @param {string} expression The model expression to match.
18118 * @param {boolean} opt_exactMatch If true, only returns exact matches
18119 * for the expression.
18121 testability.findModels = function(element, expression, opt_exactMatch) {
18122 var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
18123 for (var p = 0; p < prefixes.length; ++p) {
18124 var attributeEquals = opt_exactMatch ? '=' : '*=';
18125 var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
18126 var elements = element.querySelectorAll(selector);
18127 if (elements.length) {
18134 * @name $$testability#getLocation
18137 * Shortcut for getting the location in a browser agnostic way. Returns
18138 * the path, search, and hash. (e.g. /path?a=b#hash)
18140 testability.getLocation = function() {
18141 return $location.url();
18145 * @name $$testability#setLocation
18148 * Shortcut for navigating to a location without doing a full page reload.
18150 * @param {string} url The location url (path, search and hash,
18151 * e.g. /path?a=b#hash) to go to.
18153 testability.setLocation = function(url) {
18154 if (url !== $location.url()) {
18155 $location.url(url);
18156 $rootScope.$digest();
18161 * @name $$testability#whenStable
18164 * Calls the callback when $timeout and $http requests are completed.
18166 * @param {function} callback
18168 testability.whenStable = function(callback) {
18169 $browser.notifyWhenNoOutstandingRequests(callback);
18172 return testability;
18176 function $TimeoutProvider() {
18177 this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
18178 function($rootScope, $browser, $q, $$q, $exceptionHandler) {
18180 var deferreds = {};
18188 * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
18189 * block and delegates any exceptions to
18190 * {@link ng.$exceptionHandler $exceptionHandler} service.
18192 * The return value of calling `$timeout` is a promise, which will be resolved when
18193 * the delay has passed and the timeout function, if provided, is executed.
18195 * To cancel a timeout request, call `$timeout.cancel(promise)`.
18197 * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
18198 * synchronously flush the queue of deferred functions.
18200 * If you only want a promise that will be resolved after some specified delay
18201 * then you can call `$timeout` without the `fn` function.
18203 * @param {function()=} fn A function, whose execution should be delayed.
18204 * @param {number=} [delay=0] Delay in milliseconds.
18205 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
18206 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
18207 * @param {...*=} Pass additional parameters to the executed function.
18208 * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
18209 * promise will be resolved with is the return value of the `fn` function.
18212 function timeout(fn, delay, invokeApply) {
18213 if (!isFunction(fn)) {
18214 invokeApply = delay;
18219 var args = sliceArgs(arguments, 3),
18220 skipApply = (isDefined(invokeApply) && !invokeApply),
18221 deferred = (skipApply ? $$q : $q).defer(),
18222 promise = deferred.promise,
18225 timeoutId = $browser.defer(function() {
18227 deferred.resolve(fn.apply(null, args));
18229 deferred.reject(e);
18230 $exceptionHandler(e);
18233 delete deferreds[promise.$$timeoutId];
18236 if (!skipApply) $rootScope.$apply();
18239 promise.$$timeoutId = timeoutId;
18240 deferreds[timeoutId] = deferred;
18248 * @name $timeout#cancel
18251 * Cancels a task associated with the `promise`. As a result of this, the promise will be
18252 * resolved with a rejection.
18254 * @param {Promise=} promise Promise returned by the `$timeout` function.
18255 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
18258 timeout.cancel = function(promise) {
18259 if (promise && promise.$$timeoutId in deferreds) {
18260 deferreds[promise.$$timeoutId].reject('canceled');
18261 delete deferreds[promise.$$timeoutId];
18262 return $browser.defer.cancel(promise.$$timeoutId);
18271 // NOTE: The usage of window and document instead of $window and $document here is
18272 // deliberate. This service depends on the specific behavior of anchor nodes created by the
18273 // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
18274 // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
18275 // doesn't know about mocked locations and resolves URLs to the real document - which is
18276 // exactly the behavior needed here. There is little value is mocking these out for this
18278 var urlParsingNode = document.createElement("a");
18279 var originUrl = urlResolve(window.location.href);
18284 * Implementation Notes for non-IE browsers
18285 * ----------------------------------------
18286 * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
18287 * results both in the normalizing and parsing of the URL. Normalizing means that a relative
18288 * URL will be resolved into an absolute URL in the context of the application document.
18289 * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
18290 * properties are all populated to reflect the normalized URL. This approach has wide
18291 * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
18292 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
18294 * Implementation Notes for IE
18295 * ---------------------------
18296 * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
18297 * browsers. However, the parsed components will not be set if the URL assigned did not specify
18298 * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
18299 * work around that by performing the parsing in a 2nd step by taking a previously normalized
18300 * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
18301 * properties such as protocol, hostname, port, etc.
18304 * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
18305 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
18306 * http://url.spec.whatwg.org/#urlutils
18307 * https://github.com/angular/angular.js/pull/2902
18308 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
18311 * @param {string} url The URL to be parsed.
18312 * @description Normalizes and parses a URL.
18313 * @returns {object} Returns the normalized URL as a dictionary.
18315 * | member name | Description |
18316 * |---------------|----------------|
18317 * | href | A normalized version of the provided URL if it was not an absolute URL |
18318 * | protocol | The protocol including the trailing colon |
18319 * | host | The host and port (if the port is non-default) of the normalizedUrl |
18320 * | search | The search params, minus the question mark |
18321 * | hash | The hash string, minus the hash symbol
18322 * | hostname | The hostname
18323 * | port | The port, without ":"
18324 * | pathname | The pathname, beginning with "/"
18327 function urlResolve(url) {
18331 // Normalize before parse. Refer Implementation Notes on why this is
18332 // done in two steps on IE.
18333 urlParsingNode.setAttribute("href", href);
18334 href = urlParsingNode.href;
18337 urlParsingNode.setAttribute('href', href);
18339 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
18341 href: urlParsingNode.href,
18342 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
18343 host: urlParsingNode.host,
18344 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
18345 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
18346 hostname: urlParsingNode.hostname,
18347 port: urlParsingNode.port,
18348 pathname: (urlParsingNode.pathname.charAt(0) === '/')
18349 ? urlParsingNode.pathname
18350 : '/' + urlParsingNode.pathname
18355 * Parse a request URL and determine whether this is a same-origin request as the application document.
18357 * @param {string|object} requestUrl The url of the request as a string that will be resolved
18358 * or a parsed URL object.
18359 * @returns {boolean} Whether the request is for the same origin as the application document.
18361 function urlIsSameOrigin(requestUrl) {
18362 var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
18363 return (parsed.protocol === originUrl.protocol &&
18364 parsed.host === originUrl.host);
18372 * A reference to the browser's `window` object. While `window`
18373 * is globally available in JavaScript, it causes testability problems, because
18374 * it is a global variable. In angular we always refer to it through the
18375 * `$window` service, so it may be overridden, removed or mocked for testing.
18377 * Expressions, like the one defined for the `ngClick` directive in the example
18378 * below, are evaluated with respect to the current scope. Therefore, there is
18379 * no risk of inadvertently coding in a dependency on a global value in such an
18383 <example module="windowExample">
18384 <file name="index.html">
18386 angular.module('windowExample', [])
18387 .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
18388 $scope.greeting = 'Hello, World!';
18389 $scope.doGreeting = function(greeting) {
18390 $window.alert(greeting);
18394 <div ng-controller="ExampleController">
18395 <input type="text" ng-model="greeting" aria-label="greeting" />
18396 <button ng-click="doGreeting(greeting)">ALERT</button>
18399 <file name="protractor.js" type="protractor">
18400 it('should display the greeting in the input box', function() {
18401 element(by.model('greeting')).sendKeys('Hello, E2E Tests');
18402 // If we click the button it will block the test runner
18403 // element(':button').click();
18408 function $WindowProvider() {
18409 this.$get = valueFn(window);
18413 * @name $$cookieReader
18414 * @requires $document
18417 * This is a private service for reading cookies used by $http and ngCookies
18419 * @return {Object} a key/value map of the current cookies
18421 function $$CookieReader($document) {
18422 var rawDocument = $document[0] || {};
18423 var lastCookies = {};
18424 var lastCookieString = '';
18426 function safeDecodeURIComponent(str) {
18428 return decodeURIComponent(str);
18434 return function() {
18435 var cookieArray, cookie, i, index, name;
18436 var currentCookieString = rawDocument.cookie || '';
18438 if (currentCookieString !== lastCookieString) {
18439 lastCookieString = currentCookieString;
18440 cookieArray = lastCookieString.split('; ');
18443 for (i = 0; i < cookieArray.length; i++) {
18444 cookie = cookieArray[i];
18445 index = cookie.indexOf('=');
18446 if (index > 0) { //ignore nameless cookies
18447 name = safeDecodeURIComponent(cookie.substring(0, index));
18448 // the first value that is seen for a cookie is the most
18449 // specific one. values for the same cookie name that
18450 // follow are for less specific paths.
18451 if (isUndefined(lastCookies[name])) {
18452 lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
18457 return lastCookies;
18461 $$CookieReader.$inject = ['$document'];
18463 function $$CookieReaderProvider() {
18464 this.$get = $$CookieReader;
18467 /* global currencyFilter: true,
18469 filterFilter: true,
18471 limitToFilter: true,
18472 lowercaseFilter: true,
18473 numberFilter: true,
18474 orderByFilter: true,
18475 uppercaseFilter: true,
18480 * @name $filterProvider
18483 * Filters are just functions which transform input to an output. However filters need to be
18484 * Dependency Injected. To achieve this a filter definition consists of a factory function which is
18485 * annotated with dependencies and is responsible for creating a filter function.
18487 * <div class="alert alert-warning">
18488 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
18489 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
18490 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
18491 * (`myapp_subsection_filterx`).
18495 * // Filter registration
18496 * function MyModule($provide, $filterProvider) {
18497 * // create a service to demonstrate injection (not always needed)
18498 * $provide.value('greet', function(name){
18499 * return 'Hello ' + name + '!';
18502 * // register a filter factory which uses the
18503 * // greet service to demonstrate DI.
18504 * $filterProvider.register('greet', function(greet){
18505 * // return the filter function which uses the greet service
18506 * // to generate salutation
18507 * return function(text) {
18508 * // filters need to be forgiving so check input validity
18509 * return text && greet(text) || text;
18515 * The filter function is registered with the `$injector` under the filter name suffix with
18519 * it('should be the same instance', inject(
18520 * function($filterProvider) {
18521 * $filterProvider.register('reverse', function(){
18525 * function($filter, reverseFilter) {
18526 * expect($filter('reverse')).toBe(reverseFilter);
18531 * For more information about how angular filters work, and how to create your own filters, see
18532 * {@link guide/filter Filters} in the Angular Developer Guide.
18540 * Filters are used for formatting data displayed to the user.
18542 * The general syntax in templates is as follows:
18544 * {{ expression [| filter_name[:parameter_value] ... ] }}
18546 * @param {String} name Name of the filter function to retrieve
18547 * @return {Function} the filter function
18549 <example name="$filter" module="filterExample">
18550 <file name="index.html">
18551 <div ng-controller="MainCtrl">
18552 <h3>{{ originalText }}</h3>
18553 <h3>{{ filteredText }}</h3>
18557 <file name="script.js">
18558 angular.module('filterExample', [])
18559 .controller('MainCtrl', function($scope, $filter) {
18560 $scope.originalText = 'hello';
18561 $scope.filteredText = $filter('uppercase')($scope.originalText);
18566 $FilterProvider.$inject = ['$provide'];
18567 function $FilterProvider($provide) {
18568 var suffix = 'Filter';
18572 * @name $filterProvider#register
18573 * @param {string|Object} name Name of the filter function, or an object map of filters where
18574 * the keys are the filter names and the values are the filter factories.
18576 * <div class="alert alert-warning">
18577 * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
18578 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
18579 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
18580 * (`myapp_subsection_filterx`).
18582 * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
18583 * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
18584 * of the registered filter instances.
18586 function register(name, factory) {
18587 if (isObject(name)) {
18589 forEach(name, function(filter, key) {
18590 filters[key] = register(key, filter);
18594 return $provide.factory(name + suffix, factory);
18597 this.register = register;
18599 this.$get = ['$injector', function($injector) {
18600 return function(name) {
18601 return $injector.get(name + suffix);
18605 ////////////////////////////////////////
18608 currencyFilter: false,
18610 filterFilter: false,
18612 limitToFilter: false,
18613 lowercaseFilter: false,
18614 numberFilter: false,
18615 orderByFilter: false,
18616 uppercaseFilter: false,
18619 register('currency', currencyFilter);
18620 register('date', dateFilter);
18621 register('filter', filterFilter);
18622 register('json', jsonFilter);
18623 register('limitTo', limitToFilter);
18624 register('lowercase', lowercaseFilter);
18625 register('number', numberFilter);
18626 register('orderBy', orderByFilter);
18627 register('uppercase', uppercaseFilter);
18636 * Selects a subset of items from `array` and returns it as a new array.
18638 * @param {Array} array The source array.
18639 * @param {string|Object|function()} expression The predicate to be used for selecting items from
18644 * - `string`: The string is used for matching against the contents of the `array`. All strings or
18645 * objects with string properties in `array` that match this string will be returned. This also
18646 * applies to nested object properties.
18647 * The predicate can be negated by prefixing the string with `!`.
18649 * - `Object`: A pattern object can be used to filter specific properties on objects contained
18650 * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
18651 * which have property `name` containing "M" and property `phone` containing "1". A special
18652 * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
18653 * property of the object or its nested object properties. That's equivalent to the simple
18654 * substring match with a `string` as described above. The predicate can be negated by prefixing
18655 * the string with `!`.
18656 * For example `{name: "!M"}` predicate will return an array of items which have property `name`
18657 * not containing "M".
18659 * Note that a named property will match properties on the same level only, while the special
18660 * `$` property will match properties on the same level or deeper. E.g. an array item like
18661 * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
18662 * **will** be matched by `{$: 'John'}`.
18664 * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
18665 * The function is called for each element of the array, with the element, its index, and
18666 * the entire array itself as arguments.
18668 * The final result is an array of those elements that the predicate returned true for.
18670 * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
18671 * determining if the expected value (from the filter expression) and actual value (from
18672 * the object in the array) should be considered a match.
18676 * - `function(actual, expected)`:
18677 * The function will be given the object value and the predicate value to compare and
18678 * should return true if both values should be considered equal.
18680 * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
18681 * This is essentially strict comparison of expected and actual.
18683 * - `false|undefined`: A short hand for a function which will look for a substring match in case
18686 * Primitive values are converted to strings. Objects are not compared against primitives,
18687 * unless they have a custom `toString` method (e.g. `Date` objects).
18691 <file name="index.html">
18692 <div ng-init="friends = [{name:'John', phone:'555-1276'},
18693 {name:'Mary', phone:'800-BIG-MARY'},
18694 {name:'Mike', phone:'555-4321'},
18695 {name:'Adam', phone:'555-5678'},
18696 {name:'Julie', phone:'555-8765'},
18697 {name:'Juliette', phone:'555-5678'}]"></div>
18699 <label>Search: <input ng-model="searchText"></label>
18700 <table id="searchTextResults">
18701 <tr><th>Name</th><th>Phone</th></tr>
18702 <tr ng-repeat="friend in friends | filter:searchText">
18703 <td>{{friend.name}}</td>
18704 <td>{{friend.phone}}</td>
18708 <label>Any: <input ng-model="search.$"></label> <br>
18709 <label>Name only <input ng-model="search.name"></label><br>
18710 <label>Phone only <input ng-model="search.phone"></label><br>
18711 <label>Equality <input type="checkbox" ng-model="strict"></label><br>
18712 <table id="searchObjResults">
18713 <tr><th>Name</th><th>Phone</th></tr>
18714 <tr ng-repeat="friendObj in friends | filter:search:strict">
18715 <td>{{friendObj.name}}</td>
18716 <td>{{friendObj.phone}}</td>
18720 <file name="protractor.js" type="protractor">
18721 var expectFriendNames = function(expectedNames, key) {
18722 element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
18723 arr.forEach(function(wd, i) {
18724 expect(wd.getText()).toMatch(expectedNames[i]);
18729 it('should search across all fields when filtering with a string', function() {
18730 var searchText = element(by.model('searchText'));
18731 searchText.clear();
18732 searchText.sendKeys('m');
18733 expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
18735 searchText.clear();
18736 searchText.sendKeys('76');
18737 expectFriendNames(['John', 'Julie'], 'friend');
18740 it('should search in specific fields when filtering with a predicate object', function() {
18741 var searchAny = element(by.model('search.$'));
18743 searchAny.sendKeys('i');
18744 expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
18746 it('should use a equal comparison when comparator is true', function() {
18747 var searchName = element(by.model('search.name'));
18748 var strict = element(by.model('strict'));
18749 searchName.clear();
18750 searchName.sendKeys('Julie');
18752 expectFriendNames(['Julie'], 'friendObj');
18757 function filterFilter() {
18758 return function(array, expression, comparator) {
18759 if (!isArrayLike(array)) {
18760 if (array == null) {
18763 throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
18767 var expressionType = getTypeForFilter(expression);
18769 var matchAgainstAnyProp;
18771 switch (expressionType) {
18773 predicateFn = expression;
18779 matchAgainstAnyProp = true;
18783 predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
18789 return Array.prototype.filter.call(array, predicateFn);
18793 // Helper functions for `filterFilter`
18794 function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
18795 var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
18798 if (comparator === true) {
18799 comparator = equals;
18800 } else if (!isFunction(comparator)) {
18801 comparator = function(actual, expected) {
18802 if (isUndefined(actual)) {
18803 // No substring matching against `undefined`
18806 if ((actual === null) || (expected === null)) {
18807 // No substring matching against `null`; only match against `null`
18808 return actual === expected;
18810 if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
18811 // Should not compare primitives against objects, unless they have custom `toString` method
18815 actual = lowercase('' + actual);
18816 expected = lowercase('' + expected);
18817 return actual.indexOf(expected) !== -1;
18821 predicateFn = function(item) {
18822 if (shouldMatchPrimitives && !isObject(item)) {
18823 return deepCompare(item, expression.$, comparator, false);
18825 return deepCompare(item, expression, comparator, matchAgainstAnyProp);
18828 return predicateFn;
18831 function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
18832 var actualType = getTypeForFilter(actual);
18833 var expectedType = getTypeForFilter(expected);
18835 if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
18836 return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
18837 } else if (isArray(actual)) {
18838 // In case `actual` is an array, consider it a match
18839 // if ANY of it's items matches `expected`
18840 return actual.some(function(item) {
18841 return deepCompare(item, expected, comparator, matchAgainstAnyProp);
18845 switch (actualType) {
18848 if (matchAgainstAnyProp) {
18849 for (key in actual) {
18850 if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
18854 return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
18855 } else if (expectedType === 'object') {
18856 for (key in expected) {
18857 var expectedVal = expected[key];
18858 if (isFunction(expectedVal) || isUndefined(expectedVal)) {
18862 var matchAnyProperty = key === '$';
18863 var actualVal = matchAnyProperty ? actual : actual[key];
18864 if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
18870 return comparator(actual, expected);
18876 return comparator(actual, expected);
18880 // Used for easily differentiating between `null` and actual `object`
18881 function getTypeForFilter(val) {
18882 return (val === null) ? 'null' : typeof val;
18891 * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
18892 * symbol for current locale is used.
18894 * @param {number} amount Input to filter.
18895 * @param {string=} symbol Currency symbol or identifier to be displayed.
18896 * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
18897 * @returns {string} Formatted number.
18901 <example module="currencyExample">
18902 <file name="index.html">
18904 angular.module('currencyExample', [])
18905 .controller('ExampleController', ['$scope', function($scope) {
18906 $scope.amount = 1234.56;
18909 <div ng-controller="ExampleController">
18910 <input type="number" ng-model="amount" aria-label="amount"> <br>
18911 default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
18912 custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
18913 no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
18916 <file name="protractor.js" type="protractor">
18917 it('should init with 1234.56', function() {
18918 expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
18919 expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
18920 expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
18922 it('should update', function() {
18923 if (browser.params.browser == 'safari') {
18924 // Safari does not understand the minus key. See
18925 // https://github.com/angular/protractor/issues/481
18928 element(by.model('amount')).clear();
18929 element(by.model('amount')).sendKeys('-1234');
18930 expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
18931 expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
18932 expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
18937 currencyFilter.$inject = ['$locale'];
18938 function currencyFilter($locale) {
18939 var formats = $locale.NUMBER_FORMATS;
18940 return function(amount, currencySymbol, fractionSize) {
18941 if (isUndefined(currencySymbol)) {
18942 currencySymbol = formats.CURRENCY_SYM;
18945 if (isUndefined(fractionSize)) {
18946 fractionSize = formats.PATTERNS[1].maxFrac;
18949 // if null or undefined pass it through
18950 return (amount == null)
18952 : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
18953 replace(/\u00A4/g, currencySymbol);
18963 * Formats a number as text.
18965 * If the input is null or undefined, it will just be returned.
18966 * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
18967 * If the input is not a number an empty string is returned.
18970 * @param {number|string} number Number to format.
18971 * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
18972 * If this is not provided then the fraction size is computed from the current locale's number
18973 * formatting pattern. In the case of the default locale, it will be 3.
18974 * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
18977 <example module="numberFilterExample">
18978 <file name="index.html">
18980 angular.module('numberFilterExample', [])
18981 .controller('ExampleController', ['$scope', function($scope) {
18982 $scope.val = 1234.56789;
18985 <div ng-controller="ExampleController">
18986 <label>Enter number: <input ng-model='val'></label><br>
18987 Default formatting: <span id='number-default'>{{val | number}}</span><br>
18988 No fractions: <span>{{val | number:0}}</span><br>
18989 Negative number: <span>{{-val | number:4}}</span>
18992 <file name="protractor.js" type="protractor">
18993 it('should format numbers', function() {
18994 expect(element(by.id('number-default')).getText()).toBe('1,234.568');
18995 expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
18996 expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
18999 it('should update', function() {
19000 element(by.model('val')).clear();
19001 element(by.model('val')).sendKeys('3374.333');
19002 expect(element(by.id('number-default')).getText()).toBe('3,374.333');
19003 expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
19004 expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
19011 numberFilter.$inject = ['$locale'];
19012 function numberFilter($locale) {
19013 var formats = $locale.NUMBER_FORMATS;
19014 return function(number, fractionSize) {
19016 // if null or undefined pass it through
19017 return (number == null)
19019 : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
19024 var DECIMAL_SEP = '.';
19025 function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
19026 if (isObject(number)) return '';
19028 var isNegative = number < 0;
19029 number = Math.abs(number);
19031 var isInfinity = number === Infinity;
19032 if (!isInfinity && !isFinite(number)) return '';
19034 var numStr = number + '',
19036 hasExponent = false,
19039 if (isInfinity) formatedText = '\u221e';
19041 if (!isInfinity && numStr.indexOf('e') !== -1) {
19042 var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
19043 if (match && match[2] == '-' && match[3] > fractionSize + 1) {
19046 formatedText = numStr;
19047 hasExponent = true;
19051 if (!isInfinity && !hasExponent) {
19052 var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
19054 // determine fractionSize if it is not specified
19055 if (isUndefined(fractionSize)) {
19056 fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
19059 // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
19061 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
19062 number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
19064 var fraction = ('' + number).split(DECIMAL_SEP);
19065 var whole = fraction[0];
19066 fraction = fraction[1] || '';
19069 lgroup = pattern.lgSize,
19070 group = pattern.gSize;
19072 if (whole.length >= (lgroup + group)) {
19073 pos = whole.length - lgroup;
19074 for (i = 0; i < pos; i++) {
19075 if ((pos - i) % group === 0 && i !== 0) {
19076 formatedText += groupSep;
19078 formatedText += whole.charAt(i);
19082 for (i = pos; i < whole.length; i++) {
19083 if ((whole.length - i) % lgroup === 0 && i !== 0) {
19084 formatedText += groupSep;
19086 formatedText += whole.charAt(i);
19089 // format fraction part.
19090 while (fraction.length < fractionSize) {
19094 if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
19096 if (fractionSize > 0 && number < 1) {
19097 formatedText = number.toFixed(fractionSize);
19098 number = parseFloat(formatedText);
19099 formatedText = formatedText.replace(DECIMAL_SEP, decimalSep);
19103 if (number === 0) {
19104 isNegative = false;
19107 parts.push(isNegative ? pattern.negPre : pattern.posPre,
19109 isNegative ? pattern.negSuf : pattern.posSuf);
19110 return parts.join('');
19113 function padNumber(num, digits, trim) {
19120 while (num.length < digits) num = '0' + num;
19122 num = num.substr(num.length - digits);
19128 function dateGetter(name, size, offset, trim) {
19129 offset = offset || 0;
19130 return function(date) {
19131 var value = date['get' + name]();
19132 if (offset > 0 || value > -offset) {
19135 if (value === 0 && offset == -12) value = 12;
19136 return padNumber(value, size, trim);
19140 function dateStrGetter(name, shortForm) {
19141 return function(date, formats) {
19142 var value = date['get' + name]();
19143 var get = uppercase(shortForm ? ('SHORT' + name) : name);
19145 return formats[get][value];
19149 function timeZoneGetter(date, formats, offset) {
19150 var zone = -1 * offset;
19151 var paddedZone = (zone >= 0) ? "+" : "";
19153 paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
19154 padNumber(Math.abs(zone % 60), 2);
19159 function getFirstThursdayOfYear(year) {
19160 // 0 = index of January
19161 var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
19162 // 4 = index of Thursday (+1 to account for 1st = 5)
19163 // 11 = index of *next* Thursday (+1 account for 1st = 12)
19164 return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
19167 function getThursdayThisWeek(datetime) {
19168 return new Date(datetime.getFullYear(), datetime.getMonth(),
19169 // 4 = index of Thursday
19170 datetime.getDate() + (4 - datetime.getDay()));
19173 function weekGetter(size) {
19174 return function(date) {
19175 var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
19176 thisThurs = getThursdayThisWeek(date);
19178 var diff = +thisThurs - +firstThurs,
19179 result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
19181 return padNumber(result, size);
19185 function ampmGetter(date, formats) {
19186 return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
19189 function eraGetter(date, formats) {
19190 return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
19193 function longEraGetter(date, formats) {
19194 return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
19197 var DATE_FORMATS = {
19198 yyyy: dateGetter('FullYear', 4),
19199 yy: dateGetter('FullYear', 2, 0, true),
19200 y: dateGetter('FullYear', 1),
19201 MMMM: dateStrGetter('Month'),
19202 MMM: dateStrGetter('Month', true),
19203 MM: dateGetter('Month', 2, 1),
19204 M: dateGetter('Month', 1, 1),
19205 dd: dateGetter('Date', 2),
19206 d: dateGetter('Date', 1),
19207 HH: dateGetter('Hours', 2),
19208 H: dateGetter('Hours', 1),
19209 hh: dateGetter('Hours', 2, -12),
19210 h: dateGetter('Hours', 1, -12),
19211 mm: dateGetter('Minutes', 2),
19212 m: dateGetter('Minutes', 1),
19213 ss: dateGetter('Seconds', 2),
19214 s: dateGetter('Seconds', 1),
19215 // while ISO 8601 requires fractions to be prefixed with `.` or `,`
19216 // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
19217 sss: dateGetter('Milliseconds', 3),
19218 EEEE: dateStrGetter('Day'),
19219 EEE: dateStrGetter('Day', true),
19227 GGGG: longEraGetter
19230 var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
19231 NUMBER_STRING = /^\-?\d+$/;
19239 * Formats `date` to a string based on the requested `format`.
19241 * `format` string can be composed of the following elements:
19243 * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
19244 * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
19245 * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
19246 * * `'MMMM'`: Month in year (January-December)
19247 * * `'MMM'`: Month in year (Jan-Dec)
19248 * * `'MM'`: Month in year, padded (01-12)
19249 * * `'M'`: Month in year (1-12)
19250 * * `'dd'`: Day in month, padded (01-31)
19251 * * `'d'`: Day in month (1-31)
19252 * * `'EEEE'`: Day in Week,(Sunday-Saturday)
19253 * * `'EEE'`: Day in Week, (Sun-Sat)
19254 * * `'HH'`: Hour in day, padded (00-23)
19255 * * `'H'`: Hour in day (0-23)
19256 * * `'hh'`: Hour in AM/PM, padded (01-12)
19257 * * `'h'`: Hour in AM/PM, (1-12)
19258 * * `'mm'`: Minute in hour, padded (00-59)
19259 * * `'m'`: Minute in hour (0-59)
19260 * * `'ss'`: Second in minute, padded (00-59)
19261 * * `'s'`: Second in minute (0-59)
19262 * * `'sss'`: Millisecond in second, padded (000-999)
19263 * * `'a'`: AM/PM marker
19264 * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
19265 * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
19266 * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
19267 * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
19268 * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
19270 * `format` string can also be one of the following predefined
19271 * {@link guide/i18n localizable formats}:
19273 * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
19274 * (e.g. Sep 3, 2010 12:05:08 PM)
19275 * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
19276 * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
19277 * (e.g. Friday, September 3, 2010)
19278 * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
19279 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
19280 * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
19281 * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
19282 * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
19284 * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
19285 * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
19286 * (e.g. `"h 'o''clock'"`).
19288 * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
19289 * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
19290 * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
19291 * specified in the string input, the time is considered to be in the local timezone.
19292 * @param {string=} format Formatting rules (see Description). If not specified,
19293 * `mediumDate` is used.
19294 * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
19295 * continental US time zone abbreviations, but for general use, use a time zone offset, for
19296 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
19297 * If not specified, the timezone of the browser will be used.
19298 * @returns {string} Formatted string or the input if input is not recognized as date/millis.
19302 <file name="index.html">
19303 <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
19304 <span>{{1288323623006 | date:'medium'}}</span><br>
19305 <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
19306 <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
19307 <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
19308 <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
19309 <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
19310 <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
19312 <file name="protractor.js" type="protractor">
19313 it('should format date', function() {
19314 expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
19315 toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
19316 expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
19317 toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
19318 expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
19319 toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
19320 expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
19321 toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
19326 dateFilter.$inject = ['$locale'];
19327 function dateFilter($locale) {
19330 var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
19331 // 1 2 3 4 5 6 7 8 9 10 11
19332 function jsonStringToDate(string) {
19334 if (match = string.match(R_ISO8601_STR)) {
19335 var date = new Date(0),
19338 dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
19339 timeSetter = match[8] ? date.setUTCHours : date.setHours;
19342 tzHour = toInt(match[9] + match[10]);
19343 tzMin = toInt(match[9] + match[11]);
19345 dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
19346 var h = toInt(match[4] || 0) - tzHour;
19347 var m = toInt(match[5] || 0) - tzMin;
19348 var s = toInt(match[6] || 0);
19349 var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
19350 timeSetter.call(date, h, m, s, ms);
19357 return function(date, format, timezone) {
19362 format = format || 'mediumDate';
19363 format = $locale.DATETIME_FORMATS[format] || format;
19364 if (isString(date)) {
19365 date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
19368 if (isNumber(date)) {
19369 date = new Date(date);
19372 if (!isDate(date) || !isFinite(date.getTime())) {
19377 match = DATE_FORMATS_SPLIT.exec(format);
19379 parts = concat(parts, match, 1);
19380 format = parts.pop();
19382 parts.push(format);
19387 var dateTimezoneOffset = date.getTimezoneOffset();
19389 dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
19390 date = convertTimezoneToLocal(date, timezone, true);
19392 forEach(parts, function(value) {
19393 fn = DATE_FORMATS[value];
19394 text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
19395 : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
19409 * Allows you to convert a JavaScript object into JSON string.
19411 * This filter is mostly useful for debugging. When using the double curly {{value}} notation
19412 * the binding is automatically converted to JSON.
19414 * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
19415 * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
19416 * @returns {string} JSON string.
19421 <file name="index.html">
19422 <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
19423 <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
19425 <file name="protractor.js" type="protractor">
19426 it('should jsonify filtered objects', function() {
19427 expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
19428 expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
19434 function jsonFilter() {
19435 return function(object, spacing) {
19436 if (isUndefined(spacing)) {
19439 return toJson(object, spacing);
19449 * Converts string to lowercase.
19450 * @see angular.lowercase
19452 var lowercaseFilter = valueFn(lowercase);
19460 * Converts string to uppercase.
19461 * @see angular.uppercase
19463 var uppercaseFilter = valueFn(uppercase);
19471 * Creates a new array or string containing only a specified number of elements. The elements
19472 * are taken from either the beginning or the end of the source array, string or number, as specified by
19473 * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
19474 * converted to a string.
19476 * @param {Array|string|number} input Source array, string or number to be limited.
19477 * @param {string|number} limit The length of the returned array or string. If the `limit` number
19478 * is positive, `limit` number of items from the beginning of the source array/string are copied.
19479 * If the number is negative, `limit` number of items from the end of the source array/string
19480 * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
19481 * the input will be returned unchanged.
19482 * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
19483 * indicates an offset from the end of `input`. Defaults to `0`.
19484 * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
19485 * had less than `limit` elements.
19488 <example module="limitToExample">
19489 <file name="index.html">
19491 angular.module('limitToExample', [])
19492 .controller('ExampleController', ['$scope', function($scope) {
19493 $scope.numbers = [1,2,3,4,5,6,7,8,9];
19494 $scope.letters = "abcdefghi";
19495 $scope.longNumber = 2345432342;
19496 $scope.numLimit = 3;
19497 $scope.letterLimit = 3;
19498 $scope.longNumberLimit = 3;
19501 <div ng-controller="ExampleController">
19503 Limit {{numbers}} to:
19504 <input type="number" step="1" ng-model="numLimit">
19506 <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
19508 Limit {{letters}} to:
19509 <input type="number" step="1" ng-model="letterLimit">
19511 <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
19513 Limit {{longNumber}} to:
19514 <input type="number" step="1" ng-model="longNumberLimit">
19516 <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
19519 <file name="protractor.js" type="protractor">
19520 var numLimitInput = element(by.model('numLimit'));
19521 var letterLimitInput = element(by.model('letterLimit'));
19522 var longNumberLimitInput = element(by.model('longNumberLimit'));
19523 var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
19524 var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
19525 var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
19527 it('should limit the number array to first three items', function() {
19528 expect(numLimitInput.getAttribute('value')).toBe('3');
19529 expect(letterLimitInput.getAttribute('value')).toBe('3');
19530 expect(longNumberLimitInput.getAttribute('value')).toBe('3');
19531 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
19532 expect(limitedLetters.getText()).toEqual('Output letters: abc');
19533 expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
19536 // There is a bug in safari and protractor that doesn't like the minus key
19537 // it('should update the output when -3 is entered', function() {
19538 // numLimitInput.clear();
19539 // numLimitInput.sendKeys('-3');
19540 // letterLimitInput.clear();
19541 // letterLimitInput.sendKeys('-3');
19542 // longNumberLimitInput.clear();
19543 // longNumberLimitInput.sendKeys('-3');
19544 // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
19545 // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
19546 // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
19549 it('should not exceed the maximum size of input array', function() {
19550 numLimitInput.clear();
19551 numLimitInput.sendKeys('100');
19552 letterLimitInput.clear();
19553 letterLimitInput.sendKeys('100');
19554 longNumberLimitInput.clear();
19555 longNumberLimitInput.sendKeys('100');
19556 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
19557 expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
19558 expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
19563 function limitToFilter() {
19564 return function(input, limit, begin) {
19565 if (Math.abs(Number(limit)) === Infinity) {
19566 limit = Number(limit);
19568 limit = toInt(limit);
19570 if (isNaN(limit)) return input;
19572 if (isNumber(input)) input = input.toString();
19573 if (!isArray(input) && !isString(input)) return input;
19575 begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
19576 begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
19579 return input.slice(begin, begin + limit);
19582 return input.slice(limit, input.length);
19584 return input.slice(Math.max(0, begin + limit), begin);
19596 * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
19597 * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
19598 * as expected, make sure they are actually being saved as numbers and not strings.
19599 * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
19601 * @param {Array} array The array (or array-like object) to sort.
19602 * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
19603 * used by the comparator to determine the order of elements.
19607 * - `function`: Getter function. The result of this function will be sorted using the
19608 * `<`, `===`, `>` operator.
19609 * - `string`: An Angular expression. The result of this expression is used to compare elements
19610 * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
19611 * 3 first characters of a property called `name`). The result of a constant expression
19612 * is interpreted as a property name to be used in comparisons (for example `"special name"`
19613 * to sort object by the value of their `special name` property). An expression can be
19614 * optionally prefixed with `+` or `-` to control ascending or descending sort order
19615 * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
19616 * element itself is used to compare where sorting.
19617 * - `Array`: An array of function or string predicates. The first predicate in the array
19618 * is used for sorting, but when two items are equivalent, the next predicate is used.
19620 * If the predicate is missing or empty then it defaults to `'+'`.
19622 * @param {boolean=} reverse Reverse the order of the array.
19623 * @returns {Array} Sorted copy of the source array.
19627 * The example below demonstrates a simple ngRepeat, where the data is sorted
19628 * by age in descending order (predicate is set to `'-age'`).
19629 * `reverse` is not set, which means it defaults to `false`.
19630 <example module="orderByExample">
19631 <file name="index.html">
19633 angular.module('orderByExample', [])
19634 .controller('ExampleController', ['$scope', function($scope) {
19636 [{name:'John', phone:'555-1212', age:10},
19637 {name:'Mary', phone:'555-9876', age:19},
19638 {name:'Mike', phone:'555-4321', age:21},
19639 {name:'Adam', phone:'555-5678', age:35},
19640 {name:'Julie', phone:'555-8765', age:29}];
19643 <div ng-controller="ExampleController">
19644 <table class="friend">
19647 <th>Phone Number</th>
19650 <tr ng-repeat="friend in friends | orderBy:'-age'">
19651 <td>{{friend.name}}</td>
19652 <td>{{friend.phone}}</td>
19653 <td>{{friend.age}}</td>
19660 * The predicate and reverse parameters can be controlled dynamically through scope properties,
19661 * as shown in the next example.
19663 <example module="orderByExample">
19664 <file name="index.html">
19666 angular.module('orderByExample', [])
19667 .controller('ExampleController', ['$scope', function($scope) {
19669 [{name:'John', phone:'555-1212', age:10},
19670 {name:'Mary', phone:'555-9876', age:19},
19671 {name:'Mike', phone:'555-4321', age:21},
19672 {name:'Adam', phone:'555-5678', age:35},
19673 {name:'Julie', phone:'555-8765', age:29}];
19674 $scope.predicate = 'age';
19675 $scope.reverse = true;
19676 $scope.order = function(predicate) {
19677 $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
19678 $scope.predicate = predicate;
19682 <style type="text/css">
19686 .sortorder.reverse:after {
19690 <div ng-controller="ExampleController">
19691 <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
19693 [ <a href="" ng-click="predicate=''">unsorted</a> ]
19694 <table class="friend">
19697 <a href="" ng-click="order('name')">Name</a>
19698 <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
19701 <a href="" ng-click="order('phone')">Phone Number</a>
19702 <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
19705 <a href="" ng-click="order('age')">Age</a>
19706 <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
19709 <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
19710 <td>{{friend.name}}</td>
19711 <td>{{friend.phone}}</td>
19712 <td>{{friend.age}}</td>
19719 * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
19720 * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
19721 * desired parameters.
19726 <example module="orderByExample">
19727 <file name="index.html">
19728 <div ng-controller="ExampleController">
19729 <table class="friend">
19731 <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
19732 (<a href="" ng-click="order('-name',false)">^</a>)</th>
19733 <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
19734 <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
19736 <tr ng-repeat="friend in friends">
19737 <td>{{friend.name}}</td>
19738 <td>{{friend.phone}}</td>
19739 <td>{{friend.age}}</td>
19745 <file name="script.js">
19746 angular.module('orderByExample', [])
19747 .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
19748 var orderBy = $filter('orderBy');
19750 { name: 'John', phone: '555-1212', age: 10 },
19751 { name: 'Mary', phone: '555-9876', age: 19 },
19752 { name: 'Mike', phone: '555-4321', age: 21 },
19753 { name: 'Adam', phone: '555-5678', age: 35 },
19754 { name: 'Julie', phone: '555-8765', age: 29 }
19756 $scope.order = function(predicate, reverse) {
19757 $scope.friends = orderBy($scope.friends, predicate, reverse);
19759 $scope.order('-age',false);
19764 orderByFilter.$inject = ['$parse'];
19765 function orderByFilter($parse) {
19766 return function(array, sortPredicate, reverseOrder) {
19768 if (array == null) return array;
19769 if (!isArrayLike(array)) {
19770 throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
19773 if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
19774 if (sortPredicate.length === 0) { sortPredicate = ['+']; }
19776 var predicates = processPredicates(sortPredicate, reverseOrder);
19777 // Add a predicate at the end that evaluates to the element index. This makes the
19778 // sort stable as it works as a tie-breaker when all the input predicates cannot
19779 // distinguish between two elements.
19780 predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
19782 // The next three lines are a version of a Swartzian Transform idiom from Perl
19783 // (sometimes called the Decorate-Sort-Undecorate idiom)
19784 // See https://en.wikipedia.org/wiki/Schwartzian_transform
19785 var compareValues = Array.prototype.map.call(array, getComparisonObject);
19786 compareValues.sort(doComparison);
19787 array = compareValues.map(function(item) { return item.value; });
19791 function getComparisonObject(value, index) {
19794 predicateValues: predicates.map(function(predicate) {
19795 return getPredicateValue(predicate.get(value), index);
19800 function doComparison(v1, v2) {
19802 for (var index=0, length = predicates.length; index < length; ++index) {
19803 result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
19810 function processPredicates(sortPredicate, reverseOrder) {
19811 reverseOrder = reverseOrder ? -1 : 1;
19812 return sortPredicate.map(function(predicate) {
19813 var descending = 1, get = identity;
19815 if (isFunction(predicate)) {
19817 } else if (isString(predicate)) {
19818 if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
19819 descending = predicate.charAt(0) == '-' ? -1 : 1;
19820 predicate = predicate.substring(1);
19822 if (predicate !== '') {
19823 get = $parse(predicate);
19824 if (get.constant) {
19826 get = function(value) { return value[key]; };
19830 return { get: get, descending: descending * reverseOrder };
19834 function isPrimitive(value) {
19835 switch (typeof value) {
19836 case 'number': /* falls through */
19837 case 'boolean': /* falls through */
19845 function objectValue(value, index) {
19846 // If `valueOf` is a valid function use that
19847 if (typeof value.valueOf === 'function') {
19848 value = value.valueOf();
19849 if (isPrimitive(value)) return value;
19851 // If `toString` is a valid function and not the one from `Object.prototype` use that
19852 if (hasCustomToString(value)) {
19853 value = value.toString();
19854 if (isPrimitive(value)) return value;
19856 // We have a basic object so we use the position of the object in the collection
19860 function getPredicateValue(value, index) {
19861 var type = typeof value;
19862 if (value === null) {
19865 } else if (type === 'string') {
19866 value = value.toLowerCase();
19867 } else if (type === 'object') {
19868 value = objectValue(value, index);
19870 return { value: value, type: type };
19873 function compare(v1, v2) {
19875 if (v1.type === v2.type) {
19876 if (v1.value !== v2.value) {
19877 result = v1.value < v2.value ? -1 : 1;
19880 result = v1.type < v2.type ? -1 : 1;
19886 function ngDirective(directive) {
19887 if (isFunction(directive)) {
19892 directive.restrict = directive.restrict || 'AC';
19893 return valueFn(directive);
19902 * Modifies the default behavior of the html A tag so that the default action is prevented when
19903 * the href attribute is empty.
19905 * This change permits the easy creation of action links with the `ngClick` directive
19906 * without changing the location or causing page reloads, e.g.:
19907 * `<a href="" ng-click="list.addItem()">Add Item</a>`
19909 var htmlAnchorDirective = valueFn({
19911 compile: function(element, attr) {
19912 if (!attr.href && !attr.xlinkHref) {
19913 return function(scope, element) {
19914 // If the linked element is not an anchor tag anymore, do nothing
19915 if (element[0].nodeName.toLowerCase() !== 'a') return;
19917 // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
19918 var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
19919 'xlink:href' : 'href';
19920 element.on('click', function(event) {
19921 // if we have no href url, then don't navigate anywhere.
19922 if (!element.attr(href)) {
19923 event.preventDefault();
19938 * Using Angular markup like `{{hash}}` in an href attribute will
19939 * make the link go to the wrong URL if the user clicks it before
19940 * Angular has a chance to replace the `{{hash}}` markup with its
19941 * value. Until Angular replaces the markup the link will be broken
19942 * and will most likely return a 404 error. The `ngHref` directive
19943 * solves this problem.
19945 * The wrong way to write it:
19947 * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
19950 * The correct way to write it:
19952 * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
19956 * @param {template} ngHref any string which can contain `{{}}` markup.
19959 * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
19960 * in links and their different behaviors:
19962 <file name="index.html">
19963 <input ng-model="value" /><br />
19964 <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
19965 <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
19966 <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
19967 <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
19968 <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
19969 <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
19971 <file name="protractor.js" type="protractor">
19972 it('should execute ng-click but not reload when href without value', function() {
19973 element(by.id('link-1')).click();
19974 expect(element(by.model('value')).getAttribute('value')).toEqual('1');
19975 expect(element(by.id('link-1')).getAttribute('href')).toBe('');
19978 it('should execute ng-click but not reload when href empty string', function() {
19979 element(by.id('link-2')).click();
19980 expect(element(by.model('value')).getAttribute('value')).toEqual('2');
19981 expect(element(by.id('link-2')).getAttribute('href')).toBe('');
19984 it('should execute ng-click and change url when ng-href specified', function() {
19985 expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
19987 element(by.id('link-3')).click();
19989 // At this point, we navigate away from an Angular page, so we need
19990 // to use browser.driver to get the base webdriver.
19992 browser.wait(function() {
19993 return browser.driver.getCurrentUrl().then(function(url) {
19994 return url.match(/\/123$/);
19996 }, 5000, 'page should navigate to /123');
19999 it('should execute ng-click but not reload when href empty string and name specified', function() {
20000 element(by.id('link-4')).click();
20001 expect(element(by.model('value')).getAttribute('value')).toEqual('4');
20002 expect(element(by.id('link-4')).getAttribute('href')).toBe('');
20005 it('should execute ng-click but not reload when no href but name specified', function() {
20006 element(by.id('link-5')).click();
20007 expect(element(by.model('value')).getAttribute('value')).toEqual('5');
20008 expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
20011 it('should only change url when only ng-href', function() {
20012 element(by.model('value')).clear();
20013 element(by.model('value')).sendKeys('6');
20014 expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
20016 element(by.id('link-6')).click();
20018 // At this point, we navigate away from an Angular page, so we need
20019 // to use browser.driver to get the base webdriver.
20020 browser.wait(function() {
20021 return browser.driver.getCurrentUrl().then(function(url) {
20022 return url.match(/\/6$/);
20024 }, 5000, 'page should navigate to /6');
20037 * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
20038 * work right: The browser will fetch from the URL with the literal
20039 * text `{{hash}}` until Angular replaces the expression inside
20040 * `{{hash}}`. The `ngSrc` directive solves this problem.
20042 * The buggy way to write it:
20044 * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
20047 * The correct way to write it:
20049 * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
20053 * @param {template} ngSrc any string which can contain `{{}}` markup.
20063 * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
20064 * work right: The browser will fetch from the URL with the literal
20065 * text `{{hash}}` until Angular replaces the expression inside
20066 * `{{hash}}`. The `ngSrcset` directive solves this problem.
20068 * The buggy way to write it:
20070 * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
20073 * The correct way to write it:
20075 * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
20079 * @param {template} ngSrcset any string which can contain `{{}}` markup.
20090 * This directive sets the `disabled` attribute on the element if the
20091 * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
20093 * A special directive is necessary because we cannot use interpolation inside the `disabled`
20094 * attribute. The following example would make the button enabled on Chrome/Firefox
20095 * but not on older IEs:
20098 * <!-- See below for an example of ng-disabled being used correctly -->
20099 * <div ng-init="isDisabled = false">
20100 * <button disabled="{{isDisabled}}">Disabled</button>
20104 * This is because the HTML specification does not require browsers to preserve the values of
20105 * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
20106 * If we put an Angular interpolation expression into such an attribute then the
20107 * binding information would be lost when the browser removes the attribute.
20111 <file name="index.html">
20112 <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
20113 <button ng-model="button" ng-disabled="checked">Button</button>
20115 <file name="protractor.js" type="protractor">
20116 it('should toggle button', function() {
20117 expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
20118 element(by.model('checked')).click();
20119 expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
20125 * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
20126 * then the `disabled` attribute will be set on the element
20137 * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
20139 * Note that this directive should not be used together with {@link ngModel `ngModel`},
20140 * as this can lead to unexpected behavior.
20142 * ### Why do we need `ngChecked`?
20144 * The HTML specification does not require browsers to preserve the values of boolean attributes
20145 * such as checked. (Their presence means true and their absence means false.)
20146 * If we put an Angular interpolation expression into such an attribute then the
20147 * binding information would be lost when the browser removes the attribute.
20148 * The `ngChecked` directive solves this problem for the `checked` attribute.
20149 * This complementary directive is not removed by the browser and so provides
20150 * a permanent reliable place to store the binding information.
20153 <file name="index.html">
20154 <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
20155 <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
20157 <file name="protractor.js" type="protractor">
20158 it('should check both checkBoxes', function() {
20159 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
20160 element(by.model('master')).click();
20161 expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
20167 * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
20168 * then the `checked` attribute will be set on the element
20179 * The HTML specification does not require browsers to preserve the values of boolean attributes
20180 * such as readonly. (Their presence means true and their absence means false.)
20181 * If we put an Angular interpolation expression into such an attribute then the
20182 * binding information would be lost when the browser removes the attribute.
20183 * The `ngReadonly` directive solves this problem for the `readonly` attribute.
20184 * This complementary directive is not removed by the browser and so provides
20185 * a permanent reliable place to store the binding information.
20188 <file name="index.html">
20189 <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
20190 <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
20192 <file name="protractor.js" type="protractor">
20193 it('should toggle readonly attr', function() {
20194 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
20195 element(by.model('checked')).click();
20196 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
20202 * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
20203 * then special attribute "readonly" will be set on the element
20214 * The HTML specification does not require browsers to preserve the values of boolean attributes
20215 * such as selected. (Their presence means true and their absence means false.)
20216 * If we put an Angular interpolation expression into such an attribute then the
20217 * binding information would be lost when the browser removes the attribute.
20218 * The `ngSelected` directive solves this problem for the `selected` attribute.
20219 * This complementary directive is not removed by the browser and so provides
20220 * a permanent reliable place to store the binding information.
20224 <file name="index.html">
20225 <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
20226 <select aria-label="ngSelected demo">
20227 <option>Hello!</option>
20228 <option id="greet" ng-selected="selected">Greetings!</option>
20231 <file name="protractor.js" type="protractor">
20232 it('should select Greetings!', function() {
20233 expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
20234 element(by.model('selected')).click();
20235 expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
20241 * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
20242 * then special attribute "selected" will be set on the element
20252 * The HTML specification does not require browsers to preserve the values of boolean attributes
20253 * such as open. (Their presence means true and their absence means false.)
20254 * If we put an Angular interpolation expression into such an attribute then the
20255 * binding information would be lost when the browser removes the attribute.
20256 * The `ngOpen` directive solves this problem for the `open` attribute.
20257 * This complementary directive is not removed by the browser and so provides
20258 * a permanent reliable place to store the binding information.
20261 <file name="index.html">
20262 <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
20263 <details id="details" ng-open="open">
20264 <summary>Show/Hide me</summary>
20267 <file name="protractor.js" type="protractor">
20268 it('should toggle open', function() {
20269 expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
20270 element(by.model('open')).click();
20271 expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
20277 * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
20278 * then special attribute "open" will be set on the element
20281 var ngAttributeAliasDirectives = {};
20283 // boolean attrs are evaluated
20284 forEach(BOOLEAN_ATTR, function(propName, attrName) {
20285 // binding to multiple is not supported
20286 if (propName == "multiple") return;
20288 function defaultLinkFn(scope, element, attr) {
20289 scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
20290 attr.$set(attrName, !!value);
20294 var normalized = directiveNormalize('ng-' + attrName);
20295 var linkFn = defaultLinkFn;
20297 if (propName === 'checked') {
20298 linkFn = function(scope, element, attr) {
20299 // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
20300 if (attr.ngModel !== attr[normalized]) {
20301 defaultLinkFn(scope, element, attr);
20306 ngAttributeAliasDirectives[normalized] = function() {
20315 // aliased input attrs are evaluated
20316 forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
20317 ngAttributeAliasDirectives[ngAttr] = function() {
20320 link: function(scope, element, attr) {
20321 //special case ngPattern when a literal regular expression value
20322 //is used as the expression (this way we don't have to watch anything).
20323 if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
20324 var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
20326 attr.$set("ngPattern", new RegExp(match[1], match[2]));
20331 scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
20332 attr.$set(ngAttr, value);
20339 // ng-src, ng-srcset, ng-href are interpolated
20340 forEach(['src', 'srcset', 'href'], function(attrName) {
20341 var normalized = directiveNormalize('ng-' + attrName);
20342 ngAttributeAliasDirectives[normalized] = function() {
20344 priority: 99, // it needs to run after the attributes are interpolated
20345 link: function(scope, element, attr) {
20346 var propName = attrName,
20349 if (attrName === 'href' &&
20350 toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
20351 name = 'xlinkHref';
20352 attr.$attr[name] = 'xlink:href';
20356 attr.$observe(normalized, function(value) {
20358 if (attrName === 'href') {
20359 attr.$set(name, null);
20364 attr.$set(name, value);
20366 // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
20367 // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
20368 // to set the property as well to achieve the desired effect.
20369 // we use attr[attrName] value since $set can sanitize the url.
20370 if (msie && propName) element.prop(propName, attr[name]);
20377 /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
20379 var nullFormCtrl = {
20381 $$renameControl: nullFormRenameControl,
20382 $removeControl: noop,
20383 $setValidity: noop,
20385 $setPristine: noop,
20386 $setSubmitted: noop
20388 SUBMITTED_CLASS = 'ng-submitted';
20390 function nullFormRenameControl(control, name) {
20391 control.$name = name;
20396 * @name form.FormController
20398 * @property {boolean} $pristine True if user has not interacted with the form yet.
20399 * @property {boolean} $dirty True if user has already interacted with the form.
20400 * @property {boolean} $valid True if all of the containing forms and controls are valid.
20401 * @property {boolean} $invalid True if at least one containing control or form is invalid.
20402 * @property {boolean} $pending True if at least one containing control or form is pending.
20403 * @property {boolean} $submitted True if user has submitted the form even if its invalid.
20405 * @property {Object} $error Is an object hash, containing references to controls or
20406 * forms with failing validators, where:
20408 * - keys are validation tokens (error names),
20409 * - values are arrays of controls or forms that have a failing validator for given error name.
20411 * Built-in validation tokens:
20423 * - `datetimelocal`
20429 * `FormController` keeps track of all its controls and nested forms as well as the state of them,
20430 * such as being valid/invalid or dirty/pristine.
20432 * Each {@link ng.directive:form form} directive creates an instance
20433 * of `FormController`.
20436 //asks for $scope to fool the BC controller module
20437 FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
20438 function FormController(element, attrs, $scope, $animate, $interpolate) {
20444 form.$$success = {};
20445 form.$pending = undefined;
20446 form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
20447 form.$dirty = false;
20448 form.$pristine = true;
20449 form.$valid = true;
20450 form.$invalid = false;
20451 form.$submitted = false;
20452 form.$$parentForm = nullFormCtrl;
20456 * @name form.FormController#$rollbackViewValue
20459 * Rollback all form controls pending updates to the `$modelValue`.
20461 * Updates may be pending by a debounced event or because the input is waiting for a some future
20462 * event defined in `ng-model-options`. This method is typically needed by the reset button of
20463 * a form that uses `ng-model-options` to pend updates.
20465 form.$rollbackViewValue = function() {
20466 forEach(controls, function(control) {
20467 control.$rollbackViewValue();
20473 * @name form.FormController#$commitViewValue
20476 * Commit all form controls pending updates to the `$modelValue`.
20478 * Updates may be pending by a debounced event or because the input is waiting for a some future
20479 * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
20480 * usually handles calling this in response to input events.
20482 form.$commitViewValue = function() {
20483 forEach(controls, function(control) {
20484 control.$commitViewValue();
20490 * @name form.FormController#$addControl
20491 * @param {object} control control object, either a {@link form.FormController} or an
20492 * {@link ngModel.NgModelController}
20495 * Register a control with the form. Input elements using ngModelController do this automatically
20496 * when they are linked.
20498 * Note that the current state of the control will not be reflected on the new parent form. This
20499 * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
20502 * However, if the method is used programmatically, for example by adding dynamically created controls,
20503 * or controls that have been previously removed without destroying their corresponding DOM element,
20504 * it's the developers responsiblity to make sure the current state propagates to the parent form.
20506 * For example, if an input control is added that is already `$dirty` and has `$error` properties,
20507 * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
20509 form.$addControl = function(control) {
20510 // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
20511 // and not added to the scope. Now we throw an error.
20512 assertNotHasOwnProperty(control.$name, 'input');
20513 controls.push(control);
20515 if (control.$name) {
20516 form[control.$name] = control;
20519 control.$$parentForm = form;
20522 // Private API: rename a form control
20523 form.$$renameControl = function(control, newName) {
20524 var oldName = control.$name;
20526 if (form[oldName] === control) {
20527 delete form[oldName];
20529 form[newName] = control;
20530 control.$name = newName;
20535 * @name form.FormController#$removeControl
20536 * @param {object} control control object, either a {@link form.FormController} or an
20537 * {@link ngModel.NgModelController}
20540 * Deregister a control from the form.
20542 * Input elements using ngModelController do this automatically when they are destroyed.
20544 * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
20545 * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
20546 * different from case to case. For example, removing the only `$dirty` control from a form may or
20547 * may not mean that the form is still `$dirty`.
20549 form.$removeControl = function(control) {
20550 if (control.$name && form[control.$name] === control) {
20551 delete form[control.$name];
20553 forEach(form.$pending, function(value, name) {
20554 form.$setValidity(name, null, control);
20556 forEach(form.$error, function(value, name) {
20557 form.$setValidity(name, null, control);
20559 forEach(form.$$success, function(value, name) {
20560 form.$setValidity(name, null, control);
20563 arrayRemove(controls, control);
20564 control.$$parentForm = nullFormCtrl;
20570 * @name form.FormController#$setValidity
20573 * Sets the validity of a form control.
20575 * This method will also propagate to parent forms.
20577 addSetValidityMethod({
20580 set: function(object, property, controller) {
20581 var list = object[property];
20583 object[property] = [controller];
20585 var index = list.indexOf(controller);
20586 if (index === -1) {
20587 list.push(controller);
20591 unset: function(object, property, controller) {
20592 var list = object[property];
20596 arrayRemove(list, controller);
20597 if (list.length === 0) {
20598 delete object[property];
20606 * @name form.FormController#$setDirty
20609 * Sets the form to a dirty state.
20611 * This method can be called to add the 'ng-dirty' class and set the form to a dirty
20612 * state (ng-dirty class). This method will also propagate to parent forms.
20614 form.$setDirty = function() {
20615 $animate.removeClass(element, PRISTINE_CLASS);
20616 $animate.addClass(element, DIRTY_CLASS);
20617 form.$dirty = true;
20618 form.$pristine = false;
20619 form.$$parentForm.$setDirty();
20624 * @name form.FormController#$setPristine
20627 * Sets the form to its pristine state.
20629 * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
20630 * state (ng-pristine class). This method will also propagate to all the controls contained
20633 * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
20634 * saving or resetting it.
20636 form.$setPristine = function() {
20637 $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
20638 form.$dirty = false;
20639 form.$pristine = true;
20640 form.$submitted = false;
20641 forEach(controls, function(control) {
20642 control.$setPristine();
20648 * @name form.FormController#$setUntouched
20651 * Sets the form to its untouched state.
20653 * This method can be called to remove the 'ng-touched' class and set the form controls to their
20654 * untouched state (ng-untouched class).
20656 * Setting a form controls back to their untouched state is often useful when setting the form
20657 * back to its pristine state.
20659 form.$setUntouched = function() {
20660 forEach(controls, function(control) {
20661 control.$setUntouched();
20667 * @name form.FormController#$setSubmitted
20670 * Sets the form to its submitted state.
20672 form.$setSubmitted = function() {
20673 $animate.addClass(element, SUBMITTED_CLASS);
20674 form.$submitted = true;
20675 form.$$parentForm.$setSubmitted();
20685 * Nestable alias of {@link ng.directive:form `form`} directive. HTML
20686 * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
20687 * sub-group of controls needs to be determined.
20689 * Note: the purpose of `ngForm` is to group controls,
20690 * but not to be a replacement for the `<form>` tag with all of its capabilities
20691 * (e.g. posting to the server, ...).
20693 * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
20694 * related scope, under this name.
20704 * Directive that instantiates
20705 * {@link form.FormController FormController}.
20707 * If the `name` attribute is specified, the form controller is published onto the current scope under
20710 * # Alias: {@link ng.directive:ngForm `ngForm`}
20712 * In Angular, forms can be nested. This means that the outer form is valid when all of the child
20713 * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
20714 * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
20715 * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
20716 * using Angular validation directives in forms that are dynamically generated using the
20717 * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
20718 * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
20719 * `ngForm` directive and nest these in an outer `form` element.
20723 * - `ng-valid` is set if the form is valid.
20724 * - `ng-invalid` is set if the form is invalid.
20725 * - `ng-pending` is set if the form is pending.
20726 * - `ng-pristine` is set if the form is pristine.
20727 * - `ng-dirty` is set if the form is dirty.
20728 * - `ng-submitted` is set if the form was submitted.
20730 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
20733 * # Submitting a form and preventing the default action
20735 * Since the role of forms in client-side Angular applications is different than in classical
20736 * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
20737 * page reload that sends the data to the server. Instead some javascript logic should be triggered
20738 * to handle the form submission in an application-specific way.
20740 * For this reason, Angular prevents the default action (form submission to the server) unless the
20741 * `<form>` element has an `action` attribute specified.
20743 * You can use one of the following two ways to specify what javascript method should be called when
20744 * a form is submitted:
20746 * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
20747 * - {@link ng.directive:ngClick ngClick} directive on the first
20748 * button or input field of type submit (input[type=submit])
20750 * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
20751 * or {@link ng.directive:ngClick ngClick} directives.
20752 * This is because of the following form submission rules in the HTML specification:
20754 * - If a form has only one input field then hitting enter in this field triggers form submit
20756 * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
20757 * doesn't trigger submit
20758 * - if a form has one or more input fields and one or more buttons or input[type=submit] then
20759 * hitting enter in any of the input fields will trigger the click handler on the *first* button or
20760 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
20762 * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
20763 * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
20764 * to have access to the updated model.
20766 * ## Animation Hooks
20768 * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
20769 * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
20770 * other validations that are performed within the form. Animations in ngForm are similar to how
20771 * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
20772 * as JS animations.
20774 * The following example shows a simple way to utilize CSS transitions to style a form element
20775 * that has been rendered as invalid after it has been validated:
20778 * //be sure to include ngAnimate as a module to hook into more
20779 * //advanced animations
20781 * transition:0.5s linear all;
20782 * background: white;
20784 * .my-form.ng-invalid {
20791 <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
20792 <file name="index.html">
20794 angular.module('formExample', [])
20795 .controller('FormController', ['$scope', function($scope) {
20796 $scope.userType = 'guest';
20801 transition:all linear 0.5s;
20802 background: transparent;
20804 .my-form.ng-invalid {
20808 <form name="myForm" ng-controller="FormController" class="my-form">
20809 userType: <input name="input" ng-model="userType" required>
20810 <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
20811 <code>userType = {{userType}}</code><br>
20812 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
20813 <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
20814 <code>myForm.$valid = {{myForm.$valid}}</code><br>
20815 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
20818 <file name="protractor.js" type="protractor">
20819 it('should initialize to model', function() {
20820 var userType = element(by.binding('userType'));
20821 var valid = element(by.binding('myForm.input.$valid'));
20823 expect(userType.getText()).toContain('guest');
20824 expect(valid.getText()).toContain('true');
20827 it('should be invalid if empty', function() {
20828 var userType = element(by.binding('userType'));
20829 var valid = element(by.binding('myForm.input.$valid'));
20830 var userInput = element(by.model('userType'));
20833 userInput.sendKeys('');
20835 expect(userType.getText()).toEqual('userType =');
20836 expect(valid.getText()).toContain('false');
20841 * @param {string=} name Name of the form. If specified, the form controller will be published into
20842 * related scope, under this name.
20844 var formDirectiveFactory = function(isNgForm) {
20845 return ['$timeout', '$parse', function($timeout, $parse) {
20846 var formDirective = {
20848 restrict: isNgForm ? 'EAC' : 'E',
20849 require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
20850 controller: FormController,
20851 compile: function ngFormCompile(formElement, attr) {
20852 // Setup initial state of the control
20853 formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
20855 var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
20858 pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
20859 var controller = ctrls[0];
20861 // if `action` attr is not present on the form, prevent the default action (submission)
20862 if (!('action' in attr)) {
20863 // we can't use jq events because if a form is destroyed during submission the default
20864 // action is not prevented. see #1238
20866 // IE 9 is not affected because it doesn't fire a submit event and try to do a full
20867 // page reload if the form was destroyed by submission of the form via a click handler
20868 // on a button in the form. Looks like an IE9 specific bug.
20869 var handleFormSubmission = function(event) {
20870 scope.$apply(function() {
20871 controller.$commitViewValue();
20872 controller.$setSubmitted();
20875 event.preventDefault();
20878 addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
20880 // unregister the preventDefault listener so that we don't not leak memory but in a
20881 // way that will achieve the prevention of the default action.
20882 formElement.on('$destroy', function() {
20883 $timeout(function() {
20884 removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
20889 var parentFormCtrl = ctrls[1] || controller.$$parentForm;
20890 parentFormCtrl.$addControl(controller);
20892 var setter = nameAttr ? getSetter(controller.$name) : noop;
20895 setter(scope, controller);
20896 attr.$observe(nameAttr, function(newValue) {
20897 if (controller.$name === newValue) return;
20898 setter(scope, undefined);
20899 controller.$$parentForm.$$renameControl(controller, newValue);
20900 setter = getSetter(controller.$name);
20901 setter(scope, controller);
20904 formElement.on('$destroy', function() {
20905 controller.$$parentForm.$removeControl(controller);
20906 setter(scope, undefined);
20907 extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
20914 return formDirective;
20916 function getSetter(expression) {
20917 if (expression === '') {
20918 //create an assignable expression, so forms with an empty name can be renamed later
20919 return $parse('this[""]').assign;
20921 return $parse(expression).assign || noop;
20926 var formDirective = formDirectiveFactory();
20927 var ngFormDirective = formDirectiveFactory(true);
20929 /* global VALID_CLASS: false,
20930 INVALID_CLASS: false,
20931 PRISTINE_CLASS: false,
20932 DIRTY_CLASS: false,
20933 UNTOUCHED_CLASS: false,
20934 TOUCHED_CLASS: false,
20935 ngModelMinErr: false,
20938 // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
20939 var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
20940 // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
20941 var URL_REGEXP = /^[A-Za-z][A-Za-z\d.+-]*:\/*(?:\w+(?::\w+)?@)?[^\s/]+(?::\d+)?(?:\/[\w#!:.?+=&%@\-/]*)?$/;
20942 var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
20943 var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
20944 var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
20945 var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
20946 var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
20947 var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
20948 var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
20954 * @name input[text]
20957 * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
20960 * @param {string} ngModel Assignable angular expression to data-bind to.
20961 * @param {string=} name Property name of the form under which the control is published.
20962 * @param {string=} required Adds `required` validation error key if the value is not entered.
20963 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
20964 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
20965 * `required` when you want to data-bind to the `required` attribute.
20966 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
20968 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
20969 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
20971 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
20972 * that contains the regular expression body that will be converted to a regular expression
20973 * as in the ngPattern directive.
20974 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
20975 * a RegExp found by evaluating the Angular expression given in the attribute value.
20976 * If the expression evaluates to a RegExp object, then this is used directly.
20977 * If the expression evaluates to a string, then it will be converted to a RegExp
20978 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
20979 * `new RegExp('^abc$')`.<br />
20980 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
20981 * start at the index of the last search's match, thus not taking the whole input value into
20983 * @param {string=} ngChange Angular expression to be executed when input changes due to user
20984 * interaction with the input element.
20985 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
20986 * This parameter is ignored for input[type=password] controls, which will never trim the
20990 <example name="text-input-directive" module="textInputExample">
20991 <file name="index.html">
20993 angular.module('textInputExample', [])
20994 .controller('ExampleController', ['$scope', function($scope) {
20997 word: /^\s*\w*\s*$/
21001 <form name="myForm" ng-controller="ExampleController">
21002 <label>Single word:
21003 <input type="text" name="input" ng-model="example.text"
21004 ng-pattern="example.word" required ng-trim="false">
21007 <span class="error" ng-show="myForm.input.$error.required">
21009 <span class="error" ng-show="myForm.input.$error.pattern">
21010 Single word only!</span>
21012 <tt>text = {{example.text}}</tt><br/>
21013 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21014 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21015 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21016 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21019 <file name="protractor.js" type="protractor">
21020 var text = element(by.binding('example.text'));
21021 var valid = element(by.binding('myForm.input.$valid'));
21022 var input = element(by.model('example.text'));
21024 it('should initialize to model', function() {
21025 expect(text.getText()).toContain('guest');
21026 expect(valid.getText()).toContain('true');
21029 it('should be invalid if empty', function() {
21031 input.sendKeys('');
21033 expect(text.getText()).toEqual('text =');
21034 expect(valid.getText()).toContain('false');
21037 it('should be invalid if multi word', function() {
21039 input.sendKeys('hello world');
21041 expect(valid.getText()).toContain('false');
21046 'text': textInputType,
21050 * @name input[date]
21053 * Input with date validation and transformation. In browsers that do not yet support
21054 * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
21055 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
21056 * modern browsers do not yet support this input type, it is important to provide cues to users on the
21057 * expected input format via a placeholder or label.
21059 * The model must always be a Date object, otherwise Angular will throw an error.
21060 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21062 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21063 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21065 * @param {string} ngModel Assignable angular expression to data-bind to.
21066 * @param {string=} name Property name of the form under which the control is published.
21067 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
21068 * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
21069 * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
21070 * constraint validation.
21071 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
21072 * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
21073 * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
21074 * constraint validation.
21075 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
21076 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21077 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
21078 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21079 * @param {string=} required Sets `required` validation error key if the value is not entered.
21080 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21081 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21082 * `required` when you want to data-bind to the `required` attribute.
21083 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21084 * interaction with the input element.
21087 <example name="date-input-directive" module="dateInputExample">
21088 <file name="index.html">
21090 angular.module('dateInputExample', [])
21091 .controller('DateController', ['$scope', function($scope) {
21093 value: new Date(2013, 9, 22)
21097 <form name="myForm" ng-controller="DateController as dateCtrl">
21098 <label for="exampleInput">Pick a date in 2013:</label>
21099 <input type="date" id="exampleInput" name="input" ng-model="example.value"
21100 placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
21102 <span class="error" ng-show="myForm.input.$error.required">
21104 <span class="error" ng-show="myForm.input.$error.date">
21105 Not a valid date!</span>
21107 <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
21108 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21109 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21110 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21111 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21114 <file name="protractor.js" type="protractor">
21115 var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
21116 var valid = element(by.binding('myForm.input.$valid'));
21117 var input = element(by.model('example.value'));
21119 // currently protractor/webdriver does not support
21120 // sending keys to all known HTML5 input controls
21121 // for various browsers (see https://github.com/angular/protractor/issues/562).
21122 function setInput(val) {
21123 // set the value of the element and force validation.
21124 var scr = "var ipt = document.getElementById('exampleInput'); " +
21125 "ipt.value = '" + val + "';" +
21126 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21127 browser.executeScript(scr);
21130 it('should initialize to model', function() {
21131 expect(value.getText()).toContain('2013-10-22');
21132 expect(valid.getText()).toContain('myForm.input.$valid = true');
21135 it('should be invalid if empty', function() {
21137 expect(value.getText()).toEqual('value =');
21138 expect(valid.getText()).toContain('myForm.input.$valid = false');
21141 it('should be invalid if over max', function() {
21142 setInput('2015-01-01');
21143 expect(value.getText()).toContain('');
21144 expect(valid.getText()).toContain('myForm.input.$valid = false');
21149 'date': createDateInputType('date', DATE_REGEXP,
21150 createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
21155 * @name input[datetime-local]
21158 * Input with datetime validation and transformation. In browsers that do not yet support
21159 * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21160 * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
21162 * The model must always be a Date object, otherwise Angular will throw an error.
21163 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21165 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21166 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21168 * @param {string} ngModel Assignable angular expression to data-bind to.
21169 * @param {string=} name Property name of the form under which the control is published.
21170 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21171 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
21172 * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
21173 * Note that `min` will also add native HTML5 constraint validation.
21174 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21175 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
21176 * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
21177 * Note that `max` will also add native HTML5 constraint validation.
21178 * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
21179 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21180 * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
21181 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21182 * @param {string=} required Sets `required` validation error key if the value is not entered.
21183 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21184 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21185 * `required` when you want to data-bind to the `required` attribute.
21186 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21187 * interaction with the input element.
21190 <example name="datetimelocal-input-directive" module="dateExample">
21191 <file name="index.html">
21193 angular.module('dateExample', [])
21194 .controller('DateController', ['$scope', function($scope) {
21196 value: new Date(2010, 11, 28, 14, 57)
21200 <form name="myForm" ng-controller="DateController as dateCtrl">
21201 <label for="exampleInput">Pick a date between in 2013:</label>
21202 <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
21203 placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
21205 <span class="error" ng-show="myForm.input.$error.required">
21207 <span class="error" ng-show="myForm.input.$error.datetimelocal">
21208 Not a valid date!</span>
21210 <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
21211 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21212 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21213 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21214 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21217 <file name="protractor.js" type="protractor">
21218 var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
21219 var valid = element(by.binding('myForm.input.$valid'));
21220 var input = element(by.model('example.value'));
21222 // currently protractor/webdriver does not support
21223 // sending keys to all known HTML5 input controls
21224 // for various browsers (https://github.com/angular/protractor/issues/562).
21225 function setInput(val) {
21226 // set the value of the element and force validation.
21227 var scr = "var ipt = document.getElementById('exampleInput'); " +
21228 "ipt.value = '" + val + "';" +
21229 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21230 browser.executeScript(scr);
21233 it('should initialize to model', function() {
21234 expect(value.getText()).toContain('2010-12-28T14:57:00');
21235 expect(valid.getText()).toContain('myForm.input.$valid = true');
21238 it('should be invalid if empty', function() {
21240 expect(value.getText()).toEqual('value =');
21241 expect(valid.getText()).toContain('myForm.input.$valid = false');
21244 it('should be invalid if over max', function() {
21245 setInput('2015-01-01T23:59:00');
21246 expect(value.getText()).toContain('');
21247 expect(valid.getText()).toContain('myForm.input.$valid = false');
21252 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
21253 createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
21254 'yyyy-MM-ddTHH:mm:ss.sss'),
21258 * @name input[time]
21261 * Input with time validation and transformation. In browsers that do not yet support
21262 * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21263 * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
21264 * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
21266 * The model must always be a Date object, otherwise Angular will throw an error.
21267 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21269 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21270 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21272 * @param {string} ngModel Assignable angular expression to data-bind to.
21273 * @param {string=} name Property name of the form under which the control is published.
21274 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21275 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
21276 * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
21277 * native HTML5 constraint validation.
21278 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21279 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
21280 * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
21281 * native HTML5 constraint validation.
21282 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
21283 * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21284 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
21285 * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21286 * @param {string=} required Sets `required` validation error key if the value is not entered.
21287 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21288 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21289 * `required` when you want to data-bind to the `required` attribute.
21290 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21291 * interaction with the input element.
21294 <example name="time-input-directive" module="timeExample">
21295 <file name="index.html">
21297 angular.module('timeExample', [])
21298 .controller('DateController', ['$scope', function($scope) {
21300 value: new Date(1970, 0, 1, 14, 57, 0)
21304 <form name="myForm" ng-controller="DateController as dateCtrl">
21305 <label for="exampleInput">Pick a between 8am and 5pm:</label>
21306 <input type="time" id="exampleInput" name="input" ng-model="example.value"
21307 placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
21309 <span class="error" ng-show="myForm.input.$error.required">
21311 <span class="error" ng-show="myForm.input.$error.time">
21312 Not a valid date!</span>
21314 <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
21315 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21316 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21317 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21318 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21321 <file name="protractor.js" type="protractor">
21322 var value = element(by.binding('example.value | date: "HH:mm:ss"'));
21323 var valid = element(by.binding('myForm.input.$valid'));
21324 var input = element(by.model('example.value'));
21326 // currently protractor/webdriver does not support
21327 // sending keys to all known HTML5 input controls
21328 // for various browsers (https://github.com/angular/protractor/issues/562).
21329 function setInput(val) {
21330 // set the value of the element and force validation.
21331 var scr = "var ipt = document.getElementById('exampleInput'); " +
21332 "ipt.value = '" + val + "';" +
21333 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21334 browser.executeScript(scr);
21337 it('should initialize to model', function() {
21338 expect(value.getText()).toContain('14:57:00');
21339 expect(valid.getText()).toContain('myForm.input.$valid = true');
21342 it('should be invalid if empty', function() {
21344 expect(value.getText()).toEqual('value =');
21345 expect(valid.getText()).toContain('myForm.input.$valid = false');
21348 it('should be invalid if over max', function() {
21349 setInput('23:59:00');
21350 expect(value.getText()).toContain('');
21351 expect(valid.getText()).toContain('myForm.input.$valid = false');
21356 'time': createDateInputType('time', TIME_REGEXP,
21357 createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
21362 * @name input[week]
21365 * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
21366 * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21367 * week format (yyyy-W##), for example: `2013-W02`.
21369 * The model must always be a Date object, otherwise Angular will throw an error.
21370 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21372 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21373 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21375 * @param {string} ngModel Assignable angular expression to data-bind to.
21376 * @param {string=} name Property name of the form under which the control is published.
21377 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21378 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
21379 * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
21380 * native HTML5 constraint validation.
21381 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21382 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
21383 * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
21384 * native HTML5 constraint validation.
21385 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
21386 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21387 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
21388 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21389 * @param {string=} required Sets `required` validation error key if the value is not entered.
21390 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21391 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21392 * `required` when you want to data-bind to the `required` attribute.
21393 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21394 * interaction with the input element.
21397 <example name="week-input-directive" module="weekExample">
21398 <file name="index.html">
21400 angular.module('weekExample', [])
21401 .controller('DateController', ['$scope', function($scope) {
21403 value: new Date(2013, 0, 3)
21407 <form name="myForm" ng-controller="DateController as dateCtrl">
21408 <label>Pick a date between in 2013:
21409 <input id="exampleInput" type="week" name="input" ng-model="example.value"
21410 placeholder="YYYY-W##" min="2012-W32"
21411 max="2013-W52" required />
21414 <span class="error" ng-show="myForm.input.$error.required">
21416 <span class="error" ng-show="myForm.input.$error.week">
21417 Not a valid date!</span>
21419 <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
21420 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21421 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21422 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21423 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21426 <file name="protractor.js" type="protractor">
21427 var value = element(by.binding('example.value | date: "yyyy-Www"'));
21428 var valid = element(by.binding('myForm.input.$valid'));
21429 var input = element(by.model('example.value'));
21431 // currently protractor/webdriver does not support
21432 // sending keys to all known HTML5 input controls
21433 // for various browsers (https://github.com/angular/protractor/issues/562).
21434 function setInput(val) {
21435 // set the value of the element and force validation.
21436 var scr = "var ipt = document.getElementById('exampleInput'); " +
21437 "ipt.value = '" + val + "';" +
21438 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21439 browser.executeScript(scr);
21442 it('should initialize to model', function() {
21443 expect(value.getText()).toContain('2013-W01');
21444 expect(valid.getText()).toContain('myForm.input.$valid = true');
21447 it('should be invalid if empty', function() {
21449 expect(value.getText()).toEqual('value =');
21450 expect(valid.getText()).toContain('myForm.input.$valid = false');
21453 it('should be invalid if over max', function() {
21454 setInput('2015-W01');
21455 expect(value.getText()).toContain('');
21456 expect(valid.getText()).toContain('myForm.input.$valid = false');
21461 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
21465 * @name input[month]
21468 * Input with month validation and transformation. In browsers that do not yet support
21469 * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
21470 * month format (yyyy-MM), for example: `2009-01`.
21472 * The model must always be a Date object, otherwise Angular will throw an error.
21473 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
21474 * If the model is not set to the first of the month, the next view to model update will set it
21475 * to the first of the month.
21477 * The timezone to be used to read/write the `Date` instance in the model can be defined using
21478 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
21480 * @param {string} ngModel Assignable angular expression to data-bind to.
21481 * @param {string=} name Property name of the form under which the control is published.
21482 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21483 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
21484 * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
21485 * native HTML5 constraint validation.
21486 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21487 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
21488 * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
21489 * native HTML5 constraint validation.
21490 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
21491 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
21492 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
21493 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
21495 * @param {string=} required Sets `required` validation error key if the value is not entered.
21496 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21497 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21498 * `required` when you want to data-bind to the `required` attribute.
21499 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21500 * interaction with the input element.
21503 <example name="month-input-directive" module="monthExample">
21504 <file name="index.html">
21506 angular.module('monthExample', [])
21507 .controller('DateController', ['$scope', function($scope) {
21509 value: new Date(2013, 9, 1)
21513 <form name="myForm" ng-controller="DateController as dateCtrl">
21514 <label for="exampleInput">Pick a month in 2013:</label>
21515 <input id="exampleInput" type="month" name="input" ng-model="example.value"
21516 placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
21518 <span class="error" ng-show="myForm.input.$error.required">
21520 <span class="error" ng-show="myForm.input.$error.month">
21521 Not a valid month!</span>
21523 <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
21524 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21525 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21526 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21527 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21530 <file name="protractor.js" type="protractor">
21531 var value = element(by.binding('example.value | date: "yyyy-MM"'));
21532 var valid = element(by.binding('myForm.input.$valid'));
21533 var input = element(by.model('example.value'));
21535 // currently protractor/webdriver does not support
21536 // sending keys to all known HTML5 input controls
21537 // for various browsers (https://github.com/angular/protractor/issues/562).
21538 function setInput(val) {
21539 // set the value of the element and force validation.
21540 var scr = "var ipt = document.getElementById('exampleInput'); " +
21541 "ipt.value = '" + val + "';" +
21542 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
21543 browser.executeScript(scr);
21546 it('should initialize to model', function() {
21547 expect(value.getText()).toContain('2013-10');
21548 expect(valid.getText()).toContain('myForm.input.$valid = true');
21551 it('should be invalid if empty', function() {
21553 expect(value.getText()).toEqual('value =');
21554 expect(valid.getText()).toContain('myForm.input.$valid = false');
21557 it('should be invalid if over max', function() {
21558 setInput('2015-01');
21559 expect(value.getText()).toContain('');
21560 expect(valid.getText()).toContain('myForm.input.$valid = false');
21565 'month': createDateInputType('month', MONTH_REGEXP,
21566 createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
21571 * @name input[number]
21574 * Text input with number validation and transformation. Sets the `number` validation
21575 * error if not a valid number.
21577 * <div class="alert alert-warning">
21578 * The model must always be of type `number` otherwise Angular will throw an error.
21579 * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
21580 * error docs for more information and an example of how to convert your model if necessary.
21583 * ## Issues with HTML5 constraint validation
21585 * In browsers that follow the
21586 * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
21587 * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
21588 * If a non-number is entered in the input, the browser will report the value as an empty string,
21589 * which means the view / model values in `ngModel` and subsequently the scope value
21590 * will also be an empty string.
21593 * @param {string} ngModel Assignable angular expression to data-bind to.
21594 * @param {string=} name Property name of the form under which the control is published.
21595 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
21596 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
21597 * @param {string=} required Sets `required` validation error key if the value is not entered.
21598 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21599 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21600 * `required` when you want to data-bind to the `required` attribute.
21601 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
21603 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
21604 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
21606 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
21607 * that contains the regular expression body that will be converted to a regular expression
21608 * as in the ngPattern directive.
21609 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
21610 * a RegExp found by evaluating the Angular expression given in the attribute value.
21611 * If the expression evaluates to a RegExp object, then this is used directly.
21612 * If the expression evaluates to a string, then it will be converted to a RegExp
21613 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
21614 * `new RegExp('^abc$')`.<br />
21615 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
21616 * start at the index of the last search's match, thus not taking the whole input value into
21618 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21619 * interaction with the input element.
21622 <example name="number-input-directive" module="numberExample">
21623 <file name="index.html">
21625 angular.module('numberExample', [])
21626 .controller('ExampleController', ['$scope', function($scope) {
21632 <form name="myForm" ng-controller="ExampleController">
21634 <input type="number" name="input" ng-model="example.value"
21635 min="0" max="99" required>
21638 <span class="error" ng-show="myForm.input.$error.required">
21640 <span class="error" ng-show="myForm.input.$error.number">
21641 Not valid number!</span>
21643 <tt>value = {{example.value}}</tt><br/>
21644 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21645 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21646 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21647 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21650 <file name="protractor.js" type="protractor">
21651 var value = element(by.binding('example.value'));
21652 var valid = element(by.binding('myForm.input.$valid'));
21653 var input = element(by.model('example.value'));
21655 it('should initialize to model', function() {
21656 expect(value.getText()).toContain('12');
21657 expect(valid.getText()).toContain('true');
21660 it('should be invalid if empty', function() {
21662 input.sendKeys('');
21663 expect(value.getText()).toEqual('value =');
21664 expect(valid.getText()).toContain('false');
21667 it('should be invalid if over max', function() {
21669 input.sendKeys('123');
21670 expect(value.getText()).toEqual('value =');
21671 expect(valid.getText()).toContain('false');
21676 'number': numberInputType,
21684 * Text input with URL validation. Sets the `url` validation error key if the content is not a
21687 * <div class="alert alert-warning">
21688 * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
21689 * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
21690 * the built-in validators (see the {@link guide/forms Forms guide})
21693 * @param {string} ngModel Assignable angular expression to data-bind to.
21694 * @param {string=} name Property name of the form under which the control is published.
21695 * @param {string=} required Sets `required` validation error key if the value is not entered.
21696 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21697 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21698 * `required` when you want to data-bind to the `required` attribute.
21699 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
21701 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
21702 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
21704 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
21705 * that contains the regular expression body that will be converted to a regular expression
21706 * as in the ngPattern directive.
21707 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
21708 * a RegExp found by evaluating the Angular expression given in the attribute value.
21709 * If the expression evaluates to a RegExp object, then this is used directly.
21710 * If the expression evaluates to a string, then it will be converted to a RegExp
21711 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
21712 * `new RegExp('^abc$')`.<br />
21713 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
21714 * start at the index of the last search's match, thus not taking the whole input value into
21716 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21717 * interaction with the input element.
21720 <example name="url-input-directive" module="urlExample">
21721 <file name="index.html">
21723 angular.module('urlExample', [])
21724 .controller('ExampleController', ['$scope', function($scope) {
21726 text: 'http://google.com'
21730 <form name="myForm" ng-controller="ExampleController">
21732 <input type="url" name="input" ng-model="url.text" required>
21735 <span class="error" ng-show="myForm.input.$error.required">
21737 <span class="error" ng-show="myForm.input.$error.url">
21738 Not valid url!</span>
21740 <tt>text = {{url.text}}</tt><br/>
21741 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21742 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21743 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21744 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21745 <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
21748 <file name="protractor.js" type="protractor">
21749 var text = element(by.binding('url.text'));
21750 var valid = element(by.binding('myForm.input.$valid'));
21751 var input = element(by.model('url.text'));
21753 it('should initialize to model', function() {
21754 expect(text.getText()).toContain('http://google.com');
21755 expect(valid.getText()).toContain('true');
21758 it('should be invalid if empty', function() {
21760 input.sendKeys('');
21762 expect(text.getText()).toEqual('text =');
21763 expect(valid.getText()).toContain('false');
21766 it('should be invalid if not url', function() {
21768 input.sendKeys('box');
21770 expect(valid.getText()).toContain('false');
21775 'url': urlInputType,
21780 * @name input[email]
21783 * Text input with email validation. Sets the `email` validation error key if not a valid email
21786 * <div class="alert alert-warning">
21787 * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
21788 * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
21789 * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
21792 * @param {string} ngModel Assignable angular expression to data-bind to.
21793 * @param {string=} name Property name of the form under which the control is published.
21794 * @param {string=} required Sets `required` validation error key if the value is not entered.
21795 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
21796 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
21797 * `required` when you want to data-bind to the `required` attribute.
21798 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
21800 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
21801 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
21803 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
21804 * that contains the regular expression body that will be converted to a regular expression
21805 * as in the ngPattern directive.
21806 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
21807 * a RegExp found by evaluating the Angular expression given in the attribute value.
21808 * If the expression evaluates to a RegExp object, then this is used directly.
21809 * If the expression evaluates to a string, then it will be converted to a RegExp
21810 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
21811 * `new RegExp('^abc$')`.<br />
21812 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
21813 * start at the index of the last search's match, thus not taking the whole input value into
21815 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21816 * interaction with the input element.
21819 <example name="email-input-directive" module="emailExample">
21820 <file name="index.html">
21822 angular.module('emailExample', [])
21823 .controller('ExampleController', ['$scope', function($scope) {
21825 text: 'me@example.com'
21829 <form name="myForm" ng-controller="ExampleController">
21831 <input type="email" name="input" ng-model="email.text" required>
21834 <span class="error" ng-show="myForm.input.$error.required">
21836 <span class="error" ng-show="myForm.input.$error.email">
21837 Not valid email!</span>
21839 <tt>text = {{email.text}}</tt><br/>
21840 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
21841 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
21842 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
21843 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
21844 <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
21847 <file name="protractor.js" type="protractor">
21848 var text = element(by.binding('email.text'));
21849 var valid = element(by.binding('myForm.input.$valid'));
21850 var input = element(by.model('email.text'));
21852 it('should initialize to model', function() {
21853 expect(text.getText()).toContain('me@example.com');
21854 expect(valid.getText()).toContain('true');
21857 it('should be invalid if empty', function() {
21859 input.sendKeys('');
21860 expect(text.getText()).toEqual('text =');
21861 expect(valid.getText()).toContain('false');
21864 it('should be invalid if not email', function() {
21866 input.sendKeys('xxx');
21868 expect(valid.getText()).toContain('false');
21873 'email': emailInputType,
21878 * @name input[radio]
21881 * HTML radio button.
21883 * @param {string} ngModel Assignable angular expression to data-bind to.
21884 * @param {string} value The value to which the `ngModel` expression should be set when selected.
21885 * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
21886 * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
21887 * @param {string=} name Property name of the form under which the control is published.
21888 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21889 * interaction with the input element.
21890 * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
21891 * is selected. Should be used instead of the `value` attribute if you need
21892 * a non-string `ngModel` (`boolean`, `array`, ...).
21895 <example name="radio-input-directive" module="radioExample">
21896 <file name="index.html">
21898 angular.module('radioExample', [])
21899 .controller('ExampleController', ['$scope', function($scope) {
21903 $scope.specialValue = {
21909 <form name="myForm" ng-controller="ExampleController">
21911 <input type="radio" ng-model="color.name" value="red">
21915 <input type="radio" ng-model="color.name" ng-value="specialValue">
21919 <input type="radio" ng-model="color.name" value="blue">
21922 <tt>color = {{color.name | json}}</tt><br/>
21924 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
21926 <file name="protractor.js" type="protractor">
21927 it('should change state', function() {
21928 var color = element(by.binding('color.name'));
21930 expect(color.getText()).toContain('blue');
21932 element.all(by.model('color.name')).get(0).click();
21934 expect(color.getText()).toContain('red');
21939 'radio': radioInputType,
21944 * @name input[checkbox]
21949 * @param {string} ngModel Assignable angular expression to data-bind to.
21950 * @param {string=} name Property name of the form under which the control is published.
21951 * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
21952 * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
21953 * @param {string=} ngChange Angular expression to be executed when input changes due to user
21954 * interaction with the input element.
21957 <example name="checkbox-input-directive" module="checkboxExample">
21958 <file name="index.html">
21960 angular.module('checkboxExample', [])
21961 .controller('ExampleController', ['$scope', function($scope) {
21962 $scope.checkboxModel = {
21968 <form name="myForm" ng-controller="ExampleController">
21970 <input type="checkbox" ng-model="checkboxModel.value1">
21973 <input type="checkbox" ng-model="checkboxModel.value2"
21974 ng-true-value="'YES'" ng-false-value="'NO'">
21976 <tt>value1 = {{checkboxModel.value1}}</tt><br/>
21977 <tt>value2 = {{checkboxModel.value2}}</tt><br/>
21980 <file name="protractor.js" type="protractor">
21981 it('should change state', function() {
21982 var value1 = element(by.binding('checkboxModel.value1'));
21983 var value2 = element(by.binding('checkboxModel.value2'));
21985 expect(value1.getText()).toContain('true');
21986 expect(value2.getText()).toContain('YES');
21988 element(by.model('checkboxModel.value1')).click();
21989 element(by.model('checkboxModel.value2')).click();
21991 expect(value1.getText()).toContain('false');
21992 expect(value2.getText()).toContain('NO');
21997 'checkbox': checkboxInputType,
22006 function stringBasedInputType(ctrl) {
22007 ctrl.$formatters.push(function(value) {
22008 return ctrl.$isEmpty(value) ? value : value.toString();
22012 function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22013 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22014 stringBasedInputType(ctrl);
22017 function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22018 var type = lowercase(element[0].type);
22020 // In composition mode, users are still inputing intermediate text buffer,
22021 // hold the listener until composition is done.
22022 // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
22023 if (!$sniffer.android) {
22024 var composing = false;
22026 element.on('compositionstart', function(data) {
22030 element.on('compositionend', function() {
22036 var listener = function(ev) {
22038 $browser.defer.cancel(timeout);
22041 if (composing) return;
22042 var value = element.val(),
22043 event = ev && ev.type;
22045 // By default we will trim the value
22046 // If the attribute ng-trim exists we will avoid trimming
22047 // If input type is 'password', the value is never trimmed
22048 if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
22049 value = trim(value);
22052 // If a control is suffering from bad input (due to native validators), browsers discard its
22053 // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
22054 // control's value is the same empty value twice in a row.
22055 if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
22056 ctrl.$setViewValue(value, event);
22060 // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
22061 // input event on backspace, delete or cut
22062 if ($sniffer.hasEvent('input')) {
22063 element.on('input', listener);
22067 var deferListener = function(ev, input, origValue) {
22069 timeout = $browser.defer(function() {
22071 if (!input || input.value !== origValue) {
22078 element.on('keydown', function(event) {
22079 var key = event.keyCode;
22082 // command modifiers arrows
22083 if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
22085 deferListener(event, this, this.value);
22088 // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
22089 if ($sniffer.hasEvent('paste')) {
22090 element.on('paste cut', deferListener);
22094 // if user paste into input using mouse on older browser
22095 // or form autocomplete on newer browser, we need "change" event to catch it
22096 element.on('change', listener);
22098 ctrl.$render = function() {
22099 // Workaround for Firefox validation #12102.
22100 var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
22101 if (element.val() !== value) {
22102 element.val(value);
22107 function weekParser(isoWeek, existingDate) {
22108 if (isDate(isoWeek)) {
22112 if (isString(isoWeek)) {
22113 WEEK_REGEXP.lastIndex = 0;
22114 var parts = WEEK_REGEXP.exec(isoWeek);
22116 var year = +parts[1],
22122 firstThurs = getFirstThursdayOfYear(year),
22123 addDays = (week - 1) * 7;
22125 if (existingDate) {
22126 hours = existingDate.getHours();
22127 minutes = existingDate.getMinutes();
22128 seconds = existingDate.getSeconds();
22129 milliseconds = existingDate.getMilliseconds();
22132 return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
22139 function createDateParser(regexp, mapping) {
22140 return function(iso, date) {
22147 if (isString(iso)) {
22148 // When a date is JSON'ified to wraps itself inside of an extra
22149 // set of double quotes. This makes the date parsing code unable
22150 // to match the date string and parse it as a date.
22151 if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
22152 iso = iso.substring(1, iso.length - 1);
22154 if (ISO_DATE_REGEXP.test(iso)) {
22155 return new Date(iso);
22157 regexp.lastIndex = 0;
22158 parts = regexp.exec(iso);
22164 yyyy: date.getFullYear(),
22165 MM: date.getMonth() + 1,
22166 dd: date.getDate(),
22167 HH: date.getHours(),
22168 mm: date.getMinutes(),
22169 ss: date.getSeconds(),
22170 sss: date.getMilliseconds() / 1000
22173 map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
22176 forEach(parts, function(part, index) {
22177 if (index < mapping.length) {
22178 map[mapping[index]] = +part;
22181 return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
22189 function createDateInputType(type, regexp, parseDate, format) {
22190 return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
22191 badInputChecker(scope, element, attr, ctrl);
22192 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22193 var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
22196 ctrl.$$parserName = type;
22197 ctrl.$parsers.push(function(value) {
22198 if (ctrl.$isEmpty(value)) return null;
22199 if (regexp.test(value)) {
22200 // Note: We cannot read ctrl.$modelValue, as there might be a different
22201 // parser/formatter in the processing chain so that the model
22202 // contains some different data format!
22203 var parsedDate = parseDate(value, previousDate);
22205 parsedDate = convertTimezoneToLocal(parsedDate, timezone);
22212 ctrl.$formatters.push(function(value) {
22213 if (value && !isDate(value)) {
22214 throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
22216 if (isValidDate(value)) {
22217 previousDate = value;
22218 if (previousDate && timezone) {
22219 previousDate = convertTimezoneToLocal(previousDate, timezone, true);
22221 return $filter('date')(value, format, timezone);
22223 previousDate = null;
22228 if (isDefined(attr.min) || attr.ngMin) {
22230 ctrl.$validators.min = function(value) {
22231 return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
22233 attr.$observe('min', function(val) {
22234 minVal = parseObservedDateValue(val);
22239 if (isDefined(attr.max) || attr.ngMax) {
22241 ctrl.$validators.max = function(value) {
22242 return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
22244 attr.$observe('max', function(val) {
22245 maxVal = parseObservedDateValue(val);
22250 function isValidDate(value) {
22251 // Invalid Date: getTime() returns NaN
22252 return value && !(value.getTime && value.getTime() !== value.getTime());
22255 function parseObservedDateValue(val) {
22256 return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
22261 function badInputChecker(scope, element, attr, ctrl) {
22262 var node = element[0];
22263 var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
22264 if (nativeValidation) {
22265 ctrl.$parsers.push(function(value) {
22266 var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
22267 return validity.badInput || validity.typeMismatch ? undefined : value;
22272 function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22273 badInputChecker(scope, element, attr, ctrl);
22274 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22276 ctrl.$$parserName = 'number';
22277 ctrl.$parsers.push(function(value) {
22278 if (ctrl.$isEmpty(value)) return null;
22279 if (NUMBER_REGEXP.test(value)) return parseFloat(value);
22283 ctrl.$formatters.push(function(value) {
22284 if (!ctrl.$isEmpty(value)) {
22285 if (!isNumber(value)) {
22286 throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
22288 value = value.toString();
22293 if (isDefined(attr.min) || attr.ngMin) {
22295 ctrl.$validators.min = function(value) {
22296 return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
22299 attr.$observe('min', function(val) {
22300 if (isDefined(val) && !isNumber(val)) {
22301 val = parseFloat(val, 10);
22303 minVal = isNumber(val) && !isNaN(val) ? val : undefined;
22304 // TODO(matsko): implement validateLater to reduce number of validations
22309 if (isDefined(attr.max) || attr.ngMax) {
22311 ctrl.$validators.max = function(value) {
22312 return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
22315 attr.$observe('max', function(val) {
22316 if (isDefined(val) && !isNumber(val)) {
22317 val = parseFloat(val, 10);
22319 maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
22320 // TODO(matsko): implement validateLater to reduce number of validations
22326 function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22327 // Note: no badInputChecker here by purpose as `url` is only a validation
22328 // in browsers, i.e. we can always read out input.value even if it is not valid!
22329 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22330 stringBasedInputType(ctrl);
22332 ctrl.$$parserName = 'url';
22333 ctrl.$validators.url = function(modelValue, viewValue) {
22334 var value = modelValue || viewValue;
22335 return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
22339 function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
22340 // Note: no badInputChecker here by purpose as `url` is only a validation
22341 // in browsers, i.e. we can always read out input.value even if it is not valid!
22342 baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
22343 stringBasedInputType(ctrl);
22345 ctrl.$$parserName = 'email';
22346 ctrl.$validators.email = function(modelValue, viewValue) {
22347 var value = modelValue || viewValue;
22348 return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
22352 function radioInputType(scope, element, attr, ctrl) {
22353 // make the name unique, if not defined
22354 if (isUndefined(attr.name)) {
22355 element.attr('name', nextUid());
22358 var listener = function(ev) {
22359 if (element[0].checked) {
22360 ctrl.$setViewValue(attr.value, ev && ev.type);
22364 element.on('click', listener);
22366 ctrl.$render = function() {
22367 var value = attr.value;
22368 element[0].checked = (value == ctrl.$viewValue);
22371 attr.$observe('value', ctrl.$render);
22374 function parseConstantExpr($parse, context, name, expression, fallback) {
22376 if (isDefined(expression)) {
22377 parseFn = $parse(expression);
22378 if (!parseFn.constant) {
22379 throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
22380 '`{1}`.', name, expression);
22382 return parseFn(context);
22387 function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
22388 var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
22389 var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
22391 var listener = function(ev) {
22392 ctrl.$setViewValue(element[0].checked, ev && ev.type);
22395 element.on('click', listener);
22397 ctrl.$render = function() {
22398 element[0].checked = ctrl.$viewValue;
22401 // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
22402 // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
22403 // it to a boolean.
22404 ctrl.$isEmpty = function(value) {
22405 return value === false;
22408 ctrl.$formatters.push(function(value) {
22409 return equals(value, trueValue);
22412 ctrl.$parsers.push(function(value) {
22413 return value ? trueValue : falseValue;
22424 * HTML textarea element control with angular data-binding. The data-binding and validation
22425 * properties of this element are exactly the same as those of the
22426 * {@link ng.directive:input input element}.
22428 * @param {string} ngModel Assignable angular expression to data-bind to.
22429 * @param {string=} name Property name of the form under which the control is published.
22430 * @param {string=} required Sets `required` validation error key if the value is not entered.
22431 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
22432 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
22433 * `required` when you want to data-bind to the `required` attribute.
22434 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22436 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22437 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
22439 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
22440 * a RegExp found by evaluating the Angular expression given in the attribute value.
22441 * If the expression evaluates to a RegExp object, then this is used directly.
22442 * If the expression evaluates to a string, then it will be converted to a RegExp
22443 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22444 * `new RegExp('^abc$')`.<br />
22445 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22446 * start at the index of the last search's match, thus not taking the whole input value into
22448 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22449 * interaction with the input element.
22450 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
22460 * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
22461 * input state control, and validation.
22462 * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
22464 * <div class="alert alert-warning">
22465 * **Note:** Not every feature offered is available for all input types.
22466 * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
22469 * @param {string} ngModel Assignable angular expression to data-bind to.
22470 * @param {string=} name Property name of the form under which the control is published.
22471 * @param {string=} required Sets `required` validation error key if the value is not entered.
22472 * @param {boolean=} ngRequired Sets `required` attribute if set to true
22473 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
22475 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
22476 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
22478 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
22479 * a RegExp found by evaluating the Angular expression given in the attribute value.
22480 * If the expression evaluates to a RegExp object, then this is used directly.
22481 * If the expression evaluates to a string, then it will be converted to a RegExp
22482 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
22483 * `new RegExp('^abc$')`.<br />
22484 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
22485 * start at the index of the last search's match, thus not taking the whole input value into
22487 * @param {string=} ngChange Angular expression to be executed when input changes due to user
22488 * interaction with the input element.
22489 * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
22490 * This parameter is ignored for input[type=password] controls, which will never trim the
22494 <example name="input-directive" module="inputExample">
22495 <file name="index.html">
22497 angular.module('inputExample', [])
22498 .controller('ExampleController', ['$scope', function($scope) {
22499 $scope.user = {name: 'guest', last: 'visitor'};
22502 <div ng-controller="ExampleController">
22503 <form name="myForm">
22506 <input type="text" name="userName" ng-model="user.name" required>
22509 <span class="error" ng-show="myForm.userName.$error.required">
22514 <input type="text" name="lastName" ng-model="user.last"
22515 ng-minlength="3" ng-maxlength="10">
22518 <span class="error" ng-show="myForm.lastName.$error.minlength">
22520 <span class="error" ng-show="myForm.lastName.$error.maxlength">
22525 <tt>user = {{user}}</tt><br/>
22526 <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
22527 <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
22528 <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
22529 <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
22530 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
22531 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
22532 <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
22533 <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
22536 <file name="protractor.js" type="protractor">
22537 var user = element(by.exactBinding('user'));
22538 var userNameValid = element(by.binding('myForm.userName.$valid'));
22539 var lastNameValid = element(by.binding('myForm.lastName.$valid'));
22540 var lastNameError = element(by.binding('myForm.lastName.$error'));
22541 var formValid = element(by.binding('myForm.$valid'));
22542 var userNameInput = element(by.model('user.name'));
22543 var userLastInput = element(by.model('user.last'));
22545 it('should initialize to model', function() {
22546 expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
22547 expect(userNameValid.getText()).toContain('true');
22548 expect(formValid.getText()).toContain('true');
22551 it('should be invalid if empty when required', function() {
22552 userNameInput.clear();
22553 userNameInput.sendKeys('');
22555 expect(user.getText()).toContain('{"last":"visitor"}');
22556 expect(userNameValid.getText()).toContain('false');
22557 expect(formValid.getText()).toContain('false');
22560 it('should be valid if empty when min length is set', function() {
22561 userLastInput.clear();
22562 userLastInput.sendKeys('');
22564 expect(user.getText()).toContain('{"name":"guest","last":""}');
22565 expect(lastNameValid.getText()).toContain('true');
22566 expect(formValid.getText()).toContain('true');
22569 it('should be invalid if less than required min length', function() {
22570 userLastInput.clear();
22571 userLastInput.sendKeys('xx');
22573 expect(user.getText()).toContain('{"name":"guest"}');
22574 expect(lastNameValid.getText()).toContain('false');
22575 expect(lastNameError.getText()).toContain('minlength');
22576 expect(formValid.getText()).toContain('false');
22579 it('should be invalid if longer than max length', function() {
22580 userLastInput.clear();
22581 userLastInput.sendKeys('some ridiculously long name');
22583 expect(user.getText()).toContain('{"name":"guest"}');
22584 expect(lastNameValid.getText()).toContain('false');
22585 expect(lastNameError.getText()).toContain('maxlength');
22586 expect(formValid.getText()).toContain('false');
22591 var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
22592 function($browser, $sniffer, $filter, $parse) {
22595 require: ['?ngModel'],
22597 pre: function(scope, element, attr, ctrls) {
22599 (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
22600 $browser, $filter, $parse);
22609 var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
22615 * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
22616 * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
22619 * `ngValue` is useful when dynamically generating lists of radio buttons using
22620 * {@link ngRepeat `ngRepeat`}, as shown below.
22622 * Likewise, `ngValue` can be used to generate `<option>` elements for
22623 * the {@link select `select`} element. In that case however, only strings are supported
22624 * for the `value `attribute, so the resulting `ngModel` will always be a string.
22625 * Support for `select` models with non-string values is available via `ngOptions`.
22628 * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
22629 * of the `input` element
22632 <example name="ngValue-directive" module="valueExample">
22633 <file name="index.html">
22635 angular.module('valueExample', [])
22636 .controller('ExampleController', ['$scope', function($scope) {
22637 $scope.names = ['pizza', 'unicorns', 'robots'];
22638 $scope.my = { favorite: 'unicorns' };
22641 <form ng-controller="ExampleController">
22642 <h2>Which is your favorite?</h2>
22643 <label ng-repeat="name in names" for="{{name}}">
22645 <input type="radio"
22646 ng-model="my.favorite"
22651 <div>You chose {{my.favorite}}</div>
22654 <file name="protractor.js" type="protractor">
22655 var favorite = element(by.binding('my.favorite'));
22657 it('should initialize to model', function() {
22658 expect(favorite.getText()).toContain('unicorns');
22660 it('should bind the values to the inputs', function() {
22661 element.all(by.model('my.favorite')).get(0).click();
22662 expect(favorite.getText()).toContain('pizza');
22667 var ngValueDirective = function() {
22671 compile: function(tpl, tplAttr) {
22672 if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
22673 return function ngValueConstantLink(scope, elm, attr) {
22674 attr.$set('value', scope.$eval(attr.ngValue));
22677 return function ngValueLink(scope, elm, attr) {
22678 scope.$watch(attr.ngValue, function valueWatchAction(value) {
22679 attr.$set('value', value);
22693 * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
22694 * with the value of a given expression, and to update the text content when the value of that
22695 * expression changes.
22697 * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
22698 * `{{ expression }}` which is similar but less verbose.
22700 * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
22701 * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
22702 * element attribute, it makes the bindings invisible to the user while the page is loading.
22704 * An alternative solution to this problem would be using the
22705 * {@link ng.directive:ngCloak ngCloak} directive.
22709 * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
22712 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
22713 <example module="bindExample">
22714 <file name="index.html">
22716 angular.module('bindExample', [])
22717 .controller('ExampleController', ['$scope', function($scope) {
22718 $scope.name = 'Whirled';
22721 <div ng-controller="ExampleController">
22722 <label>Enter name: <input type="text" ng-model="name"></label><br>
22723 Hello <span ng-bind="name"></span>!
22726 <file name="protractor.js" type="protractor">
22727 it('should check ng-bind', function() {
22728 var nameInput = element(by.model('name'));
22730 expect(element(by.binding('name')).getText()).toBe('Whirled');
22732 nameInput.sendKeys('world');
22733 expect(element(by.binding('name')).getText()).toBe('world');
22738 var ngBindDirective = ['$compile', function($compile) {
22741 compile: function ngBindCompile(templateElement) {
22742 $compile.$$addBindingClass(templateElement);
22743 return function ngBindLink(scope, element, attr) {
22744 $compile.$$addBindingInfo(element, attr.ngBind);
22745 element = element[0];
22746 scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
22747 element.textContent = isUndefined(value) ? '' : value;
22757 * @name ngBindTemplate
22760 * The `ngBindTemplate` directive specifies that the element
22761 * text content should be replaced with the interpolation of the template
22762 * in the `ngBindTemplate` attribute.
22763 * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
22764 * expressions. This directive is needed since some HTML elements
22765 * (such as TITLE and OPTION) cannot contain SPAN elements.
22768 * @param {string} ngBindTemplate template of form
22769 * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
22772 * Try it here: enter text in text box and watch the greeting change.
22773 <example module="bindExample">
22774 <file name="index.html">
22776 angular.module('bindExample', [])
22777 .controller('ExampleController', ['$scope', function($scope) {
22778 $scope.salutation = 'Hello';
22779 $scope.name = 'World';
22782 <div ng-controller="ExampleController">
22783 <label>Salutation: <input type="text" ng-model="salutation"></label><br>
22784 <label>Name: <input type="text" ng-model="name"></label><br>
22785 <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
22788 <file name="protractor.js" type="protractor">
22789 it('should check ng-bind', function() {
22790 var salutationElem = element(by.binding('salutation'));
22791 var salutationInput = element(by.model('salutation'));
22792 var nameInput = element(by.model('name'));
22794 expect(salutationElem.getText()).toBe('Hello World!');
22796 salutationInput.clear();
22797 salutationInput.sendKeys('Greetings');
22799 nameInput.sendKeys('user');
22801 expect(salutationElem.getText()).toBe('Greetings user!');
22806 var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
22808 compile: function ngBindTemplateCompile(templateElement) {
22809 $compile.$$addBindingClass(templateElement);
22810 return function ngBindTemplateLink(scope, element, attr) {
22811 var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
22812 $compile.$$addBindingInfo(element, interpolateFn.expressions);
22813 element = element[0];
22814 attr.$observe('ngBindTemplate', function(value) {
22815 element.textContent = isUndefined(value) ? '' : value;
22828 * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
22829 * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
22830 * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
22831 * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
22832 * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
22834 * You may also bypass sanitization for values you know are safe. To do so, bind to
22835 * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
22836 * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
22838 * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
22839 * will have an exception (instead of an exploit.)
22842 * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
22846 <example module="bindHtmlExample" deps="angular-sanitize.js">
22847 <file name="index.html">
22848 <div ng-controller="ExampleController">
22849 <p ng-bind-html="myHTML"></p>
22853 <file name="script.js">
22854 angular.module('bindHtmlExample', ['ngSanitize'])
22855 .controller('ExampleController', ['$scope', function($scope) {
22857 'I am an <code>HTML</code>string with ' +
22858 '<a href="#">links!</a> and other <em>stuff</em>';
22862 <file name="protractor.js" type="protractor">
22863 it('should check ng-bind-html', function() {
22864 expect(element(by.binding('myHTML')).getText()).toBe(
22865 'I am an HTMLstring with links! and other stuff');
22870 var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
22873 compile: function ngBindHtmlCompile(tElement, tAttrs) {
22874 var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
22875 var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
22876 return (value || '').toString();
22878 $compile.$$addBindingClass(tElement);
22880 return function ngBindHtmlLink(scope, element, attr) {
22881 $compile.$$addBindingInfo(element, attr.ngBindHtml);
22883 scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
22884 // we re-evaluate the expr because we want a TrustedValueHolderType
22885 // for $sce, not a string
22886 element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
22898 * Evaluate the given expression when the user changes the input.
22899 * The expression is evaluated immediately, unlike the JavaScript onchange event
22900 * which only triggers at the end of a change (usually, when the user leaves the
22901 * form element or presses the return key).
22903 * The `ngChange` expression is only evaluated when a change in the input value causes
22904 * a new value to be committed to the model.
22906 * It will not be evaluated:
22907 * * if the value returned from the `$parsers` transformation pipeline has not changed
22908 * * if the input has continued to be invalid since the model will stay `null`
22909 * * if the model is changed programmatically and not by a change to the input value
22912 * Note, this directive requires `ngModel` to be present.
22915 * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
22919 * <example name="ngChange-directive" module="changeExample">
22920 * <file name="index.html">
22922 * angular.module('changeExample', [])
22923 * .controller('ExampleController', ['$scope', function($scope) {
22924 * $scope.counter = 0;
22925 * $scope.change = function() {
22926 * $scope.counter++;
22930 * <div ng-controller="ExampleController">
22931 * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
22932 * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
22933 * <label for="ng-change-example2">Confirmed</label><br />
22934 * <tt>debug = {{confirmed}}</tt><br/>
22935 * <tt>counter = {{counter}}</tt><br/>
22938 * <file name="protractor.js" type="protractor">
22939 * var counter = element(by.binding('counter'));
22940 * var debug = element(by.binding('confirmed'));
22942 * it('should evaluate the expression if changing from view', function() {
22943 * expect(counter.getText()).toContain('0');
22945 * element(by.id('ng-change-example1')).click();
22947 * expect(counter.getText()).toContain('1');
22948 * expect(debug.getText()).toContain('true');
22951 * it('should not evaluate the expression if changing from model', function() {
22952 * element(by.id('ng-change-example2')).click();
22954 * expect(counter.getText()).toContain('0');
22955 * expect(debug.getText()).toContain('true');
22960 var ngChangeDirective = valueFn({
22962 require: 'ngModel',
22963 link: function(scope, element, attr, ctrl) {
22964 ctrl.$viewChangeListeners.push(function() {
22965 scope.$eval(attr.ngChange);
22970 function classDirective(name, selector) {
22971 name = 'ngClass' + name;
22972 return ['$animate', function($animate) {
22975 link: function(scope, element, attr) {
22978 scope.$watch(attr[name], ngClassWatchAction, true);
22980 attr.$observe('class', function(value) {
22981 ngClassWatchAction(scope.$eval(attr[name]));
22985 if (name !== 'ngClass') {
22986 scope.$watch('$index', function($index, old$index) {
22987 // jshint bitwise: false
22988 var mod = $index & 1;
22989 if (mod !== (old$index & 1)) {
22990 var classes = arrayClasses(scope.$eval(attr[name]));
22992 addClasses(classes) :
22993 removeClasses(classes);
22998 function addClasses(classes) {
22999 var newClasses = digestClassCounts(classes, 1);
23000 attr.$addClass(newClasses);
23003 function removeClasses(classes) {
23004 var newClasses = digestClassCounts(classes, -1);
23005 attr.$removeClass(newClasses);
23008 function digestClassCounts(classes, count) {
23009 // Use createMap() to prevent class assumptions involving property
23010 // names in Object.prototype
23011 var classCounts = element.data('$classCounts') || createMap();
23012 var classesToUpdate = [];
23013 forEach(classes, function(className) {
23014 if (count > 0 || classCounts[className]) {
23015 classCounts[className] = (classCounts[className] || 0) + count;
23016 if (classCounts[className] === +(count > 0)) {
23017 classesToUpdate.push(className);
23021 element.data('$classCounts', classCounts);
23022 return classesToUpdate.join(' ');
23025 function updateClasses(oldClasses, newClasses) {
23026 var toAdd = arrayDifference(newClasses, oldClasses);
23027 var toRemove = arrayDifference(oldClasses, newClasses);
23028 toAdd = digestClassCounts(toAdd, 1);
23029 toRemove = digestClassCounts(toRemove, -1);
23030 if (toAdd && toAdd.length) {
23031 $animate.addClass(element, toAdd);
23033 if (toRemove && toRemove.length) {
23034 $animate.removeClass(element, toRemove);
23038 function ngClassWatchAction(newVal) {
23039 if (selector === true || scope.$index % 2 === selector) {
23040 var newClasses = arrayClasses(newVal || []);
23042 addClasses(newClasses);
23043 } else if (!equals(newVal,oldVal)) {
23044 var oldClasses = arrayClasses(oldVal);
23045 updateClasses(oldClasses, newClasses);
23048 oldVal = shallowCopy(newVal);
23053 function arrayDifference(tokens1, tokens2) {
23057 for (var i = 0; i < tokens1.length; i++) {
23058 var token = tokens1[i];
23059 for (var j = 0; j < tokens2.length; j++) {
23060 if (token == tokens2[j]) continue outer;
23062 values.push(token);
23067 function arrayClasses(classVal) {
23069 if (isArray(classVal)) {
23070 forEach(classVal, function(v) {
23071 classes = classes.concat(arrayClasses(v));
23074 } else if (isString(classVal)) {
23075 return classVal.split(' ');
23076 } else if (isObject(classVal)) {
23077 forEach(classVal, function(v, k) {
23079 classes = classes.concat(k.split(' '));
23095 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
23096 * an expression that represents all classes to be added.
23098 * The directive operates in three different ways, depending on which of three types the expression
23101 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
23104 * 2. If the expression evaluates to an object, then for each key-value pair of the
23105 * object with a truthy value the corresponding key is used as a class name.
23107 * 3. If the expression evaluates to an array, each element of the array should either be a string as in
23108 * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
23109 * to give you more control over what CSS classes appear. See the code below for an example of this.
23112 * The directive won't add duplicate classes if a particular class was already set.
23114 * When the expression changes, the previously added classes are removed and only then are the
23115 * new classes added.
23118 * **add** - happens just before the class is applied to the elements
23120 * **remove** - happens just before the class is removed from the element
23123 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
23124 * of the evaluation can be a string representing space delimited class
23125 * names, an array, or a map of class names to boolean values. In the case of a map, the
23126 * names of the properties whose values are truthy will be added as css classes to the
23129 * @example Example that demonstrates basic bindings via ngClass directive.
23131 <file name="index.html">
23132 <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
23134 <input type="checkbox" ng-model="deleted">
23135 deleted (apply "strike" class)
23138 <input type="checkbox" ng-model="important">
23139 important (apply "bold" class)
23142 <input type="checkbox" ng-model="error">
23143 error (apply "has-error" class)
23146 <p ng-class="style">Using String Syntax</p>
23147 <input type="text" ng-model="style"
23148 placeholder="Type: bold strike red" aria-label="Type: bold strike red">
23150 <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
23151 <input ng-model="style1"
23152 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
23153 <input ng-model="style2"
23154 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
23155 <input ng-model="style3"
23156 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
23158 <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
23159 <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
23160 <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
23162 <file name="style.css">
23164 text-decoration: line-through;
23174 background-color: yellow;
23180 <file name="protractor.js" type="protractor">
23181 var ps = element.all(by.css('p'));
23183 it('should let you toggle the class', function() {
23185 expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
23186 expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
23188 element(by.model('important')).click();
23189 expect(ps.first().getAttribute('class')).toMatch(/bold/);
23191 element(by.model('error')).click();
23192 expect(ps.first().getAttribute('class')).toMatch(/has-error/);
23195 it('should let you toggle string example', function() {
23196 expect(ps.get(1).getAttribute('class')).toBe('');
23197 element(by.model('style')).clear();
23198 element(by.model('style')).sendKeys('red');
23199 expect(ps.get(1).getAttribute('class')).toBe('red');
23202 it('array example should have 3 classes', function() {
23203 expect(ps.get(2).getAttribute('class')).toBe('');
23204 element(by.model('style1')).sendKeys('bold');
23205 element(by.model('style2')).sendKeys('strike');
23206 element(by.model('style3')).sendKeys('red');
23207 expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
23210 it('array with map example should have 2 classes', function() {
23211 expect(ps.last().getAttribute('class')).toBe('');
23212 element(by.model('style4')).sendKeys('bold');
23213 element(by.model('warning')).click();
23214 expect(ps.last().getAttribute('class')).toBe('bold orange');
23221 The example below demonstrates how to perform animations using ngClass.
23223 <example module="ngAnimate" deps="angular-animate.js" animations="true">
23224 <file name="index.html">
23225 <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
23226 <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
23228 <span class="base-class" ng-class="myVar">Sample Text</span>
23230 <file name="style.css">
23232 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
23235 .base-class.my-class {
23240 <file name="protractor.js" type="protractor">
23241 it('should check ng-class', function() {
23242 expect(element(by.css('.base-class')).getAttribute('class')).not.
23243 toMatch(/my-class/);
23245 element(by.id('setbtn')).click();
23247 expect(element(by.css('.base-class')).getAttribute('class')).
23248 toMatch(/my-class/);
23250 element(by.id('clearbtn')).click();
23252 expect(element(by.css('.base-class')).getAttribute('class')).not.
23253 toMatch(/my-class/);
23259 ## ngClass and pre-existing CSS3 Transitions/Animations
23260 The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
23261 Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
23262 any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
23263 to view the step by step details of {@link $animate#addClass $animate.addClass} and
23264 {@link $animate#removeClass $animate.removeClass}.
23266 var ngClassDirective = classDirective('', true);
23274 * The `ngClassOdd` and `ngClassEven` directives work exactly as
23275 * {@link ng.directive:ngClass ngClass}, except they work in
23276 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
23278 * This directive can be applied only within the scope of an
23279 * {@link ng.directive:ngRepeat ngRepeat}.
23282 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
23283 * of the evaluation can be a string representing space delimited class names or an array.
23287 <file name="index.html">
23288 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23289 <li ng-repeat="name in names">
23290 <span ng-class-odd="'odd'" ng-class-even="'even'">
23296 <file name="style.css">
23304 <file name="protractor.js" type="protractor">
23305 it('should check ng-class-odd and ng-class-even', function() {
23306 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
23308 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
23314 var ngClassOddDirective = classDirective('Odd', 0);
23318 * @name ngClassEven
23322 * The `ngClassOdd` and `ngClassEven` directives work exactly as
23323 * {@link ng.directive:ngClass ngClass}, except they work in
23324 * conjunction with `ngRepeat` and take effect only on odd (even) rows.
23326 * This directive can be applied only within the scope of an
23327 * {@link ng.directive:ngRepeat ngRepeat}.
23330 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
23331 * result of the evaluation can be a string representing space delimited class names or an array.
23335 <file name="index.html">
23336 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
23337 <li ng-repeat="name in names">
23338 <span ng-class-odd="'odd'" ng-class-even="'even'">
23339 {{name}}
23344 <file name="style.css">
23352 <file name="protractor.js" type="protractor">
23353 it('should check ng-class-odd and ng-class-even', function() {
23354 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
23356 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
23362 var ngClassEvenDirective = classDirective('Even', 1);
23370 * The `ngCloak` directive is used to prevent the Angular html template from being briefly
23371 * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
23372 * directive to avoid the undesirable flicker effect caused by the html template display.
23374 * The directive can be applied to the `<body>` element, but the preferred usage is to apply
23375 * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
23376 * of the browser view.
23378 * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
23379 * `angular.min.js`.
23380 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
23383 * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
23384 * display: none !important;
23388 * When this css rule is loaded by the browser, all html elements (including their children) that
23389 * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
23390 * during the compilation of the template it deletes the `ngCloak` element attribute, making
23391 * the compiled element visible.
23393 * For the best result, the `angular.js` script must be loaded in the head section of the html
23394 * document; alternatively, the css rule above must be included in the external stylesheet of the
23401 <file name="index.html">
23402 <div id="template1" ng-cloak>{{ 'hello' }}</div>
23403 <div id="template2" class="ng-cloak">{{ 'world' }}</div>
23405 <file name="protractor.js" type="protractor">
23406 it('should remove the template directive and css class', function() {
23407 expect($('#template1').getAttribute('ng-cloak')).
23409 expect($('#template2').getAttribute('ng-cloak')).
23416 var ngCloakDirective = ngDirective({
23417 compile: function(element, attr) {
23418 attr.$set('ngCloak', undefined);
23419 element.removeClass('ng-cloak');
23425 * @name ngController
23428 * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
23429 * supports the principles behind the Model-View-Controller design pattern.
23431 * MVC components in angular:
23433 * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
23434 * are accessed through bindings.
23435 * * View — The template (HTML with data bindings) that is rendered into the View.
23436 * * Controller — The `ngController` directive specifies a Controller class; the class contains business
23437 * logic behind the application to decorate the scope with functions and values
23439 * Note that you can also attach controllers to the DOM by declaring it in a route definition
23440 * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
23441 * again using `ng-controller` in the template itself. This will cause the controller to be attached
23442 * and executed twice.
23447 * @param {expression} ngController Name of a constructor function registered with the current
23448 * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
23449 * that on the current scope evaluates to a constructor function.
23451 * The controller instance can be published into a scope property by specifying
23452 * `ng-controller="as propertyName"`.
23454 * If the current `$controllerProvider` is configured to use globals (via
23455 * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
23456 * also be the name of a globally accessible constructor function (not recommended).
23459 * Here is a simple form for editing user contact information. Adding, removing, clearing, and
23460 * greeting are methods declared on the controller (see source tab). These methods can
23461 * easily be called from the angular markup. Any changes to the data are automatically reflected
23462 * in the View without the need for a manual update.
23464 * Two different declaration styles are included below:
23466 * * one binds methods and properties directly onto the controller using `this`:
23467 * `ng-controller="SettingsController1 as settings"`
23468 * * one injects `$scope` into the controller:
23469 * `ng-controller="SettingsController2"`
23471 * The second option is more common in the Angular community, and is generally used in boilerplates
23472 * and in this guide. However, there are advantages to binding properties directly to the controller
23473 * and avoiding scope.
23475 * * Using `controller as` makes it obvious which controller you are accessing in the template when
23476 * multiple controllers apply to an element.
23477 * * If you are writing your controllers as classes you have easier access to the properties and
23478 * methods, which will appear on the scope, from inside the controller code.
23479 * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
23480 * inheritance masking primitives.
23482 * This example demonstrates the `controller as` syntax.
23484 * <example name="ngControllerAs" module="controllerAsExample">
23485 * <file name="index.html">
23486 * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
23487 * <label>Name: <input type="text" ng-model="settings.name"/></label>
23488 * <button ng-click="settings.greet()">greet</button><br/>
23491 * <li ng-repeat="contact in settings.contacts">
23492 * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
23493 * <option>phone</option>
23494 * <option>email</option>
23496 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
23497 * <button ng-click="settings.clearContact(contact)">clear</button>
23498 * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
23500 * <li><button ng-click="settings.addContact()">add</button></li>
23504 * <file name="app.js">
23505 * angular.module('controllerAsExample', [])
23506 * .controller('SettingsController1', SettingsController1);
23508 * function SettingsController1() {
23509 * this.name = "John Smith";
23510 * this.contacts = [
23511 * {type: 'phone', value: '408 555 1212'},
23512 * {type: 'email', value: 'john.smith@example.org'} ];
23515 * SettingsController1.prototype.greet = function() {
23516 * alert(this.name);
23519 * SettingsController1.prototype.addContact = function() {
23520 * this.contacts.push({type: 'email', value: 'yourname@example.org'});
23523 * SettingsController1.prototype.removeContact = function(contactToRemove) {
23524 * var index = this.contacts.indexOf(contactToRemove);
23525 * this.contacts.splice(index, 1);
23528 * SettingsController1.prototype.clearContact = function(contact) {
23529 * contact.type = 'phone';
23530 * contact.value = '';
23533 * <file name="protractor.js" type="protractor">
23534 * it('should check controller as', function() {
23535 * var container = element(by.id('ctrl-as-exmpl'));
23536 * expect(container.element(by.model('settings.name'))
23537 * .getAttribute('value')).toBe('John Smith');
23539 * var firstRepeat =
23540 * container.element(by.repeater('contact in settings.contacts').row(0));
23541 * var secondRepeat =
23542 * container.element(by.repeater('contact in settings.contacts').row(1));
23544 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
23545 * .toBe('408 555 1212');
23547 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
23548 * .toBe('john.smith@example.org');
23550 * firstRepeat.element(by.buttonText('clear')).click();
23552 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
23555 * container.element(by.buttonText('add')).click();
23557 * expect(container.element(by.repeater('contact in settings.contacts').row(2))
23558 * .element(by.model('contact.value'))
23559 * .getAttribute('value'))
23560 * .toBe('yourname@example.org');
23565 * This example demonstrates the "attach to `$scope`" style of controller.
23567 * <example name="ngController" module="controllerExample">
23568 * <file name="index.html">
23569 * <div id="ctrl-exmpl" ng-controller="SettingsController2">
23570 * <label>Name: <input type="text" ng-model="name"/></label>
23571 * <button ng-click="greet()">greet</button><br/>
23574 * <li ng-repeat="contact in contacts">
23575 * <select ng-model="contact.type" id="select_{{$index}}">
23576 * <option>phone</option>
23577 * <option>email</option>
23579 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
23580 * <button ng-click="clearContact(contact)">clear</button>
23581 * <button ng-click="removeContact(contact)">X</button>
23583 * <li>[ <button ng-click="addContact()">add</button> ]</li>
23587 * <file name="app.js">
23588 * angular.module('controllerExample', [])
23589 * .controller('SettingsController2', ['$scope', SettingsController2]);
23591 * function SettingsController2($scope) {
23592 * $scope.name = "John Smith";
23593 * $scope.contacts = [
23594 * {type:'phone', value:'408 555 1212'},
23595 * {type:'email', value:'john.smith@example.org'} ];
23597 * $scope.greet = function() {
23598 * alert($scope.name);
23601 * $scope.addContact = function() {
23602 * $scope.contacts.push({type:'email', value:'yourname@example.org'});
23605 * $scope.removeContact = function(contactToRemove) {
23606 * var index = $scope.contacts.indexOf(contactToRemove);
23607 * $scope.contacts.splice(index, 1);
23610 * $scope.clearContact = function(contact) {
23611 * contact.type = 'phone';
23612 * contact.value = '';
23616 * <file name="protractor.js" type="protractor">
23617 * it('should check controller', function() {
23618 * var container = element(by.id('ctrl-exmpl'));
23620 * expect(container.element(by.model('name'))
23621 * .getAttribute('value')).toBe('John Smith');
23623 * var firstRepeat =
23624 * container.element(by.repeater('contact in contacts').row(0));
23625 * var secondRepeat =
23626 * container.element(by.repeater('contact in contacts').row(1));
23628 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
23629 * .toBe('408 555 1212');
23630 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
23631 * .toBe('john.smith@example.org');
23633 * firstRepeat.element(by.buttonText('clear')).click();
23635 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
23638 * container.element(by.buttonText('add')).click();
23640 * expect(container.element(by.repeater('contact in contacts').row(2))
23641 * .element(by.model('contact.value'))
23642 * .getAttribute('value'))
23643 * .toBe('yourname@example.org');
23649 var ngControllerDirective = [function() {
23665 * Angular has some features that can break certain
23666 * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
23668 * If you intend to implement these rules then you must tell Angular not to use these features.
23670 * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
23673 * The following rules affect Angular:
23675 * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
23676 * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
23677 * increase in the speed of evaluating Angular expressions.
23679 * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
23680 * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
23681 * To make these directives work when a CSP rule is blocking inline styles, you must link to the
23682 * `angular-csp.css` in your HTML manually.
23684 * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
23685 * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
23686 * however, triggers a CSP error to be logged in the console:
23689 * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
23690 * script in the following Content Security Policy directive: "default-src 'self'". Note that
23691 * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
23694 * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
23695 * directive on an element of the HTML document that appears before the `<script>` tag that loads
23696 * the `angular.js` file.
23698 * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
23700 * You can specify which of the CSP related Angular features should be deactivated by providing
23701 * a value for the `ng-csp` attribute. The options are as follows:
23703 * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
23705 * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
23707 * You can use these values in the following combinations:
23710 * * No declaration means that Angular will assume that you can do inline styles, but it will do
23711 * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
23714 * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
23715 * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
23718 * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
23719 * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
23721 * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
23722 * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
23724 * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
23725 * styles nor use eval, which is the same as an empty: ng-csp.
23726 * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
23729 * This example shows how to apply the `ngCsp` directive to the `html` tag.
23732 <html ng-app ng-csp>
23738 // Note: the suffix `.csp` in the example name triggers
23739 // csp mode in our http server!
23740 <example name="example.csp" module="cspExample" ng-csp="true">
23741 <file name="index.html">
23742 <div ng-controller="MainController as ctrl">
23744 <button ng-click="ctrl.inc()" id="inc">Increment</button>
23745 <span id="counter">
23751 <button ng-click="ctrl.evil()" id="evil">Evil</button>
23752 <span id="evilError">
23758 <file name="script.js">
23759 angular.module('cspExample', [])
23760 .controller('MainController', function() {
23762 this.inc = function() {
23765 this.evil = function() {
23766 // jshint evil:true
23770 this.evilError = e.message;
23775 <file name="protractor.js" type="protractor">
23776 var util, webdriver;
23778 var incBtn = element(by.id('inc'));
23779 var counter = element(by.id('counter'));
23780 var evilBtn = element(by.id('evil'));
23781 var evilError = element(by.id('evilError'));
23783 function getAndClearSevereErrors() {
23784 return browser.manage().logs().get('browser').then(function(browserLog) {
23785 return browserLog.filter(function(logEntry) {
23786 return logEntry.level.value > webdriver.logging.Level.WARNING.value;
23791 function clearErrors() {
23792 getAndClearSevereErrors();
23795 function expectNoErrors() {
23796 getAndClearSevereErrors().then(function(filteredLog) {
23797 expect(filteredLog.length).toEqual(0);
23798 if (filteredLog.length) {
23799 console.log('browser console errors: ' + util.inspect(filteredLog));
23804 function expectError(regex) {
23805 getAndClearSevereErrors().then(function(filteredLog) {
23807 filteredLog.forEach(function(log) {
23808 if (log.message.match(regex)) {
23813 throw new Error('expected an error that matches ' + regex);
23818 beforeEach(function() {
23819 util = require('util');
23820 webdriver = require('protractor/node_modules/selenium-webdriver');
23823 // For now, we only test on Chrome,
23824 // as Safari does not load the page with Protractor's injected scripts,
23825 // and Firefox webdriver always disables content security policy (#6358)
23826 if (browser.params.browser !== 'chrome') {
23830 it('should not report errors when the page is loaded', function() {
23831 // clear errors so we are not dependent on previous tests
23833 // Need to reload the page as the page is already loaded when
23835 browser.driver.getCurrentUrl().then(function(url) {
23841 it('should evaluate expressions', function() {
23842 expect(counter.getText()).toEqual('0');
23844 expect(counter.getText()).toEqual('1');
23848 it('should throw and report an error when using "eval"', function() {
23850 expect(evilError.getText()).toMatch(/Content Security Policy/);
23851 expectError(/Content Security Policy/);
23857 // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
23858 // bootstrap the system (before $parse is instantiated), for this reason we just have
23859 // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
23866 * The ngClick directive allows you to specify custom behavior when
23867 * an element is clicked.
23871 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
23872 * click. ({@link guide/expression#-event- Event object is available as `$event`})
23876 <file name="index.html">
23877 <button ng-click="count = count + 1" ng-init="count=0">
23884 <file name="protractor.js" type="protractor">
23885 it('should check ng-click', function() {
23886 expect(element(by.binding('count')).getText()).toMatch('0');
23887 element(by.css('button')).click();
23888 expect(element(by.binding('count')).getText()).toMatch('1');
23894 * A collection of directives that allows creation of custom event handlers that are defined as
23895 * angular expressions and are compiled and executed within the current scope.
23897 var ngEventDirectives = {};
23899 // For events that might fire synchronously during DOM manipulation
23900 // we need to execute their event handlers asynchronously using $evalAsync,
23901 // so that they are not executed in an inconsistent state.
23902 var forceAsyncEvents = {
23907 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
23908 function(eventName) {
23909 var directiveName = directiveNormalize('ng-' + eventName);
23910 ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
23913 compile: function($element, attr) {
23914 // We expose the powerful $event object on the scope that provides access to the Window,
23915 // etc. that isn't protected by the fast paths in $parse. We explicitly request better
23916 // checks at the cost of speed since event handler expressions are not executed as
23917 // frequently as regular change detection.
23918 var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
23919 return function ngEventHandler(scope, element) {
23920 element.on(eventName, function(event) {
23921 var callback = function() {
23922 fn(scope, {$event:event});
23924 if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
23925 scope.$evalAsync(callback);
23927 scope.$apply(callback);
23942 * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
23946 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
23947 * a dblclick. (The Event object is available as `$event`)
23951 <file name="index.html">
23952 <button ng-dblclick="count = count + 1" ng-init="count=0">
23953 Increment (on double click)
23963 * @name ngMousedown
23966 * The ngMousedown directive allows you to specify custom behavior on mousedown event.
23970 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
23971 * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
23975 <file name="index.html">
23976 <button ng-mousedown="count = count + 1" ng-init="count=0">
23977 Increment (on mouse down)
23990 * Specify custom behavior on mouseup event.
23994 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
23995 * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
23999 <file name="index.html">
24000 <button ng-mouseup="count = count + 1" ng-init="count=0">
24001 Increment (on mouse up)
24010 * @name ngMouseover
24013 * Specify custom behavior on mouseover event.
24017 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
24018 * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
24022 <file name="index.html">
24023 <button ng-mouseover="count = count + 1" ng-init="count=0">
24024 Increment (when mouse is over)
24034 * @name ngMouseenter
24037 * Specify custom behavior on mouseenter event.
24041 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
24042 * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
24046 <file name="index.html">
24047 <button ng-mouseenter="count = count + 1" ng-init="count=0">
24048 Increment (when mouse enters)
24058 * @name ngMouseleave
24061 * Specify custom behavior on mouseleave event.
24065 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
24066 * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
24070 <file name="index.html">
24071 <button ng-mouseleave="count = count + 1" ng-init="count=0">
24072 Increment (when mouse leaves)
24082 * @name ngMousemove
24085 * Specify custom behavior on mousemove event.
24089 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
24090 * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
24094 <file name="index.html">
24095 <button ng-mousemove="count = count + 1" ng-init="count=0">
24096 Increment (when mouse moves)
24109 * Specify custom behavior on keydown event.
24113 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
24114 * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
24118 <file name="index.html">
24119 <input ng-keydown="count = count + 1" ng-init="count=0">
24120 key down count: {{count}}
24131 * Specify custom behavior on keyup event.
24135 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
24136 * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
24140 <file name="index.html">
24141 <p>Typing in the input box below updates the key count</p>
24142 <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
24144 <p>Typing in the input box below updates the keycode</p>
24145 <input ng-keyup="event=$event">
24146 <p>event keyCode: {{ event.keyCode }}</p>
24147 <p>event altKey: {{ event.altKey }}</p>
24158 * Specify custom behavior on keypress event.
24161 * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
24162 * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
24163 * and can be interrogated for keyCode, altKey, etc.)
24167 <file name="index.html">
24168 <input ng-keypress="count = count + 1" ng-init="count=0">
24169 key press count: {{count}}
24180 * Enables binding angular expressions to onsubmit events.
24182 * Additionally it prevents the default action (which for form means sending the request to the
24183 * server and reloading the current page), but only if the form does not contain `action`,
24184 * `data-action`, or `x-action` attributes.
24186 * <div class="alert alert-warning">
24187 * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
24188 * `ngSubmit` handlers together. See the
24189 * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
24190 * for a detailed discussion of when `ngSubmit` may be triggered.
24195 * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
24196 * ({@link guide/expression#-event- Event object is available as `$event`})
24199 <example module="submitExample">
24200 <file name="index.html">
24202 angular.module('submitExample', [])
24203 .controller('ExampleController', ['$scope', function($scope) {
24205 $scope.text = 'hello';
24206 $scope.submit = function() {
24208 $scope.list.push(this.text);
24214 <form ng-submit="submit()" ng-controller="ExampleController">
24215 Enter text and hit enter:
24216 <input type="text" ng-model="text" name="text" />
24217 <input type="submit" id="submit" value="Submit" />
24218 <pre>list={{list}}</pre>
24221 <file name="protractor.js" type="protractor">
24222 it('should check ng-submit', function() {
24223 expect(element(by.binding('list')).getText()).toBe('list=[]');
24224 element(by.css('#submit')).click();
24225 expect(element(by.binding('list')).getText()).toContain('hello');
24226 expect(element(by.model('text')).getAttribute('value')).toBe('');
24228 it('should ignore empty strings', function() {
24229 expect(element(by.binding('list')).getText()).toBe('list=[]');
24230 element(by.css('#submit')).click();
24231 element(by.css('#submit')).click();
24232 expect(element(by.binding('list')).getText()).toContain('hello');
24243 * Specify custom behavior on focus event.
24245 * Note: As the `focus` event is executed synchronously when calling `input.focus()`
24246 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
24247 * during an `$apply` to ensure a consistent state.
24249 * @element window, input, select, textarea, a
24251 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
24252 * focus. ({@link guide/expression#-event- Event object is available as `$event`})
24255 * See {@link ng.directive:ngClick ngClick}
24263 * Specify custom behavior on blur event.
24265 * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
24266 * an element has lost focus.
24268 * Note: As the `blur` event is executed synchronously also during DOM manipulations
24269 * (e.g. removing a focussed input),
24270 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
24271 * during an `$apply` to ensure a consistent state.
24273 * @element window, input, select, textarea, a
24275 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
24276 * blur. ({@link guide/expression#-event- Event object is available as `$event`})
24279 * See {@link ng.directive:ngClick ngClick}
24287 * Specify custom behavior on copy event.
24289 * @element window, input, select, textarea, a
24291 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
24292 * copy. ({@link guide/expression#-event- Event object is available as `$event`})
24296 <file name="index.html">
24297 <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
24308 * Specify custom behavior on cut event.
24310 * @element window, input, select, textarea, a
24312 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
24313 * cut. ({@link guide/expression#-event- Event object is available as `$event`})
24317 <file name="index.html">
24318 <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
24329 * Specify custom behavior on paste event.
24331 * @element window, input, select, textarea, a
24333 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
24334 * paste. ({@link guide/expression#-event- Event object is available as `$event`})
24338 <file name="index.html">
24339 <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
24352 * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
24353 * {expression}. If the expression assigned to `ngIf` evaluates to a false
24354 * value then the element is removed from the DOM, otherwise a clone of the
24355 * element is reinserted into the DOM.
24357 * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
24358 * element in the DOM rather than changing its visibility via the `display` css property. A common
24359 * case when this difference is significant is when using css selectors that rely on an element's
24360 * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
24362 * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
24363 * is created when the element is restored. The scope created within `ngIf` inherits from
24364 * its parent scope using
24365 * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
24366 * An important implication of this is if `ngModel` is used within `ngIf` to bind to
24367 * a javascript primitive defined in the parent scope. In this case any modifications made to the
24368 * variable within the child scope will override (hide) the value in the parent scope.
24370 * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
24371 * is if an element's class attribute is directly modified after it's compiled, using something like
24372 * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
24373 * the added class will be lost because the original compiled state is used to regenerate the element.
24375 * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
24376 * and `leave` effects.
24379 * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
24380 * leave - happens just before the `ngIf` contents are removed from the DOM
24385 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
24386 * the element is removed from the DOM tree. If it is truthy a copy of the compiled
24387 * element is added to the DOM tree.
24390 <example module="ngAnimate" deps="angular-animate.js" animations="true">
24391 <file name="index.html">
24392 <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
24394 <span ng-if="checked" class="animate-if">
24395 This is removed when the checkbox is unchecked.
24398 <file name="animations.css">
24401 border:1px solid black;
24405 .animate-if.ng-enter, .animate-if.ng-leave {
24406 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
24409 .animate-if.ng-enter,
24410 .animate-if.ng-leave.ng-leave-active {
24414 .animate-if.ng-leave,
24415 .animate-if.ng-enter.ng-enter-active {
24421 var ngIfDirective = ['$animate', function($animate) {
24423 multiElement: true,
24424 transclude: 'element',
24429 link: function($scope, $element, $attr, ctrl, $transclude) {
24430 var block, childScope, previousElements;
24431 $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
24435 $transclude(function(clone, newScope) {
24436 childScope = newScope;
24437 clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
24438 // Note: We only need the first/last node of the cloned nodes.
24439 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
24440 // by a directive with templateUrl when its template arrives.
24444 $animate.enter(clone, $element.parent(), $element);
24448 if (previousElements) {
24449 previousElements.remove();
24450 previousElements = null;
24453 childScope.$destroy();
24457 previousElements = getBlockNodes(block.clone);
24458 $animate.leave(previousElements).then(function() {
24459 previousElements = null;
24475 * Fetches, compiles and includes an external HTML fragment.
24477 * By default, the template URL is restricted to the same domain and protocol as the
24478 * application document. This is done by calling {@link $sce#getTrustedResourceUrl
24479 * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
24480 * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
24481 * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
24482 * ng.$sce Strict Contextual Escaping}.
24484 * In addition, the browser's
24485 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
24486 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
24487 * policy may further restrict whether the template is successfully loaded.
24488 * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
24489 * access on some browsers.
24492 * enter - animation is used to bring new content into the browser.
24493 * leave - animation is used to animate existing content away.
24495 * The enter and leave animation occur concurrently.
24500 * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
24501 * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
24502 * @param {string=} onload Expression to evaluate when a new partial is loaded.
24503 * <div class="alert alert-warning">
24504 * **Note:** When using onload on SVG elements in IE11, the browser will try to call
24505 * a function with the name on the window element, which will usually throw a
24506 * "function is undefined" error. To fix this, you can instead use `data-onload` or a
24507 * different form that {@link guide/directive#normalization matches} `onload`.
24510 * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
24511 * $anchorScroll} to scroll the viewport after the content is loaded.
24513 * - If the attribute is not set, disable scrolling.
24514 * - If the attribute is set without value, enable scrolling.
24515 * - Otherwise enable scrolling only if the expression evaluates to truthy value.
24518 <example module="includeExample" deps="angular-animate.js" animations="true">
24519 <file name="index.html">
24520 <div ng-controller="ExampleController">
24521 <select ng-model="template" ng-options="t.name for t in templates">
24522 <option value="">(blank)</option>
24524 url of the template: <code>{{template.url}}</code>
24526 <div class="slide-animate-container">
24527 <div class="slide-animate" ng-include="template.url"></div>
24531 <file name="script.js">
24532 angular.module('includeExample', ['ngAnimate'])
24533 .controller('ExampleController', ['$scope', function($scope) {
24535 [ { name: 'template1.html', url: 'template1.html'},
24536 { name: 'template2.html', url: 'template2.html'} ];
24537 $scope.template = $scope.templates[0];
24540 <file name="template1.html">
24541 Content of template1.html
24543 <file name="template2.html">
24544 Content of template2.html
24546 <file name="animations.css">
24547 .slide-animate-container {
24550 border:1px solid black;
24559 .slide-animate.ng-enter, .slide-animate.ng-leave {
24560 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
24571 .slide-animate.ng-enter {
24574 .slide-animate.ng-enter.ng-enter-active {
24578 .slide-animate.ng-leave {
24581 .slide-animate.ng-leave.ng-leave-active {
24585 <file name="protractor.js" type="protractor">
24586 var templateSelect = element(by.model('template'));
24587 var includeElem = element(by.css('[ng-include]'));
24589 it('should load template1.html', function() {
24590 expect(includeElem.getText()).toMatch(/Content of template1.html/);
24593 it('should load template2.html', function() {
24594 if (browser.params.browser == 'firefox') {
24595 // Firefox can't handle using selects
24596 // See https://github.com/angular/protractor/issues/480
24599 templateSelect.click();
24600 templateSelect.all(by.css('option')).get(2).click();
24601 expect(includeElem.getText()).toMatch(/Content of template2.html/);
24604 it('should change to blank', function() {
24605 if (browser.params.browser == 'firefox') {
24606 // Firefox can't handle using selects
24609 templateSelect.click();
24610 templateSelect.all(by.css('option')).get(0).click();
24611 expect(includeElem.isPresent()).toBe(false);
24620 * @name ngInclude#$includeContentRequested
24621 * @eventType emit on the scope ngInclude was declared in
24623 * Emitted every time the ngInclude content is requested.
24625 * @param {Object} angularEvent Synthetic event object.
24626 * @param {String} src URL of content to load.
24632 * @name ngInclude#$includeContentLoaded
24633 * @eventType emit on the current ngInclude scope
24635 * Emitted every time the ngInclude content is reloaded.
24637 * @param {Object} angularEvent Synthetic event object.
24638 * @param {String} src URL of content to load.
24644 * @name ngInclude#$includeContentError
24645 * @eventType emit on the scope ngInclude was declared in
24647 * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
24649 * @param {Object} angularEvent Synthetic event object.
24650 * @param {String} src URL of content to load.
24652 var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
24653 function($templateRequest, $anchorScroll, $animate) {
24658 transclude: 'element',
24659 controller: angular.noop,
24660 compile: function(element, attr) {
24661 var srcExp = attr.ngInclude || attr.src,
24662 onloadExp = attr.onload || '',
24663 autoScrollExp = attr.autoscroll;
24665 return function(scope, $element, $attr, ctrl, $transclude) {
24666 var changeCounter = 0,
24671 var cleanupLastIncludeContent = function() {
24672 if (previousElement) {
24673 previousElement.remove();
24674 previousElement = null;
24676 if (currentScope) {
24677 currentScope.$destroy();
24678 currentScope = null;
24680 if (currentElement) {
24681 $animate.leave(currentElement).then(function() {
24682 previousElement = null;
24684 previousElement = currentElement;
24685 currentElement = null;
24689 scope.$watch(srcExp, function ngIncludeWatchAction(src) {
24690 var afterAnimation = function() {
24691 if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
24695 var thisChangeId = ++changeCounter;
24698 //set the 2nd param to true to ignore the template request error so that the inner
24699 //contents and scope can be cleaned up.
24700 $templateRequest(src, true).then(function(response) {
24701 if (thisChangeId !== changeCounter) return;
24702 var newScope = scope.$new();
24703 ctrl.template = response;
24705 // Note: This will also link all children of ng-include that were contained in the original
24706 // html. If that content contains controllers, ... they could pollute/change the scope.
24707 // However, using ng-include on an element with additional content does not make sense...
24708 // Note: We can't remove them in the cloneAttchFn of $transclude as that
24709 // function is called before linking the content, which would apply child
24710 // directives to non existing elements.
24711 var clone = $transclude(newScope, function(clone) {
24712 cleanupLastIncludeContent();
24713 $animate.enter(clone, null, $element).then(afterAnimation);
24716 currentScope = newScope;
24717 currentElement = clone;
24719 currentScope.$emit('$includeContentLoaded', src);
24720 scope.$eval(onloadExp);
24722 if (thisChangeId === changeCounter) {
24723 cleanupLastIncludeContent();
24724 scope.$emit('$includeContentError', src);
24727 scope.$emit('$includeContentRequested', src);
24729 cleanupLastIncludeContent();
24730 ctrl.template = null;
24738 // This directive is called during the $transclude call of the first `ngInclude` directive.
24739 // It will replace and compile the content of the element with the loaded template.
24740 // We need this directive so that the element content is already filled when
24741 // the link function of another directive on the same element as ngInclude
24743 var ngIncludeFillContentDirective = ['$compile',
24744 function($compile) {
24748 require: 'ngInclude',
24749 link: function(scope, $element, $attr, ctrl) {
24750 if (/SVG/.test($element[0].toString())) {
24751 // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
24752 // support innerHTML, so detect this here and try to generate the contents
24755 $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
24756 function namespaceAdaptedClone(clone) {
24757 $element.append(clone);
24758 }, {futureParentElement: $element});
24762 $element.html(ctrl.template);
24763 $compile($element.contents())(scope);
24774 * The `ngInit` directive allows you to evaluate an expression in the
24777 * <div class="alert alert-danger">
24778 * This directive can be abused to add unnecessary amounts of logic into your templates.
24779 * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
24780 * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
24781 * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
24782 * rather than `ngInit` to initialize values on a scope.
24785 * <div class="alert alert-warning">
24786 * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
24787 * sure you have parentheses to ensure correct operator precedence:
24788 * <pre class="prettyprint">
24789 * `<div ng-init="test1 = ($index | toString)"></div>`
24796 * @param {expression} ngInit {@link guide/expression Expression} to eval.
24799 <example module="initExample">
24800 <file name="index.html">
24802 angular.module('initExample', [])
24803 .controller('ExampleController', ['$scope', function($scope) {
24804 $scope.list = [['a', 'b'], ['c', 'd']];
24807 <div ng-controller="ExampleController">
24808 <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
24809 <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
24810 <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
24815 <file name="protractor.js" type="protractor">
24816 it('should alias index positions', function() {
24817 var elements = element.all(by.css('.example-init'));
24818 expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
24819 expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
24820 expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
24821 expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
24826 var ngInitDirective = ngDirective({
24828 compile: function() {
24830 pre: function(scope, element, attrs) {
24831 scope.$eval(attrs.ngInit);
24842 * Text input that converts between a delimited string and an array of strings. The default
24843 * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
24844 * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
24846 * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
24847 * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
24848 * list item is respected. This implies that the user of the directive is responsible for
24849 * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
24850 * tab or newline character.
24851 * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
24852 * when joining the list items back together) and whitespace around each list item is stripped
24853 * before it is added to the model.
24855 * ### Example with Validation
24857 * <example name="ngList-directive" module="listExample">
24858 * <file name="app.js">
24859 * angular.module('listExample', [])
24860 * .controller('ExampleController', ['$scope', function($scope) {
24861 * $scope.names = ['morpheus', 'neo', 'trinity'];
24864 * <file name="index.html">
24865 * <form name="myForm" ng-controller="ExampleController">
24866 * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
24867 * <span role="alert">
24868 * <span class="error" ng-show="myForm.namesInput.$error.required">
24872 * <tt>names = {{names}}</tt><br/>
24873 * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
24874 * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
24875 * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
24876 * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
24879 * <file name="protractor.js" type="protractor">
24880 * var listInput = element(by.model('names'));
24881 * var names = element(by.exactBinding('names'));
24882 * var valid = element(by.binding('myForm.namesInput.$valid'));
24883 * var error = element(by.css('span.error'));
24885 * it('should initialize to model', function() {
24886 * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
24887 * expect(valid.getText()).toContain('true');
24888 * expect(error.getCssValue('display')).toBe('none');
24891 * it('should be invalid if empty', function() {
24892 * listInput.clear();
24893 * listInput.sendKeys('');
24895 * expect(names.getText()).toContain('');
24896 * expect(valid.getText()).toContain('false');
24897 * expect(error.getCssValue('display')).not.toBe('none');
24902 * ### Example - splitting on newline
24903 * <example name="ngList-directive-newlines">
24904 * <file name="index.html">
24905 * <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
24906 * <pre>{{ list | json }}</pre>
24908 * <file name="protractor.js" type="protractor">
24909 * it("should split the text by newlines", function() {
24910 * var listInput = element(by.model('list'));
24911 * var output = element(by.binding('list | json'));
24912 * listInput.sendKeys('abc\ndef\nghi');
24913 * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
24919 * @param {string=} ngList optional delimiter that should be used to split the value.
24921 var ngListDirective = function() {
24925 require: 'ngModel',
24926 link: function(scope, element, attr, ctrl) {
24927 // We want to control whitespace trimming so we use this convoluted approach
24928 // to access the ngList attribute, which doesn't pre-trim the attribute
24929 var ngList = element.attr(attr.$attr.ngList) || ', ';
24930 var trimValues = attr.ngTrim !== 'false';
24931 var separator = trimValues ? trim(ngList) : ngList;
24933 var parse = function(viewValue) {
24934 // If the viewValue is invalid (say required but empty) it will be `undefined`
24935 if (isUndefined(viewValue)) return;
24940 forEach(viewValue.split(separator), function(value) {
24941 if (value) list.push(trimValues ? trim(value) : value);
24948 ctrl.$parsers.push(parse);
24949 ctrl.$formatters.push(function(value) {
24950 if (isArray(value)) {
24951 return value.join(ngList);
24957 // Override the standard $isEmpty because an empty array means the input is empty.
24958 ctrl.$isEmpty = function(value) {
24959 return !value || !value.length;
24965 /* global VALID_CLASS: true,
24966 INVALID_CLASS: true,
24967 PRISTINE_CLASS: true,
24969 UNTOUCHED_CLASS: true,
24970 TOUCHED_CLASS: true,
24973 var VALID_CLASS = 'ng-valid',
24974 INVALID_CLASS = 'ng-invalid',
24975 PRISTINE_CLASS = 'ng-pristine',
24976 DIRTY_CLASS = 'ng-dirty',
24977 UNTOUCHED_CLASS = 'ng-untouched',
24978 TOUCHED_CLASS = 'ng-touched',
24979 PENDING_CLASS = 'ng-pending',
24980 EMPTY_CLASS = 'ng-empty',
24981 NOT_EMPTY_CLASS = 'ng-not-empty';
24983 var ngModelMinErr = minErr('ngModel');
24987 * @name ngModel.NgModelController
24989 * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
24990 * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
24992 * @property {*} $modelValue The value in the model that the control is bound to.
24993 * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
24994 the control reads value from the DOM. The functions are called in array order, each passing
24995 its return value through to the next. The last return value is forwarded to the
24996 {@link ngModel.NgModelController#$validators `$validators`} collection.
24998 Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
25001 Returning `undefined` from a parser means a parse error occurred. In that case,
25002 no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
25003 will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
25004 is set to `true`. The parse error is stored in `ngModel.$error.parse`.
25007 * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
25008 the model value changes. The functions are called in reverse array order, each passing the value through to the
25009 next. The last return value is used as the actual DOM value.
25010 Used to format / convert values for display in the control.
25012 * function formatter(value) {
25014 * return value.toUpperCase();
25017 * ngModel.$formatters.push(formatter);
25020 * @property {Object.<string, function>} $validators A collection of validators that are applied
25021 * whenever the model value changes. The key value within the object refers to the name of the
25022 * validator while the function refers to the validation operation. The validation operation is
25023 * provided with the model value as an argument and must return a true or false value depending
25024 * on the response of that validation.
25027 * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
25028 * var value = modelValue || viewValue;
25029 * return /[0-9]+/.test(value) &&
25030 * /[a-z]+/.test(value) &&
25031 * /[A-Z]+/.test(value) &&
25032 * /\W+/.test(value);
25036 * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
25037 * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
25038 * is expected to return a promise when it is run during the model validation process. Once the promise
25039 * is delivered then the validation status will be set to true when fulfilled and false when rejected.
25040 * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
25041 * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
25042 * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
25043 * will only run once all synchronous validators have passed.
25045 * Please note that if $http is used then it is important that the server returns a success HTTP response code
25046 * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
25049 * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
25050 * var value = modelValue || viewValue;
25052 * // Lookup user by username
25053 * return $http.get('/api/users/' + value).
25054 * then(function resolved() {
25055 * //username exists, this means validation fails
25056 * return $q.reject('exists');
25057 * }, function rejected() {
25058 * //username does not exist, therefore this validation passes
25064 * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
25065 * view value has changed. It is called with no arguments, and its return value is ignored.
25066 * This can be used in place of additional $watches against the model value.
25068 * @property {Object} $error An object hash with all failing validator ids as keys.
25069 * @property {Object} $pending An object hash with all pending validator ids as keys.
25071 * @property {boolean} $untouched True if control has not lost focus yet.
25072 * @property {boolean} $touched True if control has lost focus.
25073 * @property {boolean} $pristine True if user has not interacted with the control yet.
25074 * @property {boolean} $dirty True if user has already interacted with the control.
25075 * @property {boolean} $valid True if there is no error.
25076 * @property {boolean} $invalid True if at least one error on the control.
25077 * @property {string} $name The name attribute of the control.
25081 * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
25082 * The controller contains services for data-binding, validation, CSS updates, and value formatting
25083 * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
25084 * listening to DOM events.
25085 * Such DOM related logic should be provided by other directives which make use of
25086 * `NgModelController` for data-binding to control elements.
25087 * Angular provides this DOM logic for most {@link input `input`} elements.
25088 * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
25089 * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
25092 * ### Custom Control Example
25093 * This example shows how to use `NgModelController` with a custom control to achieve
25094 * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
25095 * collaborate together to achieve the desired result.
25097 * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
25098 * contents be edited in place by the user.
25100 * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
25101 * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
25102 * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
25103 * that content using the `$sce` service.
25105 * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
25106 <file name="style.css">
25107 [contenteditable] {
25108 border: 1px solid black;
25109 background-color: white;
25114 border: 1px solid red;
25118 <file name="script.js">
25119 angular.module('customControl', ['ngSanitize']).
25120 directive('contenteditable', ['$sce', function($sce) {
25122 restrict: 'A', // only activate on element attribute
25123 require: '?ngModel', // get a hold of NgModelController
25124 link: function(scope, element, attrs, ngModel) {
25125 if (!ngModel) return; // do nothing if no ng-model
25127 // Specify how UI should be updated
25128 ngModel.$render = function() {
25129 element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
25132 // Listen for change events to enable binding
25133 element.on('blur keyup change', function() {
25134 scope.$evalAsync(read);
25136 read(); // initialize
25138 // Write data to the model
25140 var html = element.html();
25141 // When we clear the content editable the browser leaves a <br> behind
25142 // If strip-br attribute is provided then we strip this out
25143 if ( attrs.stripBr && html == '<br>' ) {
25146 ngModel.$setViewValue(html);
25152 <file name="index.html">
25153 <form name="myForm">
25154 <div contenteditable
25155 name="myWidget" ng-model="userContent"
25157 required>Change me!</div>
25158 <span ng-show="myForm.myWidget.$error.required">Required!</span>
25160 <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
25163 <file name="protractor.js" type="protractor">
25164 it('should data-bind and become invalid', function() {
25165 if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
25166 // SafariDriver can't handle contenteditable
25167 // and Firefox driver can't clear contenteditables very well
25170 var contentEditable = element(by.css('[contenteditable]'));
25171 var content = 'Change me!';
25173 expect(contentEditable.getText()).toEqual(content);
25175 contentEditable.clear();
25176 contentEditable.sendKeys(protractor.Key.BACK_SPACE);
25177 expect(contentEditable.getText()).toEqual('');
25178 expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
25185 var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
25186 function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
25187 this.$viewValue = Number.NaN;
25188 this.$modelValue = Number.NaN;
25189 this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
25190 this.$validators = {};
25191 this.$asyncValidators = {};
25192 this.$parsers = [];
25193 this.$formatters = [];
25194 this.$viewChangeListeners = [];
25195 this.$untouched = true;
25196 this.$touched = false;
25197 this.$pristine = true;
25198 this.$dirty = false;
25199 this.$valid = true;
25200 this.$invalid = false;
25201 this.$error = {}; // keep invalid keys here
25202 this.$$success = {}; // keep valid keys here
25203 this.$pending = undefined; // keep pending keys here
25204 this.$name = $interpolate($attr.name || '', false)($scope);
25205 this.$$parentForm = nullFormCtrl;
25207 var parsedNgModel = $parse($attr.ngModel),
25208 parsedNgModelAssign = parsedNgModel.assign,
25209 ngModelGet = parsedNgModel,
25210 ngModelSet = parsedNgModelAssign,
25211 pendingDebounce = null,
25215 this.$$setOptions = function(options) {
25216 ctrl.$options = options;
25217 if (options && options.getterSetter) {
25218 var invokeModelGetter = $parse($attr.ngModel + '()'),
25219 invokeModelSetter = $parse($attr.ngModel + '($$$p)');
25221 ngModelGet = function($scope) {
25222 var modelValue = parsedNgModel($scope);
25223 if (isFunction(modelValue)) {
25224 modelValue = invokeModelGetter($scope);
25228 ngModelSet = function($scope, newValue) {
25229 if (isFunction(parsedNgModel($scope))) {
25230 invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
25232 parsedNgModelAssign($scope, ctrl.$modelValue);
25235 } else if (!parsedNgModel.assign) {
25236 throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
25237 $attr.ngModel, startingTag($element));
25243 * @name ngModel.NgModelController#$render
25246 * Called when the view needs to be updated. It is expected that the user of the ng-model
25247 * directive will implement this method.
25249 * The `$render()` method is invoked in the following situations:
25251 * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
25252 * committed value then `$render()` is called to update the input control.
25253 * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
25254 * the `$viewValue` are different from last time.
25256 * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
25257 * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
25258 * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
25259 * invoked if you only change a property on the objects.
25261 this.$render = noop;
25265 * @name ngModel.NgModelController#$isEmpty
25268 * This is called when we need to determine if the value of an input is empty.
25270 * For instance, the required directive does this to work out if the input has data or not.
25272 * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
25274 * You can override this for input directives whose concept of being empty is different from the
25275 * default. The `checkboxInputType` directive does this because in its case a value of `false`
25278 * @param {*} value The value of the input to check for emptiness.
25279 * @returns {boolean} True if `value` is "empty".
25281 this.$isEmpty = function(value) {
25282 return isUndefined(value) || value === '' || value === null || value !== value;
25285 this.$$updateEmptyClasses = function(value) {
25286 if (ctrl.$isEmpty(value)) {
25287 $animate.removeClass($element, NOT_EMPTY_CLASS);
25288 $animate.addClass($element, EMPTY_CLASS);
25290 $animate.removeClass($element, EMPTY_CLASS);
25291 $animate.addClass($element, NOT_EMPTY_CLASS);
25296 var currentValidationRunId = 0;
25300 * @name ngModel.NgModelController#$setValidity
25303 * Change the validity state, and notify the form.
25305 * This method can be called within $parsers/$formatters or a custom validation implementation.
25306 * However, in most cases it should be sufficient to use the `ngModel.$validators` and
25307 * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
25309 * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
25310 * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
25311 * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
25312 * The `validationErrorKey` should be in camelCase and will get converted into dash-case
25313 * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
25314 * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
25315 * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
25316 * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
25317 * Skipped is used by Angular when validators do not run because of parse errors and
25318 * when `$asyncValidators` do not run because any of the `$validators` failed.
25320 addSetValidityMethod({
25322 $element: $element,
25323 set: function(object, property) {
25324 object[property] = true;
25326 unset: function(object, property) {
25327 delete object[property];
25334 * @name ngModel.NgModelController#$setPristine
25337 * Sets the control to its pristine state.
25339 * This method can be called to remove the `ng-dirty` class and set the control to its pristine
25340 * state (`ng-pristine` class). A model is considered to be pristine when the control
25341 * has not been changed from when first compiled.
25343 this.$setPristine = function() {
25344 ctrl.$dirty = false;
25345 ctrl.$pristine = true;
25346 $animate.removeClass($element, DIRTY_CLASS);
25347 $animate.addClass($element, PRISTINE_CLASS);
25352 * @name ngModel.NgModelController#$setDirty
25355 * Sets the control to its dirty state.
25357 * This method can be called to remove the `ng-pristine` class and set the control to its dirty
25358 * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
25359 * from when first compiled.
25361 this.$setDirty = function() {
25362 ctrl.$dirty = true;
25363 ctrl.$pristine = false;
25364 $animate.removeClass($element, PRISTINE_CLASS);
25365 $animate.addClass($element, DIRTY_CLASS);
25366 ctrl.$$parentForm.$setDirty();
25371 * @name ngModel.NgModelController#$setUntouched
25374 * Sets the control to its untouched state.
25376 * This method can be called to remove the `ng-touched` class and set the control to its
25377 * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
25378 * by default, however this function can be used to restore that state if the model has
25379 * already been touched by the user.
25381 this.$setUntouched = function() {
25382 ctrl.$touched = false;
25383 ctrl.$untouched = true;
25384 $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
25389 * @name ngModel.NgModelController#$setTouched
25392 * Sets the control to its touched state.
25394 * This method can be called to remove the `ng-untouched` class and set the control to its
25395 * touched state (`ng-touched` class). A model is considered to be touched when the user has
25396 * first focused the control element and then shifted focus away from the control (blur event).
25398 this.$setTouched = function() {
25399 ctrl.$touched = true;
25400 ctrl.$untouched = false;
25401 $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
25406 * @name ngModel.NgModelController#$rollbackViewValue
25409 * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
25410 * which may be caused by a pending debounced event or because the input is waiting for a some
25413 * If you have an input that uses `ng-model-options` to set up debounced events or events such
25414 * as blur you can have a situation where there is a period when the `$viewValue`
25415 * is out of synch with the ngModel's `$modelValue`.
25417 * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
25418 * programmatically before these debounced/future events have resolved/occurred, because Angular's
25419 * dirty checking mechanism is not able to tell whether the model has actually changed or not.
25421 * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
25422 * input which may have such events pending. This is important in order to make sure that the
25423 * input field will be updated with the new model value and any pending operations are cancelled.
25425 * <example name="ng-model-cancel-update" module="cancel-update-example">
25426 * <file name="app.js">
25427 * angular.module('cancel-update-example', [])
25429 * .controller('CancelUpdateController', ['$scope', function($scope) {
25430 * $scope.resetWithCancel = function(e) {
25431 * if (e.keyCode == 27) {
25432 * $scope.myForm.myInput1.$rollbackViewValue();
25433 * $scope.myValue = '';
25436 * $scope.resetWithoutCancel = function(e) {
25437 * if (e.keyCode == 27) {
25438 * $scope.myValue = '';
25443 * <file name="index.html">
25444 * <div ng-controller="CancelUpdateController">
25445 * <p>Try typing something in each input. See that the model only updates when you
25446 * blur off the input.
25448 * <p>Now see what happens if you start typing then press the Escape key</p>
25450 * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
25451 * <p id="inputDescription1">With $rollbackViewValue()</p>
25452 * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
25453 * ng-keydown="resetWithCancel($event)"><br/>
25454 * myValue: "{{ myValue }}"
25456 * <p id="inputDescription2">Without $rollbackViewValue()</p>
25457 * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
25458 * ng-keydown="resetWithoutCancel($event)"><br/>
25459 * myValue: "{{ myValue }}"
25465 this.$rollbackViewValue = function() {
25466 $timeout.cancel(pendingDebounce);
25467 ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
25473 * @name ngModel.NgModelController#$validate
25476 * Runs each of the registered validators (first synchronous validators and then
25477 * asynchronous validators).
25478 * If the validity changes to invalid, the model will be set to `undefined`,
25479 * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
25480 * If the validity changes to valid, it will set the model to the last available valid
25481 * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
25483 this.$validate = function() {
25484 // ignore $validate before model is initialized
25485 if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
25489 var viewValue = ctrl.$$lastCommittedViewValue;
25490 // Note: we use the $$rawModelValue as $modelValue might have been
25491 // set to undefined during a view -> model update that found validation
25492 // errors. We can't parse the view here, since that could change
25493 // the model although neither viewValue nor the model on the scope changed
25494 var modelValue = ctrl.$$rawModelValue;
25496 var prevValid = ctrl.$valid;
25497 var prevModelValue = ctrl.$modelValue;
25499 var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
25501 ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
25502 // If there was no change in validity, don't update the model
25503 // This prevents changing an invalid modelValue to undefined
25504 if (!allowInvalid && prevValid !== allValid) {
25505 // Note: Don't check ctrl.$valid here, as we could have
25506 // external validators (e.g. calculated on the server),
25507 // that just call $setValidity and need the model value
25508 // to calculate their validity.
25509 ctrl.$modelValue = allValid ? modelValue : undefined;
25511 if (ctrl.$modelValue !== prevModelValue) {
25512 ctrl.$$writeModelToScope();
25519 this.$$runValidators = function(modelValue, viewValue, doneCallback) {
25520 currentValidationRunId++;
25521 var localValidationRunId = currentValidationRunId;
25523 // check parser error
25524 if (!processParseErrors()) {
25525 validationDone(false);
25528 if (!processSyncValidators()) {
25529 validationDone(false);
25532 processAsyncValidators();
25534 function processParseErrors() {
25535 var errorKey = ctrl.$$parserName || 'parse';
25536 if (isUndefined(parserValid)) {
25537 setValidity(errorKey, null);
25539 if (!parserValid) {
25540 forEach(ctrl.$validators, function(v, name) {
25541 setValidity(name, null);
25543 forEach(ctrl.$asyncValidators, function(v, name) {
25544 setValidity(name, null);
25547 // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
25548 setValidity(errorKey, parserValid);
25549 return parserValid;
25554 function processSyncValidators() {
25555 var syncValidatorsValid = true;
25556 forEach(ctrl.$validators, function(validator, name) {
25557 var result = validator(modelValue, viewValue);
25558 syncValidatorsValid = syncValidatorsValid && result;
25559 setValidity(name, result);
25561 if (!syncValidatorsValid) {
25562 forEach(ctrl.$asyncValidators, function(v, name) {
25563 setValidity(name, null);
25570 function processAsyncValidators() {
25571 var validatorPromises = [];
25572 var allValid = true;
25573 forEach(ctrl.$asyncValidators, function(validator, name) {
25574 var promise = validator(modelValue, viewValue);
25575 if (!isPromiseLike(promise)) {
25576 throw ngModelMinErr("$asyncValidators",
25577 "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
25579 setValidity(name, undefined);
25580 validatorPromises.push(promise.then(function() {
25581 setValidity(name, true);
25582 }, function(error) {
25584 setValidity(name, false);
25587 if (!validatorPromises.length) {
25588 validationDone(true);
25590 $q.all(validatorPromises).then(function() {
25591 validationDone(allValid);
25596 function setValidity(name, isValid) {
25597 if (localValidationRunId === currentValidationRunId) {
25598 ctrl.$setValidity(name, isValid);
25602 function validationDone(allValid) {
25603 if (localValidationRunId === currentValidationRunId) {
25605 doneCallback(allValid);
25612 * @name ngModel.NgModelController#$commitViewValue
25615 * Commit a pending update to the `$modelValue`.
25617 * Updates may be pending by a debounced event or because the input is waiting for a some future
25618 * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
25619 * usually handles calling this in response to input events.
25621 this.$commitViewValue = function() {
25622 var viewValue = ctrl.$viewValue;
25624 $timeout.cancel(pendingDebounce);
25626 // If the view value has not changed then we should just exit, except in the case where there is
25627 // a native validator on the element. In this case the validation state may have changed even though
25628 // the viewValue has stayed empty.
25629 if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
25632 ctrl.$$updateEmptyClasses(viewValue);
25633 ctrl.$$lastCommittedViewValue = viewValue;
25636 if (ctrl.$pristine) {
25639 this.$$parseAndValidate();
25642 this.$$parseAndValidate = function() {
25643 var viewValue = ctrl.$$lastCommittedViewValue;
25644 var modelValue = viewValue;
25645 parserValid = isUndefined(modelValue) ? undefined : true;
25648 for (var i = 0; i < ctrl.$parsers.length; i++) {
25649 modelValue = ctrl.$parsers[i](modelValue);
25650 if (isUndefined(modelValue)) {
25651 parserValid = false;
25656 if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
25657 // ctrl.$modelValue has not been touched yet...
25658 ctrl.$modelValue = ngModelGet($scope);
25660 var prevModelValue = ctrl.$modelValue;
25661 var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
25662 ctrl.$$rawModelValue = modelValue;
25664 if (allowInvalid) {
25665 ctrl.$modelValue = modelValue;
25666 writeToModelIfNeeded();
25669 // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
25670 // This can happen if e.g. $setViewValue is called from inside a parser
25671 ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
25672 if (!allowInvalid) {
25673 // Note: Don't check ctrl.$valid here, as we could have
25674 // external validators (e.g. calculated on the server),
25675 // that just call $setValidity and need the model value
25676 // to calculate their validity.
25677 ctrl.$modelValue = allValid ? modelValue : undefined;
25678 writeToModelIfNeeded();
25682 function writeToModelIfNeeded() {
25683 if (ctrl.$modelValue !== prevModelValue) {
25684 ctrl.$$writeModelToScope();
25689 this.$$writeModelToScope = function() {
25690 ngModelSet($scope, ctrl.$modelValue);
25691 forEach(ctrl.$viewChangeListeners, function(listener) {
25695 $exceptionHandler(e);
25702 * @name ngModel.NgModelController#$setViewValue
25705 * Update the view value.
25707 * This method should be called when a control wants to change the view value; typically,
25708 * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
25709 * directive calls it when the value of the input changes and {@link ng.directive:select select}
25710 * calls it when an option is selected.
25712 * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
25713 * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
25714 * value sent directly for processing, finally to be applied to `$modelValue` and then the
25715 * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
25716 * in the `$viewChangeListeners` list, are called.
25718 * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
25719 * and the `default` trigger is not listed, all those actions will remain pending until one of the
25720 * `updateOn` events is triggered on the DOM element.
25721 * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
25722 * directive is used with a custom debounce for this particular event.
25723 * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
25724 * is specified, once the timer runs out.
25726 * When used with standard inputs, the view value will always be a string (which is in some cases
25727 * parsed into another type, such as a `Date` object for `input[date]`.)
25728 * However, custom controls might also pass objects to this method. In this case, we should make
25729 * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
25730 * perform a deep watch of objects, it only looks for a change of identity. If you only change
25731 * the property of the object then ngModel will not realise that the object has changed and
25732 * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
25733 * not change properties of the copy once it has been passed to `$setViewValue`.
25734 * Otherwise you may cause the model value on the scope to change incorrectly.
25736 * <div class="alert alert-info">
25737 * In any case, the value passed to the method should always reflect the current value
25738 * of the control. For example, if you are calling `$setViewValue` for an input element,
25739 * you should pass the input DOM value. Otherwise, the control and the scope model become
25740 * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
25741 * the control's DOM value in any way. If we want to change the control's DOM value
25742 * programmatically, we should update the `ngModel` scope expression. Its new value will be
25743 * picked up by the model controller, which will run it through the `$formatters`, `$render` it
25744 * to update the DOM, and finally call `$validate` on it.
25747 * @param {*} value value from the view.
25748 * @param {string} trigger Event that triggered the update.
25750 this.$setViewValue = function(value, trigger) {
25751 ctrl.$viewValue = value;
25752 if (!ctrl.$options || ctrl.$options.updateOnDefault) {
25753 ctrl.$$debounceViewValueCommit(trigger);
25757 this.$$debounceViewValueCommit = function(trigger) {
25758 var debounceDelay = 0,
25759 options = ctrl.$options,
25762 if (options && isDefined(options.debounce)) {
25763 debounce = options.debounce;
25764 if (isNumber(debounce)) {
25765 debounceDelay = debounce;
25766 } else if (isNumber(debounce[trigger])) {
25767 debounceDelay = debounce[trigger];
25768 } else if (isNumber(debounce['default'])) {
25769 debounceDelay = debounce['default'];
25773 $timeout.cancel(pendingDebounce);
25774 if (debounceDelay) {
25775 pendingDebounce = $timeout(function() {
25776 ctrl.$commitViewValue();
25778 } else if ($rootScope.$$phase) {
25779 ctrl.$commitViewValue();
25781 $scope.$apply(function() {
25782 ctrl.$commitViewValue();
25788 // Note: we cannot use a normal scope.$watch as we want to detect the following:
25789 // 1. scope value is 'a'
25790 // 2. user enters 'b'
25791 // 3. ng-change kicks in and reverts scope value to 'a'
25792 // -> scope value did not change since the last digest as
25793 // ng-change executes in apply phase
25794 // 4. view should be changed back to 'a'
25795 $scope.$watch(function ngModelWatch() {
25796 var modelValue = ngModelGet($scope);
25798 // if scope model value and ngModel value are out of sync
25799 // TODO(perf): why not move this to the action fn?
25800 if (modelValue !== ctrl.$modelValue &&
25801 // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
25802 (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
25804 ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
25805 parserValid = undefined;
25807 var formatters = ctrl.$formatters,
25808 idx = formatters.length;
25810 var viewValue = modelValue;
25812 viewValue = formatters[idx](viewValue);
25814 if (ctrl.$viewValue !== viewValue) {
25815 ctrl.$$updateEmptyClasses(viewValue);
25816 ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
25819 ctrl.$$runValidators(modelValue, viewValue, noop);
25836 * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
25837 * property on the scope using {@link ngModel.NgModelController NgModelController},
25838 * which is created and exposed by this directive.
25840 * `ngModel` is responsible for:
25842 * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
25844 * - Providing validation behavior (i.e. required, number, email, url).
25845 * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
25846 * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
25847 * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
25848 * - Registering the control with its parent {@link ng.directive:form form}.
25850 * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
25851 * current scope. If the property doesn't already exist on this scope, it will be created
25852 * implicitly and added to the scope.
25854 * For best practices on using `ngModel`, see:
25856 * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
25858 * For basic examples, how to use `ngModel`, see:
25860 * - {@link ng.directive:input input}
25861 * - {@link input[text] text}
25862 * - {@link input[checkbox] checkbox}
25863 * - {@link input[radio] radio}
25864 * - {@link input[number] number}
25865 * - {@link input[email] email}
25866 * - {@link input[url] url}
25867 * - {@link input[date] date}
25868 * - {@link input[datetime-local] datetime-local}
25869 * - {@link input[time] time}
25870 * - {@link input[month] month}
25871 * - {@link input[week] week}
25872 * - {@link ng.directive:select select}
25873 * - {@link ng.directive:textarea textarea}
25876 * The following CSS classes are added and removed on the associated input/select/textarea element
25877 * depending on the validity of the model.
25879 * - `ng-valid`: the model is valid
25880 * - `ng-invalid`: the model is invalid
25881 * - `ng-valid-[key]`: for each valid key added by `$setValidity`
25882 * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
25883 * - `ng-pristine`: the control hasn't been interacted with yet
25884 * - `ng-dirty`: the control has been interacted with
25885 * - `ng-touched`: the control has been blurred
25886 * - `ng-untouched`: the control hasn't been blurred
25887 * - `ng-pending`: any `$asyncValidators` are unfulfilled
25888 * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
25889 * by the {@link ngModel.NgModelController#$isEmpty} method
25890 * - `ng-not-empty`: the view contains a non-empty value
25892 * Keep in mind that ngAnimate can detect each of these classes when added and removed.
25894 * ## Animation Hooks
25896 * Animations within models are triggered when any of the associated CSS classes are added and removed
25897 * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
25898 * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
25899 * The animations that are triggered within ngModel are similar to how they work in ngClass and
25900 * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
25902 * The following example shows a simple way to utilize CSS transitions to style an input element
25903 * that has been rendered as invalid after it has been validated:
25906 * //be sure to include ngAnimate as a module to hook into more
25907 * //advanced animations
25909 * transition:0.5s linear all;
25910 * background: white;
25912 * .my-input.ng-invalid {
25919 * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
25920 <file name="index.html">
25922 angular.module('inputExample', [])
25923 .controller('ExampleController', ['$scope', function($scope) {
25929 transition:all linear 0.5s;
25930 background: transparent;
25932 .my-input.ng-invalid {
25937 <p id="inputDescription">
25938 Update input to see transitions when valid/invalid.
25939 Integer is a valid value.
25941 <form name="testForm" ng-controller="ExampleController">
25942 <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
25943 aria-describedby="inputDescription" />
25948 * ## Binding to a getter/setter
25950 * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
25951 * function that returns a representation of the model when called with zero arguments, and sets
25952 * the internal state of a model when called with an argument. It's sometimes useful to use this
25953 * for models that have an internal representation that's different from what the model exposes
25956 * <div class="alert alert-success">
25957 * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
25958 * frequently than other parts of your code.
25961 * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
25962 * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
25963 * a `<form>`, which will enable this behavior for all `<input>`s within it. See
25964 * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
25966 * The following example shows how to use `ngModel` with a getter/setter:
25969 * <example name="ngModel-getter-setter" module="getterSetterExample">
25970 <file name="index.html">
25971 <div ng-controller="ExampleController">
25972 <form name="userForm">
25974 <input type="text" name="userName"
25975 ng-model="user.name"
25976 ng-model-options="{ getterSetter: true }" />
25979 <pre>user.name = <span ng-bind="user.name()"></span></pre>
25982 <file name="app.js">
25983 angular.module('getterSetterExample', [])
25984 .controller('ExampleController', ['$scope', function($scope) {
25985 var _name = 'Brian';
25987 name: function(newName) {
25988 // Note that newName can be undefined for two reasons:
25989 // 1. Because it is called as a getter and thus called with no arguments
25990 // 2. Because the property should actually be set to undefined. This happens e.g. if the
25991 // input is invalid
25992 return arguments.length ? (_name = newName) : _name;
25999 var ngModelDirective = ['$rootScope', function($rootScope) {
26002 require: ['ngModel', '^?form', '^?ngModelOptions'],
26003 controller: NgModelController,
26004 // Prelink needs to run before any input directive
26005 // so that we can set the NgModelOptions in NgModelController
26006 // before anyone else uses it.
26008 compile: function ngModelCompile(element) {
26009 // Setup initial state of the control
26010 element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
26013 pre: function ngModelPreLink(scope, element, attr, ctrls) {
26014 var modelCtrl = ctrls[0],
26015 formCtrl = ctrls[1] || modelCtrl.$$parentForm;
26017 modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
26019 // notify others, especially parent forms
26020 formCtrl.$addControl(modelCtrl);
26022 attr.$observe('name', function(newValue) {
26023 if (modelCtrl.$name !== newValue) {
26024 modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
26028 scope.$on('$destroy', function() {
26029 modelCtrl.$$parentForm.$removeControl(modelCtrl);
26032 post: function ngModelPostLink(scope, element, attr, ctrls) {
26033 var modelCtrl = ctrls[0];
26034 if (modelCtrl.$options && modelCtrl.$options.updateOn) {
26035 element.on(modelCtrl.$options.updateOn, function(ev) {
26036 modelCtrl.$$debounceViewValueCommit(ev && ev.type);
26040 element.on('blur', function(ev) {
26041 if (modelCtrl.$touched) return;
26043 if ($rootScope.$$phase) {
26044 scope.$evalAsync(modelCtrl.$setTouched);
26046 scope.$apply(modelCtrl.$setTouched);
26055 var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
26059 * @name ngModelOptions
26062 * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
26063 * events that will trigger a model update and/or a debouncing delay so that the actual update only
26064 * takes place when a timer expires; this timer will be reset after another change takes place.
26066 * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
26067 * be different from the value in the actual model. This means that if you update the model you
26068 * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
26069 * order to make sure it is synchronized with the model and that any debounced action is canceled.
26071 * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
26072 * method is by making sure the input is placed inside a form that has a `name` attribute. This is
26073 * important because `form` controllers are published to the related scope under the name in their
26074 * `name` attribute.
26076 * Any pending changes will take place immediately when an enclosing form is submitted via the
26077 * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
26078 * to have access to the updated model.
26080 * `ngModelOptions` has an effect on the element it's declared on and its descendants.
26082 * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
26083 * - `updateOn`: string specifying which event should the input be bound to. You can set several
26084 * events using an space delimited list. There is a special event called `default` that
26085 * matches the default events belonging of the control.
26086 * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
26087 * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
26088 * custom value for each event. For example:
26089 * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
26090 * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
26091 * not validate correctly instead of the default behavior of setting the model to undefined.
26092 * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
26093 `ngModel` as getters/setters.
26094 * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
26095 * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
26096 * continental US time zone abbreviations, but for general use, use a time zone offset, for
26097 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
26098 * If not specified, the timezone of the browser will be used.
26102 The following example shows how to override immediate updates. Changes on the inputs within the
26103 form will update the model only when the control loses focus (blur event). If `escape` key is
26104 pressed while the input field is focused, the value is reset to the value in the current model.
26106 <example name="ngModelOptions-directive-blur" module="optionsExample">
26107 <file name="index.html">
26108 <div ng-controller="ExampleController">
26109 <form name="userForm">
26111 <input type="text" name="userName"
26112 ng-model="user.name"
26113 ng-model-options="{ updateOn: 'blur' }"
26114 ng-keyup="cancel($event)" />
26117 <input type="text" ng-model="user.data" />
26120 <pre>user.name = <span ng-bind="user.name"></span></pre>
26121 <pre>user.data = <span ng-bind="user.data"></span></pre>
26124 <file name="app.js">
26125 angular.module('optionsExample', [])
26126 .controller('ExampleController', ['$scope', function($scope) {
26127 $scope.user = { name: 'John', data: '' };
26129 $scope.cancel = function(e) {
26130 if (e.keyCode == 27) {
26131 $scope.userForm.userName.$rollbackViewValue();
26136 <file name="protractor.js" type="protractor">
26137 var model = element(by.binding('user.name'));
26138 var input = element(by.model('user.name'));
26139 var other = element(by.model('user.data'));
26141 it('should allow custom events', function() {
26142 input.sendKeys(' Doe');
26144 expect(model.getText()).toEqual('John');
26146 expect(model.getText()).toEqual('John Doe');
26149 it('should $rollbackViewValue when model changes', function() {
26150 input.sendKeys(' Doe');
26151 expect(input.getAttribute('value')).toEqual('John Doe');
26152 input.sendKeys(protractor.Key.ESCAPE);
26153 expect(input.getAttribute('value')).toEqual('John');
26155 expect(model.getText()).toEqual('John');
26160 This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
26161 If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
26163 <example name="ngModelOptions-directive-debounce" module="optionsExample">
26164 <file name="index.html">
26165 <div ng-controller="ExampleController">
26166 <form name="userForm">
26168 <input type="text" name="userName"
26169 ng-model="user.name"
26170 ng-model-options="{ debounce: 1000 }" />
26172 <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
26175 <pre>user.name = <span ng-bind="user.name"></span></pre>
26178 <file name="app.js">
26179 angular.module('optionsExample', [])
26180 .controller('ExampleController', ['$scope', function($scope) {
26181 $scope.user = { name: 'Igor' };
26186 This one shows how to bind to getter/setters:
26188 <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
26189 <file name="index.html">
26190 <div ng-controller="ExampleController">
26191 <form name="userForm">
26193 <input type="text" name="userName"
26194 ng-model="user.name"
26195 ng-model-options="{ getterSetter: true }" />
26198 <pre>user.name = <span ng-bind="user.name()"></span></pre>
26201 <file name="app.js">
26202 angular.module('getterSetterExample', [])
26203 .controller('ExampleController', ['$scope', function($scope) {
26204 var _name = 'Brian';
26206 name: function(newName) {
26207 // Note that newName can be undefined for two reasons:
26208 // 1. Because it is called as a getter and thus called with no arguments
26209 // 2. Because the property should actually be set to undefined. This happens e.g. if the
26210 // input is invalid
26211 return arguments.length ? (_name = newName) : _name;
26218 var ngModelOptionsDirective = function() {
26221 controller: ['$scope', '$attrs', function($scope, $attrs) {
26223 this.$options = copy($scope.$eval($attrs.ngModelOptions));
26224 // Allow adding/overriding bound events
26225 if (isDefined(this.$options.updateOn)) {
26226 this.$options.updateOnDefault = false;
26227 // extract "default" pseudo-event from list of events that can trigger a model update
26228 this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
26229 that.$options.updateOnDefault = true;
26233 this.$options.updateOnDefault = true;
26242 function addSetValidityMethod(context) {
26243 var ctrl = context.ctrl,
26244 $element = context.$element,
26247 unset = context.unset,
26248 $animate = context.$animate;
26250 classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
26252 ctrl.$setValidity = setValidity;
26254 function setValidity(validationErrorKey, state, controller) {
26255 if (isUndefined(state)) {
26256 createAndSet('$pending', validationErrorKey, controller);
26258 unsetAndCleanup('$pending', validationErrorKey, controller);
26260 if (!isBoolean(state)) {
26261 unset(ctrl.$error, validationErrorKey, controller);
26262 unset(ctrl.$$success, validationErrorKey, controller);
26265 unset(ctrl.$error, validationErrorKey, controller);
26266 set(ctrl.$$success, validationErrorKey, controller);
26268 set(ctrl.$error, validationErrorKey, controller);
26269 unset(ctrl.$$success, validationErrorKey, controller);
26272 if (ctrl.$pending) {
26273 cachedToggleClass(PENDING_CLASS, true);
26274 ctrl.$valid = ctrl.$invalid = undefined;
26275 toggleValidationCss('', null);
26277 cachedToggleClass(PENDING_CLASS, false);
26278 ctrl.$valid = isObjectEmpty(ctrl.$error);
26279 ctrl.$invalid = !ctrl.$valid;
26280 toggleValidationCss('', ctrl.$valid);
26283 // re-read the state as the set/unset methods could have
26284 // combined state in ctrl.$error[validationError] (used for forms),
26285 // where setting/unsetting only increments/decrements the value,
26286 // and does not replace it.
26288 if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
26289 combinedState = undefined;
26290 } else if (ctrl.$error[validationErrorKey]) {
26291 combinedState = false;
26292 } else if (ctrl.$$success[validationErrorKey]) {
26293 combinedState = true;
26295 combinedState = null;
26298 toggleValidationCss(validationErrorKey, combinedState);
26299 ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
26302 function createAndSet(name, value, controller) {
26306 set(ctrl[name], value, controller);
26309 function unsetAndCleanup(name, value, controller) {
26311 unset(ctrl[name], value, controller);
26313 if (isObjectEmpty(ctrl[name])) {
26314 ctrl[name] = undefined;
26318 function cachedToggleClass(className, switchValue) {
26319 if (switchValue && !classCache[className]) {
26320 $animate.addClass($element, className);
26321 classCache[className] = true;
26322 } else if (!switchValue && classCache[className]) {
26323 $animate.removeClass($element, className);
26324 classCache[className] = false;
26328 function toggleValidationCss(validationErrorKey, isValid) {
26329 validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
26331 cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
26332 cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
26336 function isObjectEmpty(obj) {
26338 for (var prop in obj) {
26339 if (obj.hasOwnProperty(prop)) {
26349 * @name ngNonBindable
26354 * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
26355 * DOM element. This is useful if the element contains what appears to be Angular directives and
26356 * bindings but which should be ignored by Angular. This could be the case if you have a site that
26357 * displays snippets of code, for instance.
26362 * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
26363 * but the one wrapped in `ngNonBindable` is left alone.
26367 <file name="index.html">
26368 <div>Normal: {{1 + 2}}</div>
26369 <div ng-non-bindable>Ignored: {{1 + 2}}</div>
26371 <file name="protractor.js" type="protractor">
26372 it('should check ng-non-bindable', function() {
26373 expect(element(by.binding('1 + 2')).getText()).toContain('3');
26374 expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
26379 var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
26381 /* global jqLiteRemove */
26383 var ngOptionsMinErr = minErr('ngOptions');
26392 * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
26393 * elements for the `<select>` element using the array or object obtained by evaluating the
26394 * `ngOptions` comprehension expression.
26396 * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
26397 * similar result. However, `ngOptions` provides some benefits such as reducing memory and
26398 * increasing speed by not creating a new scope for each repeated instance, as well as providing
26399 * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
26400 * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
26401 * to a non-string value. This is because an option element can only be bound to string values at
26404 * When an item in the `<select>` menu is selected, the array element or object property
26405 * represented by the selected option will be bound to the model identified by the `ngModel`
26408 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
26409 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
26410 * option. See example below for demonstration.
26412 * ## Complex Models (objects or collections)
26414 * By default, `ngModel` watches the model by reference, not value. This is important to know when
26415 * binding the select to a model that is an object or a collection.
26417 * One issue occurs if you want to preselect an option. For example, if you set
26418 * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
26419 * because the objects are not identical. So by default, you should always reference the item in your collection
26420 * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
26422 * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
26423 * of the item not by reference, but by the result of the `track by` expression. For example, if your
26424 * collection items have an id property, you would `track by item.id`.
26426 * A different issue with objects or collections is that ngModel won't detect if an object property or
26427 * a collection item changes. For that reason, `ngOptions` additionally watches the model using
26428 * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
26429 * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
26430 * has not changed identity, but only a property on the object or an item in the collection changes.
26432 * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
26433 * if the model is an array). This means that changing a property deeper than the first level inside the
26434 * object/collection will not trigger a re-rendering.
26436 * ## `select` **`as`**
26438 * Using `select` **`as`** will bind the result of the `select` expression to the model, but
26439 * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
26440 * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
26441 * is used, the result of that expression will be set as the value of the `option` and `select` elements.
26444 * ### `select` **`as`** and **`track by`**
26446 * <div class="alert alert-warning">
26447 * Be careful when using `select` **`as`** and **`track by`** in the same expression.
26450 * Given this array of items on the $scope:
26453 * $scope.items = [{
26456 * subItem: { name: 'aSubItem' }
26460 * subItem: { name: 'bSubItem' }
26467 * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
26470 * $scope.selected = $scope.items[0];
26473 * but this will not work:
26476 * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
26479 * $scope.selected = $scope.items[0].subItem;
26482 * In both examples, the **`track by`** expression is applied successfully to each `item` in the
26483 * `items` array. Because the selected option has been set programmatically in the controller, the
26484 * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
26485 * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
26486 * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
26487 * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
26488 * is not matched against any `<option>` and the `<select>` appears as having no selected value.
26491 * @param {string} ngModel Assignable angular expression to data-bind to.
26492 * @param {string=} name Property name of the form under which the control is published.
26493 * @param {string=} required The control is considered valid only if value is entered.
26494 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
26495 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
26496 * `required` when you want to data-bind to the `required` attribute.
26497 * @param {comprehension_expression=} ngOptions in one of the following forms:
26499 * * for array data sources:
26500 * * `label` **`for`** `value` **`in`** `array`
26501 * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
26502 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
26503 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
26504 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
26505 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
26506 * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
26507 * (for including a filter with `track by`)
26508 * * for object data sources:
26509 * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
26510 * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
26511 * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
26512 * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
26513 * * `select` **`as`** `label` **`group by`** `group`
26514 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
26515 * * `select` **`as`** `label` **`disable when`** `disable`
26516 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
26520 * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
26521 * * `value`: local variable which will refer to each item in the `array` or each property value
26522 * of `object` during iteration.
26523 * * `key`: local variable which will refer to a property name in `object` during iteration.
26524 * * `label`: The result of this expression will be the label for `<option>` element. The
26525 * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
26526 * * `select`: The result of this expression will be bound to the model of the parent `<select>`
26527 * element. If not specified, `select` expression will default to `value`.
26528 * * `group`: The result of this expression will be used to group options using the `<optgroup>`
26530 * * `disable`: The result of this expression will be used to disable the rendered `<option>`
26531 * element. Return `true` to disable.
26532 * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
26533 * used to identify the objects in the array. The `trackexpr` will most likely refer to the
26534 * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
26535 * even when the options are recreated (e.g. reloaded from the server).
26538 <example module="selectExample">
26539 <file name="index.html">
26541 angular.module('selectExample', [])
26542 .controller('ExampleController', ['$scope', function($scope) {
26544 {name:'black', shade:'dark'},
26545 {name:'white', shade:'light', notAnOption: true},
26546 {name:'red', shade:'dark'},
26547 {name:'blue', shade:'dark', notAnOption: true},
26548 {name:'yellow', shade:'light', notAnOption: false}
26550 $scope.myColor = $scope.colors[2]; // red
26553 <div ng-controller="ExampleController">
26555 <li ng-repeat="color in colors">
26556 <label>Name: <input ng-model="color.name"></label>
26557 <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
26558 <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
26561 <button ng-click="colors.push({})">add</button>
26565 <label>Color (null not allowed):
26566 <select ng-model="myColor" ng-options="color.name for color in colors"></select>
26568 <label>Color (null allowed):
26569 <span class="nullable">
26570 <select ng-model="myColor" ng-options="color.name for color in colors">
26571 <option value="">-- choose color --</option>
26573 </span></label><br/>
26575 <label>Color grouped by shade:
26576 <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
26580 <label>Color grouped by shade, with some disabled:
26581 <select ng-model="myColor"
26582 ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
26588 Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
26591 Currently selected: {{ {selected_color:myColor} }}
26592 <div style="border:solid 1px black; height:20px"
26593 ng-style="{'background-color':myColor.name}">
26597 <file name="protractor.js" type="protractor">
26598 it('should check ng-options', function() {
26599 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
26600 element.all(by.model('myColor')).first().click();
26601 element.all(by.css('select[ng-model="myColor"] option')).first().click();
26602 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
26603 element(by.css('.nullable select[ng-model="myColor"]')).click();
26604 element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
26605 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
26611 // jshint maxlen: false
26612 // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
26613 var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
26614 // 1: value expression (valueFn)
26615 // 2: label expression (displayFn)
26616 // 3: group by expression (groupByFn)
26617 // 4: disable when expression (disableWhenFn)
26618 // 5: array item variable name
26619 // 6: object item key variable name
26620 // 7: object item value variable name
26621 // 8: collection expression
26622 // 9: track by expression
26623 // jshint maxlen: 100
26626 var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
26628 function parseOptionsExpression(optionsExp, selectElement, scope) {
26630 var match = optionsExp.match(NG_OPTIONS_REGEXP);
26632 throw ngOptionsMinErr('iexp',
26633 "Expected expression in form of " +
26634 "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
26635 " but got '{0}'. Element: {1}",
26636 optionsExp, startingTag(selectElement));
26639 // Extract the parts from the ngOptions expression
26641 // The variable name for the value of the item in the collection
26642 var valueName = match[5] || match[7];
26643 // The variable name for the key of the item in the collection
26644 var keyName = match[6];
26646 // An expression that generates the viewValue for an option if there is a label expression
26647 var selectAs = / as /.test(match[0]) && match[1];
26648 // An expression that is used to track the id of each object in the options collection
26649 var trackBy = match[9];
26650 // An expression that generates the viewValue for an option if there is no label expression
26651 var valueFn = $parse(match[2] ? match[1] : valueName);
26652 var selectAsFn = selectAs && $parse(selectAs);
26653 var viewValueFn = selectAsFn || valueFn;
26654 var trackByFn = trackBy && $parse(trackBy);
26656 // Get the value by which we are going to track the option
26657 // if we have a trackFn then use that (passing scope and locals)
26658 // otherwise just hash the given viewValue
26659 var getTrackByValueFn = trackBy ?
26660 function(value, locals) { return trackByFn(scope, locals); } :
26661 function getHashOfValue(value) { return hashKey(value); };
26662 var getTrackByValue = function(value, key) {
26663 return getTrackByValueFn(value, getLocals(value, key));
26666 var displayFn = $parse(match[2] || match[1]);
26667 var groupByFn = $parse(match[3] || '');
26668 var disableWhenFn = $parse(match[4] || '');
26669 var valuesFn = $parse(match[8]);
26672 var getLocals = keyName ? function(value, key) {
26673 locals[keyName] = key;
26674 locals[valueName] = value;
26676 } : function(value) {
26677 locals[valueName] = value;
26682 function Option(selectValue, viewValue, label, group, disabled) {
26683 this.selectValue = selectValue;
26684 this.viewValue = viewValue;
26685 this.label = label;
26686 this.group = group;
26687 this.disabled = disabled;
26690 function getOptionValuesKeys(optionValues) {
26691 var optionValuesKeys;
26693 if (!keyName && isArrayLike(optionValues)) {
26694 optionValuesKeys = optionValues;
26696 // if object, extract keys, in enumeration order, unsorted
26697 optionValuesKeys = [];
26698 for (var itemKey in optionValues) {
26699 if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
26700 optionValuesKeys.push(itemKey);
26704 return optionValuesKeys;
26709 getTrackByValue: getTrackByValue,
26710 getWatchables: $parse(valuesFn, function(optionValues) {
26711 // Create a collection of things that we would like to watch (watchedArray)
26712 // so that they can all be watched using a single $watchCollection
26713 // that only runs the handler once if anything changes
26714 var watchedArray = [];
26715 optionValues = optionValues || [];
26717 var optionValuesKeys = getOptionValuesKeys(optionValues);
26718 var optionValuesLength = optionValuesKeys.length;
26719 for (var index = 0; index < optionValuesLength; index++) {
26720 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
26721 var value = optionValues[key];
26723 var locals = getLocals(optionValues[key], key);
26724 var selectValue = getTrackByValueFn(optionValues[key], locals);
26725 watchedArray.push(selectValue);
26727 // Only need to watch the displayFn if there is a specific label expression
26728 if (match[2] || match[1]) {
26729 var label = displayFn(scope, locals);
26730 watchedArray.push(label);
26733 // Only need to watch the disableWhenFn if there is a specific disable expression
26735 var disableWhen = disableWhenFn(scope, locals);
26736 watchedArray.push(disableWhen);
26739 return watchedArray;
26742 getOptions: function() {
26744 var optionItems = [];
26745 var selectValueMap = {};
26747 // The option values were already computed in the `getWatchables` fn,
26748 // which must have been called to trigger `getOptions`
26749 var optionValues = valuesFn(scope) || [];
26750 var optionValuesKeys = getOptionValuesKeys(optionValues);
26751 var optionValuesLength = optionValuesKeys.length;
26753 for (var index = 0; index < optionValuesLength; index++) {
26754 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
26755 var value = optionValues[key];
26756 var locals = getLocals(value, key);
26757 var viewValue = viewValueFn(scope, locals);
26758 var selectValue = getTrackByValueFn(viewValue, locals);
26759 var label = displayFn(scope, locals);
26760 var group = groupByFn(scope, locals);
26761 var disabled = disableWhenFn(scope, locals);
26762 var optionItem = new Option(selectValue, viewValue, label, group, disabled);
26764 optionItems.push(optionItem);
26765 selectValueMap[selectValue] = optionItem;
26769 items: optionItems,
26770 selectValueMap: selectValueMap,
26771 getOptionFromViewValue: function(value) {
26772 return selectValueMap[getTrackByValue(value)];
26774 getViewValueFromOption: function(option) {
26775 // If the viewValue could be an object that may be mutated by the application,
26776 // we need to make a copy and not return the reference to the value on the option.
26777 return trackBy ? angular.copy(option.viewValue) : option.viewValue;
26785 // we can't just jqLite('<option>') since jqLite is not smart enough
26786 // to create it in <select> and IE barfs otherwise.
26787 var optionTemplate = document.createElement('option'),
26788 optGroupTemplate = document.createElement('optgroup');
26790 function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
26792 var selectCtrl = ctrls[0];
26793 var ngModelCtrl = ctrls[1];
26794 var multiple = attr.multiple;
26796 // The emptyOption allows the application developer to provide their own custom "empty"
26797 // option when the viewValue does not match any of the option values.
26799 for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
26800 if (children[i].value === '') {
26801 emptyOption = children.eq(i);
26806 var providedEmptyOption = !!emptyOption;
26808 var unknownOption = jqLite(optionTemplate.cloneNode(false));
26809 unknownOption.val('?');
26812 var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
26815 var renderEmptyOption = function() {
26816 if (!providedEmptyOption) {
26817 selectElement.prepend(emptyOption);
26819 selectElement.val('');
26820 emptyOption.prop('selected', true); // needed for IE
26821 emptyOption.attr('selected', true);
26824 var removeEmptyOption = function() {
26825 if (!providedEmptyOption) {
26826 emptyOption.remove();
26831 var renderUnknownOption = function() {
26832 selectElement.prepend(unknownOption);
26833 selectElement.val('?');
26834 unknownOption.prop('selected', true); // needed for IE
26835 unknownOption.attr('selected', true);
26838 var removeUnknownOption = function() {
26839 unknownOption.remove();
26842 // Update the controller methods for multiple selectable options
26845 selectCtrl.writeValue = function writeNgOptionsValue(value) {
26846 var option = options.getOptionFromViewValue(value);
26848 if (option && !option.disabled) {
26849 if (selectElement[0].value !== option.selectValue) {
26850 removeUnknownOption();
26851 removeEmptyOption();
26853 selectElement[0].value = option.selectValue;
26854 option.element.selected = true;
26855 option.element.setAttribute('selected', 'selected');
26858 if (value === null || providedEmptyOption) {
26859 removeUnknownOption();
26860 renderEmptyOption();
26862 removeEmptyOption();
26863 renderUnknownOption();
26868 selectCtrl.readValue = function readNgOptionsValue() {
26870 var selectedOption = options.selectValueMap[selectElement.val()];
26872 if (selectedOption && !selectedOption.disabled) {
26873 removeEmptyOption();
26874 removeUnknownOption();
26875 return options.getViewValueFromOption(selectedOption);
26880 // If we are using `track by` then we must watch the tracked value on the model
26881 // since ngModel only watches for object identity change
26882 if (ngOptions.trackBy) {
26884 function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
26885 function() { ngModelCtrl.$render(); }
26891 ngModelCtrl.$isEmpty = function(value) {
26892 return !value || value.length === 0;
26896 selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
26897 options.items.forEach(function(option) {
26898 option.element.selected = false;
26902 value.forEach(function(item) {
26903 var option = options.getOptionFromViewValue(item);
26904 if (option && !option.disabled) option.element.selected = true;
26910 selectCtrl.readValue = function readNgOptionsMultiple() {
26911 var selectedValues = selectElement.val() || [],
26914 forEach(selectedValues, function(value) {
26915 var option = options.selectValueMap[value];
26916 if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
26922 // If we are using `track by` then we must watch these tracked values on the model
26923 // since ngModel only watches for object identity change
26924 if (ngOptions.trackBy) {
26926 scope.$watchCollection(function() {
26927 if (isArray(ngModelCtrl.$viewValue)) {
26928 return ngModelCtrl.$viewValue.map(function(value) {
26929 return ngOptions.getTrackByValue(value);
26933 ngModelCtrl.$render();
26940 if (providedEmptyOption) {
26942 // we need to remove it before calling selectElement.empty() because otherwise IE will
26943 // remove the label from the element. wtf?
26944 emptyOption.remove();
26946 // compile the element since there might be bindings in it
26947 $compile(emptyOption)(scope);
26949 // remove the class, which is added automatically because we recompile the element and it
26950 // becomes the compilation root
26951 emptyOption.removeClass('ng-scope');
26953 emptyOption = jqLite(optionTemplate.cloneNode(false));
26956 // We need to do this here to ensure that the options object is defined
26957 // when we first hit it in writeNgOptionsValue
26960 // We will re-render the option elements if the option values or labels change
26961 scope.$watchCollection(ngOptions.getWatchables, updateOptions);
26963 // ------------------------------------------------------------------ //
26966 function updateOptionElement(option, element) {
26967 option.element = element;
26968 element.disabled = option.disabled;
26969 // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
26970 // selects in certain circumstances when multiple selects are next to each other and display
26971 // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
26972 // See https://github.com/angular/angular.js/issues/11314 for more info.
26973 // This is unfortunately untestable with unit / e2e tests
26974 if (option.label !== element.label) {
26975 element.label = option.label;
26976 element.textContent = option.label;
26978 if (option.value !== element.value) element.value = option.selectValue;
26981 function addOrReuseElement(parent, current, type, templateElement) {
26983 // Check whether we can reuse the next element
26984 if (current && lowercase(current.nodeName) === type) {
26985 // The next element is the right type so reuse it
26988 // The next element is not the right type so create a new one
26989 element = templateElement.cloneNode(false);
26991 // There are no more elements so just append it to the select
26992 parent.appendChild(element);
26994 // The next element is not a group so insert the new one
26995 parent.insertBefore(element, current);
27002 function removeExcessElements(current) {
27005 next = current.nextSibling;
27006 jqLiteRemove(current);
27012 function skipEmptyAndUnknownOptions(current) {
27013 var emptyOption_ = emptyOption && emptyOption[0];
27014 var unknownOption_ = unknownOption && unknownOption[0];
27016 // We cannot rely on the extracted empty option being the same as the compiled empty option,
27017 // because the compiled empty option might have been replaced by a comment because
27018 // it had an "element" transclusion directive on it (such as ngIf)
27019 if (emptyOption_ || unknownOption_) {
27021 (current === emptyOption_ ||
27022 current === unknownOption_ ||
27023 current.nodeType === NODE_TYPE_COMMENT ||
27024 current.value === '')) {
27025 current = current.nextSibling;
27032 function updateOptions() {
27034 var previousValue = options && selectCtrl.readValue();
27036 options = ngOptions.getOptions();
27039 var currentElement = selectElement[0].firstChild;
27041 // Ensure that the empty option is always there if it was explicitly provided
27042 if (providedEmptyOption) {
27043 selectElement.prepend(emptyOption);
27046 currentElement = skipEmptyAndUnknownOptions(currentElement);
27048 options.items.forEach(function updateOption(option) {
27053 if (isDefined(option.group)) {
27055 // This option is to live in a group
27056 // See if we have already created this group
27057 group = groupMap[option.group];
27061 // We have not already created this group
27062 groupElement = addOrReuseElement(selectElement[0],
27066 // Move to the next element
27067 currentElement = groupElement.nextSibling;
27069 // Update the label on the group element
27070 groupElement.label = option.group;
27072 // Store it for use later
27073 group = groupMap[option.group] = {
27074 groupElement: groupElement,
27075 currentOptionElement: groupElement.firstChild
27080 // So now we have a group for this option we add the option to the group
27081 optionElement = addOrReuseElement(group.groupElement,
27082 group.currentOptionElement,
27085 updateOptionElement(option, optionElement);
27086 // Move to the next element
27087 group.currentOptionElement = optionElement.nextSibling;
27091 // This option is not in a group
27092 optionElement = addOrReuseElement(selectElement[0],
27096 updateOptionElement(option, optionElement);
27097 // Move to the next element
27098 currentElement = optionElement.nextSibling;
27103 // Now remove all excess options and group
27104 Object.keys(groupMap).forEach(function(key) {
27105 removeExcessElements(groupMap[key].currentOptionElement);
27107 removeExcessElements(currentElement);
27109 ngModelCtrl.$render();
27111 // Check to see if the value has changed due to the update to the options
27112 if (!ngModelCtrl.$isEmpty(previousValue)) {
27113 var nextValue = selectCtrl.readValue();
27114 if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
27115 ngModelCtrl.$setViewValue(nextValue);
27116 ngModelCtrl.$render();
27126 require: ['select', 'ngModel'],
27128 pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
27129 // Deactivate the SelectController.register method to prevent
27130 // option directives from accidentally registering themselves
27131 // (and unwanted $destroy handlers etc.)
27132 ctrls[0].registerOption = noop;
27134 post: ngOptionsPostLink
27141 * @name ngPluralize
27145 * `ngPluralize` is a directive that displays messages according to en-US localization rules.
27146 * These rules are bundled with angular.js, but can be overridden
27147 * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
27148 * by specifying the mappings between
27149 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
27150 * and the strings to be displayed.
27152 * # Plural categories and explicit number rules
27154 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
27155 * in Angular's default en-US locale: "one" and "other".
27157 * While a plural category may match many numbers (for example, in en-US locale, "other" can match
27158 * any number that is not 1), an explicit number rule can only match one number. For example, the
27159 * explicit number rule for "3" matches the number 3. There are examples of plural categories
27160 * and explicit number rules throughout the rest of this documentation.
27162 * # Configuring ngPluralize
27163 * You configure ngPluralize by providing 2 attributes: `count` and `when`.
27164 * You can also provide an optional attribute, `offset`.
27166 * The value of the `count` attribute can be either a string or an {@link guide/expression
27167 * Angular expression}; these are evaluated on the current scope for its bound value.
27169 * The `when` attribute specifies the mappings between plural categories and the actual
27170 * string to be displayed. The value of the attribute should be a JSON object.
27172 * The following example shows how to configure ngPluralize:
27175 * <ng-pluralize count="personCount"
27176 when="{'0': 'Nobody is viewing.',
27177 * 'one': '1 person is viewing.',
27178 * 'other': '{} people are viewing.'}">
27182 * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
27183 * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
27184 * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
27185 * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
27186 * show "a dozen people are viewing".
27188 * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
27189 * into pluralized strings. In the previous example, Angular will replace `{}` with
27190 * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
27191 * for <span ng-non-bindable>{{numberExpression}}</span>.
27193 * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
27194 * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
27196 * # Configuring ngPluralize with offset
27197 * The `offset` attribute allows further customization of pluralized text, which can result in
27198 * a better user experience. For example, instead of the message "4 people are viewing this document",
27199 * you might display "John, Kate and 2 others are viewing this document".
27200 * The offset attribute allows you to offset a number by any desired value.
27201 * Let's take a look at an example:
27204 * <ng-pluralize count="personCount" offset=2
27205 * when="{'0': 'Nobody is viewing.',
27206 * '1': '{{person1}} is viewing.',
27207 * '2': '{{person1}} and {{person2}} are viewing.',
27208 * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
27209 * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
27213 * Notice that we are still using two plural categories(one, other), but we added
27214 * three explicit number rules 0, 1 and 2.
27215 * When one person, perhaps John, views the document, "John is viewing" will be shown.
27216 * When three people view the document, no explicit number rule is found, so
27217 * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
27218 * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
27221 * Note that when you specify offsets, you must provide explicit number rules for
27222 * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
27223 * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
27224 * plural categories "one" and "other".
27226 * @param {string|expression} count The variable to be bound to.
27227 * @param {string} when The mapping between plural category to its corresponding strings.
27228 * @param {number=} offset Offset to deduct from the total number.
27231 <example module="pluralizeExample">
27232 <file name="index.html">
27234 angular.module('pluralizeExample', [])
27235 .controller('ExampleController', ['$scope', function($scope) {
27236 $scope.person1 = 'Igor';
27237 $scope.person2 = 'Misko';
27238 $scope.personCount = 1;
27241 <div ng-controller="ExampleController">
27242 <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
27243 <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
27244 <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
27246 <!--- Example with simple pluralization rules for en locale --->
27248 <ng-pluralize count="personCount"
27249 when="{'0': 'Nobody is viewing.',
27250 'one': '1 person is viewing.',
27251 'other': '{} people are viewing.'}">
27252 </ng-pluralize><br>
27254 <!--- Example with offset --->
27256 <ng-pluralize count="personCount" offset=2
27257 when="{'0': 'Nobody is viewing.',
27258 '1': '{{person1}} is viewing.',
27259 '2': '{{person1}} and {{person2}} are viewing.',
27260 'one': '{{person1}}, {{person2}} and one other person are viewing.',
27261 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
27265 <file name="protractor.js" type="protractor">
27266 it('should show correct pluralized string', function() {
27267 var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
27268 var withOffset = element.all(by.css('ng-pluralize')).get(1);
27269 var countInput = element(by.model('personCount'));
27271 expect(withoutOffset.getText()).toEqual('1 person is viewing.');
27272 expect(withOffset.getText()).toEqual('Igor is viewing.');
27274 countInput.clear();
27275 countInput.sendKeys('0');
27277 expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
27278 expect(withOffset.getText()).toEqual('Nobody is viewing.');
27280 countInput.clear();
27281 countInput.sendKeys('2');
27283 expect(withoutOffset.getText()).toEqual('2 people are viewing.');
27284 expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
27286 countInput.clear();
27287 countInput.sendKeys('3');
27289 expect(withoutOffset.getText()).toEqual('3 people are viewing.');
27290 expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
27292 countInput.clear();
27293 countInput.sendKeys('4');
27295 expect(withoutOffset.getText()).toEqual('4 people are viewing.');
27296 expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
27298 it('should show data-bound names', function() {
27299 var withOffset = element.all(by.css('ng-pluralize')).get(1);
27300 var personCount = element(by.model('personCount'));
27301 var person1 = element(by.model('person1'));
27302 var person2 = element(by.model('person2'));
27303 personCount.clear();
27304 personCount.sendKeys('4');
27306 person1.sendKeys('Di');
27308 person2.sendKeys('Vojta');
27309 expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
27314 var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
27316 IS_WHEN = /^when(Minus)?(.+)$/;
27319 link: function(scope, element, attr) {
27320 var numberExp = attr.count,
27321 whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
27322 offset = attr.offset || 0,
27323 whens = scope.$eval(whenExp) || {},
27325 startSymbol = $interpolate.startSymbol(),
27326 endSymbol = $interpolate.endSymbol(),
27327 braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
27328 watchRemover = angular.noop,
27331 forEach(attr, function(expression, attributeName) {
27332 var tmpMatch = IS_WHEN.exec(attributeName);
27334 var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
27335 whens[whenKey] = element.attr(attr.$attr[attributeName]);
27338 forEach(whens, function(expression, key) {
27339 whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
27343 scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
27344 var count = parseFloat(newVal);
27345 var countIsNaN = isNaN(count);
27347 if (!countIsNaN && !(count in whens)) {
27348 // If an explicit number rule such as 1, 2, 3... is defined, just use it.
27349 // Otherwise, check it against pluralization rules in $locale service.
27350 count = $locale.pluralCat(count - offset);
27353 // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
27354 // In JS `NaN !== NaN`, so we have to exlicitly check.
27355 if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
27357 var whenExpFn = whensExpFns[count];
27358 if (isUndefined(whenExpFn)) {
27359 if (newVal != null) {
27360 $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
27362 watchRemover = noop;
27363 updateElementText();
27365 watchRemover = scope.$watch(whenExpFn, updateElementText);
27371 function updateElementText(newText) {
27372 element.text(newText || '');
27384 * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
27385 * instance gets its own scope, where the given loop variable is set to the current collection item,
27386 * and `$index` is set to the item index or key.
27388 * Special properties are exposed on the local scope of each template instance, including:
27390 * | Variable | Type | Details |
27391 * |-----------|-----------------|-----------------------------------------------------------------------------|
27392 * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
27393 * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
27394 * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
27395 * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
27396 * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
27397 * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
27399 * <div class="alert alert-info">
27400 * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
27401 * This may be useful when, for instance, nesting ngRepeats.
27405 * # Iterating over object properties
27407 * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
27411 * <div ng-repeat="(key, value) in myObj"> ... </div>
27414 * You need to be aware that the JavaScript specification does not define the order of keys
27415 * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
27416 * used to sort the keys alphabetically.)
27418 * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
27419 * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
27420 * keys in the order in which they were defined, although there are exceptions when keys are deleted
27421 * and reinstated. See the [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
27423 * If this is not desired, the recommended workaround is to convert your object into an array
27424 * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
27425 * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
27426 * or implement a `$watch` on the object yourself.
27429 * # Tracking and Duplicates
27431 * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
27432 * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
27434 * * When an item is added, a new instance of the template is added to the DOM.
27435 * * When an item is removed, its template instance is removed from the DOM.
27436 * * When items are reordered, their respective templates are reordered in the DOM.
27438 * To minimize creation of DOM elements, `ngRepeat` uses a function
27439 * to "keep track" of all items in the collection and their corresponding DOM elements.
27440 * For example, if an item is added to the collection, ngRepeat will know that all other items
27441 * already have DOM elements, and will not re-render them.
27443 * The default tracking function (which tracks items by their identity) does not allow
27444 * duplicate items in arrays. This is because when there are duplicates, it is not possible
27445 * to maintain a one-to-one mapping between collection items and DOM elements.
27447 * If you do need to repeat duplicate items, you can substitute the default tracking behavior
27448 * with your own using the `track by` expression.
27450 * For example, you may track items by the index of each item in the collection, using the
27451 * special scope property `$index`:
27453 * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
27458 * You may also use arbitrary expressions in `track by`, including references to custom functions
27461 * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
27466 * <div class="alert alert-success">
27467 * If you are working with objects that have an identifier property, you should track
27468 * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
27469 * will not have to rebuild the DOM elements for items it has already rendered, even if the
27470 * JavaScript objects in the collection have been substituted for new ones. For large collections,
27471 * this signifincantly improves rendering performance. If you don't have a unique identifier,
27472 * `track by $index` can also provide a performance boost.
27475 * <div ng-repeat="model in collection track by model.id">
27480 * When no `track by` expression is provided, it is equivalent to tracking by the built-in
27481 * `$id` function, which tracks items by their identity:
27483 * <div ng-repeat="obj in collection track by $id(obj)">
27488 * <div class="alert alert-warning">
27489 * **Note:** `track by` must always be the last expression:
27492 * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
27497 * # Special repeat start and end points
27498 * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
27499 * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
27500 * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
27501 * up to and including the ending HTML tag where **ng-repeat-end** is placed.
27503 * The example below makes use of this feature:
27505 * <header ng-repeat-start="item in items">
27506 * Header {{ item }}
27508 * <div class="body">
27511 * <footer ng-repeat-end>
27512 * Footer {{ item }}
27516 * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
27521 * <div class="body">
27530 * <div class="body">
27538 * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
27539 * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
27542 * **.enter** - when a new item is added to the list or when an item is revealed after a filter
27544 * **.leave** - when an item is removed from the list or when an item is filtered out
27546 * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
27551 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
27552 * formats are currently supported:
27554 * * `variable in expression` – where variable is the user defined loop variable and `expression`
27555 * is a scope expression giving the collection to enumerate.
27557 * For example: `album in artist.albums`.
27559 * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
27560 * and `expression` is the scope expression giving the collection to enumerate.
27562 * For example: `(name, age) in {'adam':10, 'amalie':12}`.
27564 * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
27565 * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
27566 * is specified, ng-repeat associates elements by identity. It is an error to have
27567 * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
27568 * mapped to the same DOM element, which is not possible.)
27570 * Note that the tracking expression must come last, after any filters, and the alias expression.
27572 * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
27573 * will be associated by item identity in the array.
27575 * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
27576 * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
27577 * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
27578 * element in the same way in the DOM.
27580 * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
27581 * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
27582 * property is same.
27584 * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
27585 * to items in conjunction with a tracking expression.
27587 * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
27588 * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
27589 * when a filter is active on the repeater, but the filtered result set is empty.
27591 * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
27592 * the items have been processed through the filter.
27594 * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
27595 * (and not as operator, inside an expression).
27597 * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
27600 * This example initializes the scope to a list of names and
27601 * then uses `ngRepeat` to display every person:
27602 <example module="ngAnimate" deps="angular-animate.js" animations="true">
27603 <file name="index.html">
27604 <div ng-init="friends = [
27605 {name:'John', age:25, gender:'boy'},
27606 {name:'Jessie', age:30, gender:'girl'},
27607 {name:'Johanna', age:28, gender:'girl'},
27608 {name:'Joy', age:15, gender:'girl'},
27609 {name:'Mary', age:28, gender:'girl'},
27610 {name:'Peter', age:95, gender:'boy'},
27611 {name:'Sebastian', age:50, gender:'boy'},
27612 {name:'Erika', age:27, gender:'girl'},
27613 {name:'Patrick', age:40, gender:'boy'},
27614 {name:'Samantha', age:60, gender:'girl'}
27616 I have {{friends.length}} friends. They are:
27617 <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
27618 <ul class="example-animate-container">
27619 <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
27620 [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
27622 <li class="animate-repeat" ng-if="results.length == 0">
27623 <strong>No results found...</strong>
27628 <file name="animations.css">
27629 .example-animate-container {
27631 border:1px solid black;
27640 box-sizing:border-box;
27643 .animate-repeat.ng-move,
27644 .animate-repeat.ng-enter,
27645 .animate-repeat.ng-leave {
27646 transition:all linear 0.5s;
27649 .animate-repeat.ng-leave.ng-leave-active,
27650 .animate-repeat.ng-move,
27651 .animate-repeat.ng-enter {
27656 .animate-repeat.ng-leave,
27657 .animate-repeat.ng-move.ng-move-active,
27658 .animate-repeat.ng-enter.ng-enter-active {
27663 <file name="protractor.js" type="protractor">
27664 var friends = element.all(by.repeater('friend in friends'));
27666 it('should render initial data set', function() {
27667 expect(friends.count()).toBe(10);
27668 expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
27669 expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
27670 expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
27671 expect(element(by.binding('friends.length')).getText())
27672 .toMatch("I have 10 friends. They are:");
27675 it('should update repeater when filter predicate changes', function() {
27676 expect(friends.count()).toBe(10);
27678 element(by.model('q')).sendKeys('ma');
27680 expect(friends.count()).toBe(2);
27681 expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
27682 expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
27687 var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
27688 var NG_REMOVED = '$$NG_REMOVED';
27689 var ngRepeatMinErr = minErr('ngRepeat');
27691 var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
27692 // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
27693 scope[valueIdentifier] = value;
27694 if (keyIdentifier) scope[keyIdentifier] = key;
27695 scope.$index = index;
27696 scope.$first = (index === 0);
27697 scope.$last = (index === (arrayLength - 1));
27698 scope.$middle = !(scope.$first || scope.$last);
27699 // jshint bitwise: false
27700 scope.$odd = !(scope.$even = (index&1) === 0);
27701 // jshint bitwise: true
27704 var getBlockStart = function(block) {
27705 return block.clone[0];
27708 var getBlockEnd = function(block) {
27709 return block.clone[block.clone.length - 1];
27715 multiElement: true,
27716 transclude: 'element',
27720 compile: function ngRepeatCompile($element, $attr) {
27721 var expression = $attr.ngRepeat;
27722 var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
27724 var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
27727 throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
27731 var lhs = match[1];
27732 var rhs = match[2];
27733 var aliasAs = match[3];
27734 var trackByExp = match[4];
27736 match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
27739 throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
27742 var valueIdentifier = match[3] || match[1];
27743 var keyIdentifier = match[2];
27745 if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
27746 /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
27747 throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
27751 var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
27752 var hashFnLocals = {$id: hashKey};
27755 trackByExpGetter = $parse(trackByExp);
27757 trackByIdArrayFn = function(key, value) {
27758 return hashKey(value);
27760 trackByIdObjFn = function(key) {
27765 return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
27767 if (trackByExpGetter) {
27768 trackByIdExpFn = function(key, value, index) {
27769 // assign key, value, and $index to the locals so that they can be used in hash functions
27770 if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
27771 hashFnLocals[valueIdentifier] = value;
27772 hashFnLocals.$index = index;
27773 return trackByExpGetter($scope, hashFnLocals);
27777 // Store a list of elements from previous run. This is a hash where key is the item from the
27778 // iterator, and the value is objects with following properties.
27779 // - scope: bound scope
27780 // - element: previous element.
27781 // - index: position
27783 // We are using no-proto object so that we don't need to guard against inherited props via
27785 var lastBlockMap = createMap();
27788 $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
27790 previousNode = $element[0], // node that cloned nodes should be inserted after
27791 // initialized to the comment node anchor
27793 // Same as lastBlockMap but it has the current state. It will become the
27794 // lastBlockMap on the next iteration.
27795 nextBlockMap = createMap(),
27797 key, value, // key/value of iteration
27801 block, // last object information {scope, element, id}
27806 $scope[aliasAs] = collection;
27809 if (isArrayLike(collection)) {
27810 collectionKeys = collection;
27811 trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
27813 trackByIdFn = trackByIdExpFn || trackByIdObjFn;
27814 // if object, extract keys, in enumeration order, unsorted
27815 collectionKeys = [];
27816 for (var itemKey in collection) {
27817 if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
27818 collectionKeys.push(itemKey);
27823 collectionLength = collectionKeys.length;
27824 nextBlockOrder = new Array(collectionLength);
27826 // locate existing items
27827 for (index = 0; index < collectionLength; index++) {
27828 key = (collection === collectionKeys) ? index : collectionKeys[index];
27829 value = collection[key];
27830 trackById = trackByIdFn(key, value, index);
27831 if (lastBlockMap[trackById]) {
27832 // found previously seen block
27833 block = lastBlockMap[trackById];
27834 delete lastBlockMap[trackById];
27835 nextBlockMap[trackById] = block;
27836 nextBlockOrder[index] = block;
27837 } else if (nextBlockMap[trackById]) {
27838 // if collision detected. restore lastBlockMap and throw an error
27839 forEach(nextBlockOrder, function(block) {
27840 if (block && block.scope) lastBlockMap[block.id] = block;
27842 throw ngRepeatMinErr('dupes',
27843 "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
27844 expression, trackById, value);
27846 // new never before seen block
27847 nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
27848 nextBlockMap[trackById] = true;
27852 // remove leftover items
27853 for (var blockKey in lastBlockMap) {
27854 block = lastBlockMap[blockKey];
27855 elementsToRemove = getBlockNodes(block.clone);
27856 $animate.leave(elementsToRemove);
27857 if (elementsToRemove[0].parentNode) {
27858 // if the element was not removed yet because of pending animation, mark it as deleted
27859 // so that we can ignore it later
27860 for (index = 0, length = elementsToRemove.length; index < length; index++) {
27861 elementsToRemove[index][NG_REMOVED] = true;
27864 block.scope.$destroy();
27867 // we are not using forEach for perf reasons (trying to avoid #call)
27868 for (index = 0; index < collectionLength; index++) {
27869 key = (collection === collectionKeys) ? index : collectionKeys[index];
27870 value = collection[key];
27871 block = nextBlockOrder[index];
27874 // if we have already seen this object, then we need to reuse the
27875 // associated scope/element
27877 nextNode = previousNode;
27879 // skip nodes that are already pending removal via leave animation
27881 nextNode = nextNode.nextSibling;
27882 } while (nextNode && nextNode[NG_REMOVED]);
27884 if (getBlockStart(block) != nextNode) {
27885 // existing item which got moved
27886 $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
27888 previousNode = getBlockEnd(block);
27889 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
27891 // new item which we don't know about
27892 $transclude(function ngRepeatTransclude(clone, scope) {
27893 block.scope = scope;
27894 // http://jsperf.com/clone-vs-createcomment
27895 var endNode = ngRepeatEndComment.cloneNode(false);
27896 clone[clone.length++] = endNode;
27898 // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
27899 $animate.enter(clone, null, jqLite(previousNode));
27900 previousNode = endNode;
27901 // Note: We only need the first/last node of the cloned nodes.
27902 // However, we need to keep the reference to the jqlite wrapper as it might be changed later
27903 // by a directive with templateUrl when its template arrives.
27904 block.clone = clone;
27905 nextBlockMap[block.id] = block;
27906 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
27910 lastBlockMap = nextBlockMap;
27917 var NG_HIDE_CLASS = 'ng-hide';
27918 var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
27925 * The `ngShow` directive shows or hides the given HTML element based on the expression
27926 * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
27927 * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
27928 * in AngularJS and sets the display style to none (using an !important flag).
27929 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
27932 * <!-- when $scope.myValue is truthy (element is visible) -->
27933 * <div ng-show="myValue"></div>
27935 * <!-- when $scope.myValue is falsy (element is hidden) -->
27936 * <div ng-show="myValue" class="ng-hide"></div>
27939 * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
27940 * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
27941 * from the element causing the element not to appear hidden.
27943 * ## Why is !important used?
27945 * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
27946 * can be easily overridden by heavier selectors. For example, something as simple
27947 * as changing the display style on a HTML list item would make hidden elements appear visible.
27948 * This also becomes a bigger issue when dealing with CSS frameworks.
27950 * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
27951 * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
27952 * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
27954 * ### Overriding `.ng-hide`
27956 * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
27957 * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
27958 * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
27959 * with extra animation classes that can be added.
27962 * .ng-hide:not(.ng-hide-animate) {
27963 * /* this is just another form of hiding an element */
27964 * display: block!important;
27965 * position: absolute;
27971 * By default you don't need to override in CSS anything and the animations will work around the display style.
27973 * ## A note about animations with `ngShow`
27975 * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
27976 * is true and false. This system works like the animation system present with ngClass except that
27977 * you must also include the !important flag to override the display property
27978 * so that you can perform an animation when the element is hidden during the time of the animation.
27982 * //a working example can be found at the bottom of this page
27984 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
27985 * /* this is required as of 1.3x to properly
27986 * apply all styling in a show/hide animation */
27987 * transition: 0s linear all;
27990 * .my-element.ng-hide-add-active,
27991 * .my-element.ng-hide-remove-active {
27992 * /* the transition is defined in the active class */
27993 * transition: 1s linear all;
27996 * .my-element.ng-hide-add { ... }
27997 * .my-element.ng-hide-add.ng-hide-add-active { ... }
27998 * .my-element.ng-hide-remove { ... }
27999 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
28002 * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
28003 * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
28006 * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
28007 * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
28010 * @param {expression} ngShow If the {@link guide/expression expression} is truthy
28011 * then the element is shown or hidden respectively.
28014 <example module="ngAnimate" deps="angular-animate.js" animations="true">
28015 <file name="index.html">
28016 Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
28019 <div class="check-element animate-show" ng-show="checked">
28020 <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
28025 <div class="check-element animate-show" ng-hide="checked">
28026 <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
28030 <file name="glyphicons.css">
28031 @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
28033 <file name="animations.css">
28038 border: 1px solid black;
28042 .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
28043 transition: all linear 0.5s;
28046 .animate-show.ng-hide {
28054 border: 1px solid black;
28058 <file name="protractor.js" type="protractor">
28059 var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
28060 var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
28062 it('should check ng-show / ng-hide', function() {
28063 expect(thumbsUp.isDisplayed()).toBeFalsy();
28064 expect(thumbsDown.isDisplayed()).toBeTruthy();
28066 element(by.model('checked')).click();
28068 expect(thumbsUp.isDisplayed()).toBeTruthy();
28069 expect(thumbsDown.isDisplayed()).toBeFalsy();
28074 var ngShowDirective = ['$animate', function($animate) {
28077 multiElement: true,
28078 link: function(scope, element, attr) {
28079 scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
28080 // we're adding a temporary, animation-specific class for ng-hide since this way
28081 // we can control when the element is actually displayed on screen without having
28082 // to have a global/greedy CSS selector that breaks when other animations are run.
28083 // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
28084 $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
28085 tempClasses: NG_HIDE_IN_PROGRESS_CLASS
28099 * The `ngHide` directive shows or hides the given HTML element based on the expression
28100 * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
28101 * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
28102 * in AngularJS and sets the display style to none (using an !important flag).
28103 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
28106 * <!-- when $scope.myValue is truthy (element is hidden) -->
28107 * <div ng-hide="myValue" class="ng-hide"></div>
28109 * <!-- when $scope.myValue is falsy (element is visible) -->
28110 * <div ng-hide="myValue"></div>
28113 * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
28114 * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
28115 * from the element causing the element not to appear hidden.
28117 * ## Why is !important used?
28119 * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
28120 * can be easily overridden by heavier selectors. For example, something as simple
28121 * as changing the display style on a HTML list item would make hidden elements appear visible.
28122 * This also becomes a bigger issue when dealing with CSS frameworks.
28124 * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
28125 * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
28126 * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
28128 * ### Overriding `.ng-hide`
28130 * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
28131 * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
28136 * /* this is just another form of hiding an element */
28137 * display: block!important;
28138 * position: absolute;
28144 * By default you don't need to override in CSS anything and the animations will work around the display style.
28146 * ## A note about animations with `ngHide`
28148 * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
28149 * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
28150 * CSS class is added and removed for you instead of your own CSS class.
28154 * //a working example can be found at the bottom of this page
28156 * .my-element.ng-hide-add, .my-element.ng-hide-remove {
28157 * transition: 0.5s linear all;
28160 * .my-element.ng-hide-add { ... }
28161 * .my-element.ng-hide-add.ng-hide-add-active { ... }
28162 * .my-element.ng-hide-remove { ... }
28163 * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
28166 * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
28167 * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
28170 * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
28171 * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
28174 * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
28175 * the element is shown or hidden respectively.
28178 <example module="ngAnimate" deps="angular-animate.js" animations="true">
28179 <file name="index.html">
28180 Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
28183 <div class="check-element animate-hide" ng-show="checked">
28184 <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
28189 <div class="check-element animate-hide" ng-hide="checked">
28190 <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
28194 <file name="glyphicons.css">
28195 @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
28197 <file name="animations.css">
28199 transition: all linear 0.5s;
28203 border: 1px solid black;
28207 .animate-hide.ng-hide {
28215 border: 1px solid black;
28219 <file name="protractor.js" type="protractor">
28220 var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
28221 var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
28223 it('should check ng-show / ng-hide', function() {
28224 expect(thumbsUp.isDisplayed()).toBeFalsy();
28225 expect(thumbsDown.isDisplayed()).toBeTruthy();
28227 element(by.model('checked')).click();
28229 expect(thumbsUp.isDisplayed()).toBeTruthy();
28230 expect(thumbsDown.isDisplayed()).toBeFalsy();
28235 var ngHideDirective = ['$animate', function($animate) {
28238 multiElement: true,
28239 link: function(scope, element, attr) {
28240 scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
28241 // The comment inside of the ngShowDirective explains why we add and
28242 // remove a temporary class for the show/hide animation
28243 $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
28244 tempClasses: NG_HIDE_IN_PROGRESS_CLASS
28257 * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
28260 * @param {expression} ngStyle
28262 * {@link guide/expression Expression} which evals to an
28263 * object whose keys are CSS style names and values are corresponding values for those CSS
28266 * Since some CSS style names are not valid keys for an object, they must be quoted.
28267 * See the 'background-color' style in the example below.
28271 <file name="index.html">
28272 <input type="button" value="set color" ng-click="myStyle={color:'red'}">
28273 <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
28274 <input type="button" value="clear" ng-click="myStyle={}">
28276 <span ng-style="myStyle">Sample Text</span>
28277 <pre>myStyle={{myStyle}}</pre>
28279 <file name="style.css">
28284 <file name="protractor.js" type="protractor">
28285 var colorSpan = element(by.css('span'));
28287 it('should check ng-style', function() {
28288 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
28289 element(by.css('input[value=\'set color\']')).click();
28290 expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
28291 element(by.css('input[value=clear]')).click();
28292 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
28297 var ngStyleDirective = ngDirective(function(scope, element, attr) {
28298 scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
28299 if (oldStyles && (newStyles !== oldStyles)) {
28300 forEach(oldStyles, function(val, style) { element.css(style, '');});
28302 if (newStyles) element.css(newStyles);
28312 * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
28313 * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
28314 * as specified in the template.
28316 * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
28317 * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
28318 * matches the value obtained from the evaluated expression. In other words, you define a container element
28319 * (where you place the directive), place an expression on the **`on="..."` attribute**
28320 * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
28321 * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
28322 * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
28323 * attribute is displayed.
28325 * <div class="alert alert-info">
28326 * Be aware that the attribute values to match against cannot be expressions. They are interpreted
28327 * as literal string values to match against.
28328 * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
28329 * value of the expression `$scope.someVal`.
28333 * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
28334 * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
28339 * <ANY ng-switch="expression">
28340 * <ANY ng-switch-when="matchValue1">...</ANY>
28341 * <ANY ng-switch-when="matchValue2">...</ANY>
28342 * <ANY ng-switch-default>...</ANY>
28349 * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
28350 * On child elements add:
28352 * * `ngSwitchWhen`: the case statement to match against. If match then this
28353 * case will be displayed. If the same match appears multiple times, all the
28354 * elements will be displayed.
28355 * * `ngSwitchDefault`: the default case when no other case match. If there
28356 * are multiple default cases, all of them will be displayed when no other
28361 <example module="switchExample" deps="angular-animate.js" animations="true">
28362 <file name="index.html">
28363 <div ng-controller="ExampleController">
28364 <select ng-model="selection" ng-options="item for item in items">
28366 <code>selection={{selection}}</code>
28368 <div class="animate-switch-container"
28369 ng-switch on="selection">
28370 <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
28371 <div class="animate-switch" ng-switch-when="home">Home Span</div>
28372 <div class="animate-switch" ng-switch-default>default</div>
28376 <file name="script.js">
28377 angular.module('switchExample', ['ngAnimate'])
28378 .controller('ExampleController', ['$scope', function($scope) {
28379 $scope.items = ['settings', 'home', 'other'];
28380 $scope.selection = $scope.items[0];
28383 <file name="animations.css">
28384 .animate-switch-container {
28387 border:1px solid black;
28396 .animate-switch.ng-animate {
28397 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
28406 .animate-switch.ng-leave.ng-leave-active,
28407 .animate-switch.ng-enter {
28410 .animate-switch.ng-leave,
28411 .animate-switch.ng-enter.ng-enter-active {
28415 <file name="protractor.js" type="protractor">
28416 var switchElem = element(by.css('[ng-switch]'));
28417 var select = element(by.model('selection'));
28419 it('should start in settings', function() {
28420 expect(switchElem.getText()).toMatch(/Settings Div/);
28422 it('should change to home', function() {
28423 select.all(by.css('option')).get(1).click();
28424 expect(switchElem.getText()).toMatch(/Home Span/);
28426 it('should select default', function() {
28427 select.all(by.css('option')).get(2).click();
28428 expect(switchElem.getText()).toMatch(/default/);
28433 var ngSwitchDirective = ['$animate', function($animate) {
28435 require: 'ngSwitch',
28437 // asks for $scope to fool the BC controller module
28438 controller: ['$scope', function ngSwitchController() {
28441 link: function(scope, element, attr, ngSwitchController) {
28442 var watchExpr = attr.ngSwitch || attr.on,
28443 selectedTranscludes = [],
28444 selectedElements = [],
28445 previousLeaveAnimations = [],
28446 selectedScopes = [];
28448 var spliceFactory = function(array, index) {
28449 return function() { array.splice(index, 1); };
28452 scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
28454 for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
28455 $animate.cancel(previousLeaveAnimations[i]);
28457 previousLeaveAnimations.length = 0;
28459 for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
28460 var selected = getBlockNodes(selectedElements[i].clone);
28461 selectedScopes[i].$destroy();
28462 var promise = previousLeaveAnimations[i] = $animate.leave(selected);
28463 promise.then(spliceFactory(previousLeaveAnimations, i));
28466 selectedElements.length = 0;
28467 selectedScopes.length = 0;
28469 if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
28470 forEach(selectedTranscludes, function(selectedTransclude) {
28471 selectedTransclude.transclude(function(caseElement, selectedScope) {
28472 selectedScopes.push(selectedScope);
28473 var anchor = selectedTransclude.element;
28474 caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
28475 var block = { clone: caseElement };
28477 selectedElements.push(block);
28478 $animate.enter(caseElement, anchor.parent(), anchor);
28487 var ngSwitchWhenDirective = ngDirective({
28488 transclude: 'element',
28490 require: '^ngSwitch',
28491 multiElement: true,
28492 link: function(scope, element, attrs, ctrl, $transclude) {
28493 ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
28494 ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
28498 var ngSwitchDefaultDirective = ngDirective({
28499 transclude: 'element',
28501 require: '^ngSwitch',
28502 multiElement: true,
28503 link: function(scope, element, attr, ctrl, $transclude) {
28504 ctrl.cases['?'] = (ctrl.cases['?'] || []);
28505 ctrl.cases['?'].push({ transclude: $transclude, element: element });
28511 * @name ngTransclude
28515 * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
28517 * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
28518 * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
28520 * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
28524 * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided or empty then
28525 * the default slot is used.
28528 * ### Default transclusion
28529 * This example demonstrates simple transclusion.
28530 <example name="simpleTranscludeExample" module="transcludeExample">
28531 <file name="index.html">
28533 angular.module('transcludeExample', [])
28534 .directive('pane', function(){
28538 scope: { title:'@' },
28539 template: '<div style="border: 1px solid black;">' +
28540 '<div style="background-color: gray">{{title}}</div>' +
28541 '<ng-transclude></ng-transclude>' +
28545 .controller('ExampleController', ['$scope', function($scope) {
28546 $scope.title = 'Lorem Ipsum';
28547 $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
28550 <div ng-controller="ExampleController">
28551 <input ng-model="title" aria-label="title"> <br/>
28552 <textarea ng-model="text" aria-label="text"></textarea> <br/>
28553 <pane title="{{title}}">{{text}}</pane>
28556 <file name="protractor.js" type="protractor">
28557 it('should have transcluded', function() {
28558 var titleElement = element(by.model('title'));
28559 titleElement.clear();
28560 titleElement.sendKeys('TITLE');
28561 var textElement = element(by.model('text'));
28562 textElement.clear();
28563 textElement.sendKeys('TEXT');
28564 expect(element(by.binding('title')).getText()).toEqual('TITLE');
28565 expect(element(by.binding('text')).getText()).toEqual('TEXT');
28571 * ### Multi-slot transclusion
28572 <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
28573 <file name="index.html">
28574 <div ng-controller="ExampleController">
28575 <input ng-model="title" aria-label="title"> <br/>
28576 <textarea ng-model="text" aria-label="text"></textarea> <br/>
28578 <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
28579 <pane-body><p>{{text}}</p></pane-body>
28583 <file name="app.js">
28584 angular.module('multiSlotTranscludeExample', [])
28585 .directive('pane', function(){
28589 'paneTitle': '?title',
28592 template: '<div style="border: 1px solid black;">' +
28593 '<div ng-transclude="title" style="background-color: gray"></div>' +
28594 '<div ng-transclude="body"></div>' +
28598 .controller('ExampleController', ['$scope', function($scope) {
28599 $scope.title = 'Lorem Ipsum';
28600 $scope.link = "https://google.com";
28601 $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
28604 <file name="protractor.js" type="protractor">
28605 it('should have transcluded the title and the body', function() {
28606 var titleElement = element(by.model('title'));
28607 titleElement.clear();
28608 titleElement.sendKeys('TITLE');
28609 var textElement = element(by.model('text'));
28610 textElement.clear();
28611 textElement.sendKeys('TEXT');
28612 expect(element(by.binding('title')).getText()).toEqual('TITLE');
28613 expect(element(by.binding('text')).getText()).toEqual('TEXT');
28617 var ngTranscludeMinErr = minErr('ngTransclude');
28618 var ngTranscludeDirective = ngDirective({
28620 link: function($scope, $element, $attrs, controller, $transclude) {
28622 function ngTranscludeCloneAttachFn(clone) {
28624 $element.append(clone);
28627 if (!$transclude) {
28628 throw ngTranscludeMinErr('orphan',
28629 'Illegal use of ngTransclude directive in the template! ' +
28630 'No parent directive that requires a transclusion found. ' +
28632 startingTag($element));
28635 $transclude(ngTranscludeCloneAttachFn, null, $attrs.ngTransclude || $attrs.ngTranscludeSlot);
28645 * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
28646 * template can be used by {@link ng.directive:ngInclude `ngInclude`},
28647 * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
28648 * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
28649 * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
28651 * @param {string} type Must be set to `'text/ng-template'`.
28652 * @param {string} id Cache name of the template.
28656 <file name="index.html">
28657 <script type="text/ng-template" id="/tpl.html">
28658 Content of the template.
28661 <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
28662 <div id="tpl-content" ng-include src="currentTpl"></div>
28664 <file name="protractor.js" type="protractor">
28665 it('should load template defined inside script tag', function() {
28666 element(by.css('#tpl-link')).click();
28667 expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
28672 var scriptDirective = ['$templateCache', function($templateCache) {
28676 compile: function(element, attr) {
28677 if (attr.type == 'text/ng-template') {
28678 var templateUrl = attr.id,
28679 text = element[0].text;
28681 $templateCache.put(templateUrl, text);
28687 var noopNgModelController = { $setViewValue: noop, $render: noop };
28689 function chromeHack(optionElement) {
28690 // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
28691 // Adding an <option selected="selected"> element to a <select required="required"> should
28692 // automatically select the new element
28693 if (optionElement[0].hasAttribute('selected')) {
28694 optionElement[0].selected = true;
28700 * @name select.SelectController
28702 * The controller for the `<select>` directive. This provides support for reading
28703 * and writing the selected value(s) of the control and also coordinates dynamically
28704 * added `<option>` elements, perhaps by an `ngRepeat` directive.
28706 var SelectController =
28707 ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
28710 optionsMap = new HashMap();
28712 // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
28713 self.ngModelCtrl = noopNgModelController;
28715 // The "unknown" option is one that is prepended to the list if the viewValue
28716 // does not match any of the options. When it is rendered the value of the unknown
28717 // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
28719 // We can't just jqLite('<option>') since jqLite is not smart enough
28720 // to create it in <select> and IE barfs otherwise.
28721 self.unknownOption = jqLite(document.createElement('option'));
28722 self.renderUnknownOption = function(val) {
28723 var unknownVal = '? ' + hashKey(val) + ' ?';
28724 self.unknownOption.val(unknownVal);
28725 $element.prepend(self.unknownOption);
28726 $element.val(unknownVal);
28729 $scope.$on('$destroy', function() {
28730 // disable unknown option so that we don't do work when the whole select is being destroyed
28731 self.renderUnknownOption = noop;
28734 self.removeUnknownOption = function() {
28735 if (self.unknownOption.parent()) self.unknownOption.remove();
28739 // Read the value of the select control, the implementation of this changes depending
28740 // upon whether the select can have multiple values and whether ngOptions is at work.
28741 self.readValue = function readSingleValue() {
28742 self.removeUnknownOption();
28743 return $element.val();
28747 // Write the value to the select control, the implementation of this changes depending
28748 // upon whether the select can have multiple values and whether ngOptions is at work.
28749 self.writeValue = function writeSingleValue(value) {
28750 if (self.hasOption(value)) {
28751 self.removeUnknownOption();
28752 $element.val(value);
28753 if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
28755 if (value == null && self.emptyOption) {
28756 self.removeUnknownOption();
28759 self.renderUnknownOption(value);
28765 // Tell the select control that an option, with the given value, has been added
28766 self.addOption = function(value, element) {
28767 assertNotHasOwnProperty(value, '"option value"');
28768 if (value === '') {
28769 self.emptyOption = element;
28771 var count = optionsMap.get(value) || 0;
28772 optionsMap.put(value, count + 1);
28773 self.ngModelCtrl.$render();
28774 chromeHack(element);
28777 // Tell the select control that an option, with the given value, has been removed
28778 self.removeOption = function(value) {
28779 var count = optionsMap.get(value);
28782 optionsMap.remove(value);
28783 if (value === '') {
28784 self.emptyOption = undefined;
28787 optionsMap.put(value, count - 1);
28792 // Check whether the select control has an option matching the given value
28793 self.hasOption = function(value) {
28794 return !!optionsMap.get(value);
28798 self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
28800 if (interpolateValueFn) {
28801 // The value attribute is interpolated
28803 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
28804 if (isDefined(oldVal)) {
28805 self.removeOption(oldVal);
28808 self.addOption(newVal, optionElement);
28810 } else if (interpolateTextFn) {
28811 // The text content is interpolated
28812 optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
28813 optionAttrs.$set('value', newVal);
28814 if (oldVal !== newVal) {
28815 self.removeOption(oldVal);
28817 self.addOption(newVal, optionElement);
28820 // The value attribute is static
28821 self.addOption(optionAttrs.value, optionElement);
28824 optionElement.on('$destroy', function() {
28825 self.removeOption(optionAttrs.value);
28826 self.ngModelCtrl.$render();
28837 * HTML `SELECT` element with angular data-binding.
28839 * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
28840 * between the scope and the `<select>` control (including setting default values).
28841 * Ìt also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
28842 * {@link ngOptions `ngOptions`} directives.
28844 * When an item in the `<select>` menu is selected, the value of the selected option will be bound
28845 * to the model identified by the `ngModel` directive. With static or repeated options, this is
28846 * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
28847 * If you want dynamic value attributes, you can use interpolation inside the value attribute.
28849 * <div class="alert alert-warning">
28850 * Note that the value of a `select` directive used without `ngOptions` is always a string.
28851 * When the model needs to be bound to a non-string value, you must either explictly convert it
28852 * using a directive (see example below) or use `ngOptions` to specify the set of options.
28853 * This is because an option element can only be bound to string values at present.
28856 * If the viewValue of `ngModel` does not match any of the options, then the control
28857 * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
28859 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
28860 * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
28861 * option. See example below for demonstration.
28863 * <div class="alert alert-info">
28864 * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
28865 * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
28866 * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
28867 * comprehension expression, and additionally in reducing memory and increasing speed by not creating
28868 * a new scope for each repeated instance.
28872 * @param {string} ngModel Assignable angular expression to data-bind to.
28873 * @param {string=} name Property name of the form under which the control is published.
28874 * @param {string=} multiple Allows multiple options to be selected. The selected values will be
28875 * bound to the model as an array.
28876 * @param {string=} required Sets `required` validation error key if the value is not entered.
28877 * @param {string=} ngRequired Adds required attribute and required validation constraint to
28878 * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
28879 * when you want to data-bind to the required attribute.
28880 * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
28881 * interaction with the select element.
28882 * @param {string=} ngOptions sets the options that the select is populated with and defines what is
28883 * set on the model on selection. See {@link ngOptions `ngOptions`}.
28886 * ### Simple `select` elements with static options
28888 * <example name="static-select" module="staticSelect">
28889 * <file name="index.html">
28890 * <div ng-controller="ExampleController">
28891 * <form name="myForm">
28892 * <label for="singleSelect"> Single select: </label><br>
28893 * <select name="singleSelect" ng-model="data.singleSelect">
28894 * <option value="option-1">Option 1</option>
28895 * <option value="option-2">Option 2</option>
28898 * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
28899 * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
28900 * <option value="">---Please select---</option> <!-- not selected / blank option -->
28901 * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
28902 * <option value="option-2">Option 2</option>
28904 * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
28905 * <tt>singleSelect = {{data.singleSelect}}</tt>
28908 * <label for="multipleSelect"> Multiple select: </label><br>
28909 * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
28910 * <option value="option-1">Option 1</option>
28911 * <option value="option-2">Option 2</option>
28912 * <option value="option-3">Option 3</option>
28914 * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
28918 * <file name="app.js">
28919 * angular.module('staticSelect', [])
28920 * .controller('ExampleController', ['$scope', function($scope) {
28922 * singleSelect: null,
28923 * multipleSelect: [],
28924 * option1: 'option-1',
28927 * $scope.forceUnknownOption = function() {
28928 * $scope.data.singleSelect = 'nonsense';
28934 * ### Using `ngRepeat` to generate `select` options
28935 * <example name="ngrepeat-select" module="ngrepeatSelect">
28936 * <file name="index.html">
28937 * <div ng-controller="ExampleController">
28938 * <form name="myForm">
28939 * <label for="repeatSelect"> Repeat select: </label>
28940 * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
28941 * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
28945 * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
28948 * <file name="app.js">
28949 * angular.module('ngrepeatSelect', [])
28950 * .controller('ExampleController', ['$scope', function($scope) {
28952 * repeatSelect: null,
28953 * availableOptions: [
28954 * {id: '1', name: 'Option A'},
28955 * {id: '2', name: 'Option B'},
28956 * {id: '3', name: 'Option C'}
28964 * ### Using `select` with `ngOptions` and setting a default value
28965 * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
28967 * <example name="select-with-default-values" module="defaultValueSelect">
28968 * <file name="index.html">
28969 * <div ng-controller="ExampleController">
28970 * <form name="myForm">
28971 * <label for="mySelect">Make a choice:</label>
28972 * <select name="mySelect" id="mySelect"
28973 * ng-options="option.name for option in data.availableOptions track by option.id"
28974 * ng-model="data.selectedOption"></select>
28977 * <tt>option = {{data.selectedOption}}</tt><br/>
28980 * <file name="app.js">
28981 * angular.module('defaultValueSelect', [])
28982 * .controller('ExampleController', ['$scope', function($scope) {
28984 * availableOptions: [
28985 * {id: '1', name: 'Option A'},
28986 * {id: '2', name: 'Option B'},
28987 * {id: '3', name: 'Option C'}
28989 * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
28996 * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
28998 * <example name="select-with-non-string-options" module="nonStringSelect">
28999 * <file name="index.html">
29000 * <select ng-model="model.id" convert-to-number>
29001 * <option value="0">Zero</option>
29002 * <option value="1">One</option>
29003 * <option value="2">Two</option>
29007 * <file name="app.js">
29008 * angular.module('nonStringSelect', [])
29009 * .run(function($rootScope) {
29010 * $rootScope.model = { id: 2 };
29012 * .directive('convertToNumber', function() {
29014 * require: 'ngModel',
29015 * link: function(scope, element, attrs, ngModel) {
29016 * ngModel.$parsers.push(function(val) {
29017 * return parseInt(val, 10);
29019 * ngModel.$formatters.push(function(val) {
29026 * <file name="protractor.js" type="protractor">
29027 * it('should initialize to model', function() {
29028 * var select = element(by.css('select'));
29029 * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
29035 var selectDirective = function() {
29039 require: ['select', '?ngModel'],
29040 controller: SelectController,
29047 function selectPreLink(scope, element, attr, ctrls) {
29049 // if ngModel is not defined, we don't need to do anything
29050 var ngModelCtrl = ctrls[1];
29051 if (!ngModelCtrl) return;
29053 var selectCtrl = ctrls[0];
29055 selectCtrl.ngModelCtrl = ngModelCtrl;
29057 // We delegate rendering to the `writeValue` method, which can be changed
29058 // if the select can have multiple selected values or if the options are being
29059 // generated by `ngOptions`
29060 ngModelCtrl.$render = function() {
29061 selectCtrl.writeValue(ngModelCtrl.$viewValue);
29064 // When the selected item(s) changes we delegate getting the value of the select control
29065 // to the `readValue` method, which can be changed if the select can have multiple
29066 // selected values or if the options are being generated by `ngOptions`
29067 element.on('change', function() {
29068 scope.$apply(function() {
29069 ngModelCtrl.$setViewValue(selectCtrl.readValue());
29073 // If the select allows multiple values then we need to modify how we read and write
29074 // values from and to the control; also what it means for the value to be empty and
29075 // we have to add an extra watch since ngModel doesn't work well with arrays - it
29076 // doesn't trigger rendering if only an item in the array changes.
29077 if (attr.multiple) {
29079 // Read value now needs to check each option to see if it is selected
29080 selectCtrl.readValue = function readMultipleValue() {
29082 forEach(element.find('option'), function(option) {
29083 if (option.selected) {
29084 array.push(option.value);
29090 // Write value now needs to set the selected property of each matching option
29091 selectCtrl.writeValue = function writeMultipleValue(value) {
29092 var items = new HashMap(value);
29093 forEach(element.find('option'), function(option) {
29094 option.selected = isDefined(items.get(option.value));
29098 // we have to do it on each watch since ngModel watches reference, but
29099 // we need to work of an array, so we need to see if anything was inserted/removed
29100 var lastView, lastViewRef = NaN;
29101 scope.$watch(function selectMultipleWatch() {
29102 if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
29103 lastView = shallowCopy(ngModelCtrl.$viewValue);
29104 ngModelCtrl.$render();
29106 lastViewRef = ngModelCtrl.$viewValue;
29109 // If we are a multiple select then value is now a collection
29110 // so the meaning of $isEmpty changes
29111 ngModelCtrl.$isEmpty = function(value) {
29112 return !value || value.length === 0;
29120 // The option directive is purely designed to communicate the existence (or lack of)
29121 // of dynamically created (and destroyed) option elements to their containing select
29122 // directive via its controller.
29123 var optionDirective = ['$interpolate', function($interpolate) {
29127 compile: function(element, attr) {
29129 if (isDefined(attr.value)) {
29130 // If the value attribute is defined, check if it contains an interpolation
29131 var interpolateValueFn = $interpolate(attr.value, true);
29133 // If the value attribute is not defined then we fall back to the
29134 // text content of the option element, which may be interpolated
29135 var interpolateTextFn = $interpolate(element.text(), true);
29136 if (!interpolateTextFn) {
29137 attr.$set('value', element.text());
29141 return function(scope, element, attr) {
29143 // This is an optimization over using ^^ since we don't want to have to search
29144 // all the way to the root of the DOM for every single option element
29145 var selectCtrlName = '$selectController',
29146 parent = element.parent(),
29147 selectCtrl = parent.data(selectCtrlName) ||
29148 parent.parent().data(selectCtrlName); // in case we are in optgroup
29151 selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
29158 var styleDirective = valueFn({
29163 var requiredDirective = function() {
29166 require: '?ngModel',
29167 link: function(scope, elm, attr, ctrl) {
29169 attr.required = true; // force truthy in case we are on non input element
29171 ctrl.$validators.required = function(modelValue, viewValue) {
29172 return !attr.required || !ctrl.$isEmpty(viewValue);
29175 attr.$observe('required', function() {
29183 var patternDirective = function() {
29186 require: '?ngModel',
29187 link: function(scope, elm, attr, ctrl) {
29190 var regexp, patternExp = attr.ngPattern || attr.pattern;
29191 attr.$observe('pattern', function(regex) {
29192 if (isString(regex) && regex.length > 0) {
29193 regex = new RegExp('^' + regex + '$');
29196 if (regex && !regex.test) {
29197 throw minErr('ngPattern')('noregexp',
29198 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
29199 regex, startingTag(elm));
29202 regexp = regex || undefined;
29206 ctrl.$validators.pattern = function(modelValue, viewValue) {
29207 // HTML5 pattern constraint validates the input value, so we validate the viewValue
29208 return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
29215 var maxlengthDirective = function() {
29218 require: '?ngModel',
29219 link: function(scope, elm, attr, ctrl) {
29222 var maxlength = -1;
29223 attr.$observe('maxlength', function(value) {
29224 var intVal = toInt(value);
29225 maxlength = isNaN(intVal) ? -1 : intVal;
29228 ctrl.$validators.maxlength = function(modelValue, viewValue) {
29229 return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
29235 var minlengthDirective = function() {
29238 require: '?ngModel',
29239 link: function(scope, elm, attr, ctrl) {
29243 attr.$observe('minlength', function(value) {
29244 minlength = toInt(value) || 0;
29247 ctrl.$validators.minlength = function(modelValue, viewValue) {
29248 return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
29254 if (window.angular.bootstrap) {
29255 //AngularJS is already loaded, so we can return here...
29256 console.log('WARNING: Tried to load angular more than once.');
29260 //try to bind to jquery now so that one can write jqLite(document).ready()
29261 //but we will rebind on bootstrap again.
29264 publishExternalAPI(angular);
29266 angular.module("ngLocale", [], ["$provide", function($provide) {
29267 var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
29268 function getDecimals(n) {
29270 var i = n.indexOf('.');
29271 return (i == -1) ? 0 : n.length - i - 1;
29274 function getVF(n, opt_precision) {
29275 var v = opt_precision;
29277 if (undefined === v) {
29278 v = Math.min(getDecimals(n), 3);
29281 var base = Math.pow(10, v);
29282 var f = ((n * base) | 0) % base;
29283 return {v: v, f: f};
29286 $provide.value("$locale", {
29287 "DATETIME_FORMATS": {
29309 "FIRSTDAYOFWEEK": 6,
29351 "fullDate": "EEEE, MMMM d, y",
29352 "longDate": "MMMM d, y",
29353 "medium": "MMM d, y h:mm:ss a",
29354 "mediumDate": "MMM d, y",
29355 "mediumTime": "h:mm:ss a",
29356 "short": "M/d/yy h:mm a",
29357 "shortDate": "M/d/yy",
29358 "shortTime": "h:mm a"
29360 "NUMBER_FORMATS": {
29361 "CURRENCY_SYM": "$",
29362 "DECIMAL_SEP": ".",
29382 "negPre": "-\u00a4",
29384 "posPre": "\u00a4",
29390 "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
29394 jqLite(document).ready(function() {
29395 angularInit(document, bootstrap);
29398 })(window, document);
29400 !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');