2 * @license AngularJS v1.0.2
3 * (c) 2010-2012 Google, Inc. http://angularjs.org
6 (function(window, document, undefined) {
9 ////////////////////////////////////
13 * @name angular.lowercase
16 * @description Converts the specified string to lowercase.
17 * @param {string} string String to be converted to lowercase.
18 * @returns {string} Lowercased string.
20 var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
25 * @name angular.uppercase
28 * @description Converts the specified string to uppercase.
29 * @param {string} string String to be converted to uppercase.
30 * @returns {string} Uppercased string.
32 var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
35 var manualLowercase = function(s) {
37 ? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);})
40 var manualUppercase = function(s) {
42 ? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);})
47 // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
48 // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
49 // with correct but slower alternatives.
50 if ('i' !== 'I'.toLowerCase()) {
51 lowercase = manualLowercase;
52 uppercase = manualUppercase;
55 function fromCharCode(code) {return String.fromCharCode(code);}
58 var Error = window.Error,
59 /** holds major version number for IE or NaN for real browsers */
60 msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
61 jqLite, // delay binding since jQuery could be loaded after us.
62 jQuery, // delay binding
65 toString = Object.prototype.toString,
68 angular = window.angular || (window.angular = {}),
71 uid = ['0', '0', '0'];
75 * @name angular.forEach
79 * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
80 * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
81 * is the value of an object property or an array element and `key` is the object property key or
82 * array element index. Specifying a `context` for the function is optional.
84 * Note: this function was previously known as `angular.foreach`.
87 var values = {name: 'misko', gender: 'male'};
89 angular.forEach(values, function(value, key){
90 this.push(key + ': ' + value);
92 expect(log).toEqual(['name: misko', 'gender:male']);
95 * @param {Object|Array} obj Object to iterate over.
96 * @param {Function} iterator Iterator function.
97 * @param {Object=} context Object to become context (`this`) for the iterator function.
98 * @returns {Object|Array} Reference to `obj`.
100 function forEach(obj, iterator, context) {
103 if (isFunction(obj)){
105 if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
106 iterator.call(context, obj[key], key);
109 } else if (obj.forEach && obj.forEach !== forEach) {
110 obj.forEach(iterator, context);
111 } else if (isObject(obj) && isNumber(obj.length)) {
112 for (key = 0; key < obj.length; key++)
113 iterator.call(context, obj[key], key);
116 if (obj.hasOwnProperty(key)) {
117 iterator.call(context, obj[key], key);
125 function sortedKeys(obj) {
127 for (var key in obj) {
128 if (obj.hasOwnProperty(key)) {
135 function forEachSorted(obj, iterator, context) {
136 var keys = sortedKeys(obj);
137 for ( var i = 0; i < keys.length; i++) {
138 iterator.call(context, obj[keys[i]], keys[i]);
145 * when using forEach the params are value, key, but it is often useful to have key, value.
146 * @param {function(string, *)} iteratorFn
147 * @returns {function(*, string)}
149 function reverseParams(iteratorFn) {
150 return function(value, key) { iteratorFn(key, value) };
154 * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
155 * characters such as '012ABC'. The reason why we are not using simply a number counter is that
156 * the number string gets longer over time, and it can also overflow, where as the the nextId
157 * will grow much slower, it is a string, and it will never overflow.
159 * @returns an unique alpha-numeric string
162 var index = uid.length;
167 digit = uid[index].charCodeAt(0);
168 if (digit == 57 /*'9'*/) {
172 if (digit == 90 /*'Z'*/) {
175 uid[index] = String.fromCharCode(digit + 1);
185 * @name angular.extend
189 * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
190 * to `dst`. You can specify multiple `src` objects.
192 * @param {Object} dst Destination object.
193 * @param {...Object} src Source object(s).
195 function extend(dst) {
196 forEach(arguments, function(obj){
198 forEach(obj, function(value, key){
207 return parseInt(str, 10);
211 function inherit(parent, extra) {
212 return extend(new (extend(function() {}, {prototype:parent}))(), extra);
222 * A function that performs no operations. This function can be useful when writing code in the
225 function foo(callback) {
226 var result = calculateResult();
227 (callback || angular.noop)(result);
237 * @name angular.identity
241 * A function that returns its first argument. This function is useful when writing code in the
245 function transformer(transformationFn, value) {
246 return (transformationFn || identity)(value);
250 function identity($) {return $;}
251 identity.$inject = [];
254 function valueFn(value) {return function() {return value;};}
258 * @name angular.isUndefined
262 * Determines if a reference is undefined.
264 * @param {*} value Reference to check.
265 * @returns {boolean} True if `value` is undefined.
267 function isUndefined(value){return typeof value == 'undefined';}
272 * @name angular.isDefined
276 * Determines if a reference is defined.
278 * @param {*} value Reference to check.
279 * @returns {boolean} True if `value` is defined.
281 function isDefined(value){return typeof value != 'undefined';}
286 * @name angular.isObject
290 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
291 * considered to be objects.
293 * @param {*} value Reference to check.
294 * @returns {boolean} True if `value` is an `Object` but not `null`.
296 function isObject(value){return value != null && typeof value == 'object';}
301 * @name angular.isString
305 * Determines if a reference is a `String`.
307 * @param {*} value Reference to check.
308 * @returns {boolean} True if `value` is a `String`.
310 function isString(value){return typeof value == 'string';}
315 * @name angular.isNumber
319 * Determines if a reference is a `Number`.
321 * @param {*} value Reference to check.
322 * @returns {boolean} True if `value` is a `Number`.
324 function isNumber(value){return typeof value == 'number';}
329 * @name angular.isDate
333 * Determines if a value is a date.
335 * @param {*} value Reference to check.
336 * @returns {boolean} True if `value` is a `Date`.
338 function isDate(value){
339 return toString.apply(value) == '[object Date]';
345 * @name angular.isArray
349 * Determines if a reference is an `Array`.
351 * @param {*} value Reference to check.
352 * @returns {boolean} True if `value` is an `Array`.
354 function isArray(value) {
355 return toString.apply(value) == '[object Array]';
361 * @name angular.isFunction
365 * Determines if a reference is a `Function`.
367 * @param {*} value Reference to check.
368 * @returns {boolean} True if `value` is a `Function`.
370 function isFunction(value){return typeof value == 'function';}
374 * Checks if `obj` is a window object.
377 * @param {*} obj Object to check
378 * @returns {boolean} True if `obj` is a window obj.
380 function isWindow(obj) {
381 return obj && obj.document && obj.location && obj.alert && obj.setInterval;
385 function isScope(obj) {
386 return obj && obj.$evalAsync && obj.$watch;
390 function isFile(obj) {
391 return toString.apply(obj) === '[object File]';
395 function isBoolean(value) {
396 return typeof value == 'boolean';
400 function trim(value) {
401 return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
406 * @name angular.isElement
410 * Determines if a reference is a DOM element (or wrapped jQuery element).
412 * @param {*} value Reference to check.
413 * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
415 function isElement(node) {
417 (node.nodeName // we are a direct element
418 || (node.bind && node.find)); // we have a bind and find method part of jQuery API
422 * @param str 'key1,key2,...'
423 * @returns {object} in the form of {key1:true, key2:true, ...}
425 function makeMap(str){
426 var obj = {}, items = str.split(","), i;
427 for ( i = 0; i < items.length; i++ )
428 obj[ items[i] ] = true;
434 nodeName_ = function(element) {
435 element = element.nodeName ? element : element[0];
436 return (element.scopeName && element.scopeName != 'HTML')
437 ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
440 nodeName_ = function(element) {
441 return element.nodeName ? element.nodeName : element[0].nodeName;
446 function map(obj, iterator, context) {
448 forEach(obj, function(value, index, list) {
449 results.push(iterator.call(context, value, index, list));
457 * Determines the number of elements in an array, the number of properties an object has, or
458 * the length of a string.
460 * Note: This function is used to augment the Object type in Angular expressions. See
461 * {@link angular.Object} for more information about Angular arrays.
463 * @param {Object|Array|string} obj Object, array, or string to inspect.
464 * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
465 * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
467 function size(obj, ownPropsOnly) {
470 if (isArray(obj) || isString(obj)) {
472 } else if (isObject(obj)){
474 if (!ownPropsOnly || obj.hasOwnProperty(key))
482 function includes(array, obj) {
483 return indexOf(array, obj) != -1;
486 function indexOf(array, obj) {
487 if (array.indexOf) return array.indexOf(obj);
489 for ( var i = 0; i < array.length; i++) {
490 if (obj === array[i]) return i;
495 function arrayRemove(array, value) {
496 var index = indexOf(array, value);
498 array.splice(index, 1);
502 function isLeafNode (node) {
504 switch (node.nodeName) {
520 * Creates a deep copy of `source`, which should be an object or an array.
522 * * If no destination is supplied, a copy of the object or array is created.
523 * * If a destination is provided, all of its elements (for array) or properties (for objects)
524 * are deleted and then all elements/properties from the source are copied to it.
525 * * If `source` is not an object or array, `source` is returned.
527 * Note: this function is used to augment the Object type in Angular expressions. See
528 * {@link ng.$filter} for more information about Angular arrays.
530 * @param {*} source The source that will be used to make a copy.
531 * Can be any type, including primitives, `null`, and `undefined`.
532 * @param {(Object|Array)=} destination Destination into which the source is copied. If
533 * provided, must be of the same type as `source`.
534 * @returns {*} The copy or updated `destination`, if `destination` was specified.
536 function copy(source, destination){
537 if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
539 destination = source;
541 if (isArray(source)) {
542 destination = copy(source, []);
543 } else if (isDate(source)) {
544 destination = new Date(source.getTime());
545 } else if (isObject(source)) {
546 destination = copy(source, {});
550 if (source === destination) throw Error("Can't copy equivalent objects or arrays");
551 if (isArray(source)) {
552 while(destination.length) {
555 for ( var i = 0; i < source.length; i++) {
556 destination.push(copy(source[i]));
559 forEach(destination, function(value, key){
560 delete destination[key];
562 for ( var key in source) {
563 destination[key] = copy(source[key]);
571 * Create a shallow copy of an object
573 function shallowCopy(src, dst) {
576 for(var key in src) {
577 if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
588 * @name angular.equals
592 * Determines if two objects or two values are equivalent. Supports value types, arrays and
595 * Two objects or values are considered equivalent if at least one of the following is true:
597 * * Both objects or values pass `===` comparison.
598 * * Both objects or values are of the same type and all of their properties pass `===` comparison.
599 * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
601 * During a property comparision, properties of `function` type and properties with names
602 * that begin with `$` are ignored.
604 * Scope and DOMWindow objects are being compared only be identify (`===`).
606 * @param {*} o1 Object or value to compare.
607 * @param {*} o2 Object or value to compare.
608 * @returns {boolean} True if arguments are equal.
610 function equals(o1, o2) {
611 if (o1 === o2) return true;
612 if (o1 === null || o2 === null) return false;
613 if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
614 var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
616 if (t1 == 'object') {
618 if ((length = o1.length) == o2.length) {
619 for(key=0; key<length; key++) {
620 if (!equals(o1[key], o2[key])) return false;
624 } else if (isDate(o1)) {
625 return isDate(o2) && o1.getTime() == o2.getTime();
627 if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
630 if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) {
636 if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false;
646 function concat(array1, array2, index) {
647 return array1.concat(slice.call(array2, index));
650 function sliceArgs(args, startIndex) {
651 return slice.call(args, startIndex || 0);
661 * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
662 * `fn`). You can supply optional `args` that are are prebound to the function. This feature is also
663 * known as [function currying](http://en.wikipedia.org/wiki/Currying).
665 * @param {Object} self Context which `fn` should be evaluated in.
666 * @param {function()} fn Function to be bound.
667 * @param {...*} args Optional arguments to be prebound to the `fn` function call.
668 * @returns {function()} Function that wraps the `fn` with all the specified bindings.
670 function bind(self, fn) {
671 var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
672 if (isFunction(fn) && !(fn instanceof RegExp)) {
673 return curryArgs.length
675 return arguments.length
676 ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
677 : fn.apply(self, curryArgs);
680 return arguments.length
681 ? fn.apply(self, arguments)
685 // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
691 function toJsonReplacer(key, value) {
694 if (/^\$+/.test(key)) {
696 } else if (isWindow(value)) {
698 } else if (value && document === value) {
700 } else if (isScope(value)) {
710 * @name angular.toJson
714 * Serializes input into a JSON-formatted string.
716 * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
717 * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
718 * @returns {string} Jsonified string representing `obj`.
720 function toJson(obj, pretty) {
721 return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
727 * @name angular.fromJson
731 * Deserializes a JSON string.
733 * @param {string} json JSON string to deserialize.
734 * @returns {Object|Array|Date|string|number} Deserialized thingy.
736 function fromJson(json) {
737 return isString(json)
743 function toBoolean(value) {
744 if (value && value.length !== 0) {
745 var v = lowercase("" + value);
746 value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
754 * @returns {string} Returns the string representation of the element.
756 function startingTag(element) {
757 element = jqLite(element).clone();
759 // turns out IE does not let you set .html() on elements which
760 // are not allowed to have children. So we just ignore it.
763 return jqLite('<div>').append(element).html().
764 match(/^(<[^>]+>)/)[1].
765 replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
769 /////////////////////////////////////////////////
772 * Parses an escaped url query string into key-value pairs.
773 * @returns Object.<(string|boolean)>
775 function parseKeyValue(/**string*/keyValue) {
776 var obj = {}, key_value, key;
777 forEach((keyValue || "").split('&'), function(keyValue){
779 key_value = keyValue.split('=');
780 key = decodeURIComponent(key_value[0]);
781 obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
787 function toKeyValue(obj) {
789 forEach(obj, function(value, key) {
790 parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
792 return parts.length ? parts.join('&') : '';
797 * We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
798 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
801 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
802 * pct-encoded = "%" HEXDIG HEXDIG
803 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
804 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
805 * / "*" / "+" / "," / ";" / "="
807 function encodeUriSegment(val) {
808 return encodeUriQuery(val, true).
809 replace(/%26/gi, '&').
810 replace(/%3D/gi, '=').
811 replace(/%2B/gi, '+');
816 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
817 * method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
818 * encoded per http://tools.ietf.org/html/rfc3986:
819 * query = *( pchar / "/" / "?" )
820 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
821 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
822 * pct-encoded = "%" HEXDIG HEXDIG
823 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
824 * / "*" / "+" / "," / ";" / "="
826 function encodeUriQuery(val, pctEncodeSpaces) {
827 return encodeURIComponent(val).
828 replace(/%40/gi, '@').
829 replace(/%3A/gi, ':').
830 replace(/%24/g, '$').
831 replace(/%2C/gi, ',').
832 replace((pctEncodeSpaces ? null : /%20/g), '+');
838 * @name ng.directive:ngApp
841 * @param {angular.Module} ngApp on optional application
842 * {@link angular.module module} name to load.
846 * Use this directive to auto-bootstrap on application. Only
847 * one directive can be used per HTML document. The directive
848 * designates the root of the application and is typically placed
849 * ot the root of the page.
851 * In the example below if the `ngApp` directive would not be placed
852 * on the `html` element then the document would not be compiled
853 * and the `{{ 1+2 }}` would not be resolved to `3`.
855 * `ngApp` is the easiest way to bootstrap an application.
859 I can add: 1 + 2 = {{ 1+2 }}
864 function angularInit(element, bootstrap) {
865 var elements = [element],
868 names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
869 NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
871 function append(element) {
872 element && elements.push(element);
875 forEach(names, function(name) {
877 append(document.getElementById(name));
878 name = name.replace(':', '\\:');
879 if (element.querySelectorAll) {
880 forEach(element.querySelectorAll('.' + name), append);
881 forEach(element.querySelectorAll('.' + name + '\\:'), append);
882 forEach(element.querySelectorAll('[' + name + ']'), append);
886 forEach(elements, function(element) {
888 var className = ' ' + element.className + ' ';
889 var match = NG_APP_CLASS_REGEXP.exec(className);
891 appElement = element;
892 module = (match[2] || '').replace(/\s+/g, ',');
894 forEach(element.attributes, function(attr) {
895 if (!appElement && names[attr.name]) {
896 appElement = element;
904 bootstrap(appElement, module ? [module] : []);
910 * @name angular.bootstrap
912 * Use this function to manually start up angular application.
914 * See: {@link guide/bootstrap Bootstrap}
916 * @param {Element} element DOM element which is the root of angular application.
917 * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
918 * @returns {AUTO.$injector} Returns the newly created injector for this app.
920 function bootstrap(element, modules) {
921 element = jqLite(element);
922 modules = modules || [];
923 modules.unshift(['$provide', function($provide) {
924 $provide.value('$rootElement', element);
926 modules.unshift('ng');
927 var injector = createInjector(modules);
929 ['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){
930 scope.$apply(function() {
931 element.data('$injector', injector);
932 compile(element)(scope);
939 var SNAKE_CASE_REGEXP = /[A-Z]/g;
940 function snake_case(name, separator){
941 separator = separator || '_';
942 return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
943 return (pos ? separator : '') + letter.toLowerCase();
947 function bindJQuery() {
948 // bind to jQuery if present;
949 jQuery = window.jQuery;
950 // reset to jQuery or default to us.
954 scope: JQLitePrototype.scope,
955 controller: JQLitePrototype.controller,
956 injector: JQLitePrototype.injector,
957 inheritedData: JQLitePrototype.inheritedData
959 JQLitePatchJQueryRemove('remove', true);
960 JQLitePatchJQueryRemove('empty');
961 JQLitePatchJQueryRemove('html');
965 angular.element = jqLite;
969 * throw error of the argument is falsy.
971 function assertArg(arg, name, reason) {
973 throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
978 function assertArgFn(arg, name, acceptArrayAnnotation) {
979 if (acceptArrayAnnotation && isArray(arg)) {
980 arg = arg[arg.length - 1];
983 assertArg(isFunction(arg), name, 'not a function, got ' +
984 (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
990 * @name angular.Module
993 * Interface for configuring angular {@link angular.module modules}.
996 function setupModuleLoader(window) {
998 function ensure(obj, name, factory) {
999 return obj[name] || (obj[name] = factory());
1002 return ensure(ensure(window, 'angular', Object), 'module', function() {
1003 /** @type {Object.<string, angular.Module>} */
1008 * @name angular.module
1011 * The `angular.module` is a global place for creating and registering Angular modules. All
1012 * modules (angular core or 3rd party) that should be available to an application must be
1013 * registered using this mechanism.
1018 * A module is a collocation of services, directives, filters, and configure information. Module
1019 * is used to configure the {@link AUTO.$injector $injector}.
1022 * // Create a new module
1023 * var myModule = angular.module('myModule', []);
1025 * // register a new service
1026 * myModule.value('appName', 'MyCoolApp');
1028 * // configure existing services inside initialization blocks.
1029 * myModule.config(function($locationProvider) {
1030 * // Configure existing providers
1031 * $locationProvider.hashPrefix('!');
1035 * Then you can create an injector and load your modules like this:
1038 * var injector = angular.injector(['ng', 'MyModule'])
1041 * However it's more likely that you'll just use
1042 * {@link ng.directive:ngApp ngApp} or
1043 * {@link angular.bootstrap} to simplify this process for you.
1045 * @param {!string} name The name of the module to create or retrieve.
1046 * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
1047 * the module is being retrieved for further configuration.
1048 * @param {Function} configFn Option configuration function for the module. Same as
1049 * {@link angular.Module#config Module#config()}.
1050 * @returns {module} new module with the {@link angular.Module} api.
1052 return function module(name, requires, configFn) {
1053 if (requires && modules.hasOwnProperty(name)) {
1054 modules[name] = null;
1056 return ensure(modules, name, function() {
1058 throw Error('No module: ' + name);
1061 /** @type {!Array.<Array.<*>>} */
1062 var invokeQueue = [];
1064 /** @type {!Array.<Function>} */
1067 var config = invokeLater('$injector', 'invoke');
1069 /** @type {angular.Module} */
1070 var moduleInstance = {
1072 _invokeQueue: invokeQueue,
1073 _runBlocks: runBlocks,
1077 * @name angular.Module#requires
1078 * @propertyOf angular.Module
1079 * @returns {Array.<string>} List of module names which must be loaded before this module.
1081 * Holds the list of modules which the injector will load before the current module is loaded.
1087 * @name angular.Module#name
1088 * @propertyOf angular.Module
1089 * @returns {string} Name of the module.
1097 * @name angular.Module#provider
1098 * @methodOf angular.Module
1099 * @param {string} name service name
1100 * @param {Function} providerType Construction function for creating new instance of the service.
1102 * See {@link AUTO.$provide#provider $provide.provider()}.
1104 provider: invokeLater('$provide', 'provider'),
1108 * @name angular.Module#factory
1109 * @methodOf angular.Module
1110 * @param {string} name service name
1111 * @param {Function} providerFunction Function for creating new instance of the service.
1113 * See {@link AUTO.$provide#factory $provide.factory()}.
1115 factory: invokeLater('$provide', 'factory'),
1119 * @name angular.Module#service
1120 * @methodOf angular.Module
1121 * @param {string} name service name
1122 * @param {Function} constructor A constructor function that will be instantiated.
1124 * See {@link AUTO.$provide#service $provide.service()}.
1126 service: invokeLater('$provide', 'service'),
1130 * @name angular.Module#value
1131 * @methodOf angular.Module
1132 * @param {string} name service name
1133 * @param {*} object Service instance object.
1135 * See {@link AUTO.$provide#value $provide.value()}.
1137 value: invokeLater('$provide', 'value'),
1141 * @name angular.Module#constant
1142 * @methodOf angular.Module
1143 * @param {string} name constant name
1144 * @param {*} object Constant value.
1146 * Because the constant are fixed, they get applied before other provide methods.
1147 * See {@link AUTO.$provide#constant $provide.constant()}.
1149 constant: invokeLater('$provide', 'constant', 'unshift'),
1153 * @name angular.Module#filter
1154 * @methodOf angular.Module
1155 * @param {string} name Filter name.
1156 * @param {Function} filterFactory Factory function for creating new instance of filter.
1158 * See {@link ng.$filterProvider#register $filterProvider.register()}.
1160 filter: invokeLater('$filterProvider', 'register'),
1164 * @name angular.Module#controller
1165 * @methodOf angular.Module
1166 * @param {string} name Controller name.
1167 * @param {Function} constructor Controller constructor function.
1169 * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
1171 controller: invokeLater('$controllerProvider', 'register'),
1175 * @name angular.Module#directive
1176 * @methodOf angular.Module
1177 * @param {string} name directive name
1178 * @param {Function} directiveFactory Factory function for creating new instance of
1181 * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
1183 directive: invokeLater('$compileProvider', 'directive'),
1187 * @name angular.Module#config
1188 * @methodOf angular.Module
1189 * @param {Function} configFn Execute this function on module load. Useful for service
1192 * Use this method to register work which needs to be performed on module loading.
1198 * @name angular.Module#run
1199 * @methodOf angular.Module
1200 * @param {Function} initializationFn Execute this function after injector creation.
1201 * Useful for application initialization.
1203 * Use this method to register work which needs to be performed when the injector with
1204 * with the current module is finished loading.
1206 run: function(block) {
1207 runBlocks.push(block);
1216 return moduleInstance;
1219 * @param {string} provider
1220 * @param {string} method
1221 * @param {String=} insertMethod
1222 * @returns {angular.Module}
1224 function invokeLater(provider, method, insertMethod) {
1226 invokeQueue[insertMethod || 'push']([provider, method, arguments]);
1227 return moduleInstance;
1238 * @name angular.version
1240 * An object that contains information about the current AngularJS version. This object has the
1241 * following properties:
1243 * - `full` – `{string}` – Full version string, such as "0.9.18".
1244 * - `major` – `{number}` – Major version number, such as "0".
1245 * - `minor` – `{number}` – Minor version number, such as "9".
1246 * - `dot` – `{number}` – Dot version number, such as "18".
1247 * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
1250 full: '1.0.2', // all of these placeholder strings will be replaced by rake's
1251 major: 1, // compile task
1254 codeName: 'debilitating-awesomeness'
1258 function publishExternalAPI(angular){
1260 'bootstrap': bootstrap,
1266 'injector': createInjector,
1270 'fromJson': fromJson,
1271 'identity':identity,
1272 'isUndefined': isUndefined,
1273 'isDefined': isDefined,
1274 'isString': isString,
1275 'isFunction': isFunction,
1276 'isObject': isObject,
1277 'isNumber': isNumber,
1278 'isElement': isElement,
1282 'lowercase': lowercase,
1283 'uppercase': uppercase,
1284 'callbacks': {counter: 0}
1287 angularModule = setupModuleLoader(window);
1289 angularModule('ngLocale');
1291 angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
1294 angularModule('ng', ['ngLocale'], ['$provide',
1295 function ngModule($provide) {
1296 $provide.provider('$compile', $CompileProvider).
1298 a: htmlAnchorDirective,
1299 input: inputDirective,
1300 textarea: inputDirective,
1301 form: formDirective,
1302 script: scriptDirective,
1303 select: selectDirective,
1304 style: styleDirective,
1305 option: optionDirective,
1306 ngBind: ngBindDirective,
1307 ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
1308 ngBindTemplate: ngBindTemplateDirective,
1309 ngClass: ngClassDirective,
1310 ngClassEven: ngClassEvenDirective,
1311 ngClassOdd: ngClassOddDirective,
1312 ngCsp: ngCspDirective,
1313 ngCloak: ngCloakDirective,
1314 ngController: ngControllerDirective,
1315 ngForm: ngFormDirective,
1316 ngHide: ngHideDirective,
1317 ngInclude: ngIncludeDirective,
1318 ngInit: ngInitDirective,
1319 ngNonBindable: ngNonBindableDirective,
1320 ngPluralize: ngPluralizeDirective,
1321 ngRepeat: ngRepeatDirective,
1322 ngShow: ngShowDirective,
1323 ngSubmit: ngSubmitDirective,
1324 ngStyle: ngStyleDirective,
1325 ngSwitch: ngSwitchDirective,
1326 ngSwitchWhen: ngSwitchWhenDirective,
1327 ngSwitchDefault: ngSwitchDefaultDirective,
1328 ngOptions: ngOptionsDirective,
1329 ngView: ngViewDirective,
1330 ngTransclude: ngTranscludeDirective,
1331 ngModel: ngModelDirective,
1332 ngList: ngListDirective,
1333 ngChange: ngChangeDirective,
1334 required: requiredDirective,
1335 ngRequired: requiredDirective,
1336 ngValue: ngValueDirective
1338 directive(ngAttributeAliasDirectives).
1339 directive(ngEventDirectives);
1341 $anchorScroll: $AnchorScrollProvider,
1342 $browser: $BrowserProvider,
1343 $cacheFactory: $CacheFactoryProvider,
1344 $controller: $ControllerProvider,
1345 $document: $DocumentProvider,
1346 $exceptionHandler: $ExceptionHandlerProvider,
1347 $filter: $FilterProvider,
1348 $interpolate: $InterpolateProvider,
1349 $http: $HttpProvider,
1350 $httpBackend: $HttpBackendProvider,
1351 $location: $LocationProvider,
1353 $parse: $ParseProvider,
1354 $route: $RouteProvider,
1355 $routeParams: $RouteParamsProvider,
1356 $rootScope: $RootScopeProvider,
1358 $sniffer: $SnifferProvider,
1359 $templateCache: $TemplateCacheProvider,
1360 $timeout: $TimeoutProvider,
1361 $window: $WindowProvider
1367 //////////////////////////////////
1369 //////////////////////////////////
1373 * @name angular.element
1377 * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
1378 * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
1379 * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
1380 * implementation (commonly referred to as jqLite).
1382 * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
1385 * jqLite is a tiny, API-compatible subset of jQuery that allows
1386 * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
1387 * within a very small footprint, so only a subset of the jQuery API - methods, arguments and
1388 * invocation styles - are supported.
1390 * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
1391 * raw DOM references.
1393 * ## Angular's jQuery lite provides the following methods:
1395 * - [addClass()](http://api.jquery.com/addClass/)
1396 * - [after()](http://api.jquery.com/after/)
1397 * - [append()](http://api.jquery.com/append/)
1398 * - [attr()](http://api.jquery.com/attr/)
1399 * - [bind()](http://api.jquery.com/bind/)
1400 * - [children()](http://api.jquery.com/children/)
1401 * - [clone()](http://api.jquery.com/clone/)
1402 * - [contents()](http://api.jquery.com/contents/)
1403 * - [css()](http://api.jquery.com/css/)
1404 * - [data()](http://api.jquery.com/data/)
1405 * - [eq()](http://api.jquery.com/eq/)
1406 * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name.
1407 * - [hasClass()](http://api.jquery.com/hasClass/)
1408 * - [html()](http://api.jquery.com/html/)
1409 * - [next()](http://api.jquery.com/next/)
1410 * - [parent()](http://api.jquery.com/parent/)
1411 * - [prepend()](http://api.jquery.com/prepend/)
1412 * - [prop()](http://api.jquery.com/prop/)
1413 * - [ready()](http://api.jquery.com/ready/)
1414 * - [remove()](http://api.jquery.com/remove/)
1415 * - [removeAttr()](http://api.jquery.com/removeAttr/)
1416 * - [removeClass()](http://api.jquery.com/removeClass/)
1417 * - [removeData()](http://api.jquery.com/removeData/)
1418 * - [replaceWith()](http://api.jquery.com/replaceWith/)
1419 * - [text()](http://api.jquery.com/text/)
1420 * - [toggleClass()](http://api.jquery.com/toggleClass/)
1421 * - [unbind()](http://api.jquery.com/unbind/)
1422 * - [val()](http://api.jquery.com/val/)
1423 * - [wrap()](http://api.jquery.com/wrap/)
1425 * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite:
1427 * - `controller(name)` - retrieves the controller of the current element or its parent. By default
1428 * retrieves controller associated with the `ngController` directive. If `name` is provided as
1429 * camelCase directive name, then the controller for this directive will be retrieved (e.g.
1431 * - `injector()` - retrieves the injector of the current element or its parent.
1432 * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
1433 * element or its parent.
1434 * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
1435 * parent element is reached.
1437 * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
1438 * @returns {Object} jQuery object.
1441 var jqCache = JQLite.cache = {},
1442 jqName = JQLite.expando = 'ng-' + new Date().getTime(),
1444 addEventListenerFn = (window.document.addEventListener
1445 ? function(element, type, fn) {element.addEventListener(type, fn, false);}
1446 : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
1447 removeEventListenerFn = (window.document.removeEventListener
1448 ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
1449 : function(element, type, fn) {element.detachEvent('on' + type, fn); });
1451 function jqNextId() { return ++jqId; }
1454 var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
1455 var MOZ_HACK_REGEXP = /^moz([A-Z])/;
1458 * Converts snake_case to camelCase.
1459 * Also there is special case for Moz prefix starting with upper case letter.
1460 * @param name Name to normalize
1462 function camelCase(name) {
1464 replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
1465 return offset ? letter.toUpperCase() : letter;
1467 replace(MOZ_HACK_REGEXP, 'Moz$1');
1470 /////////////////////////////////////////////
1471 // jQuery mutation patch
1473 // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
1474 // $destroy event on all DOM nodes being removed.
1476 /////////////////////////////////////////////
1478 function JQLitePatchJQueryRemove(name, dispatchThis) {
1479 var originalJqFn = jQuery.fn[name];
1480 originalJqFn = originalJqFn.$original || originalJqFn;
1481 removePatch.$original = originalJqFn;
1482 jQuery.fn[name] = removePatch;
1484 function removePatch() {
1486 fireEvent = dispatchThis,
1487 set, setIndex, setLength,
1488 element, childIndex, childLength, children,
1491 while(list.length) {
1493 for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
1494 element = jqLite(set[setIndex]);
1496 events = element.data('events');
1497 if ( (fns = events && events.$destroy) ) {
1498 forEach(fns, function(fn){
1503 fireEvent = !fireEvent;
1505 for(childIndex = 0, childLength = (children = element.children()).length;
1506 childIndex < childLength;
1508 list.push(jQuery(children[childIndex]));
1512 return originalJqFn.apply(this, arguments);
1516 /////////////////////////////////////////////
1517 function JQLite(element) {
1518 if (element instanceof JQLite) {
1521 if (!(this instanceof JQLite)) {
1522 if (isString(element) && element.charAt(0) != '<') {
1523 throw Error('selectors not implemented');
1525 return new JQLite(element);
1528 if (isString(element)) {
1529 var div = document.createElement('div');
1530 // Read about the NoScope elements here:
1531 // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
1532 div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
1533 div.removeChild(div.firstChild); // remove the superfluous div
1534 JQLiteAddNodes(this, div.childNodes);
1535 this.remove(); // detach the elements from the temporary DOM div.
1537 JQLiteAddNodes(this, element);
1541 function JQLiteClone(element) {
1542 return element.cloneNode(true);
1545 function JQLiteDealoc(element){
1546 JQLiteRemoveData(element);
1547 for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
1548 JQLiteDealoc(children[i]);
1552 function JQLiteUnbind(element, type, fn) {
1553 var events = JQLiteExpandoStore(element, 'events'),
1554 handle = JQLiteExpandoStore(element, 'handle');
1556 if (!handle) return; //no listeners registered
1558 if (isUndefined(type)) {
1559 forEach(events, function(eventHandler, type) {
1560 removeEventListenerFn(element, type, eventHandler);
1561 delete events[type];
1564 if (isUndefined(fn)) {
1565 removeEventListenerFn(element, type, events[type]);
1566 delete events[type];
1568 arrayRemove(events[type], fn);
1573 function JQLiteRemoveData(element) {
1574 var expandoId = element[jqName],
1575 expandoStore = jqCache[expandoId];
1578 if (expandoStore.handle) {
1579 expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
1580 JQLiteUnbind(element);
1582 delete jqCache[expandoId];
1583 element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
1587 function JQLiteExpandoStore(element, key, value) {
1588 var expandoId = element[jqName],
1589 expandoStore = jqCache[expandoId || -1];
1591 if (isDefined(value)) {
1592 if (!expandoStore) {
1593 element[jqName] = expandoId = jqNextId();
1594 expandoStore = jqCache[expandoId] = {};
1596 expandoStore[key] = value;
1598 return expandoStore && expandoStore[key];
1602 function JQLiteData(element, key, value) {
1603 var data = JQLiteExpandoStore(element, 'data'),
1604 isSetter = isDefined(value),
1605 keyDefined = !isSetter && isDefined(key),
1606 isSimpleGetter = keyDefined && !isObject(key);
1608 if (!data && !isSimpleGetter) {
1609 JQLiteExpandoStore(element, 'data', data = {});
1616 if (isSimpleGetter) {
1617 // don't create data in this case.
1618 return data && data[key];
1628 function JQLiteHasClass(element, selector) {
1629 return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
1630 indexOf( " " + selector + " " ) > -1);
1633 function JQLiteRemoveClass(element, selector) {
1635 forEach(selector.split(' '), function(cssClass) {
1636 element.className = trim(
1637 (" " + element.className + " ")
1638 .replace(/[\n\t]/g, " ")
1639 .replace(" " + trim(cssClass) + " ", " ")
1645 function JQLiteAddClass(element, selector) {
1647 forEach(selector.split(' '), function(cssClass) {
1648 if (!JQLiteHasClass(element, cssClass)) {
1649 element.className = trim(element.className + ' ' + trim(cssClass));
1655 function JQLiteAddNodes(root, elements) {
1657 elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
1660 for(var i=0; i < elements.length; i++) {
1661 root.push(elements[i]);
1666 function JQLiteController(element, name) {
1667 return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
1670 function JQLiteInheritedData(element, name, value) {
1671 element = jqLite(element);
1673 // if element is the document object work with the html element instead
1674 // this makes $(document).scope() possible
1675 if(element[0].nodeType == 9) {
1676 element = element.find('html');
1679 while (element.length) {
1680 if (value = element.data(name)) return value;
1681 element = element.parent();
1685 //////////////////////////////////////////
1686 // Functions which are declared directly.
1687 //////////////////////////////////////////
1688 var JQLitePrototype = JQLite.prototype = {
1689 ready: function(fn) {
1692 function trigger() {
1698 this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
1699 // we can not use jqLite since we are not done loading and jQuery could be loaded later.
1700 JQLite(window).bind('load', trigger); // fallback to window.onload for others
1702 toString: function() {
1704 forEach(this, function(e){ value.push('' + e);});
1705 return '[' + value.join(', ') + ']';
1708 eq: function(index) {
1709 return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
1718 //////////////////////////////////////////
1719 // Functions iterating getter/setters.
1720 // these functions return self on setter and
1722 //////////////////////////////////////////
1723 var BOOLEAN_ATTR = {};
1724 forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) {
1725 BOOLEAN_ATTR[lowercase(value)] = value;
1727 var BOOLEAN_ELEMENTS = {};
1728 forEach('input,select,option,textarea,button,form'.split(','), function(value) {
1729 BOOLEAN_ELEMENTS[uppercase(value)] = true;
1732 function getBooleanAttrName(element, name) {
1733 // check dom last since we will most likely fail on name
1734 var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
1736 // booleanAttr is here twice to minimize DOM access
1737 return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
1742 inheritedData: JQLiteInheritedData,
1744 scope: function(element) {
1745 return JQLiteInheritedData(element, '$scope');
1748 controller: JQLiteController ,
1750 injector: function(element) {
1751 return JQLiteInheritedData(element, '$injector');
1754 removeAttr: function(element,name) {
1755 element.removeAttribute(name);
1758 hasClass: JQLiteHasClass,
1760 css: function(element, name, value) {
1761 name = camelCase(name);
1763 if (isDefined(value)) {
1764 element.style[name] = value;
1769 // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
1770 val = element.currentStyle && element.currentStyle[name];
1771 if (val === '') val = 'auto';
1774 val = val || element.style[name];
1777 // jquery weirdness :-/
1778 val = (val === '') ? undefined : val;
1785 attr: function(element, name, value){
1786 var lowercasedName = lowercase(name);
1787 if (BOOLEAN_ATTR[lowercasedName]) {
1788 if (isDefined(value)) {
1790 element[name] = true;
1791 element.setAttribute(name, lowercasedName);
1793 element[name] = false;
1794 element.removeAttribute(lowercasedName);
1797 return (element[name] ||
1798 (element.attributes.getNamedItem(name)|| noop).specified)
1802 } else if (isDefined(value)) {
1803 element.setAttribute(name, value);
1804 } else if (element.getAttribute) {
1805 // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
1806 // some elements (e.g. Document) don't have get attribute, so return undefined
1807 var ret = element.getAttribute(name, 2);
1808 // normalize non-existing attributes to undefined (as jQuery)
1809 return ret === null ? undefined : ret;
1813 prop: function(element, name, value) {
1814 if (isDefined(value)) {
1815 element[name] = value;
1817 return element[name];
1821 text: extend((msie < 9)
1822 ? function(element, value) {
1823 if (element.nodeType == 1 /** Element */) {
1824 if (isUndefined(value))
1825 return element.innerText;
1826 element.innerText = value;
1828 if (isUndefined(value))
1829 return element.nodeValue;
1830 element.nodeValue = value;
1833 : function(element, value) {
1834 if (isUndefined(value)) {
1835 return element.textContent;
1837 element.textContent = value;
1840 val: function(element, value) {
1841 if (isUndefined(value)) {
1842 return element.value;
1844 element.value = value;
1847 html: function(element, value) {
1848 if (isUndefined(value)) {
1849 return element.innerHTML;
1851 for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
1852 JQLiteDealoc(childNodes[i]);
1854 element.innerHTML = value;
1856 }, function(fn, name){
1858 * Properties: writes return selection, reads return first value
1860 JQLite.prototype[name] = function(arg1, arg2) {
1863 // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
1864 // in a way that survives minification.
1865 if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
1866 if (isObject(arg1)) {
1868 // we are a write, but the object properties are the key/values
1869 for(i=0; i < this.length; i++) {
1870 if (fn === JQLiteData) {
1871 // data() takes the whole object in jQuery
1875 fn(this[i], key, arg1[key]);
1879 // return self for chaining
1882 // we are a read, so read the first child.
1884 return fn(this[0], arg1, arg2);
1887 // we are a write, so apply to all children
1888 for(i=0; i < this.length; i++) {
1889 fn(this[i], arg1, arg2);
1891 // return self for chaining
1898 function createEventHandler(element, events) {
1899 var eventHandler = function (event, type) {
1900 if (!event.preventDefault) {
1901 event.preventDefault = function() {
1902 event.returnValue = false; //ie
1906 if (!event.stopPropagation) {
1907 event.stopPropagation = function() {
1908 event.cancelBubble = true; //ie
1912 if (!event.target) {
1913 event.target = event.srcElement || document;
1916 if (isUndefined(event.defaultPrevented)) {
1917 var prevent = event.preventDefault;
1918 event.preventDefault = function() {
1919 event.defaultPrevented = true;
1920 prevent.call(event);
1922 event.defaultPrevented = false;
1925 event.isDefaultPrevented = function() {
1926 return event.defaultPrevented;
1929 forEach(events[type || event.type], function(fn) {
1930 fn.call(element, event);
1933 // Remove monkey-patched methods (IE),
1934 // as they would cause memory leaks in IE8.
1936 // IE7/8 does not allow to delete property on native object
1937 event.preventDefault = null;
1938 event.stopPropagation = null;
1939 event.isDefaultPrevented = null;
1941 // It shouldn't affect normal browsers (native methods are defined on prototype).
1942 delete event.preventDefault;
1943 delete event.stopPropagation;
1944 delete event.isDefaultPrevented;
1947 eventHandler.elem = element;
1948 return eventHandler;
1951 //////////////////////////////////////////
1952 // Functions iterating traversal.
1953 // These functions chain results into a single
1955 //////////////////////////////////////////
1957 removeData: JQLiteRemoveData,
1959 dealoc: JQLiteDealoc,
1961 bind: function bindFn(element, type, fn){
1962 var events = JQLiteExpandoStore(element, 'events'),
1963 handle = JQLiteExpandoStore(element, 'handle');
1965 if (!events) JQLiteExpandoStore(element, 'events', events = {});
1966 if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
1968 forEach(type.split(' '), function(type){
1969 var eventFns = events[type];
1972 if (type == 'mouseenter' || type == 'mouseleave') {
1975 events.mouseenter = [];
1976 events.mouseleave = [];
1978 bindFn(element, 'mouseover', function(event) {
1981 handle(event, 'mouseenter');
1984 bindFn(element, 'mouseout', function(event) {
1987 handle(event, 'mouseleave');
1991 addEventListenerFn(element, type, handle);
1994 eventFns = events[type]
2000 unbind: JQLiteUnbind,
2002 replaceWith: function(element, replaceNode) {
2003 var index, parent = element.parentNode;
2004 JQLiteDealoc(element);
2005 forEach(new JQLite(replaceNode), function(node){
2007 parent.insertBefore(node, index.nextSibling);
2009 parent.replaceChild(node, element);
2015 children: function(element) {
2017 forEach(element.childNodes, function(element){
2018 if (element.nodeName != '#text')
2019 children.push(element);
2024 contents: function(element) {
2025 return element.childNodes;
2028 append: function(element, node) {
2029 forEach(new JQLite(node), function(child){
2030 if (element.nodeType === 1)
2031 element.appendChild(child);
2035 prepend: function(element, node) {
2036 if (element.nodeType === 1) {
2037 var index = element.firstChild;
2038 forEach(new JQLite(node), function(child){
2040 element.insertBefore(child, index);
2042 element.appendChild(child);
2049 wrap: function(element, wrapNode) {
2050 wrapNode = jqLite(wrapNode)[0];
2051 var parent = element.parentNode;
2053 parent.replaceChild(wrapNode, element);
2055 wrapNode.appendChild(element);
2058 remove: function(element) {
2059 JQLiteDealoc(element);
2060 var parent = element.parentNode;
2061 if (parent) parent.removeChild(element);
2064 after: function(element, newElement) {
2065 var index = element, parent = element.parentNode;
2066 forEach(new JQLite(newElement), function(node){
2067 parent.insertBefore(node, index.nextSibling);
2072 addClass: JQLiteAddClass,
2073 removeClass: JQLiteRemoveClass,
2075 toggleClass: function(element, selector, condition) {
2076 if (isUndefined(condition)) {
2077 condition = !JQLiteHasClass(element, selector);
2079 (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
2082 parent: function(element) {
2083 var parent = element.parentNode;
2084 return parent && parent.nodeType !== 11 ? parent : null;
2087 next: function(element) {
2088 return element.nextSibling;
2091 find: function(element, selector) {
2092 return element.getElementsByTagName(selector);
2096 }, function(fn, name){
2098 * chaining functions
2100 JQLite.prototype[name] = function(arg1, arg2) {
2102 for(var i=0; i < this.length; i++) {
2103 if (value == undefined) {
2104 value = fn(this[i], arg1, arg2);
2105 if (value !== undefined) {
2106 // any function which returns a value needs to be wrapped
2107 value = jqLite(value);
2110 JQLiteAddNodes(value, fn(this[i], arg1, arg2));
2113 return value == undefined ? this : value;
2118 * Computes a hash of an 'obj'.
2121 * number is number as string
2122 * object is either result of calling $$hashKey function on the object or uniquely generated id,
2123 * that is also assigned to the $$hashKey property of the object.
2126 * @returns {string} hash string such that the same input will have the same hash string.
2127 * The resulting string key is in 'type:hashKey' format.
2129 function hashKey(obj) {
2130 var objType = typeof obj,
2133 if (objType == 'object' && obj !== null) {
2134 if (typeof (key = obj.$$hashKey) == 'function') {
2135 // must invoke on object to keep the right this
2136 key = obj.$$hashKey();
2137 } else if (key === undefined) {
2138 key = obj.$$hashKey = nextUid();
2144 return objType + ':' + key;
2148 * HashMap which can use objects as keys
2150 function HashMap(array){
2151 forEach(array, this.put, this);
2153 HashMap.prototype = {
2155 * Store key value pair
2156 * @param key key to store can be any type
2157 * @param value value to store can be any type
2159 put: function(key, value) {
2160 this[hashKey(key)] = value;
2165 * @returns the value for the key
2167 get: function(key) {
2168 return this[hashKey(key)];
2172 * Remove the key/value pair
2175 remove: function(key) {
2176 var value = this[key = hashKey(key)];
2183 * A map where multiple values can be added to the same key such that they form a queue.
2184 * @returns {HashQueueMap}
2186 function HashQueueMap() {}
2187 HashQueueMap.prototype = {
2189 * Same as array push, but using an array as the value for the hash
2191 push: function(key, value) {
2192 var array = this[key = hashKey(key)];
2194 this[key] = [value];
2201 * Same as array shift, but using an array as the value for the hash
2203 shift: function(key) {
2204 var array = this[key = hashKey(key)];
2206 if (array.length == 1) {
2210 return array.shift();
2218 * @name angular.injector
2222 * Creates an injector function that can be used for retrieving services as well as for
2223 * dependency injection (see {@link guide/di dependency injection}).
2226 * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
2227 * {@link angular.module}. The `ng` module must be explicitly added.
2228 * @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
2233 * // create an injector
2234 * var $injector = angular.injector(['ng']);
2236 * // use the injector to kick of your application
2237 * // use the type inference to auto inject arguments, or use implicit injection
2238 * $injector.invoke(function($rootScope, $compile, $document){
2239 * $compile($document)($rootScope);
2240 * $rootScope.$digest();
2251 * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
2254 var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
2255 var FN_ARG_SPLIT = /,/;
2256 var FN_ARG = /^\s*(_?)(.+?)\1\s*$/;
2257 var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
2258 function annotate(fn) {
2264 if (typeof fn == 'function') {
2265 if (!($inject = fn.$inject)) {
2267 fnText = fn.toString().replace(STRIP_COMMENTS, '');
2268 argDecl = fnText.match(FN_ARGS);
2269 forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
2270 arg.replace(FN_ARG, function(all, underscore, name){
2274 fn.$inject = $inject;
2276 } else if (isArray(fn)) {
2277 last = fn.length - 1;
2278 assertArgFn(fn[last], 'fn')
2279 $inject = fn.slice(0, last);
2281 assertArgFn(fn, 'fn', true);
2286 ///////////////////////////////////////
2290 * @name AUTO.$injector
2295 * `$injector` is used to retrieve object instances as defined by
2296 * {@link AUTO.$provide provider}, instantiate types, invoke methods,
2299 * The following always holds true:
2302 * var $injector = angular.injector();
2303 * expect($injector.get('$injector')).toBe($injector);
2304 * expect($injector.invoke(function($injector){
2306 * }).toBe($injector);
2309 * # Injection Function Annotation
2311 * JavaScript does not have annotations, and annotations are needed for dependency injection. The
2312 * following ways are all valid way of annotating function with injection arguments and are equivalent.
2315 * // inferred (only works if code not minified/obfuscated)
2316 * $inject.invoke(function(serviceA){});
2319 * function explicit(serviceA) {};
2320 * explicit.$inject = ['serviceA'];
2321 * $inject.invoke(explicit);
2324 * $inject.invoke(['serviceA', function(serviceA){}]);
2329 * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
2330 * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
2331 * tools since these tools change the argument names.
2333 * ## `$inject` Annotation
2334 * By adding a `$inject` property onto a function the injection parameters can be specified.
2337 * As an array of injection names, where the last item in the array is the function to call.
2342 * @name AUTO.$injector#get
2343 * @methodOf AUTO.$injector
2346 * Return an instance of the service.
2348 * @param {string} name The name of the instance to retrieve.
2349 * @return {*} The instance.
2354 * @name AUTO.$injector#invoke
2355 * @methodOf AUTO.$injector
2358 * Invoke the method and supply the method arguments from the `$injector`.
2360 * @param {!function} fn The function to invoke. The function arguments come form the function annotation.
2361 * @param {Object=} self The `this` for the invoked method.
2362 * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
2363 * the `$injector` is consulted.
2364 * @returns {*} the value returned by the invoked `fn` function.
2369 * @name AUTO.$injector#instantiate
2370 * @methodOf AUTO.$injector
2372 * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
2373 * all of the arguments to the constructor function as specified by the constructor annotation.
2375 * @param {function} Type Annotated constructor function.
2376 * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
2377 * the `$injector` is consulted.
2378 * @returns {Object} new instance of `Type`.
2383 * @name AUTO.$injector#annotate
2384 * @methodOf AUTO.$injector
2387 * Returns an array of service names which the function is requesting for injection. This API is used by the injector
2388 * to determine which services need to be injected into the function when the function is invoked. There are three
2389 * ways in which the function can be annotated with the needed dependencies.
2393 * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
2394 * the function into a string using `toString()` method and extracting the argument names.
2397 * function MyController($scope, $route) {
2402 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
2405 * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
2408 * # The `$injector` property
2410 * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
2411 * services to be injected into the function.
2414 * var MyController = function(obfuscatedScope, obfuscatedRoute) {
2417 * // Define function dependencies
2418 * MyController.$inject = ['$scope', '$route'];
2421 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
2424 * # The array notation
2426 * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
2427 * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
2428 * minification is a better choice:
2431 * // We wish to write this (not minification / obfuscation safe)
2432 * injector.invoke(function($compile, $rootScope) {
2436 * // We are forced to write break inlining
2437 * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
2440 * tmpFn.$inject = ['$compile', '$rootScope'];
2441 * injector.invoke(tempFn);
2443 * // To better support inline function the inline annotation is supported
2444 * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
2449 * expect(injector.annotate(
2450 * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
2451 * ).toEqual(['$compile', '$rootScope']);
2454 * @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
2457 * @returns {Array.<string>} The names of the services which the function requires.
2465 * @name AUTO.$provide
2469 * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
2470 * The providers share the same name as the instance they create with the `Provider` suffixed to them.
2472 * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
2473 * a service. The Provider can have additional methods which would allow for configuration of the provider.
2476 * function GreetProvider() {
2477 * var salutation = 'Hello';
2479 * this.salutation = function(text) {
2480 * salutation = text;
2483 * this.$get = function() {
2484 * return function (name) {
2485 * return salutation + ' ' + name + '!';
2490 * describe('Greeter', function(){
2492 * beforeEach(module(function($provide) {
2493 * $provide.provider('greet', GreetProvider);
2496 * it('should greet', inject(function(greet) {
2497 * expect(greet('angular')).toEqual('Hello angular!');
2500 * it('should allow configuration of salutation', function() {
2501 * module(function(greetProvider) {
2502 * greetProvider.salutation('Ahoj');
2504 * inject(function(greet) {
2505 * expect(greet('angular')).toEqual('Ahoj angular!');
2515 * @name AUTO.$provide#provider
2516 * @methodOf AUTO.$provide
2519 * Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
2521 * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
2522 * @param {(Object|function())} provider If the provider is:
2524 * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
2525 * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
2526 * - `Constructor`: a new instance of the provider will be created using
2527 * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
2529 * @returns {Object} registered provider instance
2534 * @name AUTO.$provide#factory
2535 * @methodOf AUTO.$provide
2538 * A short hand for configuring services if only `$get` method is required.
2540 * @param {string} name The name of the instance.
2541 * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
2542 * `$provide.provider(name, {$get: $getFn})`.
2543 * @returns {Object} registered provider instance
2549 * @name AUTO.$provide#service
2550 * @methodOf AUTO.$provide
2553 * A short hand for registering service of given class.
2555 * @param {string} name The name of the instance.
2556 * @param {Function} constructor A class (constructor function) that will be instantiated.
2557 * @returns {Object} registered provider instance
2563 * @name AUTO.$provide#value
2564 * @methodOf AUTO.$provide
2567 * A short hand for configuring services if the `$get` method is a constant.
2569 * @param {string} name The name of the instance.
2570 * @param {*} value The value.
2571 * @returns {Object} registered provider instance
2577 * @name AUTO.$provide#constant
2578 * @methodOf AUTO.$provide
2581 * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
2582 * into configuration function (other modules) and it is not interceptable by
2583 * {@link AUTO.$provide#decorator decorator}.
2585 * @param {string} name The name of the constant.
2586 * @param {*} value The constant value.
2587 * @returns {Object} registered instance
2593 * @name AUTO.$provide#decorator
2594 * @methodOf AUTO.$provide
2597 * Decoration of service, allows the decorator to intercept the service instance creation. The
2598 * returned instance may be the original instance, or a new instance which delegates to the
2599 * original instance.
2601 * @param {string} name The name of the service to decorate.
2602 * @param {function()} decorator This function will be invoked when the service needs to be
2603 * instanciated. The function is called using the {@link AUTO.$injector#invoke
2604 * injector.invoke} method and is therefore fully injectable. Local injection arguments:
2606 * * `$delegate` - The original service instance, which can be monkey patched, configured,
2607 * decorated or delegated to.
2611 function createInjector(modulesToLoad) {
2612 var INSTANTIATING = {},
2613 providerSuffix = 'Provider',
2615 loadedModules = new HashMap(),
2618 provider: supportObject(provider),
2619 factory: supportObject(factory),
2620 service: supportObject(service),
2621 value: supportObject(value),
2622 constant: supportObject(constant),
2623 decorator: decorator
2626 providerInjector = createInternalInjector(providerCache, function() {
2627 throw Error("Unknown provider: " + path.join(' <- '));
2630 instanceInjector = (instanceCache.$injector =
2631 createInternalInjector(instanceCache, function(servicename) {
2632 var provider = providerInjector.get(servicename + providerSuffix);
2633 return instanceInjector.invoke(provider.$get, provider);
2637 forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
2639 return instanceInjector;
2641 ////////////////////////////////////
2643 ////////////////////////////////////
2645 function supportObject(delegate) {
2646 return function(key, value) {
2647 if (isObject(key)) {
2648 forEach(key, reverseParams(delegate));
2650 return delegate(key, value);
2655 function provider(name, provider_) {
2656 if (isFunction(provider_)) {
2657 provider_ = providerInjector.instantiate(provider_);
2659 if (!provider_.$get) {
2660 throw Error('Provider ' + name + ' must define $get factory method.');
2662 return providerCache[name + providerSuffix] = provider_;
2665 function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
2667 function service(name, constructor) {
2668 return factory(name, ['$injector', function($injector) {
2669 return $injector.instantiate(constructor);
2673 function value(name, value) { return factory(name, valueFn(value)); }
2675 function constant(name, value) {
2676 providerCache[name] = value;
2677 instanceCache[name] = value;
2680 function decorator(serviceName, decorFn) {
2681 var origProvider = providerInjector.get(serviceName + providerSuffix),
2682 orig$get = origProvider.$get;
2684 origProvider.$get = function() {
2685 var origInstance = instanceInjector.invoke(orig$get, origProvider);
2686 return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
2690 ////////////////////////////////////
2692 ////////////////////////////////////
2693 function loadModules(modulesToLoad){
2695 forEach(modulesToLoad, function(module) {
2696 if (loadedModules.get(module)) return;
2697 loadedModules.put(module, true);
2698 if (isString(module)) {
2699 var moduleFn = angularModule(module);
2700 runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
2703 for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
2704 var invokeArgs = invokeQueue[i],
2705 provider = invokeArgs[0] == '$injector'
2707 : providerInjector.get(invokeArgs[0]);
2709 provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
2712 if (e.message) e.message += ' from ' + module;
2715 } else if (isFunction(module)) {
2717 runBlocks.push(providerInjector.invoke(module));
2719 if (e.message) e.message += ' from ' + module;
2722 } else if (isArray(module)) {
2724 runBlocks.push(providerInjector.invoke(module));
2726 if (e.message) e.message += ' from ' + String(module[module.length - 1]);
2730 assertArgFn(module, 'module');
2736 ////////////////////////////////////
2737 // internal Injector
2738 ////////////////////////////////////
2740 function createInternalInjector(cache, factory) {
2742 function getService(serviceName) {
2743 if (typeof serviceName !== 'string') {
2744 throw Error('Service name expected');
2746 if (cache.hasOwnProperty(serviceName)) {
2747 if (cache[serviceName] === INSTANTIATING) {
2748 throw Error('Circular dependency: ' + path.join(' <- '));
2750 return cache[serviceName];
2753 path.unshift(serviceName);
2754 cache[serviceName] = INSTANTIATING;
2755 return cache[serviceName] = factory(serviceName);
2762 function invoke(fn, self, locals){
2764 $inject = annotate(fn),
2768 for(i = 0, length = $inject.length; i < length; i++) {
2771 locals && locals.hasOwnProperty(key)
2773 : getService(key, path)
2777 // this means that we must be an array.
2782 // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
2783 switch (self ? -1 : args.length) {
2784 case 0: return fn();
2785 case 1: return fn(args[0]);
2786 case 2: return fn(args[0], args[1]);
2787 case 3: return fn(args[0], args[1], args[2]);
2788 case 4: return fn(args[0], args[1], args[2], args[3]);
2789 case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
2790 case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
2791 case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
2792 case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
2793 case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
2794 case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
2795 default: return fn.apply(self, args);
2799 function instantiate(Type, locals) {
2800 var Constructor = function() {},
2801 instance, returnedValue;
2803 Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
2804 instance = new Constructor();
2805 returnedValue = invoke(Type, instance, locals);
2807 return isObject(returnedValue) ? returnedValue : instance;
2812 instantiate: instantiate,
2820 * @name ng.$anchorScroll
2822 * @requires $location
2823 * @requires $rootScope
2826 * When called, it checks current value of `$location.hash()` and scroll to related element,
2827 * according to rules specified in
2828 * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
2830 * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
2831 * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
2833 function $AnchorScrollProvider() {
2835 var autoScrollingEnabled = true;
2837 this.disableAutoScrolling = function() {
2838 autoScrollingEnabled = false;
2841 this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
2842 var document = $window.document;
2844 // helper function to get first anchor from a NodeList
2845 // can't use filter.filter, as it accepts only instances of Array
2846 // and IE can't convert NodeList to an array using [].slice
2847 // TODO(vojta): use filter if we change it to accept lists as well
2848 function getFirstAnchor(list) {
2850 forEach(list, function(element) {
2851 if (!result && lowercase(element.nodeName) === 'a') result = element;
2857 var hash = $location.hash(), elm;
2859 // empty hash, scroll to the top of the page
2860 if (!hash) $window.scrollTo(0, 0);
2862 // element with given id
2863 else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
2865 // first anchor with given name :-D
2866 else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
2868 // no element and hash == 'top', scroll to the top of the page
2869 else if (hash === 'top') $window.scrollTo(0, 0);
2872 // does not scroll when user clicks on anchor link that is currently on
2873 // (no url change, no $locaiton.hash() change), browser native does scroll
2874 if (autoScrollingEnabled) {
2875 $rootScope.$watch(function() {return $location.hash();}, function() {
2876 $rootScope.$evalAsync(scroll);
2885 * ! This is a private undocumented service !
2890 * This object has two goals:
2892 * - hide all the global state in the browser caused by the window object
2893 * - abstract away all the browser specific features and inconsistencies
2895 * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
2896 * service, which can be used for convenient testing of the application without the interaction with
2897 * the real browser apis.
2900 * @param {object} window The global window object.
2901 * @param {object} document jQuery wrapped document.
2902 * @param {function()} XHR XMLHttpRequest constructor.
2903 * @param {object} $log console.log or an object with the same interface.
2904 * @param {object} $sniffer $sniffer service
2906 function Browser(window, document, $log, $sniffer) {
2908 rawDocument = document[0],
2909 location = window.location,
2910 history = window.history,
2911 setTimeout = window.setTimeout,
2912 clearTimeout = window.clearTimeout,
2913 pendingDeferIds = {};
2915 self.isMock = false;
2917 var outstandingRequestCount = 0;
2918 var outstandingRequestCallbacks = [];
2920 // TODO(vojta): remove this temporary api
2921 self.$$completeOutstandingRequest = completeOutstandingRequest;
2922 self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
2925 * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
2926 * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
2928 function completeOutstandingRequest(fn) {
2930 fn.apply(null, sliceArgs(arguments, 1));
2932 outstandingRequestCount--;
2933 if (outstandingRequestCount === 0) {
2934 while(outstandingRequestCallbacks.length) {
2936 outstandingRequestCallbacks.pop()();
2947 * Note: this method is used only by scenario runner
2948 * TODO(vojta): prefix this method with $$ ?
2949 * @param {function()} callback Function that will be called when no outstanding request
2951 self.notifyWhenNoOutstandingRequests = function(callback) {
2952 // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
2953 // at some deterministic time in respect to the test runner's actions. Leaving things up to the
2954 // regular poller would result in flaky tests.
2955 forEach(pollFns, function(pollFn){ pollFn(); });
2957 if (outstandingRequestCount === 0) {
2960 outstandingRequestCallbacks.push(callback);
2964 //////////////////////////////////////////////////////////////
2966 //////////////////////////////////////////////////////////////
2971 * @name ng.$browser#addPollFn
2972 * @methodOf ng.$browser
2974 * @param {function()} fn Poll function to add
2977 * Adds a function to the list of functions that poller periodically executes,
2978 * and starts polling if not started yet.
2980 * @returns {function()} the added function
2982 self.addPollFn = function(fn) {
2983 if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
2989 * @param {number} interval How often should browser call poll functions (ms)
2990 * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
2993 * Configures the poller to run in the specified intervals, using the specified
2994 * setTimeout fn and kicks it off.
2996 function startPoller(interval, setTimeout) {
2998 forEach(pollFns, function(pollFn){ pollFn(); });
2999 pollTimeout = setTimeout(check, interval);
3003 //////////////////////////////////////////////////////////////
3005 //////////////////////////////////////////////////////////////
3007 var lastBrowserUrl = location.href,
3008 baseElement = document.find('base');
3011 * @name ng.$browser#url
3012 * @methodOf ng.$browser
3016 * Without any argument, this method just returns current value of location.href.
3019 * With at least one argument, this method sets url to new value.
3020 * If html5 history api supported, pushState/replaceState is used, otherwise
3021 * location.href/location.replace is used.
3022 * Returns its own instance to allow chaining
3024 * NOTE: this api is intended for use only by the $location service. Please use the
3025 * {@link ng.$location $location service} to change url.
3027 * @param {string} url New url (when used as setter)
3028 * @param {boolean=} replace Should new url replace current history record ?
3030 self.url = function(url, replace) {
3033 if (lastBrowserUrl == url) return;
3034 lastBrowserUrl = url;
3035 if ($sniffer.history) {
3036 if (replace) history.replaceState(null, '', url);
3038 history.pushState(null, '', url);
3039 // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
3040 baseElement.attr('href', baseElement.attr('href'));
3043 if (replace) location.replace(url);
3044 else location.href = url;
3049 // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
3050 return location.href.replace(/%27/g,"'");
3054 var urlChangeListeners = [],
3055 urlChangeInit = false;
3057 function fireUrlChange() {
3058 if (lastBrowserUrl == self.url()) return;
3060 lastBrowserUrl = self.url();
3061 forEach(urlChangeListeners, function(listener) {
3062 listener(self.url());
3067 * @name ng.$browser#onUrlChange
3068 * @methodOf ng.$browser
3069 * @TODO(vojta): refactor to use node's syntax for events
3072 * Register callback function that will be called, when url changes.
3074 * It's only called when the url is changed by outside of angular:
3075 * - user types different url into address bar
3076 * - user clicks on history (forward/back) button
3077 * - user clicks on a link
3079 * It's not called when url is changed by $browser.url() method
3081 * The listener gets called with new url as parameter.
3083 * NOTE: this api is intended for use only by the $location service. Please use the
3084 * {@link ng.$location $location service} to monitor url changes in angular apps.
3086 * @param {function(string)} listener Listener function to be called when url changes.
3087 * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
3089 self.onUrlChange = function(callback) {
3090 if (!urlChangeInit) {
3091 // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
3092 // don't fire popstate when user change the address bar and don't fire hashchange when url
3093 // changed by push/replaceState
3095 // html5 history api - popstate event
3096 if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
3098 if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
3100 else self.addPollFn(fireUrlChange);
3102 urlChangeInit = true;
3105 urlChangeListeners.push(callback);
3109 //////////////////////////////////////////////////////////////
3111 //////////////////////////////////////////////////////////////
3114 * Returns current <base href>
3115 * (always relative - without domain)
3117 * @returns {string=}
3119 self.baseHref = function() {
3120 var href = baseElement.attr('href');
3121 return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href;
3124 //////////////////////////////////////////////////////////////
3126 //////////////////////////////////////////////////////////////
3127 var lastCookies = {};
3128 var lastCookieString = '';
3129 var cookiePath = self.baseHref();
3132 * @name ng.$browser#cookies
3133 * @methodOf ng.$browser
3135 * @param {string=} name Cookie name
3136 * @param {string=} value Cokkie value
3139 * The cookies method provides a 'private' low level access to browser cookies.
3140 * It is not meant to be used directly, use the $cookie service instead.
3142 * The return values vary depending on the arguments that the method was called with as follows:
3144 * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
3145 * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
3146 * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
3149 * @returns {Object} Hash of all cookies (if called without any parameter)
3151 self.cookies = function(name, value) {
3152 var cookieLength, cookieArray, cookie, i, index;
3155 if (value === undefined) {
3156 rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
3158 if (isString(value)) {
3159 cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
3160 if (cookieLength > 4096) {
3161 $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
3162 cookieLength + " > 4096 bytes)!");
3164 if (lastCookies.length > 20) {
3165 $log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " +
3166 "were already set (" + lastCookies.length + " > 20 )");
3171 if (rawDocument.cookie !== lastCookieString) {
3172 lastCookieString = rawDocument.cookie;
3173 cookieArray = lastCookieString.split("; ");
3176 for (i = 0; i < cookieArray.length; i++) {
3177 cookie = cookieArray[i];
3178 index = cookie.indexOf('=');
3179 if (index > 0) { //ignore nameless cookies
3180 lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1));
3190 * @name ng.$browser#defer
3191 * @methodOf ng.$browser
3192 * @param {function()} fn A function, who's execution should be defered.
3193 * @param {number=} [delay=0] of milliseconds to defer the function execution.
3194 * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
3197 * Executes a fn asynchroniously via `setTimeout(fn, delay)`.
3199 * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
3200 * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
3201 * via `$browser.defer.flush()`.
3204 self.defer = function(fn, delay) {
3206 outstandingRequestCount++;
3207 timeoutId = setTimeout(function() {
3208 delete pendingDeferIds[timeoutId];
3209 completeOutstandingRequest(fn);
3211 pendingDeferIds[timeoutId] = true;
3217 * @name ng.$browser#defer.cancel
3218 * @methodOf ng.$browser.defer
3221 * Cancels a defered task identified with `deferId`.
3223 * @param {*} deferId Token returned by the `$browser.defer` function.
3224 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
3226 self.defer.cancel = function(deferId) {
3227 if (pendingDeferIds[deferId]) {
3228 delete pendingDeferIds[deferId];
3229 clearTimeout(deferId);
3230 completeOutstandingRequest(noop);
3238 function $BrowserProvider(){
3239 this.$get = ['$window', '$log', '$sniffer', '$document',
3240 function( $window, $log, $sniffer, $document){
3241 return new Browser($window, $document, $log, $sniffer);
3246 * @name ng.$cacheFactory
3249 * Factory that constructs cache objects.
3252 * @param {string} cacheId Name or id of the newly created cache.
3253 * @param {object=} options Options object that specifies the cache behavior. Properties:
3255 * - `{number=}` `capacity` — turns the cache into LRU cache.
3257 * @returns {object} Newly created cache object with the following set of methods:
3259 * - `{object}` `info()` — Returns id, size, and options of cache.
3260 * - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache.
3261 * - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss.
3262 * - `{void}` `remove({string} key) — Removes a key-value pair from the cache.
3263 * - `{void}` `removeAll() — Removes all cached values.
3264 * - `{void}` `destroy() — Removes references to this cache from $cacheFactory.
3267 function $CacheFactoryProvider() {
3269 this.$get = function() {
3272 function cacheFactory(cacheId, options) {
3273 if (cacheId in caches) {
3274 throw Error('cacheId ' + cacheId + ' taken');
3278 stats = extend({}, options, {id: cacheId}),
3280 capacity = (options && options.capacity) || Number.MAX_VALUE,
3285 return caches[cacheId] = {
3287 put: function(key, value) {
3288 var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
3292 if (isUndefined(value)) return;
3293 if (!(key in data)) size++;
3296 if (size > capacity) {
3297 this.remove(staleEnd.key);
3302 get: function(key) {
3303 var lruEntry = lruHash[key];
3305 if (!lruEntry) return;
3313 remove: function(key) {
3314 var lruEntry = lruHash[key];
3316 if (lruEntry == freshEnd) freshEnd = lruEntry.p;
3317 if (lruEntry == staleEnd) staleEnd = lruEntry.n;
3318 link(lruEntry.n,lruEntry.p);
3320 delete lruHash[key];
3326 removeAll: function() {
3330 freshEnd = staleEnd = null;
3334 destroy: function() {
3338 delete caches[cacheId];
3343 return extend({}, stats, {size: size});
3349 * makes the `entry` the freshEnd of the LRU linked list
3351 function refresh(entry) {
3352 if (entry != freshEnd) {
3355 } else if (staleEnd == entry) {
3359 link(entry.n, entry.p);
3360 link(entry, freshEnd);
3368 * bidirectionally links two entries of the LRU linked list
3370 function link(nextEntry, prevEntry) {
3371 if (nextEntry != prevEntry) {
3372 if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
3373 if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
3379 cacheFactory.info = function() {
3381 forEach(caches, function(cache, cacheId) {
3382 info[cacheId] = cache.info();
3388 cacheFactory.get = function(cacheId) {
3389 return caches[cacheId];
3393 return cacheFactory;
3399 * @name ng.$templateCache
3402 * Cache used for storing html templates.
3404 * See {@link ng.$cacheFactory $cacheFactory}.
3407 function $TemplateCacheProvider() {
3408 this.$get = ['$cacheFactory', function($cacheFactory) {
3409 return $cacheFactory('templates');
3413 /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
3415 * DOM-related variables:
3417 * - "node" - DOM Node
3418 * - "element" - DOM Element or Node
3419 * - "$node" or "$element" - jqLite-wrapped node or element
3422 * Compiler related stuff:
3424 * - "linkFn" - linking fn of a single directive
3425 * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
3426 * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
3427 * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
3431 var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
3440 * Compiles a piece of HTML string or DOM into a template and produces a template function, which
3441 * can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
3443 * The compilation is a process of walking the DOM tree and trying to match DOM elements to
3444 * {@link ng.$compileProvider#directive directives}. For each match it
3445 * executes corresponding template function and collects the
3446 * instance functions into a single template function which is then returned.
3448 * The template function can then be used once to produce the view or as it is the case with
3449 * {@link ng.directive:ngRepeat repeater} many-times, in which
3450 * case each call results in a view that is a DOM clone of the original template.
3452 <doc:example module="compile">
3455 // declare a new module, and inject the $compileProvider
3456 angular.module('compile', [], function($compileProvider) {
3457 // configure new 'compile' directive by passing a directive
3458 // factory function. The factory function injects the '$compile'
3459 $compileProvider.directive('compile', function($compile) {
3460 // directive factory creates a link function
3461 return function(scope, element, attrs) {
3464 // watch the 'compile' expression for changes
3465 return scope.$eval(attrs.compile);
3468 // when the 'compile' expression changes
3469 // assign it into the current DOM
3470 element.html(value);
3472 // compile the new DOM and link it to the current
3474 // NOTE: we only compile .childNodes so that
3475 // we don't get into infinite loop compiling ourselves
3476 $compile(element.contents())(scope);
3483 function Ctrl($scope) {
3484 $scope.name = 'Angular';
3485 $scope.html = 'Hello {{name}}';
3488 <div ng-controller="Ctrl">
3489 <input ng-model="name"> <br>
3490 <textarea ng-model="html"></textarea> <br>
3491 <div compile="html"></div>
3495 it('should auto compile', function() {
3496 expect(element('div[compile]').text()).toBe('Hello Angular');
3497 input('html').enter('{{name}}!');
3498 expect(element('div[compile]').text()).toBe('Angular!');
3505 * @param {string|DOMElement} element Element or HTML string to compile into a template function.
3506 * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
3507 * @param {number} maxPriority only apply directives lower then given priority (Only effects the
3508 * root element(s), not their children)
3509 * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
3510 * (a DOM element/tree) to a scope. Where:
3512 * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
3513 * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
3514 * `template` and call the `cloneAttachFn` function allowing the caller to attach the
3515 * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
3516 * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
3518 * * `clonedElement` - is a clone of the original `element` passed into the compiler.
3519 * * `scope` - is the current scope with which the linking function is working with.
3521 * Calling the linking function returns the element of the template. It is either the original element
3522 * passed in, or the clone of the element if the `cloneAttachFn` is provided.
3524 * After linking the view is not updated until after a call to $digest which typically is done by
3525 * Angular automatically.
3527 * If you need access to the bound view, there are two ways to do it:
3529 * - If you are not asking the linking function to clone the template, create the DOM element(s)
3530 * before you send them to the compiler and keep this reference around.
3532 * var element = $compile('<p>{{total}}</p>')(scope);
3535 * - if on the other hand, you need the element to be cloned, the view reference from the original
3536 * example would not point to the clone, but rather to the original template that was cloned. In
3537 * this case, you can access the clone via the cloneAttachFn:
3539 * var templateHTML = angular.element('<p>{{total}}</p>'),
3542 * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
3543 * //attach the clone to DOM document at the right place
3546 * //now we have reference to the cloned DOM via `clone`
3550 * For information on how the compiler works, see the
3551 * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
3557 * @name ng.$compileProvider
3562 $CompileProvider.$inject = ['$provide'];
3563 function $CompileProvider($provide) {
3564 var hasDirectives = {},
3565 Suffix = 'Directive',
3566 COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
3567 CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
3568 MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ';
3573 * @name ng.$compileProvider#directive
3574 * @methodOf ng.$compileProvider
3578 * Register a new directives with the compiler.
3580 * @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
3581 * <code>ng-bind</code>).
3582 * @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more
3584 * @returns {ng.$compileProvider} Self for chaining.
3586 this.directive = function registerDirective(name, directiveFactory) {
3587 if (isString(name)) {
3588 assertArg(directiveFactory, 'directive');
3589 if (!hasDirectives.hasOwnProperty(name)) {
3590 hasDirectives[name] = [];
3591 $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
3592 function($injector, $exceptionHandler) {
3593 var directives = [];
3594 forEach(hasDirectives[name], function(directiveFactory) {
3596 var directive = $injector.invoke(directiveFactory);
3597 if (isFunction(directive)) {
3598 directive = { compile: valueFn(directive) };
3599 } else if (!directive.compile && directive.link) {
3600 directive.compile = valueFn(directive.link);
3602 directive.priority = directive.priority || 0;
3603 directive.name = directive.name || name;
3604 directive.require = directive.require || (directive.controller && directive.name);
3605 directive.restrict = directive.restrict || 'A';
3606 directives.push(directive);
3608 $exceptionHandler(e);
3614 hasDirectives[name].push(directiveFactory);
3616 forEach(name, reverseParams(registerDirective));
3623 '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
3624 '$controller', '$rootScope',
3625 function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
3626 $controller, $rootScope) {
3628 var Attributes = function(element, attr) {
3629 this.$$element = element;
3630 this.$attr = attr || {};
3633 Attributes.prototype = {
3634 $normalize: directiveNormalize,
3638 * Set a normalized attribute on the element in a way such that all directives
3639 * can share the attribute. This function properly handles boolean attributes.
3640 * @param {string} key Normalized key. (ie ngAttribute)
3641 * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
3642 * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
3644 * @param {string=} attrName Optional none normalized name. Defaults to key.
3646 $set: function(key, value, writeAttr, attrName) {
3647 var booleanKey = getBooleanAttrName(this.$$element[0], key),
3648 $$observers = this.$$observers;
3651 this.$$element.prop(key, value);
3652 attrName = booleanKey;
3657 // translate normalized key to actual key
3659 this.$attr[key] = attrName;
3661 attrName = this.$attr[key];
3663 this.$attr[key] = attrName = snake_case(key, '-');
3667 if (writeAttr !== false) {
3668 if (value === null || value === undefined) {
3669 this.$$element.removeAttr(attrName);
3671 this.$$element.attr(attrName, value);
3676 $$observers && forEach($$observers[key], function(fn) {
3680 $exceptionHandler(e);
3687 * Observe an interpolated attribute.
3688 * The observer will never be called, if given attribute is not interpolated.
3690 * @param {string} key Normalized key. (ie ngAttribute) .
3691 * @param {function(*)} fn Function that will be called whenever the attribute value changes.
3692 * @returns {function(*)} the `fn` Function passed in.
3694 $observe: function(key, fn) {
3696 $$observers = (attrs.$$observers || (attrs.$$observers = {})),
3697 listeners = ($$observers[key] || ($$observers[key] = []));
3700 $rootScope.$evalAsync(function() {
3701 if (!listeners.$$inter) {
3702 // no one registered attribute interpolation function, so lets call it manually
3710 var startSymbol = $interpolate.startSymbol(),
3711 endSymbol = $interpolate.endSymbol(),
3712 denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
3714 : function denormalizeTemplate(template) {
3715 return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
3721 //================================
3723 function compile($compileNode, transcludeFn, maxPriority) {
3724 if (!($compileNode instanceof jqLite)) {
3725 // jquery always rewraps, where as we need to preserve the original selector so that we can modify it.
3726 $compileNode = jqLite($compileNode);
3728 // We can not compile top level text elements since text nodes can be merged and we will
3729 // not be able to attach scope data to them, so we will wrap them in <span>
3730 forEach($compileNode, function(node, index){
3731 if (node.nodeType == 3 /* text node */) {
3732 $compileNode[index] = jqLite(node).wrap('<span></span>').parent()[0];
3735 var compositeLinkFn = compileNodes($compileNode, transcludeFn, $compileNode, maxPriority);
3736 return function(scope, cloneConnectFn){
3737 assertArg(scope, 'scope');
3738 // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
3739 // and sometimes changes the structure of the DOM.
3740 var $linkNode = cloneConnectFn
3741 ? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!!
3743 $linkNode.data('$scope', scope);
3744 safeAddClass($linkNode, 'ng-scope');
3745 if (cloneConnectFn) cloneConnectFn($linkNode, scope);
3746 if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
3751 function wrongMode(localName, mode) {
3752 throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
3755 function safeAddClass($element, className) {
3757 $element.addClass(className);
3759 // ignore, since it means that we are trying to set class on
3760 // SVG element, where class name is read-only.
3765 * Compile function matches each node in nodeList against the directives. Once all directives
3766 * for a particular node are collected their compile functions are executed. The compile
3767 * functions return values - the linking functions - are combined into a composite linking
3768 * function, which is the a linking function for the node.
3770 * @param {NodeList} nodeList an array of nodes to compile
3771 * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
3772 * scope argument is auto-generated to the new child of the transcluded parent scope.
3773 * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
3774 * rootElement must be set the jqLite collection of the compile root. This is
3775 * needed so that the jqLite collection items can be replaced with widgets.
3776 * @param {number=} max directive priority
3777 * @returns {?function} A composite linking function of all of the matched directives or null.
3779 function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) {
3781 nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
3783 for(var i = 0; i < nodeList.length; i++) {
3784 attrs = new Attributes();
3786 // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
3787 directives = collectDirectives(nodeList[i], [], attrs, maxPriority);
3789 nodeLinkFn = (directives.length)
3790 ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
3793 childLinkFn = (nodeLinkFn && nodeLinkFn.terminal)
3795 : compileNodes(nodeList[i].childNodes,
3796 nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
3798 linkFns.push(nodeLinkFn);
3799 linkFns.push(childLinkFn);
3800 linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
3803 // return a linking function if we have found anything, null otherwise
3804 return linkFnFound ? compositeLinkFn : null;
3806 function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
3807 var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn;
3809 for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
3811 nodeLinkFn = linkFns[i++];
3812 childLinkFn = linkFns[i++];
3815 if (nodeLinkFn.scope) {
3816 childScope = scope.$new(isObject(nodeLinkFn.scope));
3817 jqLite(node).data('$scope', childScope);
3821 childTranscludeFn = nodeLinkFn.transclude;
3822 if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
3823 nodeLinkFn(childLinkFn, childScope, node, $rootElement,
3824 (function(transcludeFn) {
3825 return function(cloneFn) {
3826 var transcludeScope = scope.$new();
3828 return transcludeFn(transcludeScope, cloneFn).
3829 bind('$destroy', bind(transcludeScope, transcludeScope.$destroy));
3831 })(childTranscludeFn || transcludeFn)
3834 nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
3836 } else if (childLinkFn) {
3837 childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
3845 * Looks for directives on the given node ands them to the directive collection which is sorted.
3847 * @param node node to search
3848 * @param directives an array to which the directives are added to. This array is sorted before
3849 * the function returns.
3850 * @param attrs the shared attrs object which is used to populate the normalized attributes.
3851 * @param {number=} max directive priority
3853 function collectDirectives(node, directives, attrs, maxPriority) {
3854 var nodeType = node.nodeType,
3855 attrsMap = attrs.$attr,
3860 case 1: /* Element */
3861 // use the node name: <directive>
3862 addDirective(directives,
3863 directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
3865 // iterate over the attributes
3866 for (var attr, name, nName, value, nAttrs = node.attributes,
3867 j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
3869 if (attr.specified) {
3871 nName = directiveNormalize(name.toLowerCase());
3872 attrsMap[nName] = name;
3873 attrs[nName] = value = trim((msie && name == 'href')
3874 ? decodeURIComponent(node.getAttribute(name, 2))
3876 if (getBooleanAttrName(node, nName)) {
3877 attrs[nName] = true; // presence means true
3879 addAttrInterpolateDirective(node, directives, value, nName);
3880 addDirective(directives, nName, 'A', maxPriority);
3884 // use class as directive
3885 className = node.className;
3886 if (isString(className)) {
3887 while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
3888 nName = directiveNormalize(match[2]);
3889 if (addDirective(directives, nName, 'C', maxPriority)) {
3890 attrs[nName] = trim(match[3]);
3892 className = className.substr(match.index + match[0].length);
3896 case 3: /* Text Node */
3897 addTextInterpolateDirective(directives, node.nodeValue);
3899 case 8: /* Comment */
3901 match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
3903 nName = directiveNormalize(match[1]);
3904 if (addDirective(directives, nName, 'M', maxPriority)) {
3905 attrs[nName] = trim(match[2]);
3909 // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
3910 // Just ignore it and continue. (Can't seem to reproduce in test case.)
3915 directives.sort(byPriority);
3921 * Once the directives have been collected their compile functions is executed. This method
3922 * is responsible for inlining directive templates as well as terminating the application
3923 * of the directives if the terminal directive has been reached..
3925 * @param {Array} directives Array of collected directives to execute their compile function.
3926 * this needs to be pre-sorted by priority order.
3927 * @param {Node} compileNode The raw DOM node to apply the compile functions to
3928 * @param {Object} templateAttrs The shared attribute function
3929 * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
3930 * scope argument is auto-generated to the new child of the transcluded parent scope.
3931 * @param {DOMElement} $rootElement If we are working on the root of the compile tree then this
3932 * argument has the root jqLite array so that we can replace widgets on it.
3935 function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) {
3936 var terminalPriority = -Number.MAX_VALUE,
3939 newScopeDirective = null,
3940 newIsolatedScopeDirective = null,
3941 templateDirective = null,
3942 $compileNode = templateAttrs.$$element = jqLite(compileNode),
3946 transcludeDirective,
3947 childTranscludeFn = transcludeFn,
3948 controllerDirectives,
3952 // executes all directives on the current element
3953 for(var i = 0, ii = directives.length; i < ii; i++) {
3954 directive = directives[i];
3955 $template = undefined;
3957 if (terminalPriority > directive.priority) {
3958 break; // prevent further processing of directives
3961 if (directiveValue = directive.scope) {
3962 assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, $compileNode);
3963 if (isObject(directiveValue)) {
3964 safeAddClass($compileNode, 'ng-isolate-scope');
3965 newIsolatedScopeDirective = directive;
3967 safeAddClass($compileNode, 'ng-scope');
3968 newScopeDirective = newScopeDirective || directive;
3971 directiveName = directive.name;
3973 if (directiveValue = directive.controller) {
3974 controllerDirectives = controllerDirectives || {};
3975 assertNoDuplicate("'" + directiveName + "' controller",
3976 controllerDirectives[directiveName], directive, $compileNode);
3977 controllerDirectives[directiveName] = directive;
3980 if (directiveValue = directive.transclude) {
3981 assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
3982 transcludeDirective = directive;
3983 terminalPriority = directive.priority;
3984 if (directiveValue == 'element') {
3985 $template = jqLite(compileNode);
3986 $compileNode = templateAttrs.$$element =
3987 jqLite('<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->');
3988 compileNode = $compileNode[0];
3989 replaceWith($rootElement, jqLite($template[0]), compileNode);
3990 childTranscludeFn = compile($template, transcludeFn, terminalPriority);
3992 $template = jqLite(JQLiteClone(compileNode)).contents();
3993 $compileNode.html(''); // clear contents
3994 childTranscludeFn = compile($template, transcludeFn);
3998 if ((directiveValue = directive.template)) {
3999 assertNoDuplicate('template', templateDirective, directive, $compileNode);
4000 templateDirective = directive;
4001 directiveValue = denormalizeTemplate(directiveValue);
4003 if (directive.replace) {
4004 $template = jqLite('<div>' +
4005 trim(directiveValue) +
4006 '</div>').contents();
4007 compileNode = $template[0];
4009 if ($template.length != 1 || compileNode.nodeType !== 1) {
4010 throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
4013 replaceWith($rootElement, $compileNode, compileNode);
4015 var newTemplateAttrs = {$attr: {}};
4017 // combine directives from the original node and from the template:
4018 // - take the array of directives for this element
4019 // - split it into two parts, those that were already applied and those that weren't
4020 // - collect directives from the template, add them to the second group and sort them
4021 // - append the second group with new directives to the first group
4022 directives = directives.concat(
4025 directives.splice(i + 1, directives.length - (i + 1)),
4029 mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
4031 ii = directives.length;
4033 $compileNode.html(directiveValue);
4037 if (directive.templateUrl) {
4038 assertNoDuplicate('template', templateDirective, directive, $compileNode);
4039 templateDirective = directive;
4040 nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
4041 nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace,
4043 ii = directives.length;
4044 } else if (directive.compile) {
4046 linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
4047 if (isFunction(linkFn)) {
4048 addLinkFns(null, linkFn);
4049 } else if (linkFn) {
4050 addLinkFns(linkFn.pre, linkFn.post);
4053 $exceptionHandler(e, startingTag($compileNode));
4057 if (directive.terminal) {
4058 nodeLinkFn.terminal = true;
4059 terminalPriority = Math.max(terminalPriority, directive.priority);
4064 nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
4065 nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
4067 // might be normal or delayed nodeLinkFn depending on if templateUrl is present
4070 ////////////////////
4072 function addLinkFns(pre, post) {
4074 pre.require = directive.require;
4075 preLinkFns.push(pre);
4078 post.require = directive.require;
4079 postLinkFns.push(post);
4084 function getControllers(require, $element) {
4085 var value, retrievalMethod = 'data', optional = false;
4086 if (isString(require)) {
4087 while((value = require.charAt(0)) == '^' || value == '?') {
4088 require = require.substr(1);
4090 retrievalMethod = 'inheritedData';
4092 optional = optional || value == '?';
4094 value = $element[retrievalMethod]('$' + require + 'Controller');
4095 if (!value && !optional) {
4096 throw Error("No controller: " + require);
4099 } else if (isArray(require)) {
4101 forEach(require, function(require) {
4102 value.push(getControllers(require, $element));
4109 function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
4110 var attrs, $element, i, ii, linkFn, controller;
4112 if (compileNode === linkNode) {
4113 attrs = templateAttrs;
4115 attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
4117 $element = attrs.$$element;
4119 if (newScopeDirective && isObject(newScopeDirective.scope)) {
4120 var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/;
4122 var parentScope = scope.$parent || scope;
4124 forEach(newScopeDirective.scope, function(definiton, scopeName) {
4125 var match = definiton.match(LOCAL_REGEXP) || [],
4126 attrName = match[2]|| scopeName,
4127 mode = match[1], // @, =, or &
4129 parentGet, parentSet;
4134 attrs.$observe(attrName, function(value) {
4135 scope[scopeName] = value;
4137 attrs.$$observers[attrName].$$scope = parentScope;
4142 parentGet = $parse(attrs[attrName]);
4143 parentSet = parentGet.assign || function() {
4144 // reset the change, or we will throw this exception on every $digest
4145 lastValue = scope[scopeName] = parentGet(parentScope);
4146 throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
4147 ' (directive: ' + newScopeDirective.name + ')');
4149 lastValue = scope[scopeName] = parentGet(parentScope);
4150 scope.$watch(function() {
4151 var parentValue = parentGet(parentScope);
4153 if (parentValue !== scope[scopeName]) {
4154 // we are out of sync and need to copy
4155 if (parentValue !== lastValue) {
4156 // parent changed and it has precedence
4157 lastValue = scope[scopeName] = parentValue;
4159 // if the parent can be assigned then do so
4160 parentSet(parentScope, lastValue = scope[scopeName]);
4169 parentGet = $parse(attrs[attrName]);
4170 scope[scopeName] = function(locals) {
4171 return parentGet(parentScope, locals);
4177 throw Error('Invalid isolate scope definition for directive ' +
4178 newScopeDirective.name + ': ' + definiton);
4184 if (controllerDirectives) {
4185 forEach(controllerDirectives, function(directive) {
4190 $transclude: boundTranscludeFn
4193 controller = directive.controller;
4194 if (controller == '@') {
4195 controller = attrs[directive.name];
4199 '$' + directive.name + 'Controller',
4200 $controller(controller, locals));
4205 for(i = 0, ii = preLinkFns.length; i < ii; i++) {
4207 linkFn = preLinkFns[i];
4208 linkFn(scope, $element, attrs,
4209 linkFn.require && getControllers(linkFn.require, $element));
4211 $exceptionHandler(e, startingTag($element));
4216 childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
4219 for(i = 0, ii = postLinkFns.length; i < ii; i++) {
4221 linkFn = postLinkFns[i];
4222 linkFn(scope, $element, attrs,
4223 linkFn.require && getControllers(linkFn.require, $element));
4225 $exceptionHandler(e, startingTag($element));
4233 * looks up the directive and decorates it with exception handling and proper parameters. We
4234 * call this the boundDirective.
4236 * @param {string} name name of the directive to look up.
4237 * @param {string} location The directive must be found in specific format.
4238 * String containing any of theses characters:
4240 * * `E`: element name
4244 * @returns true if directive was added.
4246 function addDirective(tDirectives, name, location, maxPriority) {
4248 if (hasDirectives.hasOwnProperty(name)) {
4249 for(var directive, directives = $injector.get(name + Suffix),
4250 i = 0, ii = directives.length; i<ii; i++) {
4252 directive = directives[i];
4253 if ( (maxPriority === undefined || maxPriority > directive.priority) &&
4254 directive.restrict.indexOf(location) != -1) {
4255 tDirectives.push(directive);
4258 } catch(e) { $exceptionHandler(e); }
4266 * When the element is replaced with HTML template then the new attributes
4267 * on the template need to be merged with the existing attributes in the DOM.
4268 * The desired effect is to have both of the attributes present.
4270 * @param {object} dst destination attributes (original DOM)
4271 * @param {object} src source attributes (from the directive template)
4273 function mergeTemplateAttributes(dst, src) {
4274 var srcAttr = src.$attr,
4275 dstAttr = dst.$attr,
4276 $element = dst.$$element;
4278 // reapply the old attributes to the new element
4279 forEach(dst, function(value, key) {
4280 if (key.charAt(0) != '$') {
4282 value += (key === 'style' ? ';' : ' ') + src[key];
4284 dst.$set(key, value, true, srcAttr[key]);
4288 // copy the new attributes on the old attrs object
4289 forEach(src, function(value, key) {
4290 if (key == 'class') {
4291 safeAddClass($element, value);
4292 dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
4293 } else if (key == 'style') {
4294 $element.attr('style', $element.attr('style') + ';' + value);
4295 } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
4297 dstAttr[key] = srcAttr[key];
4303 function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
4304 $rootElement, replace, childTranscludeFn) {
4306 afterTemplateNodeLinkFn,
4307 afterTemplateChildLinkFn,
4308 beforeTemplateCompileNode = $compileNode[0],
4309 origAsyncDirective = directives.shift(),
4310 // The fact that we have to copy and patch the directive seems wrong!
4311 derivedSyncDirective = extend({}, origAsyncDirective, {
4312 controller: null, templateUrl: null, transclude: null
4315 $compileNode.html('');
4317 $http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
4318 success(function(content) {
4319 var compileNode, tempTemplateAttrs, $template;
4321 content = denormalizeTemplate(content);
4324 $template = jqLite('<div>' + trim(content) + '</div>').contents();
4325 compileNode = $template[0];
4327 if ($template.length != 1 || compileNode.nodeType !== 1) {
4328 throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
4331 tempTemplateAttrs = {$attr: {}};
4332 replaceWith($rootElement, $compileNode, compileNode);
4333 collectDirectives(compileNode, directives, tempTemplateAttrs);
4334 mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
4336 compileNode = beforeTemplateCompileNode;
4337 $compileNode.html(content);
4340 directives.unshift(derivedSyncDirective);
4341 afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn);
4342 afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn);
4345 while(linkQueue.length) {
4346 var controller = linkQueue.pop(),
4347 linkRootElement = linkQueue.pop(),
4348 beforeTemplateLinkNode = linkQueue.pop(),
4349 scope = linkQueue.pop(),
4350 linkNode = compileNode;
4352 if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
4353 // it was cloned therefore we have to clone as well.
4354 linkNode = JQLiteClone(compileNode);
4355 replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
4358 afterTemplateNodeLinkFn(function() {
4359 beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
4360 }, scope, linkNode, $rootElement, controller);
4364 error(function(response, code, headers, config) {
4365 throw Error('Failed to load template: ' + config.url);
4368 return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
4370 linkQueue.push(scope);
4371 linkQueue.push(node);
4372 linkQueue.push(rootElement);
4373 linkQueue.push(controller);
4375 afterTemplateNodeLinkFn(function() {
4376 beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
4377 }, scope, node, rootElement, controller);
4384 * Sorting function for bound directives.
4386 function byPriority(a, b) {
4387 return b.priority - a.priority;
4391 function assertNoDuplicate(what, previousDirective, directive, element) {
4392 if (previousDirective) {
4393 throw Error('Multiple directives [' + previousDirective.name + ', ' +
4394 directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
4399 function addTextInterpolateDirective(directives, text) {
4400 var interpolateFn = $interpolate(text, true);
4401 if (interpolateFn) {
4404 compile: valueFn(function(scope, node) {
4405 var parent = node.parent(),
4406 bindings = parent.data('$binding') || [];
4407 bindings.push(interpolateFn);
4408 safeAddClass(parent.data('$binding', bindings), 'ng-binding');
4409 scope.$watch(interpolateFn, function(value) {
4410 node[0].nodeValue = value;
4418 function addAttrInterpolateDirective(node, directives, value, name) {
4419 var interpolateFn = $interpolate(value, true);
4422 // no interpolation found -> ignore
4423 if (!interpolateFn) return;
4427 compile: valueFn(function(scope, element, attr) {
4428 var $$observers = (attr.$$observers || (attr.$$observers = {}));
4430 if (name === 'class') {
4431 // we need to interpolate classes again, in the case the element was replaced
4432 // and therefore the two class attrs got merged - we want to interpolate the result
4433 interpolateFn = $interpolate(attr[name], true);
4436 attr[name] = undefined;
4437 ($$observers[name] || ($$observers[name] = [])).$$inter = true;
4438 (attr.$$observers && attr.$$observers[name].$$scope || scope).
4439 $watch(interpolateFn, function(value) {
4440 attr.$set(name, value);
4448 * This is a special jqLite.replaceWith, which can replace items which
4449 * have no parents, provided that the containing jqLite collection is provided.
4451 * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
4452 * in the root of the tree.
4453 * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
4454 * but replace its DOM node reference.
4455 * @param {Node} newNode The new DOM node.
4457 function replaceWith($rootElement, $element, newNode) {
4458 var oldNode = $element[0],
4459 parent = oldNode.parentNode,
4463 for(i = 0, ii = $rootElement.length; i < ii; i++) {
4464 if ($rootElement[i] == oldNode) {
4465 $rootElement[i] = newNode;
4472 parent.replaceChild(newNode, oldNode);
4475 newNode[jqLite.expando] = oldNode[jqLite.expando];
4476 $element[0] = newNode;
4481 var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
4483 * Converts all accepted directives format into proper directive name.
4484 * All of these will become 'myDirective':
4490 * Also there is special case for Moz prefix starting with upper case letter.
4491 * @param name Name to normalize
4493 function directiveNormalize(name) {
4494 return camelCase(name.replace(PREFIX_REGEXP, ''));
4499 * @name ng.$compile.directive.Attributes
4502 * A shared object between directive compile / linking functions which contains normalized DOM element
4503 * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
4504 * since all of these are treated as equivalent in Angular:
4506 * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
4511 * @name ng.$compile.directive.Attributes#$attr
4512 * @propertyOf ng.$compile.directive.Attributes
4513 * @returns {object} A map of DOM element attribute names to the normalized name. This is
4514 * needed to do reverse lookup from normalized name back to actual name.
4520 * @name ng.$compile.directive.Attributes#$set
4521 * @methodOf ng.$compile.directive.Attributes
4525 * Set DOM element attribute value.
4528 * @param {string} name Normalized element attribute name of the property to modify. The name is
4529 * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
4530 * property to the original name.
4531 * @param {string} value Value to set the attribute to.
4537 * Closure compiler type information
4540 function nodesetLinkingFn(
4541 /* angular.Scope */ scope,
4542 /* NodeList */ nodeList,
4543 /* Element */ rootElement,
4544 /* function(Function) */ boundTranscludeFn
4547 function directiveLinkingFn(
4548 /* nodesetLinkingFn */ nodesetLinkingFn,
4549 /* angular.Scope */ scope,
4551 /* Element */ rootElement,
4552 /* function(Function) */ boundTranscludeFn
4557 * @name ng.$controllerProvider
4559 * The {@link ng.$controller $controller service} is used by Angular to create new
4562 * This provider allows controller registration via the
4563 * {@link ng.$controllerProvider#register register} method.
4565 function $ControllerProvider() {
4566 var controllers = {};
4571 * @name ng.$controllerProvider#register
4572 * @methodOf ng.$controllerProvider
4573 * @param {string} name Controller name
4574 * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
4575 * annotations in the array notation).
4577 this.register = function(name, constructor) {
4578 if (isObject(name)) {
4579 extend(controllers, name)
4581 controllers[name] = constructor;
4586 this.$get = ['$injector', '$window', function($injector, $window) {
4590 * @name ng.$controller
4591 * @requires $injector
4593 * @param {Function|string} constructor If called with a function then it's considered to be the
4594 * controller constructor function. Otherwise it's considered to be a string which is used
4595 * to retrieve the controller constructor using the following steps:
4597 * * check if a controller with given name is registered via `$controllerProvider`
4598 * * check if evaluating the string on the current scope returns a constructor
4599 * * check `window[constructor]` on the global `window` object
4601 * @param {Object} locals Injection locals for Controller.
4602 * @return {Object} Instance of given controller.
4605 * `$controller` service is responsible for instantiating controllers.
4607 * It's just simple call to {@link AUTO.$injector $injector}, but extracted into
4608 * a service, so that one can override this service with {@link https://gist.github.com/1649788
4611 return function(constructor, locals) {
4612 if(isString(constructor)) {
4613 var name = constructor;
4614 constructor = controllers.hasOwnProperty(name)
4616 : getter(locals.$scope, name, true) || getter($window, name, true);
4618 assertArgFn(constructor, name, true);
4621 return $injector.instantiate(constructor, locals);
4628 * @name ng.$document
4632 * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
4635 function $DocumentProvider(){
4636 this.$get = ['$window', function(window){
4637 return jqLite(window.document);
4643 * @name ng.$exceptionHandler
4647 * Any uncaught exception in angular expressions is delegated to this service.
4648 * The default implementation simply delegates to `$log.error` which logs it into
4649 * the browser console.
4651 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
4652 * {@link ngMock.$exceptionHandler mock $exceptionHandler}
4654 * @param {Error} exception Exception associated with the error.
4655 * @param {string=} cause optional information about the context in which
4656 * the error was thrown.
4658 function $ExceptionHandlerProvider() {
4659 this.$get = ['$log', function($log){
4660 return function(exception, cause) {
4661 $log.error.apply($log, arguments);
4668 * @name ng.$interpolateProvider
4673 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
4675 function $InterpolateProvider() {
4676 var startSymbol = '{{';
4677 var endSymbol = '}}';
4681 * @name ng.$interpolateProvider#startSymbol
4682 * @methodOf ng.$interpolateProvider
4684 * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
4686 * @param {string=} value new value to set the starting symbol to.
4687 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
4689 this.startSymbol = function(value){
4691 startSymbol = value;
4700 * @name ng.$interpolateProvider#endSymbol
4701 * @methodOf ng.$interpolateProvider
4703 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
4705 * @param {string=} value new value to set the ending symbol to.
4706 * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
4708 this.endSymbol = function(value){
4718 this.$get = ['$parse', function($parse) {
4719 var startSymbolLength = startSymbol.length,
4720 endSymbolLength = endSymbol.length;
4724 * @name ng.$interpolate
4731 * Compiles a string with markup into an interpolation function. This service is used by the
4732 * HTML {@link ng.$compile $compile} service for data binding. See
4733 * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
4734 * interpolation markup.
4738 var $interpolate = ...; // injected
4739 var exp = $interpolate('Hello {{name}}!');
4740 expect(exp({name:'Angular'}).toEqual('Hello Angular!');
4744 * @param {string} text The text with markup to interpolate.
4745 * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
4746 * embedded expression in order to return an interpolation function. Strings with no
4747 * embedded expression will return null for the interpolation function.
4748 * @returns {function(context)} an interpolation function which is used to compute the interpolated
4749 * string. The function has these parameters:
4751 * * `context`: an object against which any expressions embedded in the strings are evaluated
4755 function $interpolate(text, mustHaveExpression) {
4760 length = text.length,
4761 hasInterpolation = false,
4766 while(index < length) {
4767 if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
4768 ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
4769 (index != startIndex) && parts.push(text.substring(index, startIndex));
4770 parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
4772 index = endIndex + endSymbolLength;
4773 hasInterpolation = true;
4775 // we did not find anything, so we have to add the remainder to the parts array
4776 (index != length) && parts.push(text.substring(index));
4781 if (!(length = parts.length)) {
4782 // we added, nothing, must have been an empty string.
4787 if (!mustHaveExpression || hasInterpolation) {
4788 concat.length = length;
4789 fn = function(context) {
4790 for(var i = 0, ii = length, part; i<ii; i++) {
4791 if (typeof (part = parts[i]) == 'function') {
4792 part = part(context);
4793 if (part == null || part == undefined) {
4795 } else if (typeof part != 'string') {
4796 part = toJson(part);
4801 return concat.join('');
4812 * @name ng.$interpolate#startSymbol
4813 * @methodOf ng.$interpolate
4815 * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
4817 * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
4820 * @returns {string} start symbol.
4822 $interpolate.startSymbol = function() {
4829 * @name ng.$interpolate#endSymbol
4830 * @methodOf ng.$interpolate
4832 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
4834 * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
4837 * @returns {string} start symbol.
4839 $interpolate.endSymbol = function() {
4843 return $interpolate;
4847 var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
4848 PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
4849 HASH_MATCH = PATH_MATCH,
4850 DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
4854 * Encode path using encodeUriSegment, ignoring forward slashes
4856 * @param {string} path Path to encode
4859 function encodePath(path) {
4860 var segments = path.split('/'),
4861 i = segments.length;
4864 segments[i] = encodeUriSegment(segments[i]);
4867 return segments.join('/');
4870 function stripHash(url) {
4871 return url.split('#')[0];
4875 function matchUrl(url, obj) {
4876 var match = URL_MATCH.exec(url);
4881 port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
4882 path: match[6] || '/',
4888 obj.$$protocol = match.protocol;
4889 obj.$$host = match.host;
4890 obj.$$port = match.port;
4897 function composeProtocolHostPort(protocol, host, port) {
4898 return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
4902 function pathPrefixFromBase(basePath) {
4903 return basePath.substr(0, basePath.lastIndexOf('/'));
4907 function convertToHtml5Url(url, basePath, hashPrefix) {
4908 var match = matchUrl(url);
4910 // already html5 url
4911 if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
4912 match.hash.indexOf(hashPrefix) !== 0) {
4914 // convert hashbang url -> html5 url
4916 return composeProtocolHostPort(match.protocol, match.host, match.port) +
4917 pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
4922 function convertToHashbangUrl(url, basePath, hashPrefix) {
4923 var match = matchUrl(url);
4925 // already hashbang url
4926 if (decodeURIComponent(match.path) == basePath) {
4928 // convert html5 url -> hashbang url
4930 var search = match.search && '?' + match.search || '',
4931 hash = match.hash && '#' + match.hash || '',
4932 pathPrefix = pathPrefixFromBase(basePath),
4933 path = match.path.substr(pathPrefix.length);
4935 if (match.path.indexOf(pathPrefix) !== 0) {
4936 throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
4939 return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
4940 '#' + hashPrefix + path + search + hash;
4946 * LocationUrl represents an url
4947 * This object is exposed as $location service when HTML5 mode is enabled and supported
4950 * @param {string} url HTML5 url
4951 * @param {string} pathPrefix
4953 function LocationUrl(url, pathPrefix, appBaseUrl) {
4954 pathPrefix = pathPrefix || '';
4957 * Parse given html5 (regular) url string into properties
4958 * @param {string} newAbsoluteUrl HTML5 url
4961 this.$$parse = function(newAbsoluteUrl) {
4962 var match = matchUrl(newAbsoluteUrl, this);
4964 if (match.path.indexOf(pathPrefix) !== 0) {
4965 throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
4968 this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
4969 this.$$search = parseKeyValue(match.search);
4970 this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
4976 * Compose url and update `absUrl` property
4979 this.$$compose = function() {
4980 var search = toKeyValue(this.$$search),
4981 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
4983 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
4984 this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
4985 pathPrefix + this.$$url;
4989 this.$$rewriteAppUrl = function(absoluteLinkUrl) {
4990 if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
4991 return absoluteLinkUrl;
5001 * LocationHashbangUrl represents url
5002 * This object is exposed as $location service when html5 history api is disabled or not supported
5005 * @param {string} url Legacy url
5006 * @param {string} hashPrefix Prefix for hash part (containing path and search)
5008 function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
5012 * Parse given hashbang url into properties
5013 * @param {string} url Hashbang url
5016 this.$$parse = function(url) {
5017 var match = matchUrl(url, this);
5020 if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
5021 throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
5024 basePath = match.path + (match.search ? '?' + match.search : '');
5025 match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
5027 this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
5032 this.$$search = parseKeyValue(match[3]);
5033 this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
5039 * Compose hashbang url and update `absUrl` property
5042 this.$$compose = function() {
5043 var search = toKeyValue(this.$$search),
5044 hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
5046 this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
5047 this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
5048 basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
5051 this.$$rewriteAppUrl = function(absoluteLinkUrl) {
5052 if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
5053 return absoluteLinkUrl;
5062 LocationUrl.prototype = {
5065 * Has any change been replacing ?
5072 * @name ng.$location#absUrl
5073 * @methodOf ng.$location
5076 * This method is getter only.
5078 * Return full url representation with all segments encoded according to rules specified in
5079 * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
5081 * @return {string} full url
5083 absUrl: locationGetter('$$absUrl'),
5087 * @name ng.$location#url
5088 * @methodOf ng.$location
5091 * This method is getter / setter.
5093 * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
5095 * Change path, search and hash, when called with parameter and return `$location`.
5097 * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
5098 * @return {string} url
5100 url: function(url, replace) {
5101 if (isUndefined(url))
5104 var match = PATH_MATCH.exec(url);
5105 if (match[1]) this.path(decodeURIComponent(match[1]));
5106 if (match[2] || match[1]) this.search(match[3] || '');
5107 this.hash(match[5] || '', replace);
5114 * @name ng.$location#protocol
5115 * @methodOf ng.$location
5118 * This method is getter only.
5120 * Return protocol of current url.
5122 * @return {string} protocol of current url
5124 protocol: locationGetter('$$protocol'),
5128 * @name ng.$location#host
5129 * @methodOf ng.$location
5132 * This method is getter only.
5134 * Return host of current url.
5136 * @return {string} host of current url.
5138 host: locationGetter('$$host'),
5142 * @name ng.$location#port
5143 * @methodOf ng.$location
5146 * This method is getter only.
5148 * Return port of current url.
5150 * @return {Number} port
5152 port: locationGetter('$$port'),
5156 * @name ng.$location#path
5157 * @methodOf ng.$location
5160 * This method is getter / setter.
5162 * Return path of current url when called without any parameter.
5164 * Change path when called with parameter and return `$location`.
5166 * Note: Path should always begin with forward slash (/), this method will add the forward slash
5169 * @param {string=} path New path
5170 * @return {string} path
5172 path: locationGetterSetter('$$path', function(path) {
5173 return path.charAt(0) == '/' ? path : '/' + path;
5178 * @name ng.$location#search
5179 * @methodOf ng.$location
5182 * This method is getter / setter.
5184 * Return search part (as object) of current url when called without any parameter.
5186 * Change search part when called with parameter and return `$location`.
5188 * @param {string|object<string,string>=} search New search params - string or hash object
5189 * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
5190 * single search parameter. If the value is `null`, the parameter will be deleted.
5192 * @return {string} search
5194 search: function(search, paramValue) {
5195 if (isUndefined(search))
5196 return this.$$search;
5198 if (isDefined(paramValue)) {
5199 if (paramValue === null) {
5200 delete this.$$search[search];
5202 this.$$search[search] = paramValue;
5205 this.$$search = isString(search) ? parseKeyValue(search) : search;
5214 * @name ng.$location#hash
5215 * @methodOf ng.$location
5218 * This method is getter / setter.
5220 * Return hash fragment when called without any parameter.
5222 * Change hash fragment when called with parameter and return `$location`.
5224 * @param {string=} hash New hash fragment
5225 * @return {string} hash
5227 hash: locationGetterSetter('$$hash', identity),
5231 * @name ng.$location#replace
5232 * @methodOf ng.$location
5235 * If called, all changes to $location during current `$digest` will be replacing current history
5236 * record, instead of adding new one.
5238 replace: function() {
5239 this.$$replace = true;
5244 LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
5246 function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
5247 LocationHashbangUrl.apply(this, arguments);
5250 this.$$rewriteAppUrl = function(absoluteLinkUrl) {
5251 if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
5252 return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
5257 LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
5259 function locationGetter(property) {
5261 return this[property];
5266 function locationGetterSetter(property, preprocess) {
5267 return function(value) {
5268 if (isUndefined(value))
5269 return this[property];
5271 this[property] = preprocess(value);
5281 * @name ng.$location
5283 * @requires $browser
5284 * @requires $sniffer
5285 * @requires $rootElement
5288 * The $location service parses the URL in the browser address bar (based on the
5289 * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
5290 * available to your application. Changes to the URL in the address bar are reflected into
5291 * $location service and changes to $location are reflected into the browser address bar.
5293 * **The $location service:**
5295 * - Exposes the current URL in the browser address bar, so you can
5296 * - Watch and observe the URL.
5298 * - Synchronizes the URL with the browser when the user
5299 * - Changes the address bar.
5300 * - Clicks the back or forward button (or clicks a History link).
5301 * - Clicks on a link.
5302 * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
5304 * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
5305 * Services: Using $location}
5310 * @name ng.$locationProvider
5312 * Use the `$locationProvider` to configure how the application deep linking paths are stored.
5314 function $LocationProvider(){
5315 var hashPrefix = '',
5320 * @name ng.$locationProvider#hashPrefix
5321 * @methodOf ng.$locationProvider
5323 * @param {string=} prefix Prefix for hash part (containing path and search)
5324 * @returns {*} current value if used as getter or itself (chaining) if used as setter
5326 this.hashPrefix = function(prefix) {
5327 if (isDefined(prefix)) {
5328 hashPrefix = prefix;
5337 * @name ng.$locationProvider#html5Mode
5338 * @methodOf ng.$locationProvider
5340 * @param {string=} mode Use HTML5 strategy if available.
5341 * @returns {*} current value if used as getter or itself (chaining) if used as setter
5343 this.html5Mode = function(mode) {
5344 if (isDefined(mode)) {
5352 this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
5353 function( $rootScope, $browser, $sniffer, $rootElement) {
5357 initUrl = $browser.url(),
5358 initUrlParts = matchUrl(initUrl),
5362 basePath = $browser.baseHref() || '/';
5363 pathPrefix = pathPrefixFromBase(basePath);
5365 composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
5368 if ($sniffer.history) {
5369 $location = new LocationUrl(
5370 convertToHtml5Url(initUrl, basePath, hashPrefix),
5371 pathPrefix, appBaseUrl);
5373 $location = new LocationHashbangInHtml5Url(
5374 convertToHashbangUrl(initUrl, basePath, hashPrefix),
5375 hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
5379 composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
5380 (initUrlParts.path || '') +
5381 (initUrlParts.search ? ('?' + initUrlParts.search) : '') +
5382 '#' + hashPrefix + '/';
5384 $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
5387 $rootElement.bind('click', function(event) {
5388 // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
5389 // currently we open nice url link and redirect then
5391 if (event.ctrlKey || event.metaKey || event.which == 2) return;
5393 var elm = jqLite(event.target);
5395 // traverse the DOM up to find first A tag
5396 while (lowercase(elm[0].nodeName) !== 'a') {
5397 // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
5398 if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
5401 var absHref = elm.prop('href'),
5402 rewrittenUrl = $location.$$rewriteAppUrl(absHref);
5404 if (absHref && !elm.attr('target') && rewrittenUrl) {
5405 // update location manually
5406 $location.$$parse(rewrittenUrl);
5407 $rootScope.$apply();
5408 event.preventDefault();
5409 // hack to work around FF6 bug 684208 when scenario runner clicks on links
5410 window.angular['ff-684208-preventDefault'] = true;
5415 // rewrite hashbang url <> html5 url
5416 if ($location.absUrl() != initUrl) {
5417 $browser.url($location.absUrl(), true);
5420 // update $location when $browser url changes
5421 $browser.onUrlChange(function(newUrl) {
5422 if ($location.absUrl() != newUrl) {
5423 $rootScope.$evalAsync(function() {
5424 var oldUrl = $location.absUrl();
5426 $location.$$parse(newUrl);
5427 afterLocationChange(oldUrl);
5429 if (!$rootScope.$$phase) $rootScope.$digest();
5434 var changeCounter = 0;
5435 $rootScope.$watch(function $locationWatch() {
5436 var oldUrl = $browser.url();
5438 if (!changeCounter || oldUrl != $location.absUrl()) {
5440 $rootScope.$evalAsync(function() {
5441 if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
5443 $location.$$parse(oldUrl);
5445 $browser.url($location.absUrl(), $location.$$replace);
5446 $location.$$replace = false;
5447 afterLocationChange(oldUrl);
5452 return changeCounter;
5457 function afterLocationChange(oldUrl) {
5458 $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
5469 * Simple service for logging. Default implementation writes the message
5470 * into the browser's console (if present).
5472 * The main purpose of this service is to simplify debugging and troubleshooting.
5476 <file name="script.js">
5477 function LogCtrl($scope, $log) {
5479 $scope.message = 'Hello World!';
5482 <file name="index.html">
5483 <div ng-controller="LogCtrl">
5484 <p>Reload this page with open console, enter text and hit the log button...</p>
5486 <input type="text" ng-model="message"/>
5487 <button ng-click="$log.log(message)">log</button>
5488 <button ng-click="$log.warn(message)">warn</button>
5489 <button ng-click="$log.info(message)">info</button>
5490 <button ng-click="$log.error(message)">error</button>
5496 function $LogProvider(){
5497 this.$get = ['$window', function($window){
5505 * Write a log message
5507 log: consoleLog('log'),
5511 * @name ng.$log#warn
5515 * Write a warning message
5517 warn: consoleLog('warn'),
5521 * @name ng.$log#info
5525 * Write an information message
5527 info: consoleLog('info'),
5531 * @name ng.$log#error
5535 * Write an error message
5537 error: consoleLog('error')
5540 function formatError(arg) {
5541 if (arg instanceof Error) {
5543 arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
5544 ? 'Error: ' + arg.message + '\n' + arg.stack
5546 } else if (arg.sourceURL) {
5547 arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
5553 function consoleLog(type) {
5554 var console = $window.console || {},
5555 logFn = console[type] || console.log || noop;
5560 forEach(arguments, function(arg) {
5561 args.push(formatError(arg));
5563 return logFn.apply(console, args);
5567 // we are IE which either doesn't have window.console => this is noop and we do nothing,
5568 // or we are IE where console.log doesn't have apply so we log at least first 2 args
5569 return function(arg1, arg2) {
5577 'null':function(){return null;},
5578 'true':function(){return true;},
5579 'false':function(){return false;},
5581 '+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);},
5582 '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
5583 '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
5584 '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
5585 '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
5586 '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
5588 '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
5589 '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
5590 '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
5591 '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
5592 '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
5593 '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
5594 '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
5595 '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
5596 '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
5597 // '|':function(self, locals, a,b){return a|b;},
5598 '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
5599 '!':function(self, locals, a){return !a(self, locals);}
5601 var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
5603 function lex(text, csp){
5609 lastCh = ':'; // can start regexp
5611 while (index < text.length) {
5612 ch = text.charAt(index);
5615 } else if (isNumber(ch) || is('.') && isNumber(peek())) {
5617 } else if (isIdent(ch)) {
5619 // identifiers can only be if the preceding char was a { or ,
5620 if (was('{,') && json[0]=='{' &&
5621 (token=tokens[tokens.length-1])) {
5622 token.json = token.text.indexOf('.') == -1;
5624 } else if (is('(){}[].,;:')) {
5628 json:(was(':[,') && is('{[')) || is('}]:,')
5630 if (is('{[')) json.unshift(ch);
5631 if (is('}]')) json.shift();
5633 } else if (isWhitespace(ch)) {
5637 var ch2 = ch + peek(),
5639 fn2 = OPERATORS[ch2];
5641 tokens.push({index:index, text:ch2, fn:fn2});
5644 tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
5647 throwError("Unexpected next character ", index, index+1);
5654 function is(chars) {
5655 return chars.indexOf(ch) != -1;
5658 function was(chars) {
5659 return chars.indexOf(lastCh) != -1;
5663 return index + 1 < text.length ? text.charAt(index + 1) : false;
5665 function isNumber(ch) {
5666 return '0' <= ch && ch <= '9';
5668 function isWhitespace(ch) {
5669 return ch == ' ' || ch == '\r' || ch == '\t' ||
5670 ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
5672 function isIdent(ch) {
5673 return 'a' <= ch && ch <= 'z' ||
5674 'A' <= ch && ch <= 'Z' ||
5675 '_' == ch || ch == '$';
5677 function isExpOperator(ch) {
5678 return ch == '-' || ch == '+' || isNumber(ch);
5681 function throwError(error, start, end) {
5683 throw Error("Lexer Error: " + error + " at column" +
5685 ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
5687 " in expression [" + text + "].");
5690 function readNumber() {
5693 while (index < text.length) {
5694 var ch = lowercase(text.charAt(index));
5695 if (ch == '.' || isNumber(ch)) {
5698 var peekCh = peek();
5699 if (ch == 'e' && isExpOperator(peekCh)) {
5701 } else if (isExpOperator(ch) &&
5702 peekCh && isNumber(peekCh) &&
5703 number.charAt(number.length - 1) == 'e') {
5705 } else if (isExpOperator(ch) &&
5706 (!peekCh || !isNumber(peekCh)) &&
5707 number.charAt(number.length - 1) == 'e') {
5708 throwError('Invalid exponent');
5715 number = 1 * number;
5716 tokens.push({index:start, text:number, json:true,
5717 fn:function() {return number;}});
5719 function readIdent() {
5722 lastDot, peekIndex, methodName;
5724 while (index < text.length) {
5725 var ch = text.charAt(index);
5726 if (ch == '.' || isIdent(ch) || isNumber(ch)) {
5727 if (ch == '.') lastDot = index;
5735 //check if this is not a method invocation and if it is back out to last dot
5738 while(peekIndex < text.length) {
5739 var ch = text.charAt(peekIndex);
5741 methodName = ident.substr(lastDot - start + 1);
5742 ident = ident.substr(0, lastDot - start);
5746 if(isWhitespace(ch)) {
5760 if (OPERATORS.hasOwnProperty(ident)) {
5761 token.fn = token.json = OPERATORS[ident];
5763 var getter = getterFn(ident, csp);
5764 token.fn = extend(function(self, locals) {
5765 return (getter(self, locals));
5767 assign: function(self, value) {
5768 return setter(self, ident, value);
5789 function readString(quote) {
5793 var rawString = quote;
5795 while (index < text.length) {
5796 var ch = text.charAt(index);
5800 var hex = text.substring(index + 1, index + 5);
5801 if (!hex.match(/[\da-f]{4}/i))
5802 throwError( "Invalid unicode escape [\\u" + hex + "]");
5804 string += String.fromCharCode(parseInt(hex, 16));
5806 var rep = ESCAPE[ch];
5814 } else if (ch == '\\') {
5816 } else if (ch == quote) {
5823 fn:function() { return string; }
5831 throwError("Unterminated quote", start);
5835 /////////////////////////////////////////
5837 function parser(text, json, $filter, csp){
5838 var ZERO = valueFn(0),
5840 tokens = lex(text, csp),
5841 assignment = _assignment,
5842 functionCall = _functionCall,
5843 fieldAccess = _fieldAccess,
5844 objectIndex = _objectIndex,
5845 filterChain = _filterChain;
5848 // The extra level of aliasing is here, just in case the lexer misses something, so that
5849 // we prevent any accidental execution in JSON.
5850 assignment = logicalOR;
5855 function() { throwError("is not valid json", {text:text, index:0}); };
5858 value = statements();
5860 if (tokens.length !== 0) {
5861 throwError("is an unexpected token", tokens[0]);
5865 ///////////////////////////////////
5866 function throwError(msg, token) {
5867 throw Error("Syntax Error: Token '" + token.text +
5868 "' " + msg + " at column " +
5869 (token.index + 1) + " of the expression [" +
5870 text + "] starting at [" + text.substring(token.index) + "].");
5873 function peekToken() {
5874 if (tokens.length === 0)
5875 throw Error("Unexpected end of expression: " + text);
5879 function peek(e1, e2, e3, e4) {
5880 if (tokens.length > 0) {
5881 var token = tokens[0];
5883 if (t==e1 || t==e2 || t==e3 || t==e4 ||
5884 (!e1 && !e2 && !e3 && !e4)) {
5891 function expect(e1, e2, e3, e4){
5892 var token = peek(e1, e2, e3, e4);
5894 if (json && !token.json) {
5895 throwError("is not valid json", token);
5903 function consume(e1){
5905 throwError("is unexpected, expecting [" + e1 + "]", peek());
5909 function unaryFn(fn, right) {
5910 return function(self, locals) {
5911 return fn(self, locals, right);
5915 function binaryFn(left, fn, right) {
5916 return function(self, locals) {
5917 return fn(self, locals, left, right);
5921 function statements() {
5922 var statements = [];
5924 if (tokens.length > 0 && !peek('}', ')', ';', ']'))
5925 statements.push(filterChain());
5927 // optimize for the common case where there is only one statement.
5928 // TODO(size): maybe we should not support multiple statements?
5929 return statements.length == 1
5931 : function(self, locals){
5933 for ( var i = 0; i < statements.length; i++) {
5934 var statement = statements[i];
5936 value = statement(self, locals);
5944 function _filterChain() {
5945 var left = expression();
5948 if ((token = expect('|'))) {
5949 left = binaryFn(left, token.fn, filter());
5957 var token = expect();
5958 var fn = $filter(token.text);
5961 if ((token = expect(':'))) {
5962 argsFn.push(expression());
5964 var fnInvoke = function(self, locals, input){
5966 for ( var i = 0; i < argsFn.length; i++) {
5967 args.push(argsFn[i](self, locals));
5969 return fn.apply(self, args);
5978 function expression() {
5979 return assignment();
5982 function _assignment() {
5983 var left = logicalOR();
5986 if ((token = expect('='))) {
5988 throwError("implies assignment but [" +
5989 text.substring(0, token.index) + "] can not be assigned to", token);
5991 right = logicalOR();
5992 return function(self, locals){
5993 return left.assign(self, right(self, locals), locals);
6000 function logicalOR() {
6001 var left = logicalAND();
6004 if ((token = expect('||'))) {
6005 left = binaryFn(left, token.fn, logicalAND());
6012 function logicalAND() {
6013 var left = equality();
6015 if ((token = expect('&&'))) {
6016 left = binaryFn(left, token.fn, logicalAND());
6021 function equality() {
6022 var left = relational();
6024 if ((token = expect('==','!='))) {
6025 left = binaryFn(left, token.fn, equality());
6030 function relational() {
6031 var left = additive();
6033 if ((token = expect('<', '>', '<=', '>='))) {
6034 left = binaryFn(left, token.fn, relational());
6039 function additive() {
6040 var left = multiplicative();
6042 while ((token = expect('+','-'))) {
6043 left = binaryFn(left, token.fn, multiplicative());
6048 function multiplicative() {
6051 while ((token = expect('*','/','%'))) {
6052 left = binaryFn(left, token.fn, unary());
6061 } else if ((token = expect('-'))) {
6062 return binaryFn(ZERO, token.fn, unary());
6063 } else if ((token = expect('!'))) {
6064 return unaryFn(token.fn, unary());
6071 function primary() {
6074 primary = filterChain();
6076 } else if (expect('[')) {
6077 primary = arrayDeclaration();
6078 } else if (expect('{')) {
6081 var token = expect();
6084 throwError("not a primary expression", token);
6089 while ((next = expect('(', '[', '.'))) {
6090 if (next.text === '(') {
6091 primary = functionCall(primary, context);
6093 } else if (next.text === '[') {
6095 primary = objectIndex(primary);
6096 } else if (next.text === '.') {
6098 primary = fieldAccess(primary);
6100 throwError("IMPOSSIBLE");
6106 function _fieldAccess(object) {
6107 var field = expect().text;
6108 var getter = getterFn(field, csp);
6110 function(self, locals) {
6111 return getter(object(self, locals), locals);
6114 assign:function(self, value, locals) {
6115 return setter(object(self, locals), field, value);
6121 function _objectIndex(obj) {
6122 var indexFn = expression();
6125 function(self, locals){
6126 var o = obj(self, locals),
6127 i = indexFn(self, locals),
6130 if (!o) return undefined;
6134 if (!('$$v' in v)) {
6136 p.then(function(val) { p.$$v = val; });
6142 assign:function(self, value, locals){
6143 return obj(self, locals)[indexFn(self, locals)] = value;
6148 function _functionCall(fn, contextGetter) {
6150 if (peekToken().text != ')') {
6152 argsFn.push(expression());
6153 } while (expect(','));
6156 return function(self, locals){
6158 context = contextGetter ? contextGetter(self, locals) : self;
6160 for ( var i = 0; i < argsFn.length; i++) {
6161 args.push(argsFn[i](self, locals));
6163 var fnPtr = fn(self, locals) || noop;
6166 ? fnPtr.apply(context, args)
6167 : fnPtr(args[0], args[1], args[2], args[3], args[4]);
6171 // This is used with json array declaration
6172 function arrayDeclaration () {
6173 var elementFns = [];
6174 if (peekToken().text != ']') {
6176 elementFns.push(expression());
6177 } while (expect(','));
6180 return function(self, locals){
6182 for ( var i = 0; i < elementFns.length; i++) {
6183 array.push(elementFns[i](self, locals));
6189 function object () {
6191 if (peekToken().text != '}') {
6193 var token = expect(),
6194 key = token.string || token.text;
6196 var value = expression();
6197 keyValues.push({key:key, value:value});
6198 } while (expect(','));
6201 return function(self, locals){
6203 for ( var i = 0; i < keyValues.length; i++) {
6204 var keyValue = keyValues[i];
6205 var value = keyValue.value(self, locals);
6206 object[keyValue.key] = value;
6213 //////////////////////////////////////////////////
6214 // Parser helper functions
6215 //////////////////////////////////////////////////
6217 function setter(obj, path, setValue) {
6218 var element = path.split('.');
6219 for (var i = 0; element.length > 1; i++) {
6220 var key = element.shift();
6221 var propertyObj = obj[key];
6224 obj[key] = propertyObj;
6228 obj[element.shift()] = setValue;
6233 * Return the value accesible from the object by path. Any undefined traversals are ignored
6234 * @param {Object} obj starting object
6235 * @param {string} path path to traverse
6236 * @param {boolean=true} bindFnToScope
6237 * @returns value as accesbile by path
6239 //TODO(misko): this function needs to be removed
6240 function getter(obj, path, bindFnToScope) {
6241 if (!path) return obj;
6242 var keys = path.split('.');
6244 var lastInstance = obj;
6245 var len = keys.length;
6247 for (var i = 0; i < len; i++) {
6250 obj = (lastInstance = obj)[key];
6253 if (!bindFnToScope && isFunction(obj)) {
6254 return bind(lastInstance, obj);
6259 var getterFnCache = {};
6262 * Implementation of the "Black Hole" variant from:
6263 * - http://jsperf.com/angularjs-parse-getter/4
6264 * - http://jsperf.com/path-evaluation-simplified/7
6266 function cspSafeGetterFn(key0, key1, key2, key3, key4) {
6267 return function(scope, locals) {
6268 var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
6271 if (pathVal === null || pathVal === undefined) return pathVal;
6273 pathVal = pathVal[key0];
6274 if (pathVal && pathVal.then) {
6275 if (!("$$v" in pathVal)) {
6277 promise.$$v = undefined;
6278 promise.then(function(val) { promise.$$v = val; });
6280 pathVal = pathVal.$$v;
6282 if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
6284 pathVal = pathVal[key1];
6285 if (pathVal && pathVal.then) {
6286 if (!("$$v" in pathVal)) {
6288 promise.$$v = undefined;
6289 promise.then(function(val) { promise.$$v = val; });
6291 pathVal = pathVal.$$v;
6293 if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
6295 pathVal = pathVal[key2];
6296 if (pathVal && pathVal.then) {
6297 if (!("$$v" in pathVal)) {
6299 promise.$$v = undefined;
6300 promise.then(function(val) { promise.$$v = val; });
6302 pathVal = pathVal.$$v;
6304 if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
6306 pathVal = pathVal[key3];
6307 if (pathVal && pathVal.then) {
6308 if (!("$$v" in pathVal)) {
6310 promise.$$v = undefined;
6311 promise.then(function(val) { promise.$$v = val; });
6313 pathVal = pathVal.$$v;
6315 if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
6317 pathVal = pathVal[key4];
6318 if (pathVal && pathVal.then) {
6319 if (!("$$v" in pathVal)) {
6321 promise.$$v = undefined;
6322 promise.then(function(val) { promise.$$v = val; });
6324 pathVal = pathVal.$$v;
6330 function getterFn(path, csp) {
6331 if (getterFnCache.hasOwnProperty(path)) {
6332 return getterFnCache[path];
6335 var pathKeys = path.split('.'),
6336 pathKeysLength = pathKeys.length,
6340 fn = (pathKeysLength < 6)
6341 ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
6342 : function(scope, locals) {
6345 val = cspSafeGetterFn(
6346 pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
6349 locals = undefined; // clear after first iteration
6351 } while (i < pathKeysLength);
6355 var code = 'var l, fn, p;\n';
6356 forEach(pathKeys, function(key, index) {
6357 code += 'if(s === null || s === undefined) return s;\n' +
6360 // we simply dereference 's' on any .dot notation
6362 // but if we are first then we check locals first, and if so read it first
6363 : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
6364 'if (s && s.then) {\n' +
6365 ' if (!("$$v" in s)) {\n' +
6367 ' p.$$v = undefined;\n' +
6368 ' p.then(function(v) {p.$$v=v;});\n' +
6373 code += 'return s;';
6374 fn = Function('s', 'k', code); // s=scope, k=locals
6375 fn.toString = function() { return code; };
6378 return getterFnCache[path] = fn;
6381 ///////////////////////////////////
6390 * Converts Angular {@link guide/expression expression} into a function.
6393 * var getter = $parse('user.name');
6394 * var setter = getter.assign;
6395 * var context = {user:{name:'angular'}};
6396 * var locals = {user:{name:'local'}};
6398 * expect(getter(context)).toEqual('angular');
6399 * setter(context, 'newValue');
6400 * expect(context.user.name).toEqual('newValue');
6401 * expect(getter(context, locals)).toEqual('local');
6405 * @param {string} expression String expression to compile.
6406 * @returns {function(context, locals)} a function which represents the compiled expression:
6408 * * `context`: an object against which any expressions embedded in the strings are evaluated
6409 * against (Topically a scope object).
6410 * * `locals`: local variables context object, useful for overriding values in `context`.
6412 * The return function also has an `assign` property, if the expression is assignable, which
6413 * allows one to set values to expressions.
6416 function $ParseProvider() {
6418 this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
6419 return function(exp) {
6420 switch(typeof exp) {
6422 return cache.hasOwnProperty(exp)
6424 : cache[exp] = parser(exp, false, $filter, $sniffer.csp);
6437 * @requires $rootScope
6440 * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
6442 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
6443 * interface for interacting with an object that represents the result of an action that is
6444 * performed asynchronously, and may or may not be finished at any given point in time.
6446 * From the perspective of dealing with error handling, deferred and promise apis are to
6447 * asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing.
6450 * // for the purpose of this example let's assume that variables `$q` and `scope` are
6451 * // available in the current lexical scope (they could have been injected or passed in).
6453 * function asyncGreet(name) {
6454 * var deferred = $q.defer();
6456 * setTimeout(function() {
6457 * // since this fn executes async in a future turn of the event loop, we need to wrap
6458 * // our code into an $apply call so that the model changes are properly observed.
6459 * scope.$apply(function() {
6460 * if (okToGreet(name)) {
6461 * deferred.resolve('Hello, ' + name + '!');
6463 * deferred.reject('Greeting ' + name + ' is not allowed.');
6468 * return deferred.promise;
6471 * var promise = asyncGreet('Robin Hood');
6472 * promise.then(function(greeting) {
6473 * alert('Success: ' + greeting);
6474 * }, function(reason) {
6475 * alert('Failed: ' + reason);
6479 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
6480 * comes in the way of
6481 * [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
6483 * Additionally the promise api allows for composition that is very hard to do with the
6484 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
6485 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
6486 * section on serial or parallel joining of promises.
6489 * # The Deferred API
6491 * A new instance of deferred is constructed by calling `$q.defer()`.
6493 * The purpose of the deferred object is to expose the associated Promise instance as well as apis
6494 * that can be used for signaling the successful or unsuccessful completion of the task.
6498 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
6499 * constructed via `$q.reject`, the promise will be rejected instead.
6500 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
6501 * resolving it with a rejection constructed via `$q.reject`.
6505 * - promise – `{Promise}` – promise object associated with this deferred.
6510 * A new promise instance is created when a deferred instance is created and can be retrieved by
6511 * calling `deferred.promise`.
6513 * The purpose of the promise object is to allow for interested parties to get access to the result
6514 * of the deferred task when it completes.
6518 * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
6519 * or rejected calls one of the success or error callbacks asynchronously as soon as the result
6520 * is available. The callbacks are called with a single argument the result or rejection reason.
6522 * This method *returns a new promise* which is resolved or rejected via the return value of the
6523 * `successCallback` or `errorCallback`.
6526 * # Chaining promises
6528 * Because calling `then` api of a promise returns a new derived promise, it is easily possible
6529 * to create a chain of promises:
6532 * promiseB = promiseA.then(function(result) {
6533 * return result + 1;
6536 * // promiseB will be resolved immediately after promiseA is resolved and it's value will be
6537 * // the result of promiseA incremented by 1
6540 * It is possible to create chains of any length and since a promise can be resolved with another
6541 * promise (which will defer its resolution further), it is possible to pause/defer resolution of
6542 * the promises at any point in the chain. This makes it possible to implement powerful apis like
6543 * $http's response interceptors.
6546 * # Differences between Kris Kowal's Q and $q
6548 * There are three main differences:
6550 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
6551 * mechanism in angular, which means faster propagation of resolution or rejection into your
6552 * models and avoiding unnecessary browser repaints, which would result in flickering UI.
6553 * - $q promises are recognized by the templating engine in angular, which means that in templates
6554 * you can treat promises attached to a scope as if they were the resulting values.
6555 * - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
6556 * all the important functionality needed for common async tasks.
6558 function $QProvider() {
6560 this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
6561 return qFactory(function(callback) {
6562 $rootScope.$evalAsync(callback);
6563 }, $exceptionHandler);
6569 * Constructs a promise manager.
6571 * @param {function(function)} nextTick Function for executing functions in the next turn.
6572 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
6573 * debugging purposes.
6574 * @returns {object} Promise manager.
6576 function qFactory(nextTick, exceptionHandler) {
6583 * Creates a `Deferred` object which represents a task which will finish in the future.
6585 * @returns {Deferred} Returns a new instance of deferred.
6587 var defer = function() {
6593 resolve: function(val) {
6595 var callbacks = pending;
6596 pending = undefined;
6599 if (callbacks.length) {
6600 nextTick(function() {
6602 for (var i = 0, ii = callbacks.length; i < ii; i++) {
6603 callback = callbacks[i];
6604 value.then(callback[0], callback[1]);
6612 reject: function(reason) {
6613 deferred.resolve(reject(reason));
6618 then: function(callback, errback) {
6619 var result = defer();
6621 var wrappedCallback = function(value) {
6623 result.resolve((callback || defaultCallback)(value));
6625 exceptionHandler(e);
6630 var wrappedErrback = function(reason) {
6632 result.resolve((errback || defaultErrback)(reason));
6634 exceptionHandler(e);
6640 pending.push([wrappedCallback, wrappedErrback]);
6642 value.then(wrappedCallback, wrappedErrback);
6645 return result.promise;
6654 var ref = function(value) {
6655 if (value && value.then) return value;
6657 then: function(callback) {
6658 var result = defer();
6659 nextTick(function() {
6660 result.resolve(callback(value));
6662 return result.promise;
6670 * @name ng.$q#reject
6673 * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
6674 * used to forward rejection in a chain of promises. If you are dealing with the last promise in
6675 * a promise chain, you don't need to worry about it.
6677 * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
6678 * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
6679 * a promise error callback and you want to forward the error to the promise derived from the
6680 * current promise, you have to "rethrow" the error by returning a rejection constructed via
6684 * promiseB = promiseA.then(function(result) {
6685 * // success: do something and resolve promiseB
6686 * // with the old or a new result
6688 * }, function(reason) {
6689 * // error: handle the error if possible and
6690 * // resolve promiseB with newPromiseOrValue,
6691 * // otherwise forward the rejection to promiseB
6692 * if (canHandle(reason)) {
6693 * // handle the error and recover
6694 * return newPromiseOrValue;
6696 * return $q.reject(reason);
6700 * @param {*} reason Constant, message, exception or an object representing the rejection reason.
6701 * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
6703 var reject = function(reason) {
6705 then: function(callback, errback) {
6706 var result = defer();
6707 nextTick(function() {
6708 result.resolve((errback || defaultErrback)(reason));
6710 return result.promise;
6721 * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
6722 * This is useful when you are dealing with on object that might or might not be a promise, or if
6723 * the promise comes from a source that can't be trusted.
6725 * @param {*} value Value or a promise
6726 * @returns {Promise} Returns a single promise that will be resolved with an array of values,
6727 * each value coresponding to the promise at the same index in the `promises` array. If any of
6728 * the promises is resolved with a rejection, this resulting promise will be resolved with the
6731 var when = function(value, callback, errback) {
6732 var result = defer(),
6735 var wrappedCallback = function(value) {
6737 return (callback || defaultCallback)(value);
6739 exceptionHandler(e);
6744 var wrappedErrback = function(reason) {
6746 return (errback || defaultErrback)(reason);
6748 exceptionHandler(e);
6753 nextTick(function() {
6754 ref(value).then(function(value) {
6757 result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
6758 }, function(reason) {
6761 result.resolve(wrappedErrback(reason));
6765 return result.promise;
6769 function defaultCallback(value) {
6774 function defaultErrback(reason) {
6775 return reject(reason);
6784 * Combines multiple promises into a single promise that is resolved when all of the input
6785 * promises are resolved.
6787 * @param {Array.<Promise>} promises An array of promises.
6788 * @returns {Promise} Returns a single promise that will be resolved with an array of values,
6789 * each value coresponding to the promise at the same index in the `promises` array. If any of
6790 * the promises is resolved with a rejection, this resulting promise will be resolved with the
6793 function all(promises) {
6794 var deferred = defer(),
6795 counter = promises.length,
6799 forEach(promises, function(promise, index) {
6800 ref(promise).then(function(value) {
6801 if (index in results) return;
6802 results[index] = value;
6803 if (!(--counter)) deferred.resolve(results);
6804 }, function(reason) {
6805 if (index in results) return;
6806 deferred.reject(reason);
6810 deferred.resolve(results);
6813 return deferred.promise;
6826 * @name ng.$routeProvider
6831 * Used for configuring routes. See {@link ng.$route $route} for an example.
6833 function $RouteProvider(){
6838 * @name ng.$routeProvider#when
6839 * @methodOf ng.$routeProvider
6841 * @param {string} path Route path (matched against `$location.path`). If `$location.path`
6842 * contains redundant trailing slash or is missing one, the route will still match and the
6843 * `$location.path` will be updated to add or drop the trailing slash to exacly match the
6845 * @param {Object} route Mapping information to be assigned to `$route.current` on route
6848 * Object properties:
6850 * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly
6851 * created scope or the name of a {@link angular.Module#controller registered controller}
6852 * if passed as a string.
6853 * - `template` – `{string=}` – html template as a string that should be used by
6854 * {@link ng.directive:ngView ngView} or
6855 * {@link ng.directive:ngInclude ngInclude} directives.
6856 * this property takes precedence over `templateUrl`.
6857 * - `templateUrl` – `{string=}` – path to an html template that should be used by
6858 * {@link ng.directive:ngView ngView}.
6859 * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
6860 * be injected into the controller. If any of these dependencies are promises, they will be
6861 * resolved and converted to a value before the controller is instantiated and the
6862 * `$afterRouteChange` event is fired. The map object is:
6864 * - `key` – `{string}`: a name of a dependency to be injected into the controller.
6865 * - `factory` - `{string|function}`: If `string` then it is an alias for a service.
6866 * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
6867 * and the return value is treated as the dependency. If the result is a promise, it is resolved
6868 * before its value is injected into the controller.
6870 * - `redirectTo` – {(string|function())=} – value to update
6871 * {@link ng.$location $location} path with and trigger route redirection.
6873 * If `redirectTo` is a function, it will be called with the following parameters:
6875 * - `{Object.<string>}` - route parameters extracted from the current
6876 * `$location.path()` by applying the current route templateUrl.
6877 * - `{string}` - current `$location.path()`
6878 * - `{Object}` - current `$location.search()`
6880 * The custom `redirectTo` function is expected to return a string which will be used
6881 * to update `$location.path()` and `$location.search()`.
6883 * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
6886 * If the option is set to `false` and url in the browser changes, then
6887 * `$routeUpdate` event is broadcasted on the root scope.
6889 * @returns {Object} self
6892 * Adds a new route definition to the `$route` service.
6894 this.when = function(path, route) {
6895 routes[path] = extend({reloadOnSearch: true}, route);
6897 // create redirection for trailing slashes
6899 var redirectPath = (path[path.length-1] == '/')
6900 ? path.substr(0, path.length-1)
6903 routes[redirectPath] = {redirectTo: path};
6911 * @name ng.$routeProvider#otherwise
6912 * @methodOf ng.$routeProvider
6915 * Sets route definition that will be used on route change when no other route definition
6918 * @param {Object} params Mapping information to be assigned to `$route.current`.
6919 * @returns {Object} self
6921 this.otherwise = function(params) {
6922 this.when(null, params);
6927 this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
6928 function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) {
6933 * @requires $location
6934 * @requires $routeParams
6936 * @property {Object} current Reference to the current route definition.
6937 * The route definition contains:
6939 * - `controller`: The controller constructor as define in route definition.
6940 * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
6941 * controller instantiation. The `locals` contain
6942 * the resolved values of the `resolve` map. Additionally the `locals` also contain:
6944 * - `$scope` - The current route scope.
6945 * - `$template` - The current route template HTML.
6947 * @property {Array.<Object>} routes Array of all configured routes.
6950 * Is used for deep-linking URLs to controllers and views (HTML partials).
6951 * It watches `$location.url()` and tries to map the path to an existing route definition.
6953 * You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
6955 * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
6956 * directive and the {@link ng.$routeParams $routeParams} service.
6959 This example shows how changing the URL hash causes the `$route` to match a route against the
6960 URL, and the `ngView` pulls in the partial.
6962 Note that this example is using {@link ng.directive:script inlined templates}
6963 to get it working on jsfiddle as well.
6965 <example module="ngView">
6966 <file name="index.html">
6967 <div ng-controller="MainCntl">
6969 <a href="Book/Moby">Moby</a> |
6970 <a href="Book/Moby/ch/1">Moby: Ch1</a> |
6971 <a href="Book/Gatsby">Gatsby</a> |
6972 <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
6973 <a href="Book/Scarlet">Scarlet Letter</a><br/>
6978 <pre>$location.path() = {{$location.path()}}</pre>
6979 <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
6980 <pre>$route.current.params = {{$route.current.params}}</pre>
6981 <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
6982 <pre>$routeParams = {{$routeParams}}</pre>
6986 <file name="book.html">
6987 controller: {{name}}<br />
6988 Book Id: {{params.bookId}}<br />
6991 <file name="chapter.html">
6992 controller: {{name}}<br />
6993 Book Id: {{params.bookId}}<br />
6994 Chapter Id: {{params.chapterId}}
6997 <file name="script.js">
6998 angular.module('ngView', [], function($routeProvider, $locationProvider) {
6999 $routeProvider.when('/Book/:bookId', {
7000 templateUrl: 'book.html',
7001 controller: BookCntl,
7003 // I will cause a 1 second delay
7004 delay: function($q, $timeout) {
7005 var delay = $q.defer();
7006 $timeout(delay.resolve, 1000);
7007 return delay.promise;
7011 $routeProvider.when('/Book/:bookId/ch/:chapterId', {
7012 templateUrl: 'chapter.html',
7013 controller: ChapterCntl
7016 // configure html5 to get links working on jsfiddle
7017 $locationProvider.html5Mode(true);
7020 function MainCntl($scope, $route, $routeParams, $location) {
7021 $scope.$route = $route;
7022 $scope.$location = $location;
7023 $scope.$routeParams = $routeParams;
7026 function BookCntl($scope, $routeParams) {
7027 $scope.name = "BookCntl";
7028 $scope.params = $routeParams;
7031 function ChapterCntl($scope, $routeParams) {
7032 $scope.name = "ChapterCntl";
7033 $scope.params = $routeParams;
7037 <file name="scenario.js">
7038 it('should load and compile correct template', function() {
7039 element('a:contains("Moby: Ch1")').click();
7040 var content = element('.doc-example-live [ng-view]').text();
7041 expect(content).toMatch(/controller\: ChapterCntl/);
7042 expect(content).toMatch(/Book Id\: Moby/);
7043 expect(content).toMatch(/Chapter Id\: 1/);
7045 element('a:contains("Scarlet")').click();
7046 sleep(2); // promises are not part of scenario waiting
7047 content = element('.doc-example-live [ng-view]').text();
7048 expect(content).toMatch(/controller\: BookCntl/);
7049 expect(content).toMatch(/Book Id\: Scarlet/);
7057 * @name ng.$route#$routeChangeStart
7058 * @eventOf ng.$route
7059 * @eventType broadcast on root scope
7061 * Broadcasted before a route change. At this point the route services starts
7062 * resolving all of the dependencies needed for the route change to occurs.
7063 * Typically this involves fetching the view template as well as any dependencies
7064 * defined in `resolve` route property. Once all of the dependencies are resolved
7065 * `$routeChangeSuccess` is fired.
7067 * @param {Route} next Future route information.
7068 * @param {Route} current Current route information.
7073 * @name ng.$route#$routeChangeSuccess
7074 * @eventOf ng.$route
7075 * @eventType broadcast on root scope
7077 * Broadcasted after a route dependencies are resolved.
7078 * {@link ng.directive:ngView ngView} listens for the directive
7079 * to instantiate the controller and render the view.
7081 * @param {Route} current Current route information.
7082 * @param {Route} previous Previous route information.
7087 * @name ng.$route#$routeChangeError
7088 * @eventOf ng.$route
7089 * @eventType broadcast on root scope
7091 * Broadcasted if any of the resolve promises are rejected.
7093 * @param {Route} current Current route information.
7094 * @param {Route} previous Previous route information.
7095 * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
7100 * @name ng.$route#$routeUpdate
7101 * @eventOf ng.$route
7102 * @eventType broadcast on root scope
7105 * The `reloadOnSearch` property has been set to false, and we are reusing the same
7106 * instance of the Controller.
7109 var matcher = switchRouteMatcher,
7110 forceReload = false,
7116 * @name ng.$route#reload
7117 * @methodOf ng.$route
7120 * Causes `$route` service to reload the current route even if
7121 * {@link ng.$location $location} hasn't changed.
7123 * As a result of that, {@link ng.directive:ngView ngView}
7124 * creates new scope, reinstantiates the controller.
7126 reload: function() {
7128 $rootScope.$evalAsync(updateRoute);
7132 $rootScope.$on('$locationChangeSuccess', updateRoute);
7136 /////////////////////////////////////////////////////
7138 function switchRouteMatcher(on, when) {
7139 // TODO(i): this code is convoluted and inefficient, we should construct the route matching
7140 // regex only once and then reuse it
7141 var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$',
7144 forEach(when.split(/\W/), function(param) {
7146 var paramRegExp = new RegExp(":" + param + "([\\W])");
7147 if (regex.match(paramRegExp)) {
7148 regex = regex.replace(paramRegExp, "([^\\/]*)$1");
7153 var match = on.match(new RegExp(regex));
7155 forEach(params, function(name, index) {
7156 dst[name] = match[index + 1];
7159 return match ? dst : null;
7162 function updateRoute() {
7163 var next = parseRoute(),
7164 last = $route.current;
7166 if (next && last && next.$route === last.$route
7167 && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
7168 last.params = next.params;
7169 copy(last.params, $routeParams);
7170 $rootScope.$broadcast('$routeUpdate', last);
7171 } else if (next || last) {
7172 forceReload = false;
7173 $rootScope.$broadcast('$routeChangeStart', next, last);
7174 $route.current = next;
7176 if (next.redirectTo) {
7177 if (isString(next.redirectTo)) {
7178 $location.path(interpolate(next.redirectTo, next.params)).search(next.params)
7181 $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
7194 forEach(next.resolve || {}, function(value, key) {
7196 values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value));
7198 if (isDefined(template = next.template)) {
7199 } else if (isDefined(template = next.templateUrl)) {
7200 template = $http.get(template, {cache: $templateCache}).
7201 then(function(response) { return response.data; });
7203 if (isDefined(template)) {
7204 keys.push('$template');
7205 values.push(template);
7207 return $q.all(values).then(function(values) {
7209 forEach(values, function(value, index) {
7210 locals[keys[index]] = value;
7216 // after route change
7217 then(function(locals) {
7218 if (next == $route.current) {
7220 next.locals = locals;
7221 copy(next.params, $routeParams);
7223 $rootScope.$broadcast('$routeChangeSuccess', next, last);
7225 }, function(error) {
7226 if (next == $route.current) {
7227 $rootScope.$broadcast('$routeChangeError', next, last, error);
7235 * @returns the current active route, by matching it against the URL
7237 function parseRoute() {
7240 forEach(routes, function(route, path) {
7241 if (!match && (params = matcher($location.path(), path))) {
7242 match = inherit(route, {
7243 params: extend({}, $location.search(), params),
7244 pathParams: params});
7245 match.$route = route;
7248 // No route matched; fallback to "otherwise" route
7249 return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
7253 * @returns interpolation of the redirect path with the parametrs
7255 function interpolate(string, params) {
7257 forEach((string||'').split(':'), function(segment, i) {
7259 result.push(segment);
7261 var segmentMatch = segment.match(/(\w+)(.*)/);
7262 var key = segmentMatch[1];
7263 result.push(params[key]);
7264 result.push(segmentMatch[2] || '');
7268 return result.join('');
7275 * @name ng.$routeParams
7279 * Current set of route parameters. The route parameters are a combination of the
7280 * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
7281 * are extracted when the {@link ng.$route $route} path is matched.
7283 * In case of parameter name collision, `path` params take precedence over `search` params.
7285 * The service guarantees that the identity of the `$routeParams` object will remain unchanged
7286 * (but its properties will likely change) even when a route change occurs.
7291 * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
7292 * // Route: /Chapter/:chapterId/Section/:sectionId
7295 * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
7298 function $RouteParamsProvider() {
7299 this.$get = valueFn({});
7305 * The design decisions behind the scope ware heavily favored for speed and memory consumption.
7307 * The typical use of scope is to watch the expressions, which most of the time return the same
7308 * value as last time so we optimize the operation.
7310 * Closures construction is expensive from speed as well as memory:
7311 * - no closures, instead ups prototypical inheritance for API
7312 * - Internal state needs to be stored on scope directly, which means that private state is
7313 * exposed as $$____ properties
7315 * Loop operations are optimized by using while(count--) { ... }
7316 * - this means that in order to keep the same order of execution as addition we have to add
7317 * items to the array at the begging (shift) instead of at the end (push)
7319 * Child scopes are created and removed often
7320 * - Using array would be slow since inserts in meddle are expensive so we use linked list
7322 * There are few watches then a lot of observers. This is why you don't want the observer to be
7323 * implemented in the same way as watch. Watch requires return of initialization function which
7324 * are expensive to construct.
7330 * @name ng.$rootScopeProvider
7333 * Provider for the $rootScope service.
7338 * @name ng.$rootScopeProvider#digestTtl
7339 * @methodOf ng.$rootScopeProvider
7342 * Sets the number of digest iteration the scope should attempt to execute before giving up and
7343 * assuming that the model is unstable.
7345 * The current default is 10 iterations.
7347 * @param {number} limit The number of digest iterations.
7353 * @name ng.$rootScope
7356 * Every application has a single root {@link ng.$rootScope.Scope scope}.
7357 * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
7358 * event processing life-cycle. See {@link guide/scope developer guide on scopes}.
7360 function $RootScopeProvider(){
7363 this.digestTtl = function(value) {
7364 if (arguments.length) {
7370 this.$get = ['$injector', '$exceptionHandler', '$parse',
7371 function( $injector, $exceptionHandler, $parse) {
7375 * @name ng.$rootScope.Scope
7378 * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
7379 * {@link AUTO.$injector $injector}. Child scopes are created using the
7380 * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
7381 * compiled HTML template is executed.)
7383 * Here is a simple scope snippet to show how you can interact with the scope.
7385 angular.injector(['ng']).invoke(function($rootScope) {
7386 var scope = $rootScope.$new();
7387 scope.salutation = 'Hello';
7388 scope.name = 'World';
7390 expect(scope.greeting).toEqual(undefined);
7392 scope.$watch('name', function() {
7393 this.greeting = this.salutation + ' ' + this.name + '!';
7394 }); // initialize the watch
7396 expect(scope.greeting).toEqual(undefined);
7397 scope.name = 'Misko';
7398 // still old value, since watches have not been called yet
7399 expect(scope.greeting).toEqual(undefined);
7401 scope.$digest(); // fire all the watches
7402 expect(scope.greeting).toEqual('Hello Misko!');
7407 * A scope can inherit from a parent scope, as in this example:
7409 var parent = $rootScope;
7410 var child = parent.$new();
7412 parent.salutation = "Hello";
7413 child.name = "World";
7414 expect(child.salutation).toEqual('Hello');
7416 child.salutation = "Welcome";
7417 expect(child.salutation).toEqual('Welcome');
7418 expect(parent.salutation).toEqual('Hello');
7422 * @param {Object.<string, function()>=} providers Map of service factory which need to be provided
7423 * for the current scope. Defaults to {@link ng}.
7424 * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
7425 * append/override services provided by `providers`. This is handy when unit-testing and having
7426 * the need to override a default service.
7427 * @returns {Object} Newly created scope.
7431 this.$id = nextUid();
7432 this.$$phase = this.$parent = this.$$watchers =
7433 this.$$nextSibling = this.$$prevSibling =
7434 this.$$childHead = this.$$childTail = null;
7435 this['this'] = this.$root = this;
7436 this.$$asyncQueue = [];
7437 this.$$listeners = {};
7442 * @name ng.$rootScope.Scope#$id
7443 * @propertyOf ng.$rootScope.Scope
7444 * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
7452 * @name ng.$rootScope.Scope#$new
7453 * @methodOf ng.$rootScope.Scope
7457 * Creates a new child {@link ng.$rootScope.Scope scope}.
7459 * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
7460 * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
7461 * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
7463 * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
7464 * the scope and its child scopes to be permanently detached from the parent and thus stop
7465 * participating in model change detection and listener notification by invoking.
7467 * @param {boolean} isolate if true then the scoped does not prototypically inherit from the
7468 * parent scope. The scope is isolated, as it can not se parent scope properties.
7469 * When creating widgets it is useful for the widget to not accidently read parent
7472 * @returns {Object} The newly created child scope.
7475 $new: function(isolate) {
7479 if (isFunction(isolate)) {
7480 // TODO: remove at some point
7481 throw Error('API-CHANGE: Use $controller to instantiate controllers.');
7484 child = new Scope();
7485 child.$root = this.$root;
7487 Child = function() {}; // should be anonymous; This is so that when the minifier munges
7488 // the name it does not become random set of chars. These will then show up as class
7489 // name in the debugger.
7490 Child.prototype = this;
7491 child = new Child();
7492 child.$id = nextUid();
7494 child['this'] = child;
7495 child.$$listeners = {};
7496 child.$parent = this;
7497 child.$$asyncQueue = [];
7498 child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
7499 child.$$prevSibling = this.$$childTail;
7500 if (this.$$childHead) {
7501 this.$$childTail.$$nextSibling = child;
7502 this.$$childTail = child;
7504 this.$$childHead = this.$$childTail = child;
7511 * @name ng.$rootScope.Scope#$watch
7512 * @methodOf ng.$rootScope.Scope
7516 * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
7518 * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
7519 * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
7520 * reruns when it detects changes the `watchExpression` can execute multiple times per
7521 * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
7522 * - The `listener` is called only when the value from the current `watchExpression` and the
7523 * previous call to `watchExpression' are not equal (with the exception of the initial run
7524 * see below). The inequality is determined according to
7525 * {@link angular.equals} function. To save the value of the object for later comparison
7526 * {@link angular.copy} function is used. It also means that watching complex options will
7527 * have adverse memory and performance implications.
7528 * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
7529 * is achieved by rerunning the watchers until no changes are detected. The rerun iteration
7530 * limit is 100 to prevent infinity loop deadlock.
7533 * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
7534 * you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
7535 * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
7536 * detected, be prepared for multiple calls to your listener.)
7538 * After a watcher is registered with the scope, the `listener` fn is called asynchronously
7539 * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
7540 * watcher. In rare cases, this is undesirable because the listener is called when the result
7541 * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
7542 * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
7543 * listener was called due to initialization.
7548 // let's assume that scope was dependency injected as the $rootScope
7549 var scope = $rootScope;
7550 scope.name = 'misko';
7553 expect(scope.counter).toEqual(0);
7554 scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; });
7555 expect(scope.counter).toEqual(0);
7558 // no variable change
7559 expect(scope.counter).toEqual(0);
7561 scope.name = 'adam';
7563 expect(scope.counter).toEqual(1);
7568 * @param {(function()|string)} watchExpression Expression that is evaluated on each
7569 * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
7570 * call to the `listener`.
7572 * - `string`: Evaluated as {@link guide/expression expression}
7573 * - `function(scope)`: called with current `scope` as a parameter.
7574 * @param {(function()|string)=} listener Callback called whenever the return value of
7575 * the `watchExpression` changes.
7577 * - `string`: Evaluated as {@link guide/expression expression}
7578 * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
7580 * @param {boolean=} objectEquality Compare object for equality rather then for refference.
7581 * @returns {function()} Returns a deregistration function for this listener.
7583 $watch: function(watchExp, listener, objectEquality) {
7585 get = compileToFn(watchExp, 'watch'),
7586 array = scope.$$watchers,
7592 eq: !!objectEquality
7595 // in the case user pass string, we need to compile it, do we really need this ?
7596 if (!isFunction(listener)) {
7597 var listenFn = compileToFn(listener || noop, 'listener');
7598 watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
7602 array = scope.$$watchers = [];
7604 // we use unshift since we use a while loop in $digest for speed.
7605 // the while loop reads in reverse order.
7606 array.unshift(watcher);
7609 arrayRemove(array, watcher);
7615 * @name ng.$rootScope.Scope#$digest
7616 * @methodOf ng.$rootScope.Scope
7620 * Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
7621 * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
7622 * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
7623 * firing. This means that it is possible to get into an infinite loop. This function will throw
7624 * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
7626 * Usually you don't call `$digest()` directly in
7627 * {@link ng.directive:ngController controllers} or in
7628 * {@link ng.$compileProvider#directive directives}.
7629 * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
7630 * {@link ng.$compileProvider#directive directives}) will force a `$digest()`.
7632 * If you want to be notified whenever `$digest()` is called,
7633 * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
7634 * with no `listener`.
7636 * You may have a need to call `$digest()` from within unit-tests, to simulate the scope
7642 scope.name = 'misko';
7645 expect(scope.counter).toEqual(0);
7646 scope.$watch('name', function(newValue, oldValue) {
7647 counter = counter + 1;
7649 expect(scope.counter).toEqual(0);
7652 // no variable change
7653 expect(scope.counter).toEqual(0);
7655 scope.name = 'adam';
7657 expect(scope.counter).toEqual(1);
7661 $digest: function() {
7662 var watch, value, last,
7667 next, current, target = this,
7671 beginPhase('$digest');
7677 asyncQueue = current.$$asyncQueue;
7678 while(asyncQueue.length) {
7680 current.$eval(asyncQueue.shift());
7682 $exceptionHandler(e);
7685 if ((watchers = current.$$watchers)) {
7686 // process our watches
7687 length = watchers.length;
7690 watch = watchers[length];
7691 // Most common watches are on primitives, in which case we can short
7692 // circuit it with === operator, only when === fails do we use .equals
7693 if ((value = watch.get(current)) !== (last = watch.last) &&
7695 ? equals(value, last)
7696 : (typeof value == 'number' && typeof last == 'number'
7697 && isNaN(value) && isNaN(last)))) {
7699 watch.last = watch.eq ? copy(value) : value;
7700 watch.fn(value, ((last === initWatchVal) ? value : last), current);
7703 if (!watchLog[logIdx]) watchLog[logIdx] = [];
7704 logMsg = (isFunction(watch.exp))
7705 ? 'fn: ' + (watch.exp.name || watch.exp.toString())
7707 logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
7708 watchLog[logIdx].push(logMsg);
7712 $exceptionHandler(e);
7717 // Insanity Warning: scope depth-first traversal
7718 // yes, this code is a bit crazy, but it works and we have tests to prove it!
7719 // this piece should be kept in sync with the traversal in $broadcast
7720 if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
7721 while(current !== target && !(next = current.$$nextSibling)) {
7722 current = current.$parent;
7725 } while ((current = next));
7727 if(dirty && !(ttl--)) {
7729 throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
7730 'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
7732 } while (dirty || asyncQueue.length);
7740 * @name ng.$rootScope.Scope#$destroy
7741 * @eventOf ng.$rootScope.Scope
7742 * @eventType broadcast on scope being destroyed
7745 * Broadcasted when a scope and its children are being destroyed.
7750 * @name ng.$rootScope.Scope#$destroy
7751 * @methodOf ng.$rootScope.Scope
7755 * Remove the current scope (and all of its children) from the parent scope. Removal implies
7756 * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
7757 * propagate to the current scope and its children. Removal also implies that the current
7758 * scope is eligible for garbage collection.
7760 * The `$destroy()` is usually used by directives such as
7761 * {@link ng.directive:ngRepeat ngRepeat} for managing the
7762 * unrolling of the loop.
7764 * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
7765 * Application code can register a `$destroy` event handler that will give it chance to
7766 * perform any necessary cleanup.
7768 $destroy: function() {
7769 if ($rootScope == this) return; // we can't remove the root node;
7770 var parent = this.$parent;
7772 this.$broadcast('$destroy');
7774 if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
7775 if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
7776 if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
7777 if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
7782 * @name ng.$rootScope.Scope#$eval
7783 * @methodOf ng.$rootScope.Scope
7787 * Executes the `expression` on the current scope returning the result. Any exceptions in the
7788 * expression are propagated (uncaught). This is useful when evaluating engular expressions.
7792 var scope = ng.$rootScope.Scope();
7796 expect(scope.$eval('a+b')).toEqual(3);
7797 expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
7800 * @param {(string|function())=} expression An angular expression to be executed.
7802 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
7803 * - `function(scope)`: execute the function with the current `scope` parameter.
7805 * @returns {*} The result of evaluating the expression.
7807 $eval: function(expr, locals) {
7808 return $parse(expr)(this, locals);
7813 * @name ng.$rootScope.Scope#$evalAsync
7814 * @methodOf ng.$rootScope.Scope
7818 * Executes the expression on the current scope at a later point in time.
7820 * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
7822 * - it will execute in the current script execution context (before any DOM rendering).
7823 * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
7824 * `expression` execution.
7826 * Any exceptions from the execution of the expression are forwarded to the
7827 * {@link ng.$exceptionHandler $exceptionHandler} service.
7829 * @param {(string|function())=} expression An angular expression to be executed.
7831 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
7832 * - `function(scope)`: execute the function with the current `scope` parameter.
7835 $evalAsync: function(expr) {
7836 this.$$asyncQueue.push(expr);
7841 * @name ng.$rootScope.Scope#$apply
7842 * @methodOf ng.$rootScope.Scope
7846 * `$apply()` is used to execute an expression in angular from outside of the angular framework.
7847 * (For example from browser DOM events, setTimeout, XHR or third party libraries).
7848 * Because we are calling into the angular framework we need to perform proper scope life-cycle
7849 * of {@link ng.$exceptionHandler exception handling},
7850 * {@link ng.$rootScope.Scope#$digest executing watches}.
7854 * # Pseudo-Code of `$apply()`
7856 function $apply(expr) {
7860 $exceptionHandler(e);
7868 * Scope's `$apply()` method transitions through the following stages:
7870 * 1. The {@link guide/expression expression} is executed using the
7871 * {@link ng.$rootScope.Scope#$eval $eval()} method.
7872 * 2. Any exceptions from the execution of the expression are forwarded to the
7873 * {@link ng.$exceptionHandler $exceptionHandler} service.
7874 * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
7875 * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
7878 * @param {(string|function())=} exp An angular expression to be executed.
7880 * - `string`: execute using the rules as defined in {@link guide/expression expression}.
7881 * - `function(scope)`: execute the function with current `scope` parameter.
7883 * @returns {*} The result of evaluating the expression.
7885 $apply: function(expr) {
7887 beginPhase('$apply');
7888 return this.$eval(expr);
7890 $exceptionHandler(e);
7894 $rootScope.$digest();
7896 $exceptionHandler(e);
7904 * @name ng.$rootScope.Scope#$on
7905 * @methodOf ng.$rootScope.Scope
7909 * Listen on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
7912 * @param {string} name Event name to listen on.
7913 * @param {function(event)} listener Function to call when the event is emitted.
7914 * @returns {function()} Returns a deregistration function for this listener.
7916 * The event listener function format is: `function(event, args...)`. The `event` object
7917 * passed into the listener has the following attributes:
7919 * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
7920 * - `currentScope` - {Scope}: the current scope which is handling the event.
7921 * - `name` - {string}: Name of the event.
7922 * - `stopPropagation` - {function=}: calling `stopPropagation` function will cancel further event propagation
7923 * (available only for events that were `$emit`-ed).
7924 * - `preventDefault` - {function}: calling `preventDefault` sets `defaultPrevented` flag to true.
7925 * - `defaultPrevented` - {boolean}: true if `preventDefault` was called.
7927 $on: function(name, listener) {
7928 var namedListeners = this.$$listeners[name];
7929 if (!namedListeners) {
7930 this.$$listeners[name] = namedListeners = [];
7932 namedListeners.push(listener);
7935 arrayRemove(namedListeners, listener);
7942 * @name ng.$rootScope.Scope#$emit
7943 * @methodOf ng.$rootScope.Scope
7947 * Dispatches an event `name` upwards through the scope hierarchy notifying the
7948 * registered {@link ng.$rootScope.Scope#$on} listeners.
7950 * The event life cycle starts at the scope on which `$emit` was called. All
7951 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
7952 * Afterwards, the event traverses upwards toward the root scope and calls all registered
7953 * listeners along the way. The event will stop propagating if one of the listeners cancels it.
7955 * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
7956 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
7958 * @param {string} name Event name to emit.
7959 * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
7960 * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
7962 $emit: function(name, args) {
7966 stopPropagation = false,
7970 stopPropagation: function() {stopPropagation = true;},
7971 preventDefault: function() {
7972 event.defaultPrevented = true;
7974 defaultPrevented: false
7976 listenerArgs = concat([event], arguments, 1),
7980 namedListeners = scope.$$listeners[name] || empty;
7981 event.currentScope = scope;
7982 for (i=0, length=namedListeners.length; i<length; i++) {
7984 namedListeners[i].apply(null, listenerArgs);
7985 if (stopPropagation) return event;
7987 $exceptionHandler(e);
7991 scope = scope.$parent;
8000 * @name ng.$rootScope.Scope#$broadcast
8001 * @methodOf ng.$rootScope.Scope
8005 * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
8006 * registered {@link ng.$rootScope.Scope#$on} listeners.
8008 * The event life cycle starts at the scope on which `$broadcast` was called. All
8009 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
8010 * Afterwards, the event propagates to all direct and indirect scopes of the current scope and
8011 * calls all registered listeners along the way. The event cannot be canceled.
8013 * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
8014 * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
8016 * @param {string} name Event name to emit.
8017 * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
8018 * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
8020 $broadcast: function(name, args) {
8026 targetScope: target,
8027 preventDefault: function() {
8028 event.defaultPrevented = true;
8030 defaultPrevented: false
8032 listenerArgs = concat([event], arguments, 1);
8034 //down while you can, then up and next sibling or up and next sibling until back at root
8037 event.currentScope = current;
8038 forEach(current.$$listeners[name], function(listener) {
8040 listener.apply(null, listenerArgs);
8042 $exceptionHandler(e);
8046 // Insanity Warning: scope depth-first traversal
8047 // yes, this code is a bit crazy, but it works and we have tests to prove it!
8048 // this piece should be kept in sync with the traversal in $digest
8049 if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
8050 while(current !== target && !(next = current.$$nextSibling)) {
8051 current = current.$parent;
8054 } while ((current = next));
8060 var $rootScope = new Scope();
8065 function beginPhase(phase) {
8066 if ($rootScope.$$phase) {
8067 throw Error($rootScope.$$phase + ' already in progress');
8070 $rootScope.$$phase = phase;
8073 function clearPhase() {
8074 $rootScope.$$phase = null;
8077 function compileToFn(exp, name) {
8078 var fn = $parse(exp);
8079 assertArgFn(fn, name);
8084 * function used as an initial value for watchers.
8085 * because it's uniqueue we can easily tell it apart from other values
8087 function initWatchVal() {}
8092 * !!! This is an undocumented "private" service !!!
8097 * @property {boolean} history Does the browser support html5 history api ?
8098 * @property {boolean} hashchange Does the browser support hashchange event ?
8101 * This is very simple implementation of testing browser's features.
8103 function $SnifferProvider() {
8104 this.$get = ['$window', function($window) {
8105 var eventSupport = {},
8106 android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
8109 // Android has history.pushState, but it does not update location correctly
8110 // so let's not use the history API at all.
8111 // http://code.google.com/p/android/issues/detail?id=17471
8112 // https://github.com/angular/angular.js/issues/904
8113 history: !!($window.history && $window.history.pushState && !(android < 4)),
8114 hashchange: 'onhashchange' in $window &&
8115 // IE8 compatible mode lies
8116 (!$window.document.documentMode || $window.document.documentMode > 7),
8117 hasEvent: function(event) {
8118 // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
8119 // it. In particular the event is not fired when backspace or delete key are pressed or
8120 // when cut operation is performed.
8121 if (event == 'input' && msie == 9) return false;
8123 if (isUndefined(eventSupport[event])) {
8124 var divElm = $window.document.createElement('div');
8125 eventSupport[event] = 'on' + event in divElm;
8128 return eventSupport[event];
8130 // TODO(i): currently there is no way to feature detect CSP without triggering alerts
8141 * A reference to the browser's `window` object. While `window`
8142 * is globally available in JavaScript, it causes testability problems, because
8143 * it is a global variable. In angular we always refer to it through the
8144 * `$window` service, so it may be overriden, removed or mocked for testing.
8146 * All expressions are evaluated with respect to current scope so they don't
8147 * suffer from window globality.
8152 <input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" />
8153 <button ng-click="$window.alert(greeting)">ALERT</button>
8159 function $WindowProvider(){
8160 this.$get = valueFn(window);
8164 * Parse headers into key value object
8166 * @param {string} headers Raw headers as a string
8167 * @returns {Object} Parsed headers as key value object
8169 function parseHeaders(headers) {
8170 var parsed = {}, key, val, i;
8172 if (!headers) return parsed;
8174 forEach(headers.split('\n'), function(line) {
8175 i = line.indexOf(':');
8176 key = lowercase(trim(line.substr(0, i)));
8177 val = trim(line.substr(i + 1));
8181 parsed[key] += ', ' + val;
8193 * Returns a function that provides access to parsed headers.
8195 * Headers are lazy parsed when first requested.
8198 * @param {(string|Object)} headers Headers to provide access to.
8199 * @returns {function(string=)} Returns a getter function which if called with:
8201 * - if called with single an argument returns a single header value or null
8202 * - if called with no arguments returns an object containing all headers.
8204 function headersGetter(headers) {
8205 var headersObj = isObject(headers) ? headers : undefined;
8207 return function(name) {
8208 if (!headersObj) headersObj = parseHeaders(headers);
8211 return headersObj[lowercase(name)] || null;
8220 * Chain all given functions
8222 * This function is used for both request and response transforming
8224 * @param {*} data Data to transform.
8225 * @param {function(string=)} headers Http headers getter fn.
8226 * @param {(function|Array.<function>)} fns Function or an array of functions.
8227 * @returns {*} Transformed data.
8229 function transformData(data, headers, fns) {
8230 if (isFunction(fns))
8231 return fns(data, headers);
8233 forEach(fns, function(fn) {
8234 data = fn(data, headers);
8241 function isSuccess(status) {
8242 return 200 <= status && status < 300;
8246 function $HttpProvider() {
8247 var JSON_START = /^\s*(\[|\{[^\{])/,
8248 JSON_END = /[\}\]]\s*$/,
8249 PROTECTION_PREFIX = /^\)\]\}',?\n/;
8251 var $config = this.defaults = {
8252 // transform incoming response data
8253 transformResponse: [function(data) {
8254 if (isString(data)) {
8255 // strip json vulnerability protection prefix
8256 data = data.replace(PROTECTION_PREFIX, '');
8257 if (JSON_START.test(data) && JSON_END.test(data))
8258 data = fromJson(data, true);
8263 // transform outgoing request data
8264 transformRequest: [function(d) {
8265 return isObject(d) && !isFile(d) ? toJson(d) : d;
8271 'Accept': 'application/json, text/plain, */*',
8272 'X-Requested-With': 'XMLHttpRequest'
8274 post: {'Content-Type': 'application/json;charset=utf-8'},
8275 put: {'Content-Type': 'application/json;charset=utf-8'}
8279 var providerResponseInterceptors = this.responseInterceptors = [];
8281 this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
8282 function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
8284 var defaultCache = $cacheFactory('$http'),
8285 responseInterceptors = [];
8287 forEach(providerResponseInterceptors, function(interceptor) {
8288 responseInterceptors.push(
8289 isString(interceptor)
8290 ? $injector.get(interceptor)
8291 : $injector.invoke(interceptor)
8299 * @requires $httpBacked
8300 * @requires $browser
8301 * @requires $cacheFactory
8302 * @requires $rootScope
8304 * @requires $injector
8307 * The `$http` service is a core Angular service that facilitates communication with the remote
8308 * HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest
8309 * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
8311 * For unit testing applications that use `$http` service, see
8312 * {@link ngMock.$httpBackend $httpBackend mock}.
8314 * For a higher level of abstraction, please check out the {@link ngResource.$resource
8315 * $resource} service.
8317 * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
8318 * the $q service. While for simple usage patters this doesn't matter much, for advanced usage,
8319 * it is important to familiarize yourself with these apis and guarantees they provide.
8323 * The `$http` service is a function which takes a single argument — a configuration object —
8324 * that is used to generate an http request and returns a {@link ng.$q promise}
8325 * with two $http specific methods: `success` and `error`.
8328 * $http({method: 'GET', url: '/someUrl'}).
8329 * success(function(data, status, headers, config) {
8330 * // this callback will be called asynchronously
8331 * // when the response is available
8333 * error(function(data, status, headers, config) {
8334 * // called asynchronously if an error occurs
8335 * // or server returns response with status
8336 * // code outside of the <200, 400) range
8340 * Since the returned value of calling the $http function is a Promise object, you can also use
8341 * the `then` method to register callbacks, and these callbacks will receive a single argument –
8342 * an object representing the response. See the api signature and type info below for more
8346 * # Shortcut methods
8348 * Since all invocation of the $http service require definition of the http method and url and
8349 * POST and PUT requests require response body/data to be provided as well, shortcut methods
8350 * were created to simplify using the api:
8353 * $http.get('/someUrl').success(successCallback);
8354 * $http.post('/someUrl', data).success(successCallback);
8357 * Complete list of shortcut methods:
8359 * - {@link ng.$http#get $http.get}
8360 * - {@link ng.$http#head $http.head}
8361 * - {@link ng.$http#post $http.post}
8362 * - {@link ng.$http#put $http.put}
8363 * - {@link ng.$http#delete $http.delete}
8364 * - {@link ng.$http#jsonp $http.jsonp}
8367 * # Setting HTTP Headers
8369 * The $http service will automatically add certain http headers to all requests. These defaults
8370 * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
8371 * object, which currently contains this default configuration:
8373 * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
8374 * - `Accept: application/json, text/plain, * / *`
8375 * - `X-Requested-With: XMLHttpRequest`
8376 * - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests)
8377 * - `Content-Type: application/json`
8378 * - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests)
8379 * - `Content-Type: application/json`
8381 * To add or overwrite these defaults, simply add or remove a property from this configuration
8382 * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
8383 * with name equal to the lower-cased http method name, e.g.
8384 * `$httpProvider.defaults.headers.get['My-Header']='value'`.
8386 * Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar
8387 * fassion as described above.
8390 * # Transforming Requests and Responses
8392 * Both requests and responses can be transformed using transform functions. By default, Angular
8393 * applies these transformations:
8395 * Request transformations:
8397 * - if the `data` property of the request config object contains an object, serialize it into
8400 * Response transformations:
8402 * - if XSRF prefix is detected, strip it (see Security Considerations section below)
8403 * - if json response is detected, deserialize it using a JSON parser
8405 * To override these transformation locally, specify transform functions as `transformRequest`
8406 * and/or `transformResponse` properties of the config object. To globally override the default
8407 * transforms, override the `$httpProvider.defaults.transformRequest` and
8408 * `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`.
8413 * To enable caching set the configuration property `cache` to `true`. When the cache is
8414 * enabled, `$http` stores the response from the server in local cache. Next time the
8415 * response is served from the cache without sending a request to the server.
8417 * Note that even if the response is served from cache, delivery of the data is asynchronous in
8418 * the same way that real requests are.
8420 * If there are multiple GET requests for the same url that should be cached using the same
8421 * cache, but the cache is not populated yet, only one request to the server will be made and
8422 * the remaining requests will be fulfilled using the response for the first request.
8425 * # Response interceptors
8427 * Before you start creating interceptors, be sure to understand the
8428 * {@link ng.$q $q and deferred/promise APIs}.
8430 * For purposes of global error handling, authentication or any kind of synchronous or
8431 * asynchronous preprocessing of received responses, it is desirable to be able to intercept
8432 * responses for http requests before they are handed over to the application code that
8433 * initiated these requests. The response interceptors leverage the {@link ng.$q
8434 * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
8436 * The interceptors are service factories that are registered with the $httpProvider by
8437 * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
8438 * injected with dependencies (if specified) and returns the interceptor — a function that
8439 * takes a {@link ng.$q promise} and returns the original or a new promise.
8442 * // register the interceptor as a service
8443 * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
8444 * return function(promise) {
8445 * return promise.then(function(response) {
8446 * // do something on success
8447 * }, function(response) {
8448 * // do something on error
8449 * if (canRecover(response)) {
8450 * return responseOrNewPromise
8452 * return $q.reject(response);
8457 * $httpProvider.responseInterceptors.push('myHttpInterceptor');
8460 * // register the interceptor via an anonymous factory
8461 * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
8462 * return function(promise) {
8469 * # Security Considerations
8471 * When designing web applications, consider security threats from:
8473 * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
8474 * JSON Vulnerability}
8475 * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
8477 * Both server and the client must cooperate in order to eliminate these threats. Angular comes
8478 * pre-configured with strategies that address these issues, but for this to work backend server
8479 * cooperation is required.
8481 * ## JSON Vulnerability Protection
8483 * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
8484 * JSON Vulnerability} allows third party web-site to turn your JSON resource URL into
8485 * {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To
8486 * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
8487 * Angular will automatically strip the prefix before processing it as JSON.
8489 * For example if your server needs to return:
8494 * which is vulnerable to attack, your server can return:
8500 * Angular will strip the prefix, before processing the JSON.
8503 * ## Cross Site Request Forgery (XSRF) Protection
8505 * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
8506 * an unauthorized site can gain your user's private data. Angular provides following mechanism
8507 * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
8508 * called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that
8509 * runs on your domain could read the cookie, your server can be assured that the XHR came from
8510 * JavaScript running on your domain.
8512 * To take advantage of this, your server needs to set a token in a JavaScript readable session
8513 * cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the
8514 * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
8515 * that only JavaScript running on your domain could have read the token. The token must be
8516 * unique for each user and must be verifiable by the server (to prevent the JavaScript making
8517 * up its own tokens). We recommend that the token is a digest of your site's authentication
8518 * cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}.
8521 * @param {object} config Object describing the request to be made and how it should be
8522 * processed. The object has following properties:
8524 * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
8525 * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
8526 * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
8527 * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
8528 * - **data** – `{string|Object}` – Data to be sent as the request message data.
8529 * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server.
8530 * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
8531 * transform function or an array of such functions. The transform function takes the http
8532 * request body and headers and returns its transformed (typically serialized) version.
8533 * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
8534 * transform function or an array of such functions. The transform function takes the http
8535 * response body and headers and returns its transformed (typically deserialized) version.
8536 * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
8537 * GET request, otherwise if a cache instance built with
8538 * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
8540 * - **timeout** – `{number}` – timeout in milliseconds.
8541 * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
8542 * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
8543 * requests with credentials} for more information.
8545 * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
8546 * standard `then` method and two http specific methods: `success` and `error`. The `then`
8547 * method takes two arguments a success and an error callback which will be called with a
8548 * response object. The `success` and `error` methods take a single argument - a function that
8549 * will be called when the request succeeds or fails respectively. The arguments passed into
8550 * these functions are destructured representation of the response object passed into the
8551 * `then` method. The response object has these properties:
8553 * - **data** – `{string|Object}` – The response body transformed with the transform functions.
8554 * - **status** – `{number}` – HTTP status code of the response.
8555 * - **headers** – `{function([headerName])}` – Header getter function.
8556 * - **config** – `{Object}` – The configuration object that was used to generate the request.
8558 * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
8559 * requests. This is primarily meant to be used for debugging purposes.
8564 <file name="index.html">
8565 <div ng-controller="FetchCtrl">
8566 <select ng-model="method">
8567 <option>GET</option>
8568 <option>JSONP</option>
8570 <input type="text" ng-model="url" size="80"/>
8571 <button ng-click="fetch()">fetch</button><br>
8572 <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
8573 <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
8574 <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
8575 <pre>http status code: {{status}}</pre>
8576 <pre>http response data: {{data}}</pre>
8579 <file name="script.js">
8580 function FetchCtrl($scope, $http, $templateCache) {
8581 $scope.method = 'GET';
8582 $scope.url = 'http-hello.html';
8584 $scope.fetch = function() {
8586 $scope.response = null;
8588 $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
8589 success(function(data, status) {
8590 $scope.status = status;
8593 error(function(data, status) {
8594 $scope.data = data || "Request failed";
8595 $scope.status = status;
8599 $scope.updateModel = function(method, url) {
8600 $scope.method = method;
8605 <file name="http-hello.html">
8608 <file name="scenario.js">
8609 it('should make an xhr GET request', function() {
8610 element(':button:contains("Sample GET")').click();
8611 element(':button:contains("fetch")').click();
8612 expect(binding('status')).toBe('200');
8613 expect(binding('data')).toMatch(/Hello, \$http!/);
8616 it('should make a JSONP request to angularjs.org', function() {
8617 element(':button:contains("Sample JSONP")').click();
8618 element(':button:contains("fetch")').click();
8619 expect(binding('status')).toBe('200');
8620 expect(binding('data')).toMatch(/Super Hero!/);
8623 it('should make JSONP request to invalid URL and invoke the error handler',
8625 element(':button:contains("Invalid JSONP")').click();
8626 element(':button:contains("fetch")').click();
8627 expect(binding('status')).toBe('0');
8628 expect(binding('data')).toBe('Request failed');
8633 function $http(config) {
8634 config.method = uppercase(config.method);
8636 var reqTransformFn = config.transformRequest || $config.transformRequest,
8637 respTransformFn = config.transformResponse || $config.transformResponse,
8638 defHeaders = $config.headers,
8639 reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']},
8640 defHeaders.common, defHeaders[lowercase(config.method)], config.headers),
8641 reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn),
8644 // strip content-type if data is undefined
8645 if (isUndefined(config.data)) {
8646 delete reqHeaders['Content-Type'];
8650 promise = sendReq(config, reqData, reqHeaders);
8653 // transform future response
8654 promise = promise.then(transformResponse, transformResponse);
8656 // apply interceptors
8657 forEach(responseInterceptors, function(interceptor) {
8658 promise = interceptor(promise);
8661 promise.success = function(fn) {
8662 promise.then(function(response) {
8663 fn(response.data, response.status, response.headers, config);
8668 promise.error = function(fn) {
8669 promise.then(null, function(response) {
8670 fn(response.data, response.status, response.headers, config);
8677 function transformResponse(response) {
8678 // make a copy since the response must be cacheable
8679 var resp = extend({}, response, {
8680 data: transformData(response.data, response.headers, respTransformFn)
8682 return (isSuccess(response.status))
8688 $http.pendingRequests = [];
8692 * @name ng.$http#get
8693 * @methodOf ng.$http
8696 * Shortcut method to perform `GET` request
8698 * @param {string} url Relative or absolute URL specifying the destination of the request
8699 * @param {Object=} config Optional configuration object
8700 * @returns {HttpPromise} Future object
8705 * @name ng.$http#delete
8706 * @methodOf ng.$http
8709 * Shortcut method to perform `DELETE` request
8711 * @param {string} url Relative or absolute URL specifying the destination of the request
8712 * @param {Object=} config Optional configuration object
8713 * @returns {HttpPromise} Future object
8718 * @name ng.$http#head
8719 * @methodOf ng.$http
8722 * Shortcut method to perform `HEAD` request
8724 * @param {string} url Relative or absolute URL specifying the destination of the request
8725 * @param {Object=} config Optional configuration object
8726 * @returns {HttpPromise} Future object
8731 * @name ng.$http#jsonp
8732 * @methodOf ng.$http
8735 * Shortcut method to perform `JSONP` request
8737 * @param {string} url Relative or absolute URL specifying the destination of the request.
8738 * Should contain `JSON_CALLBACK` string.
8739 * @param {Object=} config Optional configuration object
8740 * @returns {HttpPromise} Future object
8742 createShortMethods('get', 'delete', 'head', 'jsonp');
8746 * @name ng.$http#post
8747 * @methodOf ng.$http
8750 * Shortcut method to perform `POST` request
8752 * @param {string} url Relative or absolute URL specifying the destination of the request
8753 * @param {*} data Request content
8754 * @param {Object=} config Optional configuration object
8755 * @returns {HttpPromise} Future object
8760 * @name ng.$http#put
8761 * @methodOf ng.$http
8764 * Shortcut method to perform `PUT` request
8766 * @param {string} url Relative or absolute URL specifying the destination of the request
8767 * @param {*} data Request content
8768 * @param {Object=} config Optional configuration object
8769 * @returns {HttpPromise} Future object
8771 createShortMethodsWithData('post', 'put');
8775 * @name ng.$http#defaults
8776 * @propertyOf ng.$http
8779 * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
8780 * default headers as well as request and response transformations.
8782 * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
8784 $http.defaults = $config;
8790 function createShortMethods(names) {
8791 forEach(arguments, function(name) {
8792 $http[name] = function(url, config) {
8793 return $http(extend(config || {}, {
8802 function createShortMethodsWithData(name) {
8803 forEach(arguments, function(name) {
8804 $http[name] = function(url, data, config) {
8805 return $http(extend(config || {}, {
8818 * !!! ACCESSES CLOSURE VARS:
8819 * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
8821 function sendReq(config, reqData, reqHeaders) {
8822 var deferred = $q.defer(),
8823 promise = deferred.promise,
8826 url = buildUrl(config.url, config.params);
8828 $http.pendingRequests.push(config);
8829 promise.then(removePendingReq, removePendingReq);
8832 if (config.cache && config.method == 'GET') {
8833 cache = isObject(config.cache) ? config.cache : defaultCache;
8837 cachedResp = cache.get(url);
8839 if (cachedResp.then) {
8840 // cached request has already been sent, but there is no response yet
8841 cachedResp.then(removePendingReq, removePendingReq);
8844 // serving from cache
8845 if (isArray(cachedResp)) {
8846 resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
8848 resolvePromise(cachedResp, 200, {});
8852 // put the promise for the non-transformed response into cache as a placeholder
8853 cache.put(url, promise);
8857 // if we won't have the response in cache, send the request to the backend
8859 $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
8860 config.withCredentials);
8867 * Callback registered to $httpBackend():
8868 * - caches the response if desired
8869 * - resolves the raw $http promise
8872 function done(status, response, headersString) {
8874 if (isSuccess(status)) {
8875 cache.put(url, [status, response, parseHeaders(headersString)]);
8877 // remove promise from the cache
8882 resolvePromise(response, status, headersString);
8883 $rootScope.$apply();
8888 * Resolves the raw $http promise.
8890 function resolvePromise(response, status, headers) {
8891 // normalize internal statuses to 0
8892 status = Math.max(status, 0);
8894 (isSuccess(status) ? deferred.resolve : deferred.reject)({
8897 headers: headersGetter(headers),
8903 function removePendingReq() {
8904 var idx = indexOf($http.pendingRequests, config);
8905 if (idx !== -1) $http.pendingRequests.splice(idx, 1);
8910 function buildUrl(url, params) {
8911 if (!params) return url;
8913 forEachSorted(params, function(value, key) {
8914 if (value == null || value == undefined) return;
8915 if (isObject(value)) {
8916 value = toJson(value);
8918 parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
8920 return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
8926 var XHR = window.XMLHttpRequest || function() {
8927 try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
8928 try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
8929 try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
8930 throw new Error("This browser does not support XMLHttpRequest.");
8936 * @name ng.$httpBackend
8937 * @requires $browser
8939 * @requires $document
8942 * HTTP backend used by the {@link ng.$http service} that delegates to
8943 * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
8945 * You should never need to use this service directly, instead use the higher-level abstractions:
8946 * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
8948 * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
8949 * $httpBackend} which can be trained with responses.
8951 function $HttpBackendProvider() {
8952 this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
8953 return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
8954 $document[0], $window.location.protocol.replace(':', ''));
8958 function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
8959 // TODO(vojta): fix the signature
8960 return function(method, url, post, callback, headers, timeout, withCredentials) {
8961 $browser.$$incOutstandingRequestCount();
8962 url = url || $browser.url();
8964 if (lowercase(method) == 'jsonp') {
8965 var callbackId = '_' + (callbacks.counter++).toString(36);
8966 callbacks[callbackId] = function(data) {
8967 callbacks[callbackId].data = data;
8970 jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
8972 if (callbacks[callbackId].data) {
8973 completeRequest(callback, 200, callbacks[callbackId].data);
8975 completeRequest(callback, -2);
8977 delete callbacks[callbackId];
8980 var xhr = new XHR();
8981 xhr.open(method, url, true);
8982 forEach(headers, function(value, key) {
8983 if (value) xhr.setRequestHeader(key, value);
8988 // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
8989 // response is in the cache. the promise api will ensure that to the app code the api is
8991 xhr.onreadystatechange = function() {
8992 if (xhr.readyState == 4) {
8994 callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders());
8998 if (withCredentials) {
8999 xhr.withCredentials = true;
9002 xhr.send(post || '');
9005 $browserDefer(function() {
9013 function completeRequest(callback, status, response, headersString) {
9014 // URL_MATCH is defined in src/service/location.js
9015 var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1];
9017 // fix status code for file protocol (it's always 0)
9018 status = (protocol == 'file') ? (response ? 200 : 404) : status;
9020 // normalize IE bug (http://bugs.jquery.com/ticket/1450)
9021 status = status == 1223 ? 204 : status;
9023 callback(status, response, headersString);
9024 $browser.$$completeOutstandingRequest(noop);
9028 function jsonpReq(url, done) {
9029 // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
9030 // - fetches local scripts via XHR and evals them
9031 // - adds and immediately removes script elements from the document
9032 var script = rawDocument.createElement('script'),
9033 doneWrapper = function() {
9034 rawDocument.body.removeChild(script);
9038 script.type = 'text/javascript';
9042 script.onreadystatechange = function() {
9043 if (/loaded|complete/.test(script.readyState)) doneWrapper();
9046 script.onload = script.onerror = doneWrapper;
9049 rawDocument.body.appendChild(script);
9058 * $locale service provides localization rules for various Angular components. As of right now the
9059 * only public api is:
9061 * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
9063 function $LocaleProvider(){
9064 this.$get = function() {
9072 { // Decimal Pattern
9082 },{ //Currency Pattern
9098 MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
9100 SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
9101 DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
9102 SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
9104 medium: 'MMM d, y h:mm:ss a',
9105 short: 'M/d/yy h:mm a',
9106 fullDate: 'EEEE, MMMM d, y',
9107 longDate: 'MMMM d, y',
9108 mediumDate: 'MMM d, y',
9109 shortDate: 'M/d/yy',
9110 mediumTime: 'h:mm:ss a',
9114 pluralCat: function(num) {
9124 function $TimeoutProvider() {
9125 this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
9126 function($rootScope, $browser, $q, $exceptionHandler) {
9133 * @requires $browser
9136 * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
9137 * block and delegates any exceptions to
9138 * {@link ng.$exceptionHandler $exceptionHandler} service.
9140 * The return value of registering a timeout function is a promise which will be resolved when
9141 * the timeout is reached and the timeout function is executed.
9143 * To cancel a the timeout request, call `$timeout.cancel(promise)`.
9145 * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
9146 * synchronously flush the queue of deferred functions.
9148 * @param {function()} fn A function, who's execution should be delayed.
9149 * @param {number=} [delay=0] Delay in milliseconds.
9150 * @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise
9151 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
9152 * @returns {*} Promise that will be resolved when the timeout is reached. The value this
9153 * promise will be resolved with is the return value of the `fn` function.
9155 function timeout(fn, delay, invokeApply) {
9156 var deferred = $q.defer(),
9157 promise = deferred.promise,
9158 skipApply = (isDefined(invokeApply) && !invokeApply),
9161 timeoutId = $browser.defer(function() {
9163 deferred.resolve(fn());
9166 $exceptionHandler(e);
9169 if (!skipApply) $rootScope.$apply();
9172 cleanup = function() {
9173 delete deferreds[promise.$$timeoutId];
9176 promise.$$timeoutId = timeoutId;
9177 deferreds[timeoutId] = deferred;
9178 promise.then(cleanup, cleanup);
9186 * @name ng.$timeout#cancel
9187 * @methodOf ng.$timeout
9190 * Cancels a task associated with the `promise`. As a result of this the promise will be
9191 * resolved with a rejection.
9193 * @param {Promise=} promise Promise returned by the `$timeout` function.
9194 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
9197 timeout.cancel = function(promise) {
9198 if (promise && promise.$$timeoutId in deferreds) {
9199 deferreds[promise.$$timeoutId].reject('canceled');
9200 return $browser.defer.cancel(promise.$$timeoutId);
9211 * @name ng.$filterProvider
9214 * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
9215 * achieve this a filter definition consists of a factory function which is annotated with dependencies and is
9216 * responsible for creating a the filter function.
9219 * // Filter registration
9220 * function MyModule($provide, $filterProvider) {
9221 * // create a service to demonstrate injection (not always needed)
9222 * $provide.value('greet', function(name){
9223 * return 'Hello ' + name + '!';
9226 * // register a filter factory which uses the
9227 * // greet service to demonstrate DI.
9228 * $filterProvider.register('greet', function(greet){
9229 * // return the filter function which uses the greet service
9230 * // to generate salutation
9231 * return function(text) {
9232 * // filters need to be forgiving so check input validity
9233 * return text && greet(text) || text;
9239 * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
9241 * it('should be the same instance', inject(
9242 * function($filterProvider) {
9243 * $filterProvider.register('reverse', function(){
9247 * function($filter, reverseFilter) {
9248 * expect($filter('reverse')).toBe(reverseFilter);
9253 * For more information about how angular filters work, and how to create your own filters, see
9254 * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
9259 * @name ng.$filterProvider#register
9260 * @methodOf ng.$filterProvider
9262 * Register filter factory function.
9264 * @param {String} name Name of the filter.
9265 * @param {function} fn The filter factory function which is injectable.
9274 * Filters are used for formatting data displayed to the user.
9276 * The general syntax in templates is as follows:
9278 * {{ expression | [ filter_name ] }}
9280 * @param {String} name Name of the filter function to retrieve
9281 * @return {Function} the filter function
9283 $FilterProvider.$inject = ['$provide'];
9284 function $FilterProvider($provide) {
9285 var suffix = 'Filter';
9287 function register(name, factory) {
9288 return $provide.factory(name + suffix, factory);
9290 this.register = register;
9292 this.$get = ['$injector', function($injector) {
9293 return function(name) {
9294 return $injector.get(name + suffix);
9298 ////////////////////////////////////////
9300 register('currency', currencyFilter);
9301 register('date', dateFilter);
9302 register('filter', filterFilter);
9303 register('json', jsonFilter);
9304 register('limitTo', limitToFilter);
9305 register('lowercase', lowercaseFilter);
9306 register('number', numberFilter);
9307 register('orderBy', orderByFilter);
9308 register('uppercase', uppercaseFilter);
9313 * @name ng.filter:filter
9317 * Selects a subset of items from `array` and returns it as a new array.
9319 * Note: This function is used to augment the `Array` type in Angular expressions. See
9320 * {@link ng.$filter} for more information about Angular arrays.
9322 * @param {Array} array The source array.
9323 * @param {string|Object|function()} expression The predicate to be used for selecting items from
9328 * - `string`: Predicate that results in a substring match using the value of `expression`
9329 * string. All strings or objects with string properties in `array` that contain this string
9330 * will be returned. The predicate can be negated by prefixing the string with `!`.
9332 * - `Object`: A pattern object can be used to filter specific properties on objects contained
9333 * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
9334 * which have property `name` containing "M" and property `phone` containing "1". A special
9335 * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
9336 * property of the object. That's equivalent to the simple substring match with a `string`
9337 * as described above.
9339 * - `function`: A predicate function can be used to write arbitrary filters. The function is
9340 * called for each element of `array`. The final result is an array of those elements that
9341 * the predicate returned true for.
9346 <div ng-init="friends = [{name:'John', phone:'555-1276'},
9347 {name:'Mary', phone:'800-BIG-MARY'},
9348 {name:'Mike', phone:'555-4321'},
9349 {name:'Adam', phone:'555-5678'},
9350 {name:'Julie', phone:'555-8765'}]"></div>
9352 Search: <input ng-model="searchText">
9353 <table id="searchTextResults">
9354 <tr><th>Name</th><th>Phone</th><tr>
9355 <tr ng-repeat="friend in friends | filter:searchText">
9356 <td>{{friend.name}}</td>
9357 <td>{{friend.phone}}</td>
9361 Any: <input ng-model="search.$"> <br>
9362 Name only <input ng-model="search.name"><br>
9363 Phone only <input ng-model="search.phone"å><br>
9364 <table id="searchObjResults">
9365 <tr><th>Name</th><th>Phone</th><tr>
9366 <tr ng-repeat="friend in friends | filter:search">
9367 <td>{{friend.name}}</td>
9368 <td>{{friend.phone}}</td>
9373 it('should search across all fields when filtering with a string', function() {
9374 input('searchText').enter('m');
9375 expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
9376 toEqual(['Mary', 'Mike', 'Adam']);
9378 input('searchText').enter('76');
9379 expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
9380 toEqual(['John', 'Julie']);
9383 it('should search in specific fields when filtering with a predicate object', function() {
9384 input('search.$').enter('i');
9385 expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
9386 toEqual(['Mary', 'Mike', 'Julie']);
9391 function filterFilter() {
9392 return function(array, expression) {
9393 if (!(array instanceof Array)) return array;
9394 var predicates = [];
9395 predicates.check = function(value) {
9396 for (var j = 0; j < predicates.length; j++) {
9397 if(!predicates[j](value)) {
9403 var search = function(obj, text){
9404 if (text.charAt(0) === '!') {
9405 return !search(obj, text.substr(1));
9407 switch (typeof obj) {
9411 return ('' + obj).toLowerCase().indexOf(text) > -1;
9413 for ( var objKey in obj) {
9414 if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
9420 for ( var i = 0; i < obj.length; i++) {
9421 if (search(obj[i], text)) {
9430 switch (typeof expression) {
9434 expression = {$:expression};
9436 for (var key in expression) {
9439 var text = (''+expression[key]).toLowerCase();
9441 predicates.push(function(value) {
9442 return search(value, text);
9448 var text = (''+expression[key]).toLowerCase();
9450 predicates.push(function(value) {
9451 return search(getter(value, path), text);
9458 predicates.push(expression);
9464 for ( var j = 0; j < array.length; j++) {
9465 var value = array[j];
9466 if (predicates.check(value)) {
9467 filtered.push(value);
9476 * @name ng.filter:currency
9480 * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
9481 * symbol for current locale is used.
9483 * @param {number} amount Input to filter.
9484 * @param {string=} symbol Currency symbol or identifier to be displayed.
9485 * @returns {string} Formatted number.
9492 function Ctrl($scope) {
9493 $scope.amount = 1234.56;
9496 <div ng-controller="Ctrl">
9497 <input type="number" ng-model="amount"> <br>
9498 default currency symbol ($): {{amount | currency}}<br>
9499 custom currency identifier (USD$): {{amount | currency:"USD$"}}
9503 it('should init with 1234.56', function() {
9504 expect(binding('amount | currency')).toBe('$1,234.56');
9505 expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
9507 it('should update', function() {
9508 input('amount').enter('-1234');
9509 expect(binding('amount | currency')).toBe('($1,234.00)');
9510 expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
9515 currencyFilter.$inject = ['$locale'];
9516 function currencyFilter($locale) {
9517 var formats = $locale.NUMBER_FORMATS;
9518 return function(amount, currencySymbol){
9519 if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
9520 return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
9521 replace(/\u00A4/g, currencySymbol);
9527 * @name ng.filter:number
9531 * Formats a number as text.
9533 * If the input is not a number an empty string is returned.
9535 * @param {number|string} number Number to format.
9536 * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
9537 * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
9543 function Ctrl($scope) {
9544 $scope.val = 1234.56789;
9547 <div ng-controller="Ctrl">
9548 Enter number: <input ng-model='val'><br>
9549 Default formatting: {{val | number}}<br>
9550 No fractions: {{val | number:0}}<br>
9551 Negative number: {{-val | number:4}}
9555 it('should format numbers', function() {
9556 expect(binding('val | number')).toBe('1,234.568');
9557 expect(binding('val | number:0')).toBe('1,235');
9558 expect(binding('-val | number:4')).toBe('-1,234.5679');
9561 it('should update', function() {
9562 input('val').enter('3374.333');
9563 expect(binding('val | number')).toBe('3,374.333');
9564 expect(binding('val | number:0')).toBe('3,374');
9565 expect(binding('-val | number:4')).toBe('-3,374.3330');
9572 numberFilter.$inject = ['$locale'];
9573 function numberFilter($locale) {
9574 var formats = $locale.NUMBER_FORMATS;
9575 return function(number, fractionSize) {
9576 return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
9581 var DECIMAL_SEP = '.';
9582 function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
9583 if (isNaN(number) || !isFinite(number)) return '';
9585 var isNegative = number < 0;
9586 number = Math.abs(number);
9587 var numStr = number + '',
9591 if (numStr.indexOf('e') !== -1) {
9592 formatedText = numStr;
9594 var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
9596 // determine fractionSize if it is not specified
9597 if (isUndefined(fractionSize)) {
9598 fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
9601 var pow = Math.pow(10, fractionSize);
9602 number = Math.round(number * pow) / pow;
9603 var fraction = ('' + number).split(DECIMAL_SEP);
9604 var whole = fraction[0];
9605 fraction = fraction[1] || '';
9608 lgroup = pattern.lgSize,
9609 group = pattern.gSize;
9611 if (whole.length >= (lgroup + group)) {
9612 pos = whole.length - lgroup;
9613 for (var i = 0; i < pos; i++) {
9614 if ((pos - i)%group === 0 && i !== 0) {
9615 formatedText += groupSep;
9617 formatedText += whole.charAt(i);
9621 for (i = pos; i < whole.length; i++) {
9622 if ((whole.length - i)%lgroup === 0 && i !== 0) {
9623 formatedText += groupSep;
9625 formatedText += whole.charAt(i);
9628 // format fraction part.
9629 while(fraction.length < fractionSize) {
9633 if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize);
9636 parts.push(isNegative ? pattern.negPre : pattern.posPre);
9637 parts.push(formatedText);
9638 parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
9639 return parts.join('');
9642 function padNumber(num, digits, trim) {
9649 while(num.length < digits) num = '0' + num;
9651 num = num.substr(num.length - digits);
9656 function dateGetter(name, size, offset, trim) {
9657 return function(date) {
9658 var value = date['get' + name]();
9659 if (offset > 0 || value > -offset)
9661 if (value === 0 && offset == -12 ) value = 12;
9662 return padNumber(value, size, trim);
9666 function dateStrGetter(name, shortForm) {
9667 return function(date, formats) {
9668 var value = date['get' + name]();
9669 var get = uppercase(shortForm ? ('SHORT' + name) : name);
9671 return formats[get][value];
9675 function timeZoneGetter(date) {
9676 var offset = date.getTimezoneOffset();
9677 return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2);
9680 function ampmGetter(date, formats) {
9681 return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
9684 var DATE_FORMATS = {
9685 yyyy: dateGetter('FullYear', 4),
9686 yy: dateGetter('FullYear', 2, 0, true),
9687 y: dateGetter('FullYear', 1),
9688 MMMM: dateStrGetter('Month'),
9689 MMM: dateStrGetter('Month', true),
9690 MM: dateGetter('Month', 2, 1),
9691 M: dateGetter('Month', 1, 1),
9692 dd: dateGetter('Date', 2),
9693 d: dateGetter('Date', 1),
9694 HH: dateGetter('Hours', 2),
9695 H: dateGetter('Hours', 1),
9696 hh: dateGetter('Hours', 2, -12),
9697 h: dateGetter('Hours', 1, -12),
9698 mm: dateGetter('Minutes', 2),
9699 m: dateGetter('Minutes', 1),
9700 ss: dateGetter('Seconds', 2),
9701 s: dateGetter('Seconds', 1),
9702 EEEE: dateStrGetter('Day'),
9703 EEE: dateStrGetter('Day', true),
9708 var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
9709 NUMBER_STRING = /^\d+$/;
9713 * @name ng.filter:date
9717 * Formats `date` to a string based on the requested `format`.
9719 * `format` string can be composed of the following elements:
9721 * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
9722 * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
9723 * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
9724 * * `'MMMM'`: Month in year (January-December)
9725 * * `'MMM'`: Month in year (Jan-Dec)
9726 * * `'MM'`: Month in year, padded (01-12)
9727 * * `'M'`: Month in year (1-12)
9728 * * `'dd'`: Day in month, padded (01-31)
9729 * * `'d'`: Day in month (1-31)
9730 * * `'EEEE'`: Day in Week,(Sunday-Saturday)
9731 * * `'EEE'`: Day in Week, (Sun-Sat)
9732 * * `'HH'`: Hour in day, padded (00-23)
9733 * * `'H'`: Hour in day (0-23)
9734 * * `'hh'`: Hour in am/pm, padded (01-12)
9735 * * `'h'`: Hour in am/pm, (1-12)
9736 * * `'mm'`: Minute in hour, padded (00-59)
9737 * * `'m'`: Minute in hour (0-59)
9738 * * `'ss'`: Second in minute, padded (00-59)
9739 * * `'s'`: Second in minute (0-59)
9740 * * `'a'`: am/pm marker
9741 * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200)
9743 * `format` string can also be one of the following predefined
9744 * {@link guide/i18n localizable formats}:
9746 * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
9747 * (e.g. Sep 3, 2010 12:05:08 pm)
9748 * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
9749 * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
9750 * (e.g. Friday, September 3, 2010)
9751 * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
9752 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
9753 * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
9754 * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
9755 * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
9757 * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
9758 * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
9759 * (e.g. `"h o''clock"`).
9761 * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
9762 * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's
9763 * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ).
9764 * @param {string=} format Formatting rules (see Description). If not specified,
9765 * `mediumDate` is used.
9766 * @returns {string} Formatted string or the input if input is not recognized as date/millis.
9771 <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
9772 {{1288323623006 | date:'medium'}}<br>
9773 <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
9774 {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
9775 <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
9776 {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
9779 it('should format date', function() {
9780 expect(binding("1288323623006 | date:'medium'")).
9781 toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
9782 expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
9783 toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/);
9784 expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
9785 toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
9790 dateFilter.$inject = ['$locale'];
9791 function dateFilter($locale) {
9794 var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
9795 function jsonStringToDate(string){
9797 if (match = string.match(R_ISO8601_STR)) {
9798 var date = new Date(0),
9802 tzHour = int(match[9] + match[10]);
9803 tzMin = int(match[9] + match[11]);
9805 date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
9806 date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
9813 return function(date, format) {
9818 format = format || 'mediumDate';
9819 format = $locale.DATETIME_FORMATS[format] || format;
9820 if (isString(date)) {
9821 if (NUMBER_STRING.test(date)) {
9824 date = jsonStringToDate(date);
9828 if (isNumber(date)) {
9829 date = new Date(date);
9832 if (!isDate(date)) {
9837 match = DATE_FORMATS_SPLIT.exec(format);
9839 parts = concat(parts, match, 1);
9840 format = parts.pop();
9847 forEach(parts, function(value){
9848 fn = DATE_FORMATS[value];
9849 text += fn ? fn(date, $locale.DATETIME_FORMATS)
9850 : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
9860 * @name ng.filter:json
9864 * Allows you to convert a JavaScript object into JSON string.
9866 * This filter is mostly useful for debugging. When using the double curly {{value}} notation
9867 * the binding is automatically converted to JSON.
9869 * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
9870 * @returns {string} JSON string.
9876 <pre>{{ {'name':'value'} | json }}</pre>
9879 it('should jsonify filtered objects', function() {
9880 expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
9886 function jsonFilter() {
9887 return function(object) {
9888 return toJson(object, true);
9895 * @name ng.filter:lowercase
9898 * Converts string to lowercase.
9899 * @see angular.lowercase
9901 var lowercaseFilter = valueFn(lowercase);
9906 * @name ng.filter:uppercase
9909 * Converts string to uppercase.
9910 * @see angular.uppercase
9912 var uppercaseFilter = valueFn(uppercase);
9916 * @name ng.filter:limitTo
9920 * Creates a new array containing only a specified number of elements in an array. The elements
9921 * are taken from either the beginning or the end of the source array, as specified by the
9922 * value and sign (positive or negative) of `limit`.
9924 * Note: This function is used to augment the `Array` type in Angular expressions. See
9925 * {@link ng.$filter} for more information about Angular arrays.
9927 * @param {Array} array Source array to be limited.
9928 * @param {string|Number} limit The length of the returned array. If the `limit` number is
9929 * positive, `limit` number of items from the beginning of the source array are copied.
9930 * If the number is negative, `limit` number of items from the end of the source array are
9931 * copied. The `limit` will be trimmed if it exceeds `array.length`
9932 * @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit`
9939 function Ctrl($scope) {
9940 $scope.numbers = [1,2,3,4,5,6,7,8,9];
9944 <div ng-controller="Ctrl">
9945 Limit {{numbers}} to: <input type="integer" ng-model="limit">
9946 <p>Output: {{ numbers | limitTo:limit }}</p>
9950 it('should limit the numer array to first three items', function() {
9951 expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
9952 expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
9955 it('should update the output when -3 is entered', function() {
9956 input('limit').enter(-3);
9957 expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
9960 it('should not exceed the maximum size of input array', function() {
9961 input('limit').enter(100);
9962 expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
9967 function limitToFilter(){
9968 return function(array, limit) {
9969 if (!(array instanceof Array)) return array;
9974 // check that array is iterable
9975 if (!array || !(array instanceof Array))
9978 // if abs(limit) exceeds maximum length, trim it
9979 if (limit > array.length)
9980 limit = array.length;
9981 else if (limit < -array.length)
9982 limit = -array.length;
9988 i = array.length + limit;
10002 * @name ng.filter:orderBy
10006 * Orders a specified `array` by the `expression` predicate.
10008 * Note: this function is used to augment the `Array` type in Angular expressions. See
10009 * {@link ng.$filter} for more informaton about Angular arrays.
10011 * @param {Array} array The array to sort.
10012 * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
10013 * used by the comparator to determine the order of elements.
10017 * - `function`: Getter function. The result of this function will be sorted using the
10018 * `<`, `=`, `>` operator.
10019 * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
10020 * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
10021 * ascending or descending sort order (for example, +name or -name).
10022 * - `Array`: An array of function or string predicates. The first predicate in the array
10023 * is used for sorting, but when two items are equivalent, the next predicate is used.
10025 * @param {boolean=} reverse Reverse the order the array.
10026 * @returns {Array} Sorted copy of the source array.
10032 function Ctrl($scope) {
10034 [{name:'John', phone:'555-1212', age:10},
10035 {name:'Mary', phone:'555-9876', age:19},
10036 {name:'Mike', phone:'555-4321', age:21},
10037 {name:'Adam', phone:'555-5678', age:35},
10038 {name:'Julie', phone:'555-8765', age:29}]
10039 $scope.predicate = '-age';
10042 <div ng-controller="Ctrl">
10043 <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
10045 [ <a href="" ng-click="predicate=''">unsorted</a> ]
10046 <table class="friend">
10048 <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
10049 (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
10050 <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
10051 <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
10053 <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
10054 <td>{{friend.name}}</td>
10055 <td>{{friend.phone}}</td>
10056 <td>{{friend.age}}</td>
10062 it('should be reverse ordered by aged', function() {
10063 expect(binding('predicate')).toBe('-age');
10064 expect(repeater('table.friend', 'friend in friends').column('friend.age')).
10065 toEqual(['35', '29', '21', '19', '10']);
10066 expect(repeater('table.friend', 'friend in friends').column('friend.name')).
10067 toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
10070 it('should reorder the table when user selects different predicate', function() {
10071 element('.doc-example-live a:contains("Name")').click();
10072 expect(repeater('table.friend', 'friend in friends').column('friend.name')).
10073 toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
10074 expect(repeater('table.friend', 'friend in friends').column('friend.age')).
10075 toEqual(['35', '10', '29', '19', '21']);
10077 element('.doc-example-live a:contains("Phone")').click();
10078 expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
10079 toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
10080 expect(repeater('table.friend', 'friend in friends').column('friend.name')).
10081 toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
10086 orderByFilter.$inject = ['$parse'];
10087 function orderByFilter($parse){
10088 return function(array, sortPredicate, reverseOrder) {
10089 if (!(array instanceof Array)) return array;
10090 if (!sortPredicate) return array;
10091 sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
10092 sortPredicate = map(sortPredicate, function(predicate){
10093 var descending = false, get = predicate || identity;
10094 if (isString(predicate)) {
10095 if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
10096 descending = predicate.charAt(0) == '-';
10097 predicate = predicate.substring(1);
10099 get = $parse(predicate);
10101 return reverseComparator(function(a,b){
10102 return compare(get(a),get(b));
10105 var arrayCopy = [];
10106 for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
10107 return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
10109 function comparator(o1, o2){
10110 for ( var i = 0; i < sortPredicate.length; i++) {
10111 var comp = sortPredicate[i](o1, o2);
10112 if (comp !== 0) return comp;
10116 function reverseComparator(comp, descending) {
10117 return toBoolean(descending)
10118 ? function(a,b){return comp(b,a);}
10121 function compare(v1, v2){
10122 var t1 = typeof v1;
10123 var t2 = typeof v2;
10125 if (t1 == "string") v1 = v1.toLowerCase();
10126 if (t1 == "string") v2 = v2.toLowerCase();
10127 if (v1 === v2) return 0;
10128 return v1 < v2 ? -1 : 1;
10130 return t1 < t2 ? -1 : 1;
10136 function ngDirective(directive) {
10137 if (isFunction(directive)) {
10142 directive.restrict = directive.restrict || 'AC';
10143 return valueFn(directive);
10148 * @name ng.directive:a
10152 * Modifies the default behavior of html A tag, so that the default action is prevented when href
10153 * attribute is empty.
10155 * The reasoning for this change is to allow easy creation of action links with `ngClick` directive
10156 * without changing the location or causing page reloads, e.g.:
10157 * <a href="" ng-click="model.$save()">Save</a>
10159 var htmlAnchorDirective = valueFn({
10161 compile: function(element, attr) {
10162 // turn <a href ng-click="..">link</a> into a link in IE
10163 // but only if it doesn't have name attribute, in which case it's an anchor
10165 attr.$set('href', '');
10168 return function(scope, element) {
10169 element.bind('click', function(event){
10170 // if we have no href url, then don't navigate anywhere.
10171 if (!element.attr('href')) {
10172 event.preventDefault();
10181 * @name ng.directive:ngHref
10185 * Using Angular markup like {{hash}} in an href attribute makes
10186 * the page open to a wrong URL, if the user clicks that link before
10187 * angular has a chance to replace the {{hash}} with actual URL, the
10188 * link will be broken and will most likely return a 404 error.
10189 * The `ngHref` directive solves this problem.
10191 * The buggy way to write it:
10193 * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
10196 * The correct way to write it:
10198 * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
10202 * @param {template} ngHref any string which can contain `{{}}` markup.
10205 * This example uses `link` variable inside `href` attribute:
10208 <input ng-model="value" /><br />
10209 <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
10210 <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
10211 <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
10212 <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
10213 <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
10214 <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
10217 it('should execute ng-click but not reload when href without value', function() {
10218 element('#link-1').click();
10219 expect(input('value').val()).toEqual('1');
10220 expect(element('#link-1').attr('href')).toBe("");
10223 it('should execute ng-click but not reload when href empty string', function() {
10224 element('#link-2').click();
10225 expect(input('value').val()).toEqual('2');
10226 expect(element('#link-2').attr('href')).toBe("");
10229 it('should execute ng-click and change url when ng-href specified', function() {
10230 expect(element('#link-3').attr('href')).toBe("/123");
10232 element('#link-3').click();
10233 expect(browser().window().path()).toEqual('/123');
10236 it('should execute ng-click but not reload when href empty string and name specified', function() {
10237 element('#link-4').click();
10238 expect(input('value').val()).toEqual('4');
10239 expect(element('#link-4').attr('href')).toBe('');
10242 it('should execute ng-click but not reload when no href but name specified', function() {
10243 element('#link-5').click();
10244 expect(input('value').val()).toEqual('5');
10245 expect(element('#link-5').attr('href')).toBe('');
10248 it('should only change url when only ng-href', function() {
10249 input('value').enter('6');
10250 expect(element('#link-6').attr('href')).toBe('6');
10252 element('#link-6').click();
10253 expect(browser().location().url()).toEqual('/6');
10261 * @name ng.directive:ngSrc
10265 * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
10266 * work right: The browser will fetch from the URL with the literal
10267 * text `{{hash}}` until Angular replaces the expression inside
10268 * `{{hash}}`. The `ngSrc` directive solves this problem.
10270 * The buggy way to write it:
10272 * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
10275 * The correct way to write it:
10277 * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
10281 * @param {template} ngSrc any string which can contain `{{}}` markup.
10286 * @name ng.directive:ngDisabled
10291 * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
10293 * <div ng-init="scope = { isDisabled: false }">
10294 * <button disabled="{{scope.isDisabled}}">Disabled</button>
10298 * The HTML specs do not require browsers to preserve the special attributes such as disabled.
10299 * (The presence of them means true and absence means false)
10300 * This prevents the angular compiler from correctly retrieving the binding expression.
10301 * To solve this problem, we introduce the `ngDisabled` directive.
10306 Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
10307 <button ng-model="button" ng-disabled="checked">Button</button>
10310 it('should toggle button', function() {
10311 expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
10312 input('checked').check();
10313 expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
10319 * @param {expression} ngDisabled Angular expression that will be evaluated.
10325 * @name ng.directive:ngChecked
10329 * The HTML specs do not require browsers to preserve the special attributes such as checked.
10330 * (The presence of them means true and absence means false)
10331 * This prevents the angular compiler from correctly retrieving the binding expression.
10332 * To solve this problem, we introduce the `ngChecked` directive.
10336 Check me to check both: <input type="checkbox" ng-model="master"><br/>
10337 <input id="checkSlave" type="checkbox" ng-checked="master">
10340 it('should check both checkBoxes', function() {
10341 expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
10342 input('master').check();
10343 expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
10349 * @param {expression} ngChecked Angular expression that will be evaluated.
10355 * @name ng.directive:ngMultiple
10359 * The HTML specs do not require browsers to preserve the special attributes such as multiple.
10360 * (The presence of them means true and absence means false)
10361 * This prevents the angular compiler from correctly retrieving the binding expression.
10362 * To solve this problem, we introduce the `ngMultiple` directive.
10367 Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
10368 <select id="select" ng-multiple="checked">
10369 <option>Misko</option>
10370 <option>Igor</option>
10371 <option>Vojta</option>
10372 <option>Di</option>
10376 it('should toggle multiple', function() {
10377 expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
10378 input('checked').check();
10379 expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
10385 * @param {expression} ngMultiple Angular expression that will be evaluated.
10391 * @name ng.directive:ngReadonly
10395 * The HTML specs do not require browsers to preserve the special attributes such as readonly.
10396 * (The presence of them means true and absence means false)
10397 * This prevents the angular compiler from correctly retrieving the binding expression.
10398 * To solve this problem, we introduce the `ngReadonly` directive.
10402 Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
10403 <input type="text" ng-readonly="checked" value="I'm Angular"/>
10406 it('should toggle readonly attr', function() {
10407 expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
10408 input('checked').check();
10409 expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
10415 * @param {string} expression Angular expression that will be evaluated.
10421 * @name ng.directive:ngSelected
10425 * The HTML specs do not require browsers to preserve the special attributes such as selected.
10426 * (The presence of them means true and absence means false)
10427 * This prevents the angular compiler from correctly retrieving the binding expression.
10428 * To solve this problem, we introduced the `ngSelected` directive.
10432 Check me to select: <input type="checkbox" ng-model="selected"><br/>
10434 <option>Hello!</option>
10435 <option id="greet" ng-selected="selected">Greetings!</option>
10439 it('should select Greetings!', function() {
10440 expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
10441 input('selected').check();
10442 expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
10448 * @param {string} expression Angular expression that will be evaluated.
10452 var ngAttributeAliasDirectives = {};
10455 // boolean attrs are evaluated
10456 forEach(BOOLEAN_ATTR, function(propName, attrName) {
10457 var normalized = directiveNormalize('ng-' + attrName);
10458 ngAttributeAliasDirectives[normalized] = function() {
10461 compile: function() {
10462 return function(scope, element, attr) {
10463 scope.$watch(attr[normalized], function(value) {
10464 attr.$set(attrName, !!value);
10473 // ng-src, ng-href are interpolated
10474 forEach(['src', 'href'], function(attrName) {
10475 var normalized = directiveNormalize('ng-' + attrName);
10476 ngAttributeAliasDirectives[normalized] = function() {
10478 priority: 99, // it needs to run after the attributes are interpolated
10479 link: function(scope, element, attr) {
10480 attr.$observe(normalized, function(value) {
10481 attr.$set(attrName, value);
10483 // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
10484 // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
10485 // to set the property as well to achieve the desired effect
10486 if (msie) element.prop(attrName, value);
10493 var nullFormCtrl = {
10495 $removeControl: noop,
10496 $setValidity: noop,
10502 * @name ng.directive:form.FormController
10504 * @property {boolean} $pristine True if user has not interacted with the form yet.
10505 * @property {boolean} $dirty True if user has already interacted with the form.
10506 * @property {boolean} $valid True if all of the containg forms and controls are valid.
10507 * @property {boolean} $invalid True if at least one containing control or form is invalid.
10509 * @property {Object} $error Is an object hash, containing references to all invalid controls or
10512 * - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`),
10513 * - values are arrays of controls or forms that are invalid with given error.
10516 * `FormController` keeps track of all its controls and nested forms as well as state of them,
10517 * such as being valid/invalid or dirty/pristine.
10519 * Each {@link ng.directive:form form} directive creates an instance
10520 * of `FormController`.
10523 //asks for $scope to fool the BC controller module
10524 FormController.$inject = ['$element', '$attrs', '$scope'];
10525 function FormController(element, attrs) {
10527 parentForm = element.parent().controller('form') || nullFormCtrl,
10528 invalidCount = 0, // used to easily determine if we are valid
10529 errors = form.$error = {};
10532 form.$name = attrs.name;
10533 form.$dirty = false;
10534 form.$pristine = true;
10535 form.$valid = true;
10536 form.$invalid = false;
10538 parentForm.$addControl(form);
10540 // Setup initial state of the control
10541 element.addClass(PRISTINE_CLASS);
10542 toggleValidCss(true);
10544 // convenience method for easy toggling of classes
10545 function toggleValidCss(isValid, validationErrorKey) {
10546 validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
10548 removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
10549 addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
10552 form.$addControl = function(control) {
10553 if (control.$name && !form.hasOwnProperty(control.$name)) {
10554 form[control.$name] = control;
10558 form.$removeControl = function(control) {
10559 if (control.$name && form[control.$name] === control) {
10560 delete form[control.$name];
10562 forEach(errors, function(queue, validationToken) {
10563 form.$setValidity(validationToken, true, control);
10567 form.$setValidity = function(validationToken, isValid, control) {
10568 var queue = errors[validationToken];
10572 arrayRemove(queue, control);
10573 if (!queue.length) {
10575 if (!invalidCount) {
10576 toggleValidCss(isValid);
10577 form.$valid = true;
10578 form.$invalid = false;
10580 errors[validationToken] = false;
10581 toggleValidCss(true, validationToken);
10582 parentForm.$setValidity(validationToken, true, form);
10587 if (!invalidCount) {
10588 toggleValidCss(isValid);
10591 if (includes(queue, control)) return;
10593 errors[validationToken] = queue = [];
10595 toggleValidCss(false, validationToken);
10596 parentForm.$setValidity(validationToken, false, form);
10598 queue.push(control);
10600 form.$valid = false;
10601 form.$invalid = true;
10605 form.$setDirty = function() {
10606 element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
10607 form.$dirty = true;
10608 form.$pristine = false;
10616 * @name ng.directive:ngForm
10620 * Nestable alias of {@link ng.directive:form `form`} directive. HTML
10621 * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
10622 * sub-group of controls needs to be determined.
10624 * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
10625 * related scope, under this name.
10631 * @name ng.directive:form
10635 * Directive that instantiates
10636 * {@link ng.directive:form.FormController FormController}.
10638 * If `name` attribute is specified, the form controller is published onto the current scope under
10641 * # Alias: {@link ng.directive:ngForm `ngForm`}
10643 * In angular forms can be nested. This means that the outer form is valid when all of the child
10644 * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
10645 * reason angular provides {@link ng.directive:ngForm `ngForm`} alias
10646 * which behaves identical to `<form>` but allows form nesting.
10650 * - `ng-valid` Is set if the form is valid.
10651 * - `ng-invalid` Is set if the form is invalid.
10652 * - `ng-pristine` Is set if the form is pristine.
10653 * - `ng-dirty` Is set if the form is dirty.
10656 * # Submitting a form and preventing default action
10658 * Since the role of forms in client-side Angular applications is different than in classical
10659 * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
10660 * page reload that sends the data to the server. Instead some javascript logic should be triggered
10661 * to handle the form submission in application specific way.
10663 * For this reason, Angular prevents the default action (form submission to the server) unless the
10664 * `<form>` element has an `action` attribute specified.
10666 * You can use one of the following two ways to specify what javascript method should be called when
10667 * a form is submitted:
10669 * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
10670 * - {@link ng.directive:ngClick ngClick} directive on the first
10671 * button or input field of type submit (input[type=submit])
10673 * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
10674 * is because of the following form submission rules coming from the html spec:
10676 * - If a form has only one input field then hitting enter in this field triggers form submit
10678 * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
10679 * doesn't trigger submit
10680 * - if a form has one or more input fields and one or more buttons or input[type=submit] then
10681 * hitting enter in any of the input fields will trigger the click handler on the *first* button or
10682 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
10684 * @param {string=} name Name of the form. If specified, the form controller will be published into
10685 * related scope, under this name.
10691 function Ctrl($scope) {
10692 $scope.userType = 'guest';
10695 <form name="myForm" ng-controller="Ctrl">
10696 userType: <input name="input" ng-model="userType" required>
10697 <span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br>
10698 <tt>userType = {{userType}}</tt><br>
10699 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
10700 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
10701 <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
10702 <tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br>
10706 it('should initialize to model', function() {
10707 expect(binding('userType')).toEqual('guest');
10708 expect(binding('myForm.input.$valid')).toEqual('true');
10711 it('should be invalid if empty', function() {
10712 input('userType').enter('');
10713 expect(binding('userType')).toEqual('');
10714 expect(binding('myForm.input.$valid')).toEqual('false');
10719 var formDirectiveFactory = function(isNgForm) {
10720 return ['$timeout', function($timeout) {
10721 var formDirective = {
10724 controller: FormController,
10725 compile: function() {
10727 pre: function(scope, formElement, attr, controller) {
10728 if (!attr.action) {
10729 // we can't use jq events because if a form is destroyed during submission the default
10730 // action is not prevented. see #1238
10732 // IE 9 is not affected because it doesn't fire a submit event and try to do a full
10733 // page reload if the form was destroyed by submission of the form via a click handler
10734 // on a button in the form. Looks like an IE9 specific bug.
10735 var preventDefaultListener = function(event) {
10736 event.preventDefault
10737 ? event.preventDefault()
10738 : event.returnValue = false; // IE
10741 addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
10743 // unregister the preventDefault listener so that we don't not leak memory but in a
10744 // way that will achieve the prevention of the default action.
10745 formElement.bind('$destroy', function() {
10746 $timeout(function() {
10747 removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
10752 var parentFormCtrl = formElement.parent().controller('form'),
10753 alias = attr.name || attr.ngForm;
10756 scope[alias] = controller;
10758 if (parentFormCtrl) {
10759 formElement.bind('$destroy', function() {
10760 parentFormCtrl.$removeControl(controller);
10762 scope[alias] = undefined;
10764 extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
10772 return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective;
10776 var formDirective = formDirectiveFactory();
10777 var ngFormDirective = formDirectiveFactory(true);
10779 var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
10780 var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
10781 var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
10787 * @name ng.directive:input.text
10790 * Standard HTML text input with angular data binding.
10792 * @param {string} ngModel Assignable angular expression to data-bind to.
10793 * @param {string=} name Property name of the form under which the control is published.
10794 * @param {string=} required Sets `required` validation error key if the value is not entered.
10795 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
10797 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
10799 * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
10800 * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
10801 * patterns defined as scope expressions.
10802 * @param {string=} ngChange Angular expression to be executed when input changes due to user
10803 * interaction with the input element.
10809 function Ctrl($scope) {
10810 $scope.text = 'guest';
10811 $scope.word = /^\w*$/;
10814 <form name="myForm" ng-controller="Ctrl">
10815 Single word: <input type="text" name="input" ng-model="text"
10816 ng-pattern="word" required>
10817 <span class="error" ng-show="myForm.input.$error.required">
10819 <span class="error" ng-show="myForm.input.$error.pattern">
10820 Single word only!</span>
10822 <tt>text = {{text}}</tt><br/>
10823 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
10824 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
10825 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
10826 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
10830 it('should initialize to model', function() {
10831 expect(binding('text')).toEqual('guest');
10832 expect(binding('myForm.input.$valid')).toEqual('true');
10835 it('should be invalid if empty', function() {
10836 input('text').enter('');
10837 expect(binding('text')).toEqual('');
10838 expect(binding('myForm.input.$valid')).toEqual('false');
10841 it('should be invalid if multi word', function() {
10842 input('text').enter('hello world');
10843 expect(binding('myForm.input.$valid')).toEqual('false');
10848 'text': textInputType,
10853 * @name ng.directive:input.number
10856 * Text input with number validation and transformation. Sets the `number` validation
10857 * error if not a valid number.
10859 * @param {string} ngModel Assignable angular expression to data-bind to.
10860 * @param {string=} name Property name of the form under which the control is published.
10861 * @param {string=} min Sets the `min` validation error key if the value entered is less then `min`.
10862 * @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`.
10863 * @param {string=} required Sets `required` validation error key if the value is not entered.
10864 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
10866 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
10868 * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
10869 * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
10870 * patterns defined as scope expressions.
10871 * @param {string=} ngChange Angular expression to be executed when input changes due to user
10872 * interaction with the input element.
10878 function Ctrl($scope) {
10882 <form name="myForm" ng-controller="Ctrl">
10883 Number: <input type="number" name="input" ng-model="value"
10884 min="0" max="99" required>
10885 <span class="error" ng-show="myForm.list.$error.required">
10887 <span class="error" ng-show="myForm.list.$error.number">
10888 Not valid number!</span>
10889 <tt>value = {{value}}</tt><br/>
10890 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
10891 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
10892 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
10893 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
10897 it('should initialize to model', function() {
10898 expect(binding('value')).toEqual('12');
10899 expect(binding('myForm.input.$valid')).toEqual('true');
10902 it('should be invalid if empty', function() {
10903 input('value').enter('');
10904 expect(binding('value')).toEqual('');
10905 expect(binding('myForm.input.$valid')).toEqual('false');
10908 it('should be invalid if over max', function() {
10909 input('value').enter('123');
10910 expect(binding('value')).toEqual('');
10911 expect(binding('myForm.input.$valid')).toEqual('false');
10916 'number': numberInputType,
10921 * @name ng.directive:input.url
10924 * Text input with URL validation. Sets the `url` validation error key if the content is not a
10927 * @param {string} ngModel Assignable angular expression to data-bind to.
10928 * @param {string=} name Property name of the form under which the control is published.
10929 * @param {string=} required Sets `required` validation error key if the value is not entered.
10930 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
10932 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
10934 * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
10935 * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
10936 * patterns defined as scope expressions.
10937 * @param {string=} ngChange Angular expression to be executed when input changes due to user
10938 * interaction with the input element.
10944 function Ctrl($scope) {
10945 $scope.text = 'http://google.com';
10948 <form name="myForm" ng-controller="Ctrl">
10949 URL: <input type="url" name="input" ng-model="text" required>
10950 <span class="error" ng-show="myForm.input.$error.required">
10952 <span class="error" ng-show="myForm.input.$error.url">
10953 Not valid url!</span>
10954 <tt>text = {{text}}</tt><br/>
10955 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
10956 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
10957 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
10958 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
10959 <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
10963 it('should initialize to model', function() {
10964 expect(binding('text')).toEqual('http://google.com');
10965 expect(binding('myForm.input.$valid')).toEqual('true');
10968 it('should be invalid if empty', function() {
10969 input('text').enter('');
10970 expect(binding('text')).toEqual('');
10971 expect(binding('myForm.input.$valid')).toEqual('false');
10974 it('should be invalid if not url', function() {
10975 input('text').enter('xxx');
10976 expect(binding('myForm.input.$valid')).toEqual('false');
10981 'url': urlInputType,
10986 * @name ng.directive:input.email
10989 * Text input with email validation. Sets the `email` validation error key if not a valid email
10992 * @param {string} ngModel Assignable angular expression to data-bind to.
10993 * @param {string=} name Property name of the form under which the control is published.
10994 * @param {string=} required Sets `required` validation error key if the value is not entered.
10995 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
10997 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
10999 * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
11000 * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
11001 * patterns defined as scope expressions.
11007 function Ctrl($scope) {
11008 $scope.text = 'me@example.com';
11011 <form name="myForm" ng-controller="Ctrl">
11012 Email: <input type="email" name="input" ng-model="text" required>
11013 <span class="error" ng-show="myForm.input.$error.required">
11015 <span class="error" ng-show="myForm.input.$error.email">
11016 Not valid email!</span>
11017 <tt>text = {{text}}</tt><br/>
11018 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
11019 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
11020 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
11021 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
11022 <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
11026 it('should initialize to model', function() {
11027 expect(binding('text')).toEqual('me@example.com');
11028 expect(binding('myForm.input.$valid')).toEqual('true');
11031 it('should be invalid if empty', function() {
11032 input('text').enter('');
11033 expect(binding('text')).toEqual('');
11034 expect(binding('myForm.input.$valid')).toEqual('false');
11037 it('should be invalid if not email', function() {
11038 input('text').enter('xxx');
11039 expect(binding('myForm.input.$valid')).toEqual('false');
11044 'email': emailInputType,
11049 * @name ng.directive:input.radio
11052 * HTML radio button.
11054 * @param {string} ngModel Assignable angular expression to data-bind to.
11055 * @param {string} value The value to which the expression should be set when selected.
11056 * @param {string=} name Property name of the form under which the control is published.
11057 * @param {string=} ngChange Angular expression to be executed when input changes due to user
11058 * interaction with the input element.
11064 function Ctrl($scope) {
11065 $scope.color = 'blue';
11068 <form name="myForm" ng-controller="Ctrl">
11069 <input type="radio" ng-model="color" value="red"> Red <br/>
11070 <input type="radio" ng-model="color" value="green"> Green <br/>
11071 <input type="radio" ng-model="color" value="blue"> Blue <br/>
11072 <tt>color = {{color}}</tt><br/>
11076 it('should change state', function() {
11077 expect(binding('color')).toEqual('blue');
11079 input('color').select('red');
11080 expect(binding('color')).toEqual('red');
11085 'radio': radioInputType,
11090 * @name ng.directive:input.checkbox
11095 * @param {string} ngModel Assignable angular expression to data-bind to.
11096 * @param {string=} name Property name of the form under which the control is published.
11097 * @param {string=} ngTrueValue The value to which the expression should be set when selected.
11098 * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
11099 * @param {string=} ngChange Angular expression to be executed when input changes due to user
11100 * interaction with the input element.
11106 function Ctrl($scope) {
11107 $scope.value1 = true;
11108 $scope.value2 = 'YES'
11111 <form name="myForm" ng-controller="Ctrl">
11112 Value1: <input type="checkbox" ng-model="value1"> <br/>
11113 Value2: <input type="checkbox" ng-model="value2"
11114 ng-true-value="YES" ng-false-value="NO"> <br/>
11115 <tt>value1 = {{value1}}</tt><br/>
11116 <tt>value2 = {{value2}}</tt><br/>
11120 it('should change state', function() {
11121 expect(binding('value1')).toEqual('true');
11122 expect(binding('value2')).toEqual('YES');
11124 input('value1').check();
11125 input('value2').check();
11126 expect(binding('value1')).toEqual('false');
11127 expect(binding('value2')).toEqual('NO');
11132 'checkbox': checkboxInputType,
11141 function isEmpty(value) {
11142 return isUndefined(value) || value === '' || value === null || value !== value;
11146 function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11148 var listener = function() {
11149 var value = trim(element.val());
11151 if (ctrl.$viewValue !== value) {
11152 scope.$apply(function() {
11153 ctrl.$setViewValue(value);
11158 // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
11159 // input event on backspace, delete or cut
11160 if ($sniffer.hasEvent('input')) {
11161 element.bind('input', listener);
11165 element.bind('keydown', function(event) {
11166 var key = event.keyCode;
11169 // command modifiers arrows
11170 if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
11173 timeout = $browser.defer(function() {
11180 // if user paste into input using mouse, we need "change" event to catch it
11181 element.bind('change', listener);
11185 ctrl.$render = function() {
11186 element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
11189 // pattern validator
11190 var pattern = attr.ngPattern,
11193 var validate = function(regexp, value) {
11194 if (isEmpty(value) || regexp.test(value)) {
11195 ctrl.$setValidity('pattern', true);
11198 ctrl.$setValidity('pattern', false);
11204 if (pattern.match(/^\/(.*)\/$/)) {
11205 pattern = new RegExp(pattern.substr(1, pattern.length - 2));
11206 patternValidator = function(value) {
11207 return validate(pattern, value)
11210 patternValidator = function(value) {
11211 var patternObj = scope.$eval(pattern);
11213 if (!patternObj || !patternObj.test) {
11214 throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
11216 return validate(patternObj, value);
11220 ctrl.$formatters.push(patternValidator);
11221 ctrl.$parsers.push(patternValidator);
11224 // min length validator
11225 if (attr.ngMinlength) {
11226 var minlength = int(attr.ngMinlength);
11227 var minLengthValidator = function(value) {
11228 if (!isEmpty(value) && value.length < minlength) {
11229 ctrl.$setValidity('minlength', false);
11232 ctrl.$setValidity('minlength', true);
11237 ctrl.$parsers.push(minLengthValidator);
11238 ctrl.$formatters.push(minLengthValidator);
11241 // max length validator
11242 if (attr.ngMaxlength) {
11243 var maxlength = int(attr.ngMaxlength);
11244 var maxLengthValidator = function(value) {
11245 if (!isEmpty(value) && value.length > maxlength) {
11246 ctrl.$setValidity('maxlength', false);
11249 ctrl.$setValidity('maxlength', true);
11254 ctrl.$parsers.push(maxLengthValidator);
11255 ctrl.$formatters.push(maxLengthValidator);
11259 function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11260 textInputType(scope, element, attr, ctrl, $sniffer, $browser);
11262 ctrl.$parsers.push(function(value) {
11263 var empty = isEmpty(value);
11264 if (empty || NUMBER_REGEXP.test(value)) {
11265 ctrl.$setValidity('number', true);
11266 return value === '' ? null : (empty ? value : parseFloat(value));
11268 ctrl.$setValidity('number', false);
11273 ctrl.$formatters.push(function(value) {
11274 return isEmpty(value) ? '' : '' + value;
11278 var min = parseFloat(attr.min);
11279 var minValidator = function(value) {
11280 if (!isEmpty(value) && value < min) {
11281 ctrl.$setValidity('min', false);
11284 ctrl.$setValidity('min', true);
11289 ctrl.$parsers.push(minValidator);
11290 ctrl.$formatters.push(minValidator);
11294 var max = parseFloat(attr.max);
11295 var maxValidator = function(value) {
11296 if (!isEmpty(value) && value > max) {
11297 ctrl.$setValidity('max', false);
11300 ctrl.$setValidity('max', true);
11305 ctrl.$parsers.push(maxValidator);
11306 ctrl.$formatters.push(maxValidator);
11309 ctrl.$formatters.push(function(value) {
11311 if (isEmpty(value) || isNumber(value)) {
11312 ctrl.$setValidity('number', true);
11315 ctrl.$setValidity('number', false);
11321 function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11322 textInputType(scope, element, attr, ctrl, $sniffer, $browser);
11324 var urlValidator = function(value) {
11325 if (isEmpty(value) || URL_REGEXP.test(value)) {
11326 ctrl.$setValidity('url', true);
11329 ctrl.$setValidity('url', false);
11334 ctrl.$formatters.push(urlValidator);
11335 ctrl.$parsers.push(urlValidator);
11338 function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11339 textInputType(scope, element, attr, ctrl, $sniffer, $browser);
11341 var emailValidator = function(value) {
11342 if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
11343 ctrl.$setValidity('email', true);
11346 ctrl.$setValidity('email', false);
11351 ctrl.$formatters.push(emailValidator);
11352 ctrl.$parsers.push(emailValidator);
11355 function radioInputType(scope, element, attr, ctrl) {
11356 // make the name unique, if not defined
11357 if (isUndefined(attr.name)) {
11358 element.attr('name', nextUid());
11361 element.bind('click', function() {
11362 if (element[0].checked) {
11363 scope.$apply(function() {
11364 ctrl.$setViewValue(attr.value);
11369 ctrl.$render = function() {
11370 var value = attr.value;
11371 element[0].checked = (value == ctrl.$viewValue);
11374 attr.$observe('value', ctrl.$render);
11377 function checkboxInputType(scope, element, attr, ctrl) {
11378 var trueValue = attr.ngTrueValue,
11379 falseValue = attr.ngFalseValue;
11381 if (!isString(trueValue)) trueValue = true;
11382 if (!isString(falseValue)) falseValue = false;
11384 element.bind('click', function() {
11385 scope.$apply(function() {
11386 ctrl.$setViewValue(element[0].checked);
11390 ctrl.$render = function() {
11391 element[0].checked = ctrl.$viewValue;
11394 ctrl.$formatters.push(function(value) {
11395 return value === trueValue;
11398 ctrl.$parsers.push(function(value) {
11399 return value ? trueValue : falseValue;
11406 * @name ng.directive:textarea
11410 * HTML textarea element control with angular data-binding. The data-binding and validation
11411 * properties of this element are exactly the same as those of the
11412 * {@link ng.directive:input input element}.
11414 * @param {string} ngModel Assignable angular expression to data-bind to.
11415 * @param {string=} name Property name of the form under which the control is published.
11416 * @param {string=} required Sets `required` validation error key if the value is not entered.
11417 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
11419 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
11421 * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
11422 * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
11423 * patterns defined as scope expressions.
11424 * @param {string=} ngChange Angular expression to be executed when input changes due to user
11425 * interaction with the input element.
11431 * @name ng.directive:input
11435 * HTML input element control with angular data-binding. Input control follows HTML5 input types
11436 * and polyfills the HTML5 validation behavior for older browsers.
11438 * @param {string} ngModel Assignable angular expression to data-bind to.
11439 * @param {string=} name Property name of the form under which the control is published.
11440 * @param {string=} required Sets `required` validation error key if the value is not entered.
11441 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
11443 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
11445 * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
11446 * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
11447 * patterns defined as scope expressions.
11448 * @param {string=} ngChange Angular expression to be executed when input changes due to user
11449 * interaction with the input element.
11455 function Ctrl($scope) {
11456 $scope.user = {name: 'guest', last: 'visitor'};
11459 <div ng-controller="Ctrl">
11460 <form name="myForm">
11461 User name: <input type="text" name="userName" ng-model="user.name" required>
11462 <span class="error" ng-show="myForm.userName.$error.required">
11463 Required!</span><br>
11464 Last name: <input type="text" name="lastName" ng-model="user.last"
11465 ng-minlength="3" ng-maxlength="10">
11466 <span class="error" ng-show="myForm.lastName.$error.minlength">
11468 <span class="error" ng-show="myForm.lastName.$error.maxlength">
11469 Too long!</span><br>
11472 <tt>user = {{user}}</tt><br/>
11473 <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
11474 <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
11475 <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
11476 <tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br>
11477 <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
11478 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
11479 <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
11480 <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
11484 it('should initialize to model', function() {
11485 expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
11486 expect(binding('myForm.userName.$valid')).toEqual('true');
11487 expect(binding('myForm.$valid')).toEqual('true');
11490 it('should be invalid if empty when required', function() {
11491 input('user.name').enter('');
11492 expect(binding('user')).toEqual('{"last":"visitor"}');
11493 expect(binding('myForm.userName.$valid')).toEqual('false');
11494 expect(binding('myForm.$valid')).toEqual('false');
11497 it('should be valid if empty when min length is set', function() {
11498 input('user.last').enter('');
11499 expect(binding('user')).toEqual('{"name":"guest","last":""}');
11500 expect(binding('myForm.lastName.$valid')).toEqual('true');
11501 expect(binding('myForm.$valid')).toEqual('true');
11504 it('should be invalid if less than required min length', function() {
11505 input('user.last').enter('xx');
11506 expect(binding('user')).toEqual('{"name":"guest"}');
11507 expect(binding('myForm.lastName.$valid')).toEqual('false');
11508 expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
11509 expect(binding('myForm.$valid')).toEqual('false');
11512 it('should be invalid if longer than max length', function() {
11513 input('user.last').enter('some ridiculously long name');
11514 expect(binding('user'))
11515 .toEqual('{"name":"guest"}');
11516 expect(binding('myForm.lastName.$valid')).toEqual('false');
11517 expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
11518 expect(binding('myForm.$valid')).toEqual('false');
11523 var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
11526 require: '?ngModel',
11527 link: function(scope, element, attr, ctrl) {
11529 (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
11536 var VALID_CLASS = 'ng-valid',
11537 INVALID_CLASS = 'ng-invalid',
11538 PRISTINE_CLASS = 'ng-pristine',
11539 DIRTY_CLASS = 'ng-dirty';
11543 * @name ng.directive:ngModel.NgModelController
11545 * @property {string} $viewValue Actual string value in the view.
11546 * @property {*} $modelValue The value in the model, that the control is bound to.
11547 * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
11548 * all of these functions to sanitize / convert the value as well as validate.
11550 * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
11551 * these functions to convert the value as well as validate.
11553 * @property {Object} $error An bject hash with all errors as keys.
11555 * @property {boolean} $pristine True if user has not interacted with the control yet.
11556 * @property {boolean} $dirty True if user has already interacted with the control.
11557 * @property {boolean} $valid True if there is no error.
11558 * @property {boolean} $invalid True if at least one error on the control.
11562 * `NgModelController` provides API for the `ng-model` directive. The controller contains
11563 * services for data-binding, validation, CSS update, value formatting and parsing. It
11564 * specifically does not contain any logic which deals with DOM rendering or listening to
11565 * DOM events. The `NgModelController` is meant to be extended by other directives where, the
11566 * directive provides DOM manipulation and the `NgModelController` provides the data-binding.
11568 * This example shows how to use `NgModelController` with a custom control to achieve
11569 * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
11570 * collaborate together to achieve the desired result.
11572 * <example module="customControl">
11573 <file name="style.css">
11574 [contenteditable] {
11575 border: 1px solid black;
11576 background-color: white;
11581 border: 1px solid red;
11585 <file name="script.js">
11586 angular.module('customControl', []).
11587 directive('contenteditable', function() {
11589 restrict: 'A', // only activate on element attribute
11590 require: '?ngModel', // get a hold of NgModelController
11591 link: function(scope, element, attrs, ngModel) {
11592 if(!ngModel) return; // do nothing if no ng-model
11594 // Specify how UI should be updated
11595 ngModel.$render = function() {
11596 element.html(ngModel.$viewValue || '');
11599 // Listen for change events to enable binding
11600 element.bind('blur keyup change', function() {
11601 scope.$apply(read);
11603 read(); // initialize
11605 // Write data to the model
11607 ngModel.$setViewValue(element.html());
11613 <file name="index.html">
11614 <form name="myForm">
11615 <div contenteditable
11616 name="myWidget" ng-model="userContent"
11617 required>Change me!</div>
11618 <span ng-show="myForm.myWidget.$error.required">Required!</span>
11620 <textarea ng-model="userContent"></textarea>
11623 <file name="scenario.js">
11624 it('should data-bind and become invalid', function() {
11625 var contentEditable = element('[contenteditable]');
11627 expect(contentEditable.text()).toEqual('Change me!');
11628 input('userContent').enter('');
11629 expect(contentEditable.text()).toEqual('');
11630 expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
11636 var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
11637 function($scope, $exceptionHandler, $attr, $element, $parse) {
11638 this.$viewValue = Number.NaN;
11639 this.$modelValue = Number.NaN;
11640 this.$parsers = [];
11641 this.$formatters = [];
11642 this.$viewChangeListeners = [];
11643 this.$pristine = true;
11644 this.$dirty = false;
11645 this.$valid = true;
11646 this.$invalid = false;
11647 this.$name = $attr.name;
11649 var ngModelGet = $parse($attr.ngModel),
11650 ngModelSet = ngModelGet.assign;
11653 throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
11654 ' (' + startingTag($element) + ')');
11659 * @name ng.directive:ngModel.NgModelController#$render
11660 * @methodOf ng.directive:ngModel.NgModelController
11663 * Called when the view needs to be updated. It is expected that the user of the ng-model
11664 * directive will implement this method.
11666 this.$render = noop;
11668 var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
11669 invalidCount = 0, // used to easily determine if we are valid
11670 $error = this.$error = {}; // keep invalid keys here
11673 // Setup initial state of the control
11674 $element.addClass(PRISTINE_CLASS);
11675 toggleValidCss(true);
11677 // convenience method for easy toggling of classes
11678 function toggleValidCss(isValid, validationErrorKey) {
11679 validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
11681 removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
11682 addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
11687 * @name ng.directive:ngModel.NgModelController#$setValidity
11688 * @methodOf ng.directive:ngModel.NgModelController
11691 * Change the validity state, and notifies the form when the control changes validity. (i.e. it
11692 * does not notify form if given validator is already marked as invalid).
11694 * This method should be called by validators - i.e. the parser or formatter functions.
11696 * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
11697 * to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
11698 * The `validationErrorKey` should be in camelCase and will get converted into dash-case
11699 * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
11700 * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
11701 * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
11703 this.$setValidity = function(validationErrorKey, isValid) {
11704 if ($error[validationErrorKey] === !isValid) return;
11707 if ($error[validationErrorKey]) invalidCount--;
11708 if (!invalidCount) {
11709 toggleValidCss(true);
11710 this.$valid = true;
11711 this.$invalid = false;
11714 toggleValidCss(false);
11715 this.$invalid = true;
11716 this.$valid = false;
11720 $error[validationErrorKey] = !isValid;
11721 toggleValidCss(isValid, validationErrorKey);
11723 parentForm.$setValidity(validationErrorKey, isValid, this);
11729 * @name ng.directive:ngModel.NgModelController#$setViewValue
11730 * @methodOf ng.directive:ngModel.NgModelController
11733 * Read a value from view.
11735 * This method should be called from within a DOM event handler.
11736 * For example {@link ng.directive:input input} or
11737 * {@link ng.directive:select select} directives call it.
11739 * It internally calls all `formatters` and if resulted value is valid, updates the model and
11740 * calls all registered change listeners.
11742 * @param {string} value Value from the view.
11744 this.$setViewValue = function(value) {
11745 this.$viewValue = value;
11748 if (this.$pristine) {
11749 this.$dirty = true;
11750 this.$pristine = false;
11751 $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
11752 parentForm.$setDirty();
11755 forEach(this.$parsers, function(fn) {
11759 if (this.$modelValue !== value) {
11760 this.$modelValue = value;
11761 ngModelSet($scope, value);
11762 forEach(this.$viewChangeListeners, function(listener) {
11766 $exceptionHandler(e);
11774 $scope.$watch(ngModelGet, function(value) {
11776 // ignore change from view
11777 if (ctrl.$modelValue === value) return;
11779 var formatters = ctrl.$formatters,
11780 idx = formatters.length;
11782 ctrl.$modelValue = value;
11784 value = formatters[idx](value);
11787 if (ctrl.$viewValue !== value) {
11788 ctrl.$viewValue = value;
11797 * @name ng.directive:ngModel
11802 * Is directive that tells Angular to do two-way data binding. It works together with `input`,
11803 * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
11805 * `ngModel` is responsible for:
11807 * - binding the view into the model, which other directives such as `input`, `textarea` or `select`
11809 * - providing validation behavior (i.e. required, number, email, url),
11810 * - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
11811 * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
11812 * - register the control with parent {@link ng.directive:form form}.
11814 * For basic examples, how to use `ngModel`, see:
11816 * - {@link ng.directive:input input}
11817 * - {@link ng.directive:input.text text}
11818 * - {@link ng.directive:input.checkbox checkbox}
11819 * - {@link ng.directive:input.radio radio}
11820 * - {@link ng.directive:input.number number}
11821 * - {@link ng.directive:input.email email}
11822 * - {@link ng.directive:input.url url}
11823 * - {@link ng.directive:select select}
11824 * - {@link ng.directive:textarea textarea}
11827 var ngModelDirective = function() {
11829 require: ['ngModel', '^?form'],
11830 controller: NgModelController,
11831 link: function(scope, element, attr, ctrls) {
11832 // notify others, especially parent forms
11834 var modelCtrl = ctrls[0],
11835 formCtrl = ctrls[1] || nullFormCtrl;
11837 formCtrl.$addControl(modelCtrl);
11839 element.bind('$destroy', function() {
11840 formCtrl.$removeControl(modelCtrl);
11849 * @name ng.directive:ngChange
11853 * Evaluate given expression when user changes the input.
11854 * The expression is not evaluated when the value change is coming from the model.
11856 * Note, this directive requires `ngModel` to be present.
11864 * function Controller($scope) {
11865 * $scope.counter = 0;
11866 * $scope.change = function() {
11867 * $scope.counter++;
11871 * <div ng-controller="Controller">
11872 * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
11873 * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
11874 * <label for="ng-change-example2">Confirmed</label><br />
11875 * debug = {{confirmed}}<br />
11876 * counter = {{counter}}
11880 * it('should evaluate the expression if changing from view', function() {
11881 * expect(binding('counter')).toEqual('0');
11882 * element('#ng-change-example1').click();
11883 * expect(binding('counter')).toEqual('1');
11884 * expect(binding('confirmed')).toEqual('true');
11887 * it('should not evaluate the expression if changing from model', function() {
11888 * element('#ng-change-example2').click();
11889 * expect(binding('counter')).toEqual('0');
11890 * expect(binding('confirmed')).toEqual('true');
11895 var ngChangeDirective = valueFn({
11896 require: 'ngModel',
11897 link: function(scope, element, attr, ctrl) {
11898 ctrl.$viewChangeListeners.push(function() {
11899 scope.$eval(attr.ngChange);
11905 var requiredDirective = function() {
11907 require: '?ngModel',
11908 link: function(scope, elm, attr, ctrl) {
11910 attr.required = true; // force truthy in case we are on non input element
11912 var validator = function(value) {
11913 if (attr.required && (isEmpty(value) || value === false)) {
11914 ctrl.$setValidity('required', false);
11917 ctrl.$setValidity('required', true);
11922 ctrl.$formatters.push(validator);
11923 ctrl.$parsers.unshift(validator);
11925 attr.$observe('required', function() {
11926 validator(ctrl.$viewValue);
11935 * @name ng.directive:ngList
11938 * Text input that converts between comma-seperated string into an array of strings.
11941 * @param {string=} ngList optional delimiter that should be used to split the value. If
11942 * specified in form `/something/` then the value will be converted into a regular expression.
11948 function Ctrl($scope) {
11949 $scope.names = ['igor', 'misko', 'vojta'];
11952 <form name="myForm" ng-controller="Ctrl">
11953 List: <input name="namesInput" ng-model="names" ng-list required>
11954 <span class="error" ng-show="myForm.list.$error.required">
11956 <tt>names = {{names}}</tt><br/>
11957 <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
11958 <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
11959 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
11960 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
11964 it('should initialize to model', function() {
11965 expect(binding('names')).toEqual('["igor","misko","vojta"]');
11966 expect(binding('myForm.namesInput.$valid')).toEqual('true');
11969 it('should be invalid if empty', function() {
11970 input('names').enter('');
11971 expect(binding('names')).toEqual('[]');
11972 expect(binding('myForm.namesInput.$valid')).toEqual('false');
11977 var ngListDirective = function() {
11979 require: 'ngModel',
11980 link: function(scope, element, attr, ctrl) {
11981 var match = /\/(.*)\//.exec(attr.ngList),
11982 separator = match && new RegExp(match[1]) || attr.ngList || ',';
11984 var parse = function(viewValue) {
11988 forEach(viewValue.split(separator), function(value) {
11989 if (value) list.push(trim(value));
11996 ctrl.$parsers.push(parse);
11997 ctrl.$formatters.push(function(value) {
11998 if (isArray(value)) {
11999 return value.join(', ');
12009 var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
12011 var ngValueDirective = function() {
12014 compile: function(tpl, tplAttr) {
12015 if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
12016 return function(scope, elm, attr) {
12017 attr.$set('value', scope.$eval(attr.ngValue));
12020 return function(scope, elm, attr) {
12021 scope.$watch(attr.ngValue, function(value) {
12022 attr.$set('value', value, false);
12032 * @name ng.directive:ngBind
12035 * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
12036 * with the value of a given expression, and to update the text content when the value of that
12037 * expression changes.
12039 * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
12040 * `{{ expression }}` which is similar but less verbose.
12042 * Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when
12043 * it's desirable to put bindings into template that is momentarily displayed by the browser in its
12044 * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the
12045 * bindings invisible to the user while the page is loading.
12047 * An alternative solution to this problem would be using the
12048 * {@link ng.directive:ngCloak ngCloak} directive.
12052 * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
12055 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
12059 function Ctrl($scope) {
12060 $scope.name = 'Whirled';
12063 <div ng-controller="Ctrl">
12064 Enter name: <input type="text" ng-model="name"><br>
12065 Hello <span ng-bind="name"></span>!
12069 it('should check ng-bind', function() {
12070 expect(using('.doc-example-live').binding('name')).toBe('Whirled');
12071 using('.doc-example-live').input('name').enter('world');
12072 expect(using('.doc-example-live').binding('name')).toBe('world');
12077 var ngBindDirective = ngDirective(function(scope, element, attr) {
12078 element.addClass('ng-binding').data('$binding', attr.ngBind);
12079 scope.$watch(attr.ngBind, function(value) {
12080 element.text(value == undefined ? '' : value);
12087 * @name ng.directive:ngBindTemplate
12090 * The `ngBindTemplate` directive specifies that the element
12091 * text should be replaced with the template in ngBindTemplate.
12092 * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
12093 * expressions. (This is required since some HTML elements
12094 * can not have SPAN elements such as TITLE, or OPTION to name a few.)
12097 * @param {string} ngBindTemplate template of form
12098 * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
12101 * Try it here: enter text in text box and watch the greeting change.
12105 function Ctrl($scope) {
12106 $scope.salutation = 'Hello';
12107 $scope.name = 'World';
12110 <div ng-controller="Ctrl">
12111 Salutation: <input type="text" ng-model="salutation"><br>
12112 Name: <input type="text" ng-model="name"><br>
12113 <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
12117 it('should check ng-bind', function() {
12118 expect(using('.doc-example-live').binding('salutation')).
12120 expect(using('.doc-example-live').binding('name')).
12122 using('.doc-example-live').input('salutation').enter('Greetings');
12123 using('.doc-example-live').input('name').enter('user');
12124 expect(using('.doc-example-live').binding('salutation')).
12126 expect(using('.doc-example-live').binding('name')).
12132 var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
12133 return function(scope, element, attr) {
12134 // TODO: move this to scenario runner
12135 var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
12136 element.addClass('ng-binding').data('$binding', interpolateFn);
12137 attr.$observe('ngBindTemplate', function(value) {
12138 element.text(value);
12146 * @name ng.directive:ngBindHtmlUnsafe
12149 * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
12150 * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
12151 * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
12152 * restrictive and when you absolutely trust the source of the content you are binding to.
12154 * See {@link ngSanitize.$sanitize $sanitize} docs for examples.
12157 * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
12159 var ngBindHtmlUnsafeDirective = [function() {
12160 return function(scope, element, attr) {
12161 element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
12162 scope.$watch(attr.ngBindHtmlUnsafe, function(value) {
12163 element.html(value || '');
12168 function classDirective(name, selector) {
12169 name = 'ngClass' + name;
12170 return ngDirective(function(scope, element, attr) {
12171 scope.$watch(attr[name], function(newVal, oldVal) {
12172 if (selector === true || scope.$index % 2 === selector) {
12173 if (oldVal && (newVal !== oldVal)) {
12174 if (isObject(oldVal) && !isArray(oldVal))
12175 oldVal = map(oldVal, function(v, k) { if (v) return k });
12176 element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal);
12178 if (isObject(newVal) && !isArray(newVal))
12179 newVal = map(newVal, function(v, k) { if (v) return k });
12180 if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); }
12187 * @name ng.directive:ngClass
12190 * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an
12191 * expression that represents all classes to be added.
12193 * The directive won't add duplicate classes if a particular class was already set.
12195 * When the expression changes, the previously added classes are removed and only then the classes
12196 * new classes are added.
12199 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
12200 * of the evaluation can be a string representing space delimited class
12201 * names, an array, or a map of class names to boolean values.
12205 <file name="index.html">
12206 <input type="button" value="set" ng-click="myVar='my-class'">
12207 <input type="button" value="clear" ng-click="myVar=''">
12209 <span ng-class="myVar">Sample Text</span>
12211 <file name="style.css">
12216 <file name="scenario.js">
12217 it('should check ng-class', function() {
12218 expect(element('.doc-example-live span').prop('className')).not().
12219 toMatch(/my-class/);
12221 using('.doc-example-live').element(':button:first').click();
12223 expect(element('.doc-example-live span').prop('className')).
12224 toMatch(/my-class/);
12226 using('.doc-example-live').element(':button:last').click();
12228 expect(element('.doc-example-live span').prop('className')).not().
12229 toMatch(/my-class/);
12234 var ngClassDirective = classDirective('', true);
12238 * @name ng.directive:ngClassOdd
12241 * The `ngClassOdd` and `ngClassEven` directives work exactly as
12242 * {@link ng.directive:ngClass ngClass}, except it works in
12243 * conjunction with `ngRepeat` and takes affect only on odd (even) rows.
12245 * This directive can be applied only within a scope of an
12246 * {@link ng.directive:ngRepeat ngRepeat}.
12249 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
12250 * of the evaluation can be a string representing space delimited class names or an array.
12254 <file name="index.html">
12255 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
12256 <li ng-repeat="name in names">
12257 <span ng-class-odd="'odd'" ng-class-even="'even'">
12263 <file name="style.css">
12271 <file name="scenario.js">
12272 it('should check ng-class-odd and ng-class-even', function() {
12273 expect(element('.doc-example-live li:first span').prop('className')).
12275 expect(element('.doc-example-live li:last span').prop('className')).
12281 var ngClassOddDirective = classDirective('Odd', 0);
12285 * @name ng.directive:ngClassEven
12288 * The `ngClassOdd` and `ngClassEven` works exactly as
12289 * {@link ng.directive:ngClass ngClass}, except it works in
12290 * conjunction with `ngRepeat` and takes affect only on odd (even) rows.
12292 * This directive can be applied only within a scope of an
12293 * {@link ng.directive:ngRepeat ngRepeat}.
12296 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
12297 * result of the evaluation can be a string representing space delimited class names or an array.
12301 <file name="index.html">
12302 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
12303 <li ng-repeat="name in names">
12304 <span ng-class-odd="'odd'" ng-class-even="'even'">
12305 {{name}}
12310 <file name="style.css">
12318 <file name="scenario.js">
12319 it('should check ng-class-odd and ng-class-even', function() {
12320 expect(element('.doc-example-live li:first span').prop('className')).
12322 expect(element('.doc-example-live li:last span').prop('className')).
12328 var ngClassEvenDirective = classDirective('Even', 1);
12332 * @name ng.directive:ngCloak
12335 * The `ngCloak` directive is used to prevent the Angular html template from being briefly
12336 * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
12337 * directive to avoid the undesirable flicker effect caused by the html template display.
12339 * The directive can be applied to the `<body>` element, but typically a fine-grained application is
12340 * prefered in order to benefit from progressive rendering of the browser view.
12342 * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
12343 * `angular.min.js` files. Following is the css rule:
12346 * [ng\:cloak], [ng-cloak], .ng-cloak {
12351 * When this css rule is loaded by the browser, all html elements (including their children) that
12352 * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
12353 * during the compilation of the template it deletes the `ngCloak` element attribute, which
12354 * makes the compiled element visible.
12356 * For the best result, `angular.js` script must be loaded in the head section of the html file;
12357 * alternatively, the css rule (above) must be included in the external stylesheet of the
12360 * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
12361 * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
12362 * class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
12369 <div id="template1" ng-cloak>{{ 'hello' }}</div>
12370 <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
12373 it('should remove the template directive and css class', function() {
12374 expect(element('.doc-example-live #template1').attr('ng-cloak')).
12375 not().toBeDefined();
12376 expect(element('.doc-example-live #template2').attr('ng-cloak')).
12377 not().toBeDefined();
12383 var ngCloakDirective = ngDirective({
12384 compile: function(element, attr) {
12385 attr.$set('ngCloak', undefined);
12386 element.removeClass('ng-cloak');
12392 * @name ng.directive:ngController
12395 * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
12396 * supports the principles behind the Model-View-Controller design pattern.
12398 * MVC components in angular:
12400 * * Model — The Model is data in scope properties; scopes are attached to the DOM.
12401 * * View — The template (HTML with data bindings) is rendered into the View.
12402 * * Controller — The `ngController` directive specifies a Controller class; the class has
12403 * methods that typically express the business logic behind the application.
12405 * Note that an alternative way to define controllers is via the `{@link ng.$route}`
12410 * @param {expression} ngController Name of a globally accessible constructor function or an
12411 * {@link guide/expression expression} that on the current scope evaluates to a
12412 * constructor function.
12415 * Here is a simple form for editing user contact information. Adding, removing, clearing, and
12416 * greeting are methods declared on the controller (see source tab). These methods can
12417 * easily be called from the angular markup. Notice that the scope becomes the `this` for the
12418 * controller's instance. This allows for easy access to the view data from the controller. Also
12419 * notice that any changes to the data are automatically reflected in the View without the need
12420 * for a manual update.
12424 function SettingsController($scope) {
12425 $scope.name = "John Smith";
12426 $scope.contacts = [
12427 {type:'phone', value:'408 555 1212'},
12428 {type:'email', value:'john.smith@example.org'} ];
12430 $scope.greet = function() {
12434 $scope.addContact = function() {
12435 this.contacts.push({type:'email', value:'yourname@example.org'});
12438 $scope.removeContact = function(contactToRemove) {
12439 var index = this.contacts.indexOf(contactToRemove);
12440 this.contacts.splice(index, 1);
12443 $scope.clearContact = function(contact) {
12444 contact.type = 'phone';
12445 contact.value = '';
12449 <div ng-controller="SettingsController">
12450 Name: <input type="text" ng-model="name"/>
12451 [ <a href="" ng-click="greet()">greet</a> ]<br/>
12454 <li ng-repeat="contact in contacts">
12455 <select ng-model="contact.type">
12456 <option>phone</option>
12457 <option>email</option>
12459 <input type="text" ng-model="contact.value"/>
12460 [ <a href="" ng-click="clearContact(contact)">clear</a>
12461 | <a href="" ng-click="removeContact(contact)">X</a> ]
12463 <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
12468 it('should check controller', function() {
12469 expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
12470 expect(element('.doc-example-live li:nth-child(1) input').val())
12471 .toBe('408 555 1212');
12472 expect(element('.doc-example-live li:nth-child(2) input').val())
12473 .toBe('john.smith@example.org');
12475 element('.doc-example-live li:first a:contains("clear")').click();
12476 expect(element('.doc-example-live li:first input').val()).toBe('');
12478 element('.doc-example-live li:last a:contains("add")').click();
12479 expect(element('.doc-example-live li:nth-child(3) input').val())
12480 .toBe('yourname@example.org');
12485 var ngControllerDirective = [function() {
12494 * @name ng.directive:ngCsp
12498 * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
12499 * This directive should be used on the root element of the application (typically the `<html>`
12500 * element or other element with the {@link ng.directive:ngApp ngApp}
12503 * If enabled the performance of template expression evaluator will suffer slightly, so don't enable
12504 * this mode unless you need it.
12509 var ngCspDirective = ['$sniffer', function($sniffer) {
12512 compile: function() {
12513 $sniffer.csp = true;
12520 * @name ng.directive:ngClick
12523 * The ngClick allows you to specify custom behavior when
12524 * element is clicked.
12527 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
12528 * click. (Event object is available as `$event`)
12533 <button ng-click="count = count + 1" ng-init="count=0">
12539 it('should check ng-click', function() {
12540 expect(binding('count')).toBe('0');
12541 element('.doc-example-live :button').click();
12542 expect(binding('count')).toBe('1');
12548 * A directive that allows creation of custom onclick handlers that are defined as angular
12549 * expressions and are compiled and executed within the current scope.
12551 * Events that are handled via these handler are always configured not to propagate further.
12553 var ngEventDirectives = {};
12555 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '),
12557 var directiveName = directiveNormalize('ng-' + name);
12558 ngEventDirectives[directiveName] = ['$parse', function($parse) {
12559 return function(scope, element, attr) {
12560 var fn = $parse(attr[directiveName]);
12561 element.bind(lowercase(name), function(event) {
12562 scope.$apply(function() {
12563 fn(scope, {$event:event});
12573 * @name ng.directive:ngDblclick
12576 * The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
12579 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
12580 * dblclick. (Event object is available as `$event`)
12583 * See {@link ng.directive:ngClick ngClick}
12589 * @name ng.directive:ngMousedown
12592 * The ngMousedown directive allows you to specify custom behavior on mousedown event.
12595 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
12596 * mousedown. (Event object is available as `$event`)
12599 * See {@link ng.directive:ngClick ngClick}
12605 * @name ng.directive:ngMouseup
12608 * Specify custom behavior on mouseup event.
12611 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
12612 * mouseup. (Event object is available as `$event`)
12615 * See {@link ng.directive:ngClick ngClick}
12620 * @name ng.directive:ngMouseover
12623 * Specify custom behavior on mouseover event.
12626 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
12627 * mouseover. (Event object is available as `$event`)
12630 * See {@link ng.directive:ngClick ngClick}
12636 * @name ng.directive:ngMouseenter
12639 * Specify custom behavior on mouseenter event.
12642 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
12643 * mouseenter. (Event object is available as `$event`)
12646 * See {@link ng.directive:ngClick ngClick}
12652 * @name ng.directive:ngMouseleave
12655 * Specify custom behavior on mouseleave event.
12658 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
12659 * mouseleave. (Event object is available as `$event`)
12662 * See {@link ng.directive:ngClick ngClick}
12668 * @name ng.directive:ngMousemove
12671 * Specify custom behavior on mousemove event.
12674 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
12675 * mousemove. (Event object is available as `$event`)
12678 * See {@link ng.directive:ngClick ngClick}
12684 * @name ng.directive:ngSubmit
12687 * Enables binding angular expressions to onsubmit events.
12689 * Additionally it prevents the default action (which for form means sending the request to the
12690 * server and reloading the current page).
12693 * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
12699 function Ctrl($scope) {
12701 $scope.text = 'hello';
12702 $scope.submit = function() {
12704 this.list.push(this.text);
12710 <form ng-submit="submit()" ng-controller="Ctrl">
12711 Enter text and hit enter:
12712 <input type="text" ng-model="text" name="text" />
12713 <input type="submit" id="submit" value="Submit" />
12714 <pre>list={{list}}</pre>
12718 it('should check ng-submit', function() {
12719 expect(binding('list')).toBe('[]');
12720 element('.doc-example-live #submit').click();
12721 expect(binding('list')).toBe('["hello"]');
12722 expect(input('text').val()).toBe('');
12724 it('should ignore empty strings', function() {
12725 expect(binding('list')).toBe('[]');
12726 element('.doc-example-live #submit').click();
12727 element('.doc-example-live #submit').click();
12728 expect(binding('list')).toBe('["hello"]');
12733 var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
12734 element.bind('submit', function() {
12735 scope.$apply(attrs.ngSubmit);
12741 * @name ng.directive:ngInclude
12745 * Fetches, compiles and includes an external HTML fragment.
12747 * Keep in mind that Same Origin Policy applies to included resources
12748 * (e.g. ngInclude won't work for cross-domain requests on all browsers and for
12749 * file:// access on some browsers).
12753 * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
12754 * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
12755 * @param {string=} onload Expression to evaluate when a new partial is loaded.
12757 * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
12758 * $anchorScroll} to scroll the viewport after the content is loaded.
12760 * - If the attribute is not set, disable scrolling.
12761 * - If the attribute is set without value, enable scrolling.
12762 * - Otherwise enable scrolling only if the expression evaluates to truthy value.
12766 <file name="index.html">
12767 <div ng-controller="Ctrl">
12768 <select ng-model="template" ng-options="t.name for t in templates">
12769 <option value="">(blank)</option>
12771 url of the template: <tt>{{template.url}}</tt>
12773 <div ng-include src="template.url"></div>
12776 <file name="script.js">
12777 function Ctrl($scope) {
12779 [ { name: 'template1.html', url: 'template1.html'}
12780 , { name: 'template2.html', url: 'template2.html'} ];
12781 $scope.template = $scope.templates[0];
12784 <file name="template1.html">
12785 Content of template1.html
12787 <file name="template2.html">
12788 Content of template2.html
12790 <file name="scenario.js">
12791 it('should load template1.html', function() {
12792 expect(element('.doc-example-live [ng-include]').text()).
12793 toMatch(/Content of template1.html/);
12795 it('should load template2.html', function() {
12796 select('template').option('1');
12797 expect(element('.doc-example-live [ng-include]').text()).
12798 toMatch(/Content of template2.html/);
12800 it('should change to blank', function() {
12801 select('template').option('');
12802 expect(element('.doc-example-live [ng-include]').text()).toEqual('');
12811 * @name ng.directive:ngInclude#$includeContentLoaded
12812 * @eventOf ng.directive:ngInclude
12813 * @eventType emit on the current ngInclude scope
12815 * Emitted every time the ngInclude content is reloaded.
12817 var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile',
12818 function($http, $templateCache, $anchorScroll, $compile) {
12822 compile: function(element, attr) {
12823 var srcExp = attr.ngInclude || attr.src,
12824 onloadExp = attr.onload || '',
12825 autoScrollExp = attr.autoscroll;
12827 return function(scope, element) {
12828 var changeCounter = 0,
12831 var clearContent = function() {
12833 childScope.$destroy();
12840 scope.$watch(srcExp, function(src) {
12841 var thisChangeId = ++changeCounter;
12844 $http.get(src, {cache: $templateCache}).success(function(response) {
12845 if (thisChangeId !== changeCounter) return;
12847 if (childScope) childScope.$destroy();
12848 childScope = scope.$new();
12850 element.html(response);
12851 $compile(element.contents())(childScope);
12853 if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
12857 childScope.$emit('$includeContentLoaded');
12858 scope.$eval(onloadExp);
12859 }).error(function() {
12860 if (thisChangeId === changeCounter) clearContent();
12862 } else clearContent();
12871 * @name ng.directive:ngInit
12874 * The `ngInit` directive specifies initialization tasks to be executed
12875 * before the template enters execution mode during bootstrap.
12878 * @param {expression} ngInit {@link guide/expression Expression} to eval.
12883 <div ng-init="greeting='Hello'; person='World'">
12884 {{greeting}} {{person}}!
12888 it('should check greeting', function() {
12889 expect(binding('greeting')).toBe('Hello');
12890 expect(binding('person')).toBe('World');
12895 var ngInitDirective = ngDirective({
12896 compile: function() {
12898 pre: function(scope, element, attrs) {
12899 scope.$eval(attrs.ngInit);
12907 * @name ng.directive:ngNonBindable
12911 * Sometimes it is necessary to write code which looks like bindings but which should be left alone
12912 * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
12917 * In this example there are two location where a simple binding (`{{}}`) is present, but the one
12918 * wrapped in `ngNonBindable` is left alone.
12923 <div>Normal: {{1 + 2}}</div>
12924 <div ng-non-bindable>Ignored: {{1 + 2}}</div>
12927 it('should check ng-non-bindable', function() {
12928 expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
12929 expect(using('.doc-example-live').element('div:last').text()).
12935 var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
12939 * @name ng.directive:ngPluralize
12944 * `ngPluralize` is a directive that displays messages according to en-US localization rules.
12945 * These rules are bundled with angular.js and the rules can be overridden
12946 * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
12947 * by specifying the mappings between
12948 * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
12949 * plural categories} and the strings to be displayed.
12951 * # Plural categories and explicit number rules
12953 * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
12954 * plural categories} in Angular's default en-US locale: "one" and "other".
12956 * While a pural category may match many numbers (for example, in en-US locale, "other" can match
12957 * any number that is not 1), an explicit number rule can only match one number. For example, the
12958 * explicit number rule for "3" matches the number 3. You will see the use of plural categories
12959 * and explicit number rules throughout later parts of this documentation.
12961 * # Configuring ngPluralize
12962 * You configure ngPluralize by providing 2 attributes: `count` and `when`.
12963 * You can also provide an optional attribute, `offset`.
12965 * The value of the `count` attribute can be either a string or an {@link guide/expression
12966 * Angular expression}; these are evaluated on the current scope for its bound value.
12968 * The `when` attribute specifies the mappings between plural categories and the actual
12969 * string to be displayed. The value of the attribute should be a JSON object so that Angular
12970 * can interpret it correctly.
12972 * The following example shows how to configure ngPluralize:
12975 * <ng-pluralize count="personCount"
12976 when="{'0': 'Nobody is viewing.',
12977 * 'one': '1 person is viewing.',
12978 * 'other': '{} people are viewing.'}">
12982 * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
12983 * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
12984 * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
12985 * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
12986 * show "a dozen people are viewing".
12988 * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
12989 * into pluralized strings. In the previous example, Angular will replace `{}` with
12990 * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
12991 * for <span ng-non-bindable>{{numberExpression}}</span>.
12993 * # Configuring ngPluralize with offset
12994 * The `offset` attribute allows further customization of pluralized text, which can result in
12995 * a better user experience. For example, instead of the message "4 people are viewing this document",
12996 * you might display "John, Kate and 2 others are viewing this document".
12997 * The offset attribute allows you to offset a number by any desired value.
12998 * Let's take a look at an example:
13001 * <ng-pluralize count="personCount" offset=2
13002 * when="{'0': 'Nobody is viewing.',
13003 * '1': '{{person1}} is viewing.',
13004 * '2': '{{person1}} and {{person2}} are viewing.',
13005 * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
13006 * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
13010 * Notice that we are still using two plural categories(one, other), but we added
13011 * three explicit number rules 0, 1 and 2.
13012 * When one person, perhaps John, views the document, "John is viewing" will be shown.
13013 * When three people view the document, no explicit number rule is found, so
13014 * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
13015 * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
13018 * Note that when you specify offsets, you must provide explicit number rules for
13019 * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
13020 * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
13021 * plural categories "one" and "other".
13023 * @param {string|expression} count The variable to be bounded to.
13024 * @param {string} when The mapping between plural category to its correspoding strings.
13025 * @param {number=} offset Offset to deduct from the total number.
13031 function Ctrl($scope) {
13032 $scope.person1 = 'Igor';
13033 $scope.person2 = 'Misko';
13034 $scope.personCount = 1;
13037 <div ng-controller="Ctrl">
13038 Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
13039 Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
13040 Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
13042 <!--- Example with simple pluralization rules for en locale --->
13044 <ng-pluralize count="personCount"
13045 when="{'0': 'Nobody is viewing.',
13046 'one': '1 person is viewing.',
13047 'other': '{} people are viewing.'}">
13048 </ng-pluralize><br>
13050 <!--- Example with offset --->
13052 <ng-pluralize count="personCount" offset=2
13053 when="{'0': 'Nobody is viewing.',
13054 '1': '{{person1}} is viewing.',
13055 '2': '{{person1}} and {{person2}} are viewing.',
13056 'one': '{{person1}}, {{person2}} and one other person are viewing.',
13057 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
13062 it('should show correct pluralized string', function() {
13063 expect(element('.doc-example-live ng-pluralize:first').text()).
13064 toBe('1 person is viewing.');
13065 expect(element('.doc-example-live ng-pluralize:last').text()).
13066 toBe('Igor is viewing.');
13068 using('.doc-example-live').input('personCount').enter('0');
13069 expect(element('.doc-example-live ng-pluralize:first').text()).
13070 toBe('Nobody is viewing.');
13071 expect(element('.doc-example-live ng-pluralize:last').text()).
13072 toBe('Nobody is viewing.');
13074 using('.doc-example-live').input('personCount').enter('2');
13075 expect(element('.doc-example-live ng-pluralize:first').text()).
13076 toBe('2 people are viewing.');
13077 expect(element('.doc-example-live ng-pluralize:last').text()).
13078 toBe('Igor and Misko are viewing.');
13080 using('.doc-example-live').input('personCount').enter('3');
13081 expect(element('.doc-example-live ng-pluralize:first').text()).
13082 toBe('3 people are viewing.');
13083 expect(element('.doc-example-live ng-pluralize:last').text()).
13084 toBe('Igor, Misko and one other person are viewing.');
13086 using('.doc-example-live').input('personCount').enter('4');
13087 expect(element('.doc-example-live ng-pluralize:first').text()).
13088 toBe('4 people are viewing.');
13089 expect(element('.doc-example-live ng-pluralize:last').text()).
13090 toBe('Igor, Misko and 2 other people are viewing.');
13093 it('should show data-binded names', function() {
13094 using('.doc-example-live').input('personCount').enter('4');
13095 expect(element('.doc-example-live ng-pluralize:last').text()).
13096 toBe('Igor, Misko and 2 other people are viewing.');
13098 using('.doc-example-live').input('person1').enter('Di');
13099 using('.doc-example-live').input('person2').enter('Vojta');
13100 expect(element('.doc-example-live ng-pluralize:last').text()).
13101 toBe('Di, Vojta and 2 other people are viewing.');
13106 var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
13110 link: function(scope, element, attr) {
13111 var numberExp = attr.count,
13112 whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
13113 offset = attr.offset || 0,
13114 whens = scope.$eval(whenExp),
13116 startSymbol = $interpolate.startSymbol(),
13117 endSymbol = $interpolate.endSymbol();
13119 forEach(whens, function(expression, key) {
13121 $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
13122 offset + endSymbol));
13125 scope.$watch(function() {
13126 var value = parseFloat(scope.$eval(numberExp));
13128 if (!isNaN(value)) {
13129 //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
13130 //check it against pluralization rules in $locale service
13131 if (!whens[value]) value = $locale.pluralCat(value - offset);
13132 return whensExpFns[value](scope, element, true);
13136 }, function(newVal) {
13137 element.text(newVal);
13145 * @name ng.directive:ngRepeat
13148 * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
13149 * instance gets its own scope, where the given loop variable is set to the current collection item,
13150 * and `$index` is set to the item index or key.
13152 * Special properties are exposed on the local scope of each template instance, including:
13154 * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
13155 * * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
13156 * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
13157 * * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
13163 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
13164 * formats are currently supported:
13166 * * `variable in expression` – where variable is the user defined loop variable and `expression`
13167 * is a scope expression giving the collection to enumerate.
13169 * For example: `track in cd.tracks`.
13171 * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
13172 * and `expression` is the scope expression giving the collection to enumerate.
13174 * For example: `(name, age) in {'adam':10, 'amalie':12}`.
13177 * This example initializes the scope to a list of names and
13178 * then uses `ngRepeat` to display every person:
13181 <div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
13182 I have {{friends.length}} friends. They are:
13184 <li ng-repeat="friend in friends">
13185 [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
13191 it('should check ng-repeat', function() {
13192 var r = using('.doc-example-live').repeater('ul li');
13193 expect(r.count()).toBe(2);
13194 expect(r.row(0)).toEqual(["1","John","25"]);
13195 expect(r.row(1)).toEqual(["2","Mary","28"]);
13200 var ngRepeatDirective = ngDirective({
13201 transclude: 'element',
13204 compile: function(element, attr, linker) {
13205 return function(scope, iterStartElement, attr){
13206 var expression = attr.ngRepeat;
13207 var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
13208 lhs, rhs, valueIdent, keyIdent;
13210 throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
13211 expression + "'.");
13215 match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
13217 throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
13220 valueIdent = match[3] || match[1];
13221 keyIdent = match[2];
13223 // Store a list of elements from previous run. This is a hash where key is the item from the
13224 // iterator, and the value is an array of objects with following properties.
13225 // - scope: bound scope
13226 // - element: previous element.
13227 // - index: position
13228 // We need an array of these objects since the same object can be returned from the iterator.
13229 // We expect this to be a rare case.
13230 var lastOrder = new HashQueueMap();
13231 scope.$watch(function(scope){
13233 collection = scope.$eval(rhs),
13234 collectionLength = size(collection, true),
13236 // Same as lastOrder but it has the current state. It will become the
13237 // lastOrder on the next iteration.
13238 nextOrder = new HashQueueMap(),
13239 key, value, // key/value of iteration
13240 array, last, // last object information {scope, element, index}
13241 cursor = iterStartElement; // current position of the node
13243 if (!isArray(collection)) {
13244 // if object, extract keys, sort them and use to determine order of iteration over obj props
13246 for(key in collection) {
13247 if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
13253 array = collection || [];
13256 // we are not using forEach for perf reasons (trying to avoid #call)
13257 for (index = 0, length = array.length; index < length; index++) {
13258 key = (collection === array) ? index : array[index];
13259 value = collection[key];
13260 last = lastOrder.shift(value);
13262 // if we have already seen this object, then we need to reuse the
13263 // associated scope/element
13264 childScope = last.scope;
13265 nextOrder.push(value, last);
13267 if (index === last.index) {
13269 cursor = last.element;
13271 // existing item which got moved
13272 last.index = index;
13273 // This may be a noop, if the element is next, but I don't know of a good way to
13274 // figure this out, since it would require extra DOM access, so let's just hope that
13275 // the browsers realizes that it is noop, and treats it as such.
13276 cursor.after(last.element);
13277 cursor = last.element;
13280 // new item which we don't know about
13281 childScope = scope.$new();
13284 childScope[valueIdent] = value;
13285 if (keyIdent) childScope[keyIdent] = key;
13286 childScope.$index = index;
13288 childScope.$first = (index === 0);
13289 childScope.$last = (index === (collectionLength - 1));
13290 childScope.$middle = !(childScope.$first || childScope.$last);
13293 linker(childScope, function(clone){
13294 cursor.after(clone);
13297 element: (cursor = clone),
13300 nextOrder.push(value, last);
13306 for (key in lastOrder) {
13307 if (lastOrder.hasOwnProperty(key)) {
13308 array = lastOrder[key];
13309 while(array.length) {
13310 value = array.pop();
13311 value.element.remove();
13312 value.scope.$destroy();
13317 lastOrder = nextOrder;
13325 * @name ng.directive:ngShow
13328 * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
13332 * @param {expression} ngShow If the {@link guide/expression expression} is truthy
13333 * then the element is shown or hidden respectively.
13338 Click me: <input type="checkbox" ng-model="checked"><br/>
13339 Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/>
13340 Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
13343 it('should check ng-show / ng-hide', function() {
13344 expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
13345 expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
13347 input('checked').check();
13349 expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
13350 expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
13355 //TODO(misko): refactor to remove element from the DOM
13356 var ngShowDirective = ngDirective(function(scope, element, attr){
13357 scope.$watch(attr.ngShow, function(value){
13358 element.css('display', toBoolean(value) ? '' : 'none');
13365 * @name ng.directive:ngHide
13368 * The `ngHide` and `ngShow` directives hide or show a portion
13369 * of the HTML conditionally.
13372 * @param {expression} ngHide If the {@link guide/expression expression} truthy then
13373 * the element is shown or hidden respectively.
13378 Click me: <input type="checkbox" ng-model="checked"><br/>
13379 Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
13380 Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
13383 it('should check ng-show / ng-hide', function() {
13384 expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
13385 expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
13387 input('checked').check();
13389 expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
13390 expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
13395 //TODO(misko): refactor to remove element from the DOM
13396 var ngHideDirective = ngDirective(function(scope, element, attr){
13397 scope.$watch(attr.ngHide, function(value){
13398 element.css('display', toBoolean(value) ? 'none' : '');
13404 * @name ng.directive:ngStyle
13407 * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
13410 * @param {expression} ngStyle {@link guide/expression Expression} which evals to an
13411 * object whose keys are CSS style names and values are corresponding values for those CSS
13416 <file name="index.html">
13417 <input type="button" value="set" ng-click="myStyle={color:'red'}">
13418 <input type="button" value="clear" ng-click="myStyle={}">
13420 <span ng-style="myStyle">Sample Text</span>
13421 <pre>myStyle={{myStyle}}</pre>
13423 <file name="style.css">
13428 <file name="scenario.js">
13429 it('should check ng-style', function() {
13430 expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
13431 element('.doc-example-live :button[value=set]').click();
13432 expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
13433 element('.doc-example-live :button[value=clear]').click();
13434 expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
13439 var ngStyleDirective = ngDirective(function(scope, element, attr) {
13440 scope.$watch(attr.ngStyle, function(newStyles, oldStyles) {
13441 if (oldStyles && (newStyles !== oldStyles)) {
13442 forEach(oldStyles, function(val, style) { element.css(style, '');});
13444 if (newStyles) element.css(newStyles);
13450 * @name ng.directive:ngSwitch
13454 * Conditionally change the DOM structure.
13457 * <ANY ng-switch-when="matchValue1">...</ANY>
13458 * <ANY ng-switch-when="matchValue2">...</ANY>
13460 * <ANY ng-switch-default>...</ANY>
13463 * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
13464 * @paramDescription
13465 * On child elments add:
13467 * * `ngSwitchWhen`: the case statement to match against. If match then this
13468 * case will be displayed.
13469 * * `ngSwitchDefault`: the default case when no other casses match.
13475 function Ctrl($scope) {
13476 $scope.items = ['settings', 'home', 'other'];
13477 $scope.selection = $scope.items[0];
13480 <div ng-controller="Ctrl">
13481 <select ng-model="selection" ng-options="item for item in items">
13483 <tt>selection={{selection}}</tt>
13485 <div ng-switch on="selection" >
13486 <div ng-switch-when="settings">Settings Div</div>
13487 <span ng-switch-when="home">Home Span</span>
13488 <span ng-switch-default>default</span>
13493 it('should start in settings', function() {
13494 expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
13496 it('should change to home', function() {
13497 select('selection').option('home');
13498 expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
13500 it('should select deafault', function() {
13501 select('selection').option('other');
13502 expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
13507 var NG_SWITCH = 'ng-switch';
13508 var ngSwitchDirective = valueFn({
13510 compile: function(element, attr) {
13511 var watchExpr = attr.ngSwitch || attr.on,
13514 element.data(NG_SWITCH, cases);
13515 return function(scope, element){
13516 var selectedTransclude,
13520 scope.$watch(watchExpr, function(value) {
13521 if (selectedElement) {
13522 selectedScope.$destroy();
13523 selectedElement.remove();
13524 selectedElement = selectedScope = null;
13526 if ((selectedTransclude = cases['!' + value] || cases['?'])) {
13527 scope.$eval(attr.change);
13528 selectedScope = scope.$new();
13529 selectedTransclude(selectedScope, function(caseElement) {
13530 selectedElement = caseElement;
13531 element.append(caseElement);
13539 var ngSwitchWhenDirective = ngDirective({
13540 transclude: 'element',
13542 compile: function(element, attrs, transclude) {
13543 var cases = element.inheritedData(NG_SWITCH);
13545 cases['!' + attrs.ngSwitchWhen] = transclude;
13549 var ngSwitchDefaultDirective = ngDirective({
13550 transclude: 'element',
13552 compile: function(element, attrs, transclude) {
13553 var cases = element.inheritedData(NG_SWITCH);
13555 cases['?'] = transclude;
13561 * @name ng.directive:ngTransclude
13564 * Insert the transcluded DOM here.
13569 <doc:example module="transclude">
13572 function Ctrl($scope) {
13573 $scope.title = 'Lorem Ipsum';
13574 $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
13577 angular.module('transclude', [])
13578 .directive('pane', function(){
13583 locals: { title:'bind' },
13584 template: '<div style="border: 1px solid black;">' +
13585 '<div style="background-color: gray">{{title}}</div>' +
13586 '<div ng-transclude></div>' +
13591 <div ng-controller="Ctrl">
13592 <input ng-model="title"><br>
13593 <textarea ng-model="text"></textarea> <br/>
13594 <pane title="{{title}}">{{text}}</pane>
13598 it('should have transcluded', function() {
13599 input('title').enter('TITLE');
13600 input('text').enter('TEXT');
13601 expect(binding('title')).toEqual('TITLE');
13602 expect(binding('text')).toEqual('TEXT');
13608 var ngTranscludeDirective = ngDirective({
13609 controller: ['$transclude', '$element', function($transclude, $element) {
13610 $transclude(function(clone) {
13611 $element.append(clone);
13618 * @name ng.directive:ngView
13623 * `ngView` is a directive that complements the {@link ng.$route $route} service by
13624 * including the rendered template of the current route into the main layout (`index.html`) file.
13625 * Every time the current route changes, the included view changes with it according to the
13626 * configuration of the `$route` service.
13630 <example module="ngView">
13631 <file name="index.html">
13632 <div ng-controller="MainCntl">
13634 <a href="Book/Moby">Moby</a> |
13635 <a href="Book/Moby/ch/1">Moby: Ch1</a> |
13636 <a href="Book/Gatsby">Gatsby</a> |
13637 <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
13638 <a href="Book/Scarlet">Scarlet Letter</a><br/>
13640 <div ng-view></div>
13643 <pre>$location.path() = {{$location.path()}}</pre>
13644 <pre>$route.current.template = {{$route.current.template}}</pre>
13645 <pre>$route.current.params = {{$route.current.params}}</pre>
13646 <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
13647 <pre>$routeParams = {{$routeParams}}</pre>
13651 <file name="book.html">
13652 controller: {{name}}<br />
13653 Book Id: {{params.bookId}}<br />
13656 <file name="chapter.html">
13657 controller: {{name}}<br />
13658 Book Id: {{params.bookId}}<br />
13659 Chapter Id: {{params.chapterId}}
13662 <file name="script.js">
13663 angular.module('ngView', [], function($routeProvider, $locationProvider) {
13664 $routeProvider.when('/Book/:bookId', {
13665 templateUrl: 'book.html',
13666 controller: BookCntl
13668 $routeProvider.when('/Book/:bookId/ch/:chapterId', {
13669 templateUrl: 'chapter.html',
13670 controller: ChapterCntl
13673 // configure html5 to get links working on jsfiddle
13674 $locationProvider.html5Mode(true);
13677 function MainCntl($scope, $route, $routeParams, $location) {
13678 $scope.$route = $route;
13679 $scope.$location = $location;
13680 $scope.$routeParams = $routeParams;
13683 function BookCntl($scope, $routeParams) {
13684 $scope.name = "BookCntl";
13685 $scope.params = $routeParams;
13688 function ChapterCntl($scope, $routeParams) {
13689 $scope.name = "ChapterCntl";
13690 $scope.params = $routeParams;
13694 <file name="scenario.js">
13695 it('should load and compile correct template', function() {
13696 element('a:contains("Moby: Ch1")').click();
13697 var content = element('.doc-example-live [ng-view]').text();
13698 expect(content).toMatch(/controller\: ChapterCntl/);
13699 expect(content).toMatch(/Book Id\: Moby/);
13700 expect(content).toMatch(/Chapter Id\: 1/);
13702 element('a:contains("Scarlet")').click();
13703 content = element('.doc-example-live [ng-view]').text();
13704 expect(content).toMatch(/controller\: BookCntl/);
13705 expect(content).toMatch(/Book Id\: Scarlet/);
13714 * @name ng.directive:ngView#$viewContentLoaded
13715 * @eventOf ng.directive:ngView
13716 * @eventType emit on the current ngView scope
13718 * Emitted every time the ngView content is reloaded.
13720 var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
13722 function($http, $templateCache, $route, $anchorScroll, $compile,
13727 link: function(scope, element, attr) {
13729 onloadExp = attr.onload || '';
13731 scope.$on('$routeChangeSuccess', update);
13735 function destroyLastScope() {
13737 lastScope.$destroy();
13742 function clearContent() {
13744 destroyLastScope();
13747 function update() {
13748 var locals = $route.current && $route.current.locals,
13749 template = locals && locals.$template;
13752 element.html(template);
13753 destroyLastScope();
13755 var link = $compile(element.contents()),
13756 current = $route.current,
13759 lastScope = current.scope = scope.$new();
13760 if (current.controller) {
13761 locals.$scope = lastScope;
13762 controller = $controller(current.controller, locals);
13763 element.contents().data('$ngControllerController', controller);
13767 lastScope.$emit('$viewContentLoaded');
13768 lastScope.$eval(onloadExp);
13770 // $anchorScroll might listen on event...
13782 * @name ng.directive:script
13785 * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
13786 * template can be used by `ngInclude`, `ngView` or directive templates.
13789 * @param {'text/ng-template'} type must be set to `'text/ng-template'`
13794 <script type="text/ng-template" id="/tpl.html">
13795 Content of the template.
13798 <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
13799 <div id="tpl-content" ng-include src="currentTpl"></div>
13802 it('should load template defined inside script tag', function() {
13803 element('#tpl-link').click();
13804 expect(element('#tpl-content').text()).toMatch(/Content of the template/);
13809 var scriptDirective = ['$templateCache', function($templateCache) {
13813 compile: function(element, attr) {
13814 if (attr.type == 'text/ng-template') {
13815 var templateUrl = attr.id,
13816 // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
13817 text = element[0].text;
13819 $templateCache.put(templateUrl, text);
13827 * @name ng.directive:select
13831 * HTML `SELECT` element with angular data-binding.
13835 * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
13836 * elements for a `<select>` element using an array or an object obtained by evaluating the
13837 * `ngOptions` expression.
13839 * When an item in the select menu is select, the value of array element or object property
13840 * represented by the selected option will be bound to the model identified by the `ngModel`
13841 * directive of the parent select element.
13843 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
13844 * be nested into the `<select>` element. This element will then represent `null` or "not selected"
13845 * option. See example below for demonstration.
13847 * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
13848 * of {@link ng.directive:ngRepeat ngRepeat} when you want the
13849 * `select` model to be bound to a non-string value. This is because an option element can currently
13850 * be bound to string values only.
13852 * @param {string} name assignable expression to data-bind to.
13853 * @param {string=} required The control is considered valid only if value is entered.
13854 * @param {comprehension_expression=} ngOptions in one of the following forms:
13856 * * for array data sources:
13857 * * `label` **`for`** `value` **`in`** `array`
13858 * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
13859 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
13860 * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
13861 * * for object data sources:
13862 * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
13863 * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
13864 * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
13865 * * `select` **`as`** `label` **`group by`** `group`
13866 * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
13870 * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
13871 * * `value`: local variable which will refer to each item in the `array` or each property value
13872 * of `object` during iteration.
13873 * * `key`: local variable which will refer to a property name in `object` during iteration.
13874 * * `label`: The result of this expression will be the label for `<option>` element. The
13875 * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
13876 * * `select`: The result of this expression will be bound to the model of the parent `<select>`
13877 * element. If not specified, `select` expression will default to `value`.
13878 * * `group`: The result of this expression will be used to group options using the `<optgroup>`
13885 function MyCntrl($scope) {
13887 {name:'black', shade:'dark'},
13888 {name:'white', shade:'light'},
13889 {name:'red', shade:'dark'},
13890 {name:'blue', shade:'dark'},
13891 {name:'yellow', shade:'light'}
13893 $scope.color = $scope.colors[2]; // red
13896 <div ng-controller="MyCntrl">
13898 <li ng-repeat="color in colors">
13899 Name: <input ng-model="color.name">
13900 [<a href ng-click="colors.splice($index, 1)">X</a>]
13903 [<a href ng-click="colors.push({})">add</a>]
13907 Color (null not allowed):
13908 <select ng-model="color" ng-options="c.name for c in colors"></select><br>
13910 Color (null allowed):
13911 <span class="nullable">
13912 <select ng-model="color" ng-options="c.name for c in colors">
13913 <option value="">-- chose color --</option>
13917 Color grouped by shade:
13918 <select ng-model="color" ng-options="c.name group by c.shade for c in colors">
13922 Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
13924 Currently selected: {{ {selected_color:color} }}
13925 <div style="border:solid 1px black; height:20px"
13926 ng-style="{'background-color':color.name}">
13931 it('should check ng-options', function() {
13932 expect(binding('{selected_color:color}')).toMatch('red');
13933 select('color').option('0');
13934 expect(binding('{selected_color:color}')).toMatch('black');
13935 using('.nullable').select('color').option('');
13936 expect(binding('{selected_color:color}')).toMatch('null');
13942 var ngOptionsDirective = valueFn({ terminal: true });
13943 var selectDirective = ['$compile', '$parse', function($compile, $parse) {
13944 //00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777
13945 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/,
13946 nullModelCtrl = {$setViewValue: noop};
13950 require: ['select', '?ngModel'],
13951 controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
13954 ngModelCtrl = nullModelCtrl,
13959 self.databound = $attrs.ngModel;
13962 self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
13963 ngModelCtrl = ngModelCtrl_;
13964 nullOption = nullOption_;
13965 unknownOption = unknownOption_;
13969 self.addOption = function(value) {
13970 optionsMap[value] = true;
13972 if (ngModelCtrl.$viewValue == value) {
13973 $element.val(value);
13974 if (unknownOption.parent()) unknownOption.remove();
13979 self.removeOption = function(value) {
13980 if (this.hasOption(value)) {
13981 delete optionsMap[value];
13982 if (ngModelCtrl.$viewValue == value) {
13983 this.renderUnknownOption(value);
13989 self.renderUnknownOption = function(val) {
13990 var unknownVal = '? ' + hashKey(val) + ' ?';
13991 unknownOption.val(unknownVal);
13992 $element.prepend(unknownOption);
13993 $element.val(unknownVal);
13994 unknownOption.prop('selected', true); // needed for IE
13998 self.hasOption = function(value) {
13999 return optionsMap.hasOwnProperty(value);
14002 $scope.$on('$destroy', function() {
14003 // disable unknown option so that we don't do work when the whole select is being destroyed
14004 self.renderUnknownOption = noop;
14008 link: function(scope, element, attr, ctrls) {
14009 // if ngModel is not defined, we don't need to do anything
14010 if (!ctrls[1]) return;
14012 var selectCtrl = ctrls[0],
14013 ngModelCtrl = ctrls[1],
14014 multiple = attr.multiple,
14015 optionsExp = attr.ngOptions,
14016 nullOption = false, // if false, user will not be able to select it (used by ngOptions)
14018 // we can't just jqLite('<option>') since jqLite is not smart enough
14019 // to create it in <select> and IE barfs otherwise.
14020 optionTemplate = jqLite(document.createElement('option')),
14021 optGroupTemplate =jqLite(document.createElement('optgroup')),
14022 unknownOption = optionTemplate.clone();
14024 // find "null" option
14025 for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
14026 if (children[i].value == '') {
14027 emptyOption = nullOption = children.eq(i);
14032 selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
14034 // required validator
14035 if (multiple && (attr.required || attr.ngRequired)) {
14036 var requiredValidator = function(value) {
14037 ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
14041 ngModelCtrl.$parsers.push(requiredValidator);
14042 ngModelCtrl.$formatters.unshift(requiredValidator);
14044 attr.$observe('required', function() {
14045 requiredValidator(ngModelCtrl.$viewValue);
14049 if (optionsExp) Options(scope, element, ngModelCtrl);
14050 else if (multiple) Multiple(scope, element, ngModelCtrl);
14051 else Single(scope, element, ngModelCtrl, selectCtrl);
14054 ////////////////////////////
14058 function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
14059 ngModelCtrl.$render = function() {
14060 var viewValue = ngModelCtrl.$viewValue;
14062 if (selectCtrl.hasOption(viewValue)) {
14063 if (unknownOption.parent()) unknownOption.remove();
14064 selectElement.val(viewValue);
14065 if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
14067 if (isUndefined(viewValue) && emptyOption) {
14068 selectElement.val('');
14070 selectCtrl.renderUnknownOption(viewValue);
14075 selectElement.bind('change', function() {
14076 scope.$apply(function() {
14077 if (unknownOption.parent()) unknownOption.remove();
14078 ngModelCtrl.$setViewValue(selectElement.val());
14083 function Multiple(scope, selectElement, ctrl) {
14085 ctrl.$render = function() {
14086 var items = new HashMap(ctrl.$viewValue);
14087 forEach(selectElement.children(), function(option) {
14088 option.selected = isDefined(items.get(option.value));
14092 // we have to do it on each watch since ngModel watches reference, but
14093 // we need to work of an array, so we need to see if anything was inserted/removed
14094 scope.$watch(function() {
14095 if (!equals(lastView, ctrl.$viewValue)) {
14096 lastView = copy(ctrl.$viewValue);
14101 selectElement.bind('change', function() {
14102 scope.$apply(function() {
14104 forEach(selectElement.children(), function(option) {
14105 if (option.selected) {
14106 array.push(option.value);
14109 ctrl.$setViewValue(array);
14114 function Options(scope, selectElement, ctrl) {
14117 if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
14119 "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
14120 " but got '" + optionsExp + "'.");
14123 var displayFn = $parse(match[2] || match[1]),
14124 valueName = match[4] || match[6],
14125 keyName = match[5],
14126 groupByFn = $parse(match[3] || ''),
14127 valueFn = $parse(match[2] ? match[1] : valueName),
14128 valuesFn = $parse(match[7]),
14129 // This is an array of array of existing option groups in DOM. We try to reuse these if possible
14130 // optionGroupsCache[0] is the options with no option group
14131 // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
14132 optionGroupsCache = [[{element: selectElement, label:''}]];
14135 // compile the element since there might be bindings in it
14136 $compile(nullOption)(scope);
14138 // remove the class, which is added automatically because we recompile the element and it
14139 // becomes the compilation root
14140 nullOption.removeClass('ng-scope');
14142 // we need to remove it before calling selectElement.html('') because otherwise IE will
14143 // remove the label from the element. wtf?
14144 nullOption.remove();
14147 // clear contents, we'll add what's needed based on the model
14148 selectElement.html('');
14150 selectElement.bind('change', function() {
14151 scope.$apply(function() {
14153 collection = valuesFn(scope) || [],
14155 key, value, optionElement, index, groupIndex, length, groupLength;
14159 for (groupIndex = 0, groupLength = optionGroupsCache.length;
14160 groupIndex < groupLength;
14162 // list of options for that group. (first item has the parent)
14163 optionGroup = optionGroupsCache[groupIndex];
14165 for(index = 1, length = optionGroup.length; index < length; index++) {
14166 if ((optionElement = optionGroup[index].element)[0].selected) {
14167 key = optionElement.val();
14168 if (keyName) locals[keyName] = key;
14169 locals[valueName] = collection[key];
14170 value.push(valueFn(scope, locals));
14175 key = selectElement.val();
14178 } else if (key == ''){
14181 locals[valueName] = collection[key];
14182 if (keyName) locals[keyName] = key;
14183 value = valueFn(scope, locals);
14186 ctrl.$setViewValue(value);
14190 ctrl.$render = render;
14192 // TODO(vojta): can't we optimize this ?
14193 scope.$watch(render);
14195 function render() {
14196 var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
14197 optionGroupNames = [''],
14201 existingParent, existingOptions, existingOption,
14202 modelValue = ctrl.$modelValue,
14203 values = valuesFn(scope) || [],
14204 keys = keyName ? sortedKeys(values) : values,
14205 groupLength, length,
14209 selectedSet = false, // nothing is selected yet
14214 selectedSet = new HashMap(modelValue);
14215 } else if (modelValue === null || nullOption) {
14216 // if we are not multiselect, and we are null then we have to add the nullOption
14217 optionGroups[''].push({selected:modelValue === null, id:'', label:''});
14218 selectedSet = true;
14221 // We now build up the list of options we need (we merge later)
14222 for (index = 0; length = keys.length, index < length; index++) {
14223 locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
14224 optionGroupName = groupByFn(scope, locals) || '';
14225 if (!(optionGroup = optionGroups[optionGroupName])) {
14226 optionGroup = optionGroups[optionGroupName] = [];
14227 optionGroupNames.push(optionGroupName);
14230 selected = selectedSet.remove(valueFn(scope, locals)) != undefined;
14232 selected = modelValue === valueFn(scope, locals);
14233 selectedSet = selectedSet || selected; // see if at least one item is selected
14236 id: keyName ? keys[index] : index, // either the index into array or key from object
14237 label: displayFn(scope, locals) || '', // what will be seen by the user
14238 selected: selected // determine if we should be selected
14241 if (!multiple && !selectedSet) {
14242 // nothing was selected, we have to insert the undefined item
14243 optionGroups[''].unshift({id:'?', label:'', selected:true});
14246 // Now we need to update the list of DOM nodes to match the optionGroups we computed above
14247 for (groupIndex = 0, groupLength = optionGroupNames.length;
14248 groupIndex < groupLength;
14250 // current option group name or '' if no group
14251 optionGroupName = optionGroupNames[groupIndex];
14253 // list of options for that group. (first item has the parent)
14254 optionGroup = optionGroups[optionGroupName];
14256 if (optionGroupsCache.length <= groupIndex) {
14257 // we need to grow the optionGroups
14259 element: optGroupTemplate.clone().attr('label', optionGroupName),
14260 label: optionGroup.label
14262 existingOptions = [existingParent];
14263 optionGroupsCache.push(existingOptions);
14264 selectElement.append(existingParent.element);
14266 existingOptions = optionGroupsCache[groupIndex];
14267 existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
14269 // update the OPTGROUP label if not the same.
14270 if (existingParent.label != optionGroupName) {
14271 existingParent.element.attr('label', existingParent.label = optionGroupName);
14275 lastElement = null; // start at the beginning
14276 for(index = 0, length = optionGroup.length; index < length; index++) {
14277 option = optionGroup[index];
14278 if ((existingOption = existingOptions[index+1])) {
14280 lastElement = existingOption.element;
14281 if (existingOption.label !== option.label) {
14282 lastElement.text(existingOption.label = option.label);
14284 if (existingOption.id !== option.id) {
14285 lastElement.val(existingOption.id = option.id);
14287 if (existingOption.element.selected !== option.selected) {
14288 lastElement.prop('selected', (existingOption.selected = option.selected));
14293 // if it's a null option
14294 if (option.id === '' && nullOption) {
14295 // put back the pre-compiled element
14296 element = nullOption;
14298 // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
14299 // in this version of jQuery on some browser the .text() returns a string
14300 // rather then the element.
14301 (element = optionTemplate.clone())
14303 .attr('selected', option.selected)
14304 .text(option.label);
14307 existingOptions.push(existingOption = {
14309 label: option.label,
14311 selected: option.selected
14314 lastElement.after(element);
14316 existingParent.element.append(element);
14318 lastElement = element;
14321 // remove any excessive OPTIONs in a group
14322 index++; // increment since the existingOptions[0] is parent element not OPTION
14323 while(existingOptions.length > index) {
14324 existingOptions.pop().element.remove();
14327 // remove any excessive OPTGROUPs from select
14328 while(optionGroupsCache.length > groupIndex) {
14329 optionGroupsCache.pop()[0].element.remove();
14337 var optionDirective = ['$interpolate', function($interpolate) {
14338 var nullSelectCtrl = {
14346 compile: function(element, attr) {
14347 if (isUndefined(attr.value)) {
14348 var interpolateFn = $interpolate(element.text(), true);
14349 if (!interpolateFn) {
14350 attr.$set('value', element.text());
14354 return function (scope, element, attr) {
14355 var selectCtrlName = '$selectController',
14356 parent = element.parent(),
14357 selectCtrl = parent.data(selectCtrlName) ||
14358 parent.parent().data(selectCtrlName); // in case we are in optgroup
14360 if (selectCtrl && selectCtrl.databound) {
14361 // For some reason Opera defaults to true and if not overridden this messes up the repeater.
14362 // We don't want the view to drive the initialization of the model anyway.
14363 element.prop('selected', false);
14365 selectCtrl = nullSelectCtrl;
14368 if (interpolateFn) {
14369 scope.$watch(interpolateFn, function(newVal, oldVal) {
14370 attr.$set('value', newVal);
14371 if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
14372 selectCtrl.addOption(newVal);
14375 selectCtrl.addOption(attr.value);
14378 element.bind('$destroy', function() {
14379 selectCtrl.removeOption(attr.value);
14386 var styleDirective = valueFn({
14390 //try to bind to jquery now so that one can write angular.element().read()
14391 //but we will rebind on bootstrap again.
14394 publishExternalAPI(angular);
14396 jqLite(document).ready(function() {
14397 angularInit(document, bootstrap);
14400 })(window, document);
14401 angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}</style>');