Add Intel copyright header.
[profile/ivi/cowhide.git] / lib / angular.js
1 /**
2  * @license AngularJS v1.0.2
3  * (c) 2010-2012 Google, Inc. http://angularjs.org
4  * License: MIT
5  */
6 (function(window, document, undefined) {
7 'use strict';
8
9 ////////////////////////////////////
10
11 /**
12  * @ngdoc function
13  * @name angular.lowercase
14  * @function
15  *
16  * @description Converts the specified string to lowercase.
17  * @param {string} string String to be converted to lowercase.
18  * @returns {string} Lowercased string.
19  */
20 var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
21
22
23 /**
24  * @ngdoc function
25  * @name angular.uppercase
26  * @function
27  *
28  * @description Converts the specified string to uppercase.
29  * @param {string} string String to be converted to uppercase.
30  * @returns {string} Uppercased string.
31  */
32 var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
33
34
35 var manualLowercase = function(s) {
36   return isString(s)
37       ? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);})
38       : s;
39 };
40 var manualUppercase = function(s) {
41   return isString(s)
42       ? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);})
43       : s;
44 };
45
46
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;
53 }
54
55 function fromCharCode(code) {return String.fromCharCode(code);}
56
57
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
63     slice             = [].slice,
64     push              = [].push,
65     toString          = Object.prototype.toString,
66
67     /** @name angular */
68     angular           = window.angular || (window.angular = {}),
69     angularModule,
70     nodeName_,
71     uid               = ['0', '0', '0'];
72
73 /**
74  * @ngdoc function
75  * @name angular.forEach
76  * @function
77  *
78  * @description
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.
83  *
84  * Note: this function was previously known as `angular.foreach`.
85  *
86    <pre>
87      var values = {name: 'misko', gender: 'male'};
88      var log = [];
89      angular.forEach(values, function(value, key){
90        this.push(key + ': ' + value);
91      }, log);
92      expect(log).toEqual(['name: misko', 'gender:male']);
93    </pre>
94  *
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`.
99  */
100 function forEach(obj, iterator, context) {
101   var key;
102   if (obj) {
103     if (isFunction(obj)){
104       for (key in obj) {
105         if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
106           iterator.call(context, obj[key], key);
107         }
108       }
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);
114     } else {
115       for (key in obj) {
116         if (obj.hasOwnProperty(key)) {
117           iterator.call(context, obj[key], key);
118         }
119       }
120     }
121   }
122   return obj;
123 }
124
125 function sortedKeys(obj) {
126   var keys = [];
127   for (var key in obj) {
128     if (obj.hasOwnProperty(key)) {
129       keys.push(key);
130     }
131   }
132   return keys.sort();
133 }
134
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]);
139   }
140   return keys;
141 }
142
143
144 /**
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)}
148  */
149 function reverseParams(iteratorFn) {
150   return function(value, key) { iteratorFn(key, value) };
151 }
152
153 /**
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.
158  *
159  * @returns an unique alpha-numeric string
160  */
161 function nextUid() {
162   var index = uid.length;
163   var digit;
164
165   while(index) {
166     index--;
167     digit = uid[index].charCodeAt(0);
168     if (digit == 57 /*'9'*/) {
169       uid[index] = 'A';
170       return uid.join('');
171     }
172     if (digit == 90  /*'Z'*/) {
173       uid[index] = '0';
174     } else {
175       uid[index] = String.fromCharCode(digit + 1);
176       return uid.join('');
177     }
178   }
179   uid.unshift('0');
180   return uid.join('');
181 }
182
183 /**
184  * @ngdoc function
185  * @name angular.extend
186  * @function
187  *
188  * @description
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.
191  *
192  * @param {Object} dst Destination object.
193  * @param {...Object} src Source object(s).
194  */
195 function extend(dst) {
196   forEach(arguments, function(obj){
197     if (obj !== dst) {
198       forEach(obj, function(value, key){
199         dst[key] = value;
200       });
201     }
202   });
203   return dst;
204 }
205
206 function int(str) {
207   return parseInt(str, 10);
208 }
209
210
211 function inherit(parent, extra) {
212   return extend(new (extend(function() {}, {prototype:parent}))(), extra);
213 }
214
215
216 /**
217  * @ngdoc function
218  * @name angular.noop
219  * @function
220  *
221  * @description
222  * A function that performs no operations. This function can be useful when writing code in the
223  * functional style.
224    <pre>
225      function foo(callback) {
226        var result = calculateResult();
227        (callback || angular.noop)(result);
228      }
229    </pre>
230  */
231 function noop() {}
232 noop.$inject = [];
233
234
235 /**
236  * @ngdoc function
237  * @name angular.identity
238  * @function
239  *
240  * @description
241  * A function that returns its first argument. This function is useful when writing code in the
242  * functional style.
243  *
244    <pre>
245      function transformer(transformationFn, value) {
246        return (transformationFn || identity)(value);
247      };
248    </pre>
249  */
250 function identity($) {return $;}
251 identity.$inject = [];
252
253
254 function valueFn(value) {return function() {return value;};}
255
256 /**
257  * @ngdoc function
258  * @name angular.isUndefined
259  * @function
260  *
261  * @description
262  * Determines if a reference is undefined.
263  *
264  * @param {*} value Reference to check.
265  * @returns {boolean} True if `value` is undefined.
266  */
267 function isUndefined(value){return typeof value == 'undefined';}
268
269
270 /**
271  * @ngdoc function
272  * @name angular.isDefined
273  * @function
274  *
275  * @description
276  * Determines if a reference is defined.
277  *
278  * @param {*} value Reference to check.
279  * @returns {boolean} True if `value` is defined.
280  */
281 function isDefined(value){return typeof value != 'undefined';}
282
283
284 /**
285  * @ngdoc function
286  * @name angular.isObject
287  * @function
288  *
289  * @description
290  * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
291  * considered to be objects.
292  *
293  * @param {*} value Reference to check.
294  * @returns {boolean} True if `value` is an `Object` but not `null`.
295  */
296 function isObject(value){return value != null && typeof value == 'object';}
297
298
299 /**
300  * @ngdoc function
301  * @name angular.isString
302  * @function
303  *
304  * @description
305  * Determines if a reference is a `String`.
306  *
307  * @param {*} value Reference to check.
308  * @returns {boolean} True if `value` is a `String`.
309  */
310 function isString(value){return typeof value == 'string';}
311
312
313 /**
314  * @ngdoc function
315  * @name angular.isNumber
316  * @function
317  *
318  * @description
319  * Determines if a reference is a `Number`.
320  *
321  * @param {*} value Reference to check.
322  * @returns {boolean} True if `value` is a `Number`.
323  */
324 function isNumber(value){return typeof value == 'number';}
325
326
327 /**
328  * @ngdoc function
329  * @name angular.isDate
330  * @function
331  *
332  * @description
333  * Determines if a value is a date.
334  *
335  * @param {*} value Reference to check.
336  * @returns {boolean} True if `value` is a `Date`.
337  */
338 function isDate(value){
339   return toString.apply(value) == '[object Date]';
340 }
341
342
343 /**
344  * @ngdoc function
345  * @name angular.isArray
346  * @function
347  *
348  * @description
349  * Determines if a reference is an `Array`.
350  *
351  * @param {*} value Reference to check.
352  * @returns {boolean} True if `value` is an `Array`.
353  */
354 function isArray(value) {
355   return toString.apply(value) == '[object Array]';
356 }
357
358
359 /**
360  * @ngdoc function
361  * @name angular.isFunction
362  * @function
363  *
364  * @description
365  * Determines if a reference is a `Function`.
366  *
367  * @param {*} value Reference to check.
368  * @returns {boolean} True if `value` is a `Function`.
369  */
370 function isFunction(value){return typeof value == 'function';}
371
372
373 /**
374  * Checks if `obj` is a window object.
375  *
376  * @private
377  * @param {*} obj Object to check
378  * @returns {boolean} True if `obj` is a window obj.
379  */
380 function isWindow(obj) {
381   return obj && obj.document && obj.location && obj.alert && obj.setInterval;
382 }
383
384
385 function isScope(obj) {
386   return obj && obj.$evalAsync && obj.$watch;
387 }
388
389
390 function isFile(obj) {
391   return toString.apply(obj) === '[object File]';
392 }
393
394
395 function isBoolean(value) {
396   return typeof value == 'boolean';
397 }
398
399
400 function trim(value) {
401   return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
402 }
403
404 /**
405  * @ngdoc function
406  * @name angular.isElement
407  * @function
408  *
409  * @description
410  * Determines if a reference is a DOM element (or wrapped jQuery element).
411  *
412  * @param {*} value Reference to check.
413  * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
414  */
415 function isElement(node) {
416   return 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
419 }
420
421 /**
422  * @param str 'key1,key2,...'
423  * @returns {object} in the form of {key1:true, key2:true, ...}
424  */
425 function makeMap(str){
426   var obj = {}, items = str.split(","), i;
427   for ( i = 0; i < items.length; i++ )
428     obj[ items[i] ] = true;
429   return obj;
430 }
431
432
433 if (msie < 9) {
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;
438   };
439 } else {
440   nodeName_ = function(element) {
441     return element.nodeName ? element.nodeName : element[0].nodeName;
442   };
443 }
444
445
446 function map(obj, iterator, context) {
447   var results = [];
448   forEach(obj, function(value, index, list) {
449     results.push(iterator.call(context, value, index, list));
450   });
451   return results;
452 }
453
454
455 /**
456  * @description
457  * Determines the number of elements in an array, the number of properties an object has, or
458  * the length of a string.
459  *
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.
462  *
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.
466  */
467 function size(obj, ownPropsOnly) {
468   var size = 0, key;
469
470   if (isArray(obj) || isString(obj)) {
471     return obj.length;
472   } else if (isObject(obj)){
473     for (key in obj)
474       if (!ownPropsOnly || obj.hasOwnProperty(key))
475         size++;
476   }
477
478   return size;
479 }
480
481
482 function includes(array, obj) {
483   return indexOf(array, obj) != -1;
484 }
485
486 function indexOf(array, obj) {
487   if (array.indexOf) return array.indexOf(obj);
488
489   for ( var i = 0; i < array.length; i++) {
490     if (obj === array[i]) return i;
491   }
492   return -1;
493 }
494
495 function arrayRemove(array, value) {
496   var index = indexOf(array, value);
497   if (index >=0)
498     array.splice(index, 1);
499   return value;
500 }
501
502 function isLeafNode (node) {
503   if (node) {
504     switch (node.nodeName) {
505     case "OPTION":
506     case "PRE":
507     case "TITLE":
508       return true;
509     }
510   }
511   return false;
512 }
513
514 /**
515  * @ngdoc function
516  * @name angular.copy
517  * @function
518  *
519  * @description
520  * Creates a deep copy of `source`, which should be an object or an array.
521  *
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.
526  *
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.
529  *
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.
535  */
536 function copy(source, destination){
537   if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
538   if (!destination) {
539     destination = source;
540     if (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, {});
547       }
548     }
549   } else {
550     if (source === destination) throw Error("Can't copy equivalent objects or arrays");
551     if (isArray(source)) {
552       while(destination.length) {
553         destination.pop();
554       }
555       for ( var i = 0; i < source.length; i++) {
556         destination.push(copy(source[i]));
557       }
558     } else {
559       forEach(destination, function(value, key){
560         delete destination[key];
561       });
562       for ( var key in source) {
563         destination[key] = copy(source[key]);
564       }
565     }
566   }
567   return destination;
568 }
569
570 /**
571  * Create a shallow copy of an object
572  */
573 function shallowCopy(src, dst) {
574   dst = dst || {};
575
576   for(var key in src) {
577     if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
578       dst[key] = src[key];
579     }
580   }
581
582   return dst;
583 }
584
585
586 /**
587  * @ngdoc function
588  * @name angular.equals
589  * @function
590  *
591  * @description
592  * Determines if two objects or two values are equivalent. Supports value types, arrays and
593  * objects.
594  *
595  * Two objects or values are considered equivalent if at least one of the following is true:
596  *
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)
600  *
601  * During a property comparision, properties of `function` type and properties with names
602  * that begin with `$` are ignored.
603  *
604  * Scope and DOMWindow objects are being compared only be identify (`===`).
605  *
606  * @param {*} o1 Object or value to compare.
607  * @param {*} o2 Object or value to compare.
608  * @returns {boolean} True if arguments are equal.
609  */
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;
615   if (t1 == t2) {
616     if (t1 == 'object') {
617       if (isArray(o1)) {
618         if ((length = o1.length) == o2.length) {
619           for(key=0; key<length; key++) {
620             if (!equals(o1[key], o2[key])) return false;
621           }
622           return true;
623         }
624       } else if (isDate(o1)) {
625         return isDate(o2) && o1.getTime() == o2.getTime();
626       } else {
627         if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
628         keySet = {};
629         for(key in o1) {
630           if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) {
631             return false;
632           }
633           keySet[key] = true;
634         }
635         for(key in o2) {
636           if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false;
637         }
638         return true;
639       }
640     }
641   }
642   return false;
643 }
644
645
646 function concat(array1, array2, index) {
647   return array1.concat(slice.call(array2, index));
648 }
649
650 function sliceArgs(args, startIndex) {
651   return slice.call(args, startIndex || 0);
652 }
653
654
655 /**
656  * @ngdoc function
657  * @name angular.bind
658  * @function
659  *
660  * @description
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).
664  *
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.
669  */
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
674       ? function() {
675           return arguments.length
676             ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
677             : fn.apply(self, curryArgs);
678         }
679       : function() {
680           return arguments.length
681             ? fn.apply(self, arguments)
682             : fn.call(self);
683         };
684   } else {
685     // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
686     return fn;
687   }
688 }
689
690
691 function toJsonReplacer(key, value) {
692   var val = value;
693
694   if (/^\$+/.test(key)) {
695     val = undefined;
696   } else if (isWindow(value)) {
697     val = '$WINDOW';
698   } else if (value &&  document === value) {
699     val = '$DOCUMENT';
700   } else if (isScope(value)) {
701     val = '$SCOPE';
702   }
703
704   return val;
705 }
706
707
708 /**
709  * @ngdoc function
710  * @name angular.toJson
711  * @function
712  *
713  * @description
714  * Serializes input into a JSON-formatted string.
715  *
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`.
719  */
720 function toJson(obj, pretty) {
721   return JSON.stringify(obj, toJsonReplacer, pretty ? '  ' : null);
722 }
723
724
725 /**
726  * @ngdoc function
727  * @name angular.fromJson
728  * @function
729  *
730  * @description
731  * Deserializes a JSON string.
732  *
733  * @param {string} json JSON string to deserialize.
734  * @returns {Object|Array|Date|string|number} Deserialized thingy.
735  */
736 function fromJson(json) {
737   return isString(json)
738       ? JSON.parse(json)
739       : json;
740 }
741
742
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 == '[]');
747   } else {
748     value = false;
749   }
750   return value;
751 }
752
753 /**
754  * @returns {string} Returns the string representation of the element.
755  */
756 function startingTag(element) {
757   element = jqLite(element).clone();
758   try {
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.
761     element.html('');
762   } catch(e) {}
763   return jqLite('<div>').append(element).html().
764       match(/^(<[^>]+>)/)[1].
765       replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
766 }
767
768
769 /////////////////////////////////////////////////
770
771 /**
772  * Parses an escaped url query string into key-value pairs.
773  * @returns Object.<(string|boolean)>
774  */
775 function parseKeyValue(/**string*/keyValue) {
776   var obj = {}, key_value, key;
777   forEach((keyValue || "").split('&'), function(keyValue){
778     if (keyValue) {
779       key_value = keyValue.split('=');
780       key = decodeURIComponent(key_value[0]);
781       obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
782     }
783   });
784   return obj;
785 }
786
787 function toKeyValue(obj) {
788   var parts = [];
789   forEach(obj, function(value, key) {
790     parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
791   });
792   return parts.length ? parts.join('&') : '';
793 }
794
795
796 /**
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
799  * segments:
800  *    segment       = *pchar
801  *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
802  *    pct-encoded   = "%" HEXDIG HEXDIG
803  *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
804  *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
805  *                     / "*" / "+" / "," / ";" / "="
806  */
807 function encodeUriSegment(val) {
808   return encodeUriQuery(val, true).
809              replace(/%26/gi, '&').
810              replace(/%3D/gi, '=').
811              replace(/%2B/gi, '+');
812 }
813
814
815 /**
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  *                     / "*" / "+" / "," / ";" / "="
825  */
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), '+');
833 }
834
835
836 /**
837  * @ngdoc directive
838  * @name ng.directive:ngApp
839  *
840  * @element ANY
841  * @param {angular.Module} ngApp on optional application
842  *   {@link angular.module module} name to load.
843  *
844  * @description
845  *
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.
850  *
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`.
854  *
855  * `ngApp` is the easiest way to bootstrap an application.
856  *
857  <doc:example>
858    <doc:source>
859     I can add: 1 + 2 =  {{ 1+2 }}
860    </doc:source>
861  </doc:example>
862  *
863  */
864 function angularInit(element, bootstrap) {
865   var elements = [element],
866       appElement,
867       module,
868       names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
869       NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
870
871   function append(element) {
872     element && elements.push(element);
873   }
874
875   forEach(names, function(name) {
876     names[name] = true;
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);
883     }
884   });
885
886   forEach(elements, function(element) {
887     if (!appElement) {
888       var className = ' ' + element.className + ' ';
889       var match = NG_APP_CLASS_REGEXP.exec(className);
890       if (match) {
891         appElement = element;
892         module = (match[2] || '').replace(/\s+/g, ',');
893       } else {
894         forEach(element.attributes, function(attr) {
895           if (!appElement && names[attr.name]) {
896             appElement = element;
897             module = attr.value;
898           }
899         });
900       }
901     }
902   });
903   if (appElement) {
904     bootstrap(appElement, module ? [module] : []);
905   }
906 }
907
908 /**
909  * @ngdoc function
910  * @name angular.bootstrap
911  * @description
912  * Use this function to manually start up angular application.
913  *
914  * See: {@link guide/bootstrap Bootstrap}
915  *
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.
919  */
920 function bootstrap(element, modules) {
921   element = jqLite(element);
922   modules = modules || [];
923   modules.unshift(['$provide', function($provide) {
924     $provide.value('$rootElement', element);
925   }]);
926   modules.unshift('ng');
927   var injector = createInjector(modules);
928   injector.invoke(
929     ['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){
930       scope.$apply(function() {
931         element.data('$injector', injector);
932         compile(element)(scope);
933       });
934     }]
935   );
936   return injector;
937 }
938
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();
944   });
945 }
946
947 function bindJQuery() {
948   // bind to jQuery if present;
949   jQuery = window.jQuery;
950   // reset to jQuery or default to us.
951   if (jQuery) {
952     jqLite = jQuery;
953     extend(jQuery.fn, {
954       scope: JQLitePrototype.scope,
955       controller: JQLitePrototype.controller,
956       injector: JQLitePrototype.injector,
957       inheritedData: JQLitePrototype.inheritedData
958     });
959     JQLitePatchJQueryRemove('remove', true);
960     JQLitePatchJQueryRemove('empty');
961     JQLitePatchJQueryRemove('html');
962   } else {
963     jqLite = JQLite;
964   }
965   angular.element = jqLite;
966 }
967
968 /**
969  * throw error of the argument is falsy.
970  */
971 function assertArg(arg, name, reason) {
972   if (!arg) {
973     throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
974   }
975   return arg;
976 }
977
978 function assertArgFn(arg, name, acceptArrayAnnotation) {
979   if (acceptArrayAnnotation && isArray(arg)) {
980       arg = arg[arg.length - 1];
981   }
982
983   assertArg(isFunction(arg), name, 'not a function, got ' +
984       (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
985   return arg;
986 }
987
988 /**
989  * @ngdoc interface
990  * @name angular.Module
991  * @description
992  *
993  * Interface for configuring angular {@link angular.module modules}.
994  */
995
996 function setupModuleLoader(window) {
997
998   function ensure(obj, name, factory) {
999     return obj[name] || (obj[name] = factory());
1000   }
1001
1002   return ensure(ensure(window, 'angular', Object), 'module', function() {
1003     /** @type {Object.<string, angular.Module>} */
1004     var modules = {};
1005
1006     /**
1007      * @ngdoc function
1008      * @name angular.module
1009      * @description
1010      *
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.
1014      *
1015      *
1016      * # Module
1017      *
1018      * A module is a collocation of services, directives, filters, and configure information. Module
1019      * is used to configure the {@link AUTO.$injector $injector}.
1020      *
1021      * <pre>
1022      * // Create a new module
1023      * var myModule = angular.module('myModule', []);
1024      *
1025      * // register a new service
1026      * myModule.value('appName', 'MyCoolApp');
1027      *
1028      * // configure existing services inside initialization blocks.
1029      * myModule.config(function($locationProvider) {
1030      *   // Configure existing providers
1031      *   $locationProvider.hashPrefix('!');
1032      * });
1033      * </pre>
1034      *
1035      * Then you can create an injector and load your modules like this:
1036      *
1037      * <pre>
1038      * var injector = angular.injector(['ng', 'MyModule'])
1039      * </pre>
1040      *
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.
1044      *
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.
1051      */
1052     return function module(name, requires, configFn) {
1053       if (requires && modules.hasOwnProperty(name)) {
1054         modules[name] = null;
1055       }
1056       return ensure(modules, name, function() {
1057         if (!requires) {
1058           throw Error('No module: ' + name);
1059         }
1060
1061         /** @type {!Array.<Array.<*>>} */
1062         var invokeQueue = [];
1063
1064         /** @type {!Array.<Function>} */
1065         var runBlocks = [];
1066
1067         var config = invokeLater('$injector', 'invoke');
1068
1069         /** @type {angular.Module} */
1070         var moduleInstance = {
1071           // Private state
1072           _invokeQueue: invokeQueue,
1073           _runBlocks: runBlocks,
1074
1075           /**
1076            * @ngdoc property
1077            * @name angular.Module#requires
1078            * @propertyOf angular.Module
1079            * @returns {Array.<string>} List of module names which must be loaded before this module.
1080            * @description
1081            * Holds the list of modules which the injector will load before the current module is loaded.
1082            */
1083           requires: requires,
1084
1085           /**
1086            * @ngdoc property
1087            * @name angular.Module#name
1088            * @propertyOf angular.Module
1089            * @returns {string} Name of the module.
1090            * @description
1091            */
1092           name: name,
1093
1094
1095           /**
1096            * @ngdoc method
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.
1101            * @description
1102            * See {@link AUTO.$provide#provider $provide.provider()}.
1103            */
1104           provider: invokeLater('$provide', 'provider'),
1105
1106           /**
1107            * @ngdoc method
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.
1112            * @description
1113            * See {@link AUTO.$provide#factory $provide.factory()}.
1114            */
1115           factory: invokeLater('$provide', 'factory'),
1116
1117           /**
1118            * @ngdoc method
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.
1123            * @description
1124            * See {@link AUTO.$provide#service $provide.service()}.
1125            */
1126           service: invokeLater('$provide', 'service'),
1127
1128           /**
1129            * @ngdoc method
1130            * @name angular.Module#value
1131            * @methodOf angular.Module
1132            * @param {string} name service name
1133            * @param {*} object Service instance object.
1134            * @description
1135            * See {@link AUTO.$provide#value $provide.value()}.
1136            */
1137           value: invokeLater('$provide', 'value'),
1138
1139           /**
1140            * @ngdoc method
1141            * @name angular.Module#constant
1142            * @methodOf angular.Module
1143            * @param {string} name constant name
1144            * @param {*} object Constant value.
1145            * @description
1146            * Because the constant are fixed, they get applied before other provide methods.
1147            * See {@link AUTO.$provide#constant $provide.constant()}.
1148            */
1149           constant: invokeLater('$provide', 'constant', 'unshift'),
1150
1151           /**
1152            * @ngdoc method
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.
1157            * @description
1158            * See {@link ng.$filterProvider#register $filterProvider.register()}.
1159            */
1160           filter: invokeLater('$filterProvider', 'register'),
1161
1162           /**
1163            * @ngdoc method
1164            * @name angular.Module#controller
1165            * @methodOf angular.Module
1166            * @param {string} name Controller name.
1167            * @param {Function} constructor Controller constructor function.
1168            * @description
1169            * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
1170            */
1171           controller: invokeLater('$controllerProvider', 'register'),
1172
1173           /**
1174            * @ngdoc method
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
1179            * directives.
1180            * @description
1181            * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
1182            */
1183           directive: invokeLater('$compileProvider', 'directive'),
1184
1185           /**
1186            * @ngdoc method
1187            * @name angular.Module#config
1188            * @methodOf angular.Module
1189            * @param {Function} configFn Execute this function on module load. Useful for service
1190            *    configuration.
1191            * @description
1192            * Use this method to register work which needs to be performed on module loading.
1193            */
1194           config: config,
1195
1196           /**
1197            * @ngdoc method
1198            * @name angular.Module#run
1199            * @methodOf angular.Module
1200            * @param {Function} initializationFn Execute this function after injector creation.
1201            *    Useful for application initialization.
1202            * @description
1203            * Use this method to register work which needs to be performed when the injector with
1204            * with the current module is finished loading.
1205            */
1206           run: function(block) {
1207             runBlocks.push(block);
1208             return this;
1209           }
1210         };
1211
1212         if (configFn) {
1213           config(configFn);
1214         }
1215
1216         return  moduleInstance;
1217
1218         /**
1219          * @param {string} provider
1220          * @param {string} method
1221          * @param {String=} insertMethod
1222          * @returns {angular.Module}
1223          */
1224         function invokeLater(provider, method, insertMethod) {
1225           return function() {
1226             invokeQueue[insertMethod || 'push']([provider, method, arguments]);
1227             return moduleInstance;
1228           }
1229         }
1230       });
1231     };
1232   });
1233
1234 }
1235
1236 /**
1237  * @ngdoc property
1238  * @name angular.version
1239  * @description
1240  * An object that contains information about the current AngularJS version. This object has the
1241  * following properties:
1242  *
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".
1248  */
1249 var version = {
1250   full: '1.0.2',    // all of these placeholder strings will be replaced by rake's
1251   major: 1,    // compile task
1252   minor: 0,
1253   dot: 2,
1254   codeName: 'debilitating-awesomeness'
1255 };
1256
1257
1258 function publishExternalAPI(angular){
1259   extend(angular, {
1260     'bootstrap': bootstrap,
1261     'copy': copy,
1262     'extend': extend,
1263     'equals': equals,
1264     'element': jqLite,
1265     'forEach': forEach,
1266     'injector': createInjector,
1267     'noop':noop,
1268     'bind':bind,
1269     'toJson': toJson,
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,
1279     'isArray': isArray,
1280     'version': version,
1281     'isDate': isDate,
1282     'lowercase': lowercase,
1283     'uppercase': uppercase,
1284     'callbacks': {counter: 0}
1285   });
1286
1287   angularModule = setupModuleLoader(window);
1288   try {
1289     angularModule('ngLocale');
1290   } catch (e) {
1291     angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
1292   }
1293
1294   angularModule('ng', ['ngLocale'], ['$provide',
1295     function ngModule($provide) {
1296       $provide.provider('$compile', $CompileProvider).
1297         directive({
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
1337         }).
1338         directive(ngAttributeAliasDirectives).
1339         directive(ngEventDirectives);
1340       $provide.provider({
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,
1352         $log: $LogProvider,
1353         $parse: $ParseProvider,
1354         $route: $RouteProvider,
1355         $routeParams: $RouteParamsProvider,
1356         $rootScope: $RootScopeProvider,
1357         $q: $QProvider,
1358         $sniffer: $SnifferProvider,
1359         $templateCache: $TemplateCacheProvider,
1360         $timeout: $TimeoutProvider,
1361         $window: $WindowProvider
1362       });
1363     }
1364   ]);
1365 }
1366
1367 //////////////////////////////////
1368 //JQLite
1369 //////////////////////////////////
1370
1371 /**
1372  * @ngdoc function
1373  * @name angular.element
1374  * @function
1375  *
1376  * @description
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).
1381  *
1382  * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
1383  * event fired.
1384  *
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.
1389  *
1390  * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
1391  * raw DOM references.
1392  *
1393  * ## Angular's jQuery lite provides the following methods:
1394  *
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/)
1424  *
1425  * ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite:
1426  *
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.
1430  *   `'ngModel'`).
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.
1436  *
1437  * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
1438  * @returns {Object} jQuery object.
1439  */
1440
1441 var jqCache = JQLite.cache = {},
1442     jqName = JQLite.expando = 'ng-' + new Date().getTime(),
1443     jqId = 1,
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); });
1450
1451 function jqNextId() { return ++jqId; }
1452
1453
1454 var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
1455 var MOZ_HACK_REGEXP = /^moz([A-Z])/;
1456
1457 /**
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
1461  */
1462 function camelCase(name) {
1463   return name.
1464     replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
1465       return offset ? letter.toUpperCase() : letter;
1466     }).
1467     replace(MOZ_HACK_REGEXP, 'Moz$1');
1468 }
1469
1470 /////////////////////////////////////////////
1471 // jQuery mutation patch
1472 //
1473 //  In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
1474 // $destroy event on all DOM nodes being removed.
1475 //
1476 /////////////////////////////////////////////
1477
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;
1483
1484   function removePatch() {
1485     var list = [this],
1486         fireEvent = dispatchThis,
1487         set, setIndex, setLength,
1488         element, childIndex, childLength, children,
1489         fns, events;
1490
1491     while(list.length) {
1492       set = list.shift();
1493       for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
1494         element = jqLite(set[setIndex]);
1495         if (fireEvent) {
1496           events = element.data('events');
1497           if ( (fns = events && events.$destroy) ) {
1498             forEach(fns, function(fn){
1499               fn.handler();
1500             });
1501           }
1502         } else {
1503           fireEvent = !fireEvent;
1504         }
1505         for(childIndex = 0, childLength = (children = element.children()).length;
1506             childIndex < childLength;
1507             childIndex++) {
1508           list.push(jQuery(children[childIndex]));
1509         }
1510       }
1511     }
1512     return originalJqFn.apply(this, arguments);
1513   }
1514 }
1515
1516 /////////////////////////////////////////////
1517 function JQLite(element) {
1518   if (element instanceof JQLite) {
1519     return element;
1520   }
1521   if (!(this instanceof JQLite)) {
1522     if (isString(element) && element.charAt(0) != '<') {
1523       throw Error('selectors not implemented');
1524     }
1525     return new JQLite(element);
1526   }
1527
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>&#160;</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.
1536   } else {
1537     JQLiteAddNodes(this, element);
1538   }
1539 }
1540
1541 function JQLiteClone(element) {
1542   return element.cloneNode(true);
1543 }
1544
1545 function JQLiteDealoc(element){
1546   JQLiteRemoveData(element);
1547   for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
1548     JQLiteDealoc(children[i]);
1549   }
1550 }
1551
1552 function JQLiteUnbind(element, type, fn) {
1553   var events = JQLiteExpandoStore(element, 'events'),
1554       handle = JQLiteExpandoStore(element, 'handle');
1555
1556   if (!handle) return; //no listeners registered
1557
1558   if (isUndefined(type)) {
1559     forEach(events, function(eventHandler, type) {
1560       removeEventListenerFn(element, type, eventHandler);
1561       delete events[type];
1562     });
1563   } else {
1564     if (isUndefined(fn)) {
1565       removeEventListenerFn(element, type, events[type]);
1566       delete events[type];
1567     } else {
1568       arrayRemove(events[type], fn);
1569     }
1570   }
1571 }
1572
1573 function JQLiteRemoveData(element) {
1574   var expandoId = element[jqName],
1575       expandoStore = jqCache[expandoId];
1576
1577   if (expandoStore) {
1578     if (expandoStore.handle) {
1579       expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
1580       JQLiteUnbind(element);
1581     }
1582     delete jqCache[expandoId];
1583     element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
1584   }
1585 }
1586
1587 function JQLiteExpandoStore(element, key, value) {
1588   var expandoId = element[jqName],
1589       expandoStore = jqCache[expandoId || -1];
1590
1591   if (isDefined(value)) {
1592     if (!expandoStore) {
1593       element[jqName] = expandoId = jqNextId();
1594       expandoStore = jqCache[expandoId] = {};
1595     }
1596     expandoStore[key] = value;
1597   } else {
1598     return expandoStore && expandoStore[key];
1599   }
1600 }
1601
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);
1607
1608   if (!data && !isSimpleGetter) {
1609     JQLiteExpandoStore(element, 'data', data = {});
1610   }
1611
1612   if (isSetter) {
1613     data[key] = value;
1614   } else {
1615     if (keyDefined) {
1616       if (isSimpleGetter) {
1617         // don't create data in this case.
1618         return data && data[key];
1619       } else {
1620         extend(data, key);
1621       }
1622     } else {
1623       return data;
1624     }
1625   }
1626 }
1627
1628 function JQLiteHasClass(element, selector) {
1629   return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
1630       indexOf( " " + selector + " " ) > -1);
1631 }
1632
1633 function JQLiteRemoveClass(element, selector) {
1634   if (selector) {
1635     forEach(selector.split(' '), function(cssClass) {
1636       element.className = trim(
1637           (" " + element.className + " ")
1638           .replace(/[\n\t]/g, " ")
1639           .replace(" " + trim(cssClass) + " ", " ")
1640       );
1641     });
1642   }
1643 }
1644
1645 function JQLiteAddClass(element, selector) {
1646   if (selector) {
1647     forEach(selector.split(' '), function(cssClass) {
1648       if (!JQLiteHasClass(element, cssClass)) {
1649         element.className = trim(element.className + ' ' + trim(cssClass));
1650       }
1651     });
1652   }
1653 }
1654
1655 function JQLiteAddNodes(root, elements) {
1656   if (elements) {
1657     elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
1658       ? elements
1659       : [ elements ];
1660     for(var i=0; i < elements.length; i++) {
1661       root.push(elements[i]);
1662     }
1663   }
1664 }
1665
1666 function JQLiteController(element, name) {
1667   return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
1668 }
1669
1670 function JQLiteInheritedData(element, name, value) {
1671   element = jqLite(element);
1672
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');
1677   }
1678
1679   while (element.length) {
1680     if (value = element.data(name)) return value;
1681     element = element.parent();
1682   }
1683 }
1684
1685 //////////////////////////////////////////
1686 // Functions which are declared directly.
1687 //////////////////////////////////////////
1688 var JQLitePrototype = JQLite.prototype = {
1689   ready: function(fn) {
1690     var fired = false;
1691
1692     function trigger() {
1693       if (fired) return;
1694       fired = true;
1695       fn();
1696     }
1697
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
1701   },
1702   toString: function() {
1703     var value = [];
1704     forEach(this, function(e){ value.push('' + e);});
1705     return '[' + value.join(', ') + ']';
1706   },
1707
1708   eq: function(index) {
1709       return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
1710   },
1711
1712   length: 0,
1713   push: push,
1714   sort: [].sort,
1715   splice: [].splice
1716 };
1717
1718 //////////////////////////////////////////
1719 // Functions iterating getter/setters.
1720 // these functions return self on setter and
1721 // value on get.
1722 //////////////////////////////////////////
1723 var BOOLEAN_ATTR = {};
1724 forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) {
1725   BOOLEAN_ATTR[lowercase(value)] = value;
1726 });
1727 var BOOLEAN_ELEMENTS = {};
1728 forEach('input,select,option,textarea,button,form'.split(','), function(value) {
1729   BOOLEAN_ELEMENTS[uppercase(value)] = true;
1730 });
1731
1732 function getBooleanAttrName(element, name) {
1733   // check dom last since we will most likely fail on name
1734   var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
1735
1736   // booleanAttr is here twice to minimize DOM access
1737   return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
1738 }
1739
1740 forEach({
1741   data: JQLiteData,
1742   inheritedData: JQLiteInheritedData,
1743
1744   scope: function(element) {
1745     return JQLiteInheritedData(element, '$scope');
1746   },
1747
1748   controller: JQLiteController ,
1749
1750   injector: function(element) {
1751     return JQLiteInheritedData(element, '$injector');
1752   },
1753
1754   removeAttr: function(element,name) {
1755     element.removeAttribute(name);
1756   },
1757
1758   hasClass: JQLiteHasClass,
1759
1760   css: function(element, name, value) {
1761     name = camelCase(name);
1762
1763     if (isDefined(value)) {
1764       element.style[name] = value;
1765     } else {
1766       var val;
1767
1768       if (msie <= 8) {
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';
1772       }
1773
1774       val = val || element.style[name];
1775
1776       if (msie <= 8) {
1777         // jquery weirdness :-/
1778         val = (val === '') ? undefined : val;
1779       }
1780
1781       return  val;
1782     }
1783   },
1784
1785   attr: function(element, name, value){
1786     var lowercasedName = lowercase(name);
1787     if (BOOLEAN_ATTR[lowercasedName]) {
1788       if (isDefined(value)) {
1789         if (!!value) {
1790           element[name] = true;
1791           element.setAttribute(name, lowercasedName);
1792         } else {
1793           element[name] = false;
1794           element.removeAttribute(lowercasedName);
1795         }
1796       } else {
1797         return (element[name] ||
1798                  (element.attributes.getNamedItem(name)|| noop).specified)
1799                ? lowercasedName
1800                : undefined;
1801       }
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;
1810     }
1811   },
1812
1813   prop: function(element, name, value) {
1814     if (isDefined(value)) {
1815       element[name] = value;
1816     } else {
1817       return element[name];
1818     }
1819   },
1820
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;
1827         } else {
1828           if (isUndefined(value))
1829             return element.nodeValue;
1830           element.nodeValue = value;
1831         }
1832       }
1833       : function(element, value) {
1834         if (isUndefined(value)) {
1835           return element.textContent;
1836         }
1837         element.textContent = value;
1838       }, {$dv:''}),
1839
1840   val: function(element, value) {
1841     if (isUndefined(value)) {
1842       return element.value;
1843     }
1844     element.value = value;
1845   },
1846
1847   html: function(element, value) {
1848     if (isUndefined(value)) {
1849       return element.innerHTML;
1850     }
1851     for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
1852       JQLiteDealoc(childNodes[i]);
1853     }
1854     element.innerHTML = value;
1855   }
1856 }, function(fn, name){
1857   /**
1858    * Properties: writes return selection, reads return first value
1859    */
1860   JQLite.prototype[name] = function(arg1, arg2) {
1861     var i, key;
1862
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)) {
1867
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
1872             fn(this[i], arg1);
1873           } else {
1874             for (key in arg1) {
1875               fn(this[i], key, arg1[key]);
1876             }
1877           }
1878         }
1879         // return self for chaining
1880         return this;
1881       } else {
1882         // we are a read, so read the first child.
1883         if (this.length)
1884           return fn(this[0], arg1, arg2);
1885       }
1886     } else {
1887       // we are a write, so apply to all children
1888       for(i=0; i < this.length; i++) {
1889         fn(this[i], arg1, arg2);
1890       }
1891       // return self for chaining
1892       return this;
1893     }
1894     return fn.$dv;
1895   };
1896 });
1897
1898 function createEventHandler(element, events) {
1899   var eventHandler = function (event, type) {
1900     if (!event.preventDefault) {
1901       event.preventDefault = function() {
1902         event.returnValue = false; //ie
1903       };
1904     }
1905
1906     if (!event.stopPropagation) {
1907       event.stopPropagation = function() {
1908         event.cancelBubble = true; //ie
1909       };
1910     }
1911
1912     if (!event.target) {
1913       event.target = event.srcElement || document;
1914     }
1915
1916     if (isUndefined(event.defaultPrevented)) {
1917       var prevent = event.preventDefault;
1918       event.preventDefault = function() {
1919         event.defaultPrevented = true;
1920         prevent.call(event);
1921       };
1922       event.defaultPrevented = false;
1923     }
1924
1925     event.isDefaultPrevented = function() {
1926       return event.defaultPrevented;
1927     };
1928
1929     forEach(events[type || event.type], function(fn) {
1930       fn.call(element, event);
1931     });
1932
1933     // Remove monkey-patched methods (IE),
1934     // as they would cause memory leaks in IE8.
1935     if (msie <= 8) {
1936       // IE7/8 does not allow to delete property on native object
1937       event.preventDefault = null;
1938       event.stopPropagation = null;
1939       event.isDefaultPrevented = null;
1940     } else {
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;
1945     }
1946   };
1947   eventHandler.elem = element;
1948   return eventHandler;
1949 }
1950
1951 //////////////////////////////////////////
1952 // Functions iterating traversal.
1953 // These functions chain results into a single
1954 // selector.
1955 //////////////////////////////////////////
1956 forEach({
1957   removeData: JQLiteRemoveData,
1958
1959   dealoc: JQLiteDealoc,
1960
1961   bind: function bindFn(element, type, fn){
1962     var events = JQLiteExpandoStore(element, 'events'),
1963         handle = JQLiteExpandoStore(element, 'handle');
1964
1965     if (!events) JQLiteExpandoStore(element, 'events', events = {});
1966     if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
1967
1968     forEach(type.split(' '), function(type){
1969       var eventFns = events[type];
1970
1971       if (!eventFns) {
1972         if (type == 'mouseenter' || type == 'mouseleave') {
1973           var counter = 0;
1974
1975           events.mouseenter = [];
1976           events.mouseleave = [];
1977
1978           bindFn(element, 'mouseover', function(event) {
1979             counter++;
1980             if (counter == 1) {
1981               handle(event, 'mouseenter');
1982             }
1983           });
1984           bindFn(element, 'mouseout', function(event) {
1985             counter --;
1986             if (counter == 0) {
1987               handle(event, 'mouseleave');
1988             }
1989           });
1990         } else {
1991           addEventListenerFn(element, type, handle);
1992           events[type] = [];
1993         }
1994         eventFns = events[type]
1995       }
1996       eventFns.push(fn);
1997     });
1998   },
1999
2000   unbind: JQLiteUnbind,
2001
2002   replaceWith: function(element, replaceNode) {
2003     var index, parent = element.parentNode;
2004     JQLiteDealoc(element);
2005     forEach(new JQLite(replaceNode), function(node){
2006       if (index) {
2007         parent.insertBefore(node, index.nextSibling);
2008       } else {
2009         parent.replaceChild(node, element);
2010       }
2011       index = node;
2012     });
2013   },
2014
2015   children: function(element) {
2016     var children = [];
2017     forEach(element.childNodes, function(element){
2018       if (element.nodeName != '#text')
2019         children.push(element);
2020     });
2021     return children;
2022   },
2023
2024   contents: function(element) {
2025     return element.childNodes;
2026   },
2027
2028   append: function(element, node) {
2029     forEach(new JQLite(node), function(child){
2030       if (element.nodeType === 1)
2031         element.appendChild(child);
2032     });
2033   },
2034
2035   prepend: function(element, node) {
2036     if (element.nodeType === 1) {
2037       var index = element.firstChild;
2038       forEach(new JQLite(node), function(child){
2039         if (index) {
2040           element.insertBefore(child, index);
2041         } else {
2042           element.appendChild(child);
2043           index = child;
2044         }
2045       });
2046     }
2047   },
2048
2049   wrap: function(element, wrapNode) {
2050     wrapNode = jqLite(wrapNode)[0];
2051     var parent = element.parentNode;
2052     if (parent) {
2053       parent.replaceChild(wrapNode, element);
2054     }
2055     wrapNode.appendChild(element);
2056   },
2057
2058   remove: function(element) {
2059     JQLiteDealoc(element);
2060     var parent = element.parentNode;
2061     if (parent) parent.removeChild(element);
2062   },
2063
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);
2068       index = node;
2069     });
2070   },
2071
2072   addClass: JQLiteAddClass,
2073   removeClass: JQLiteRemoveClass,
2074
2075   toggleClass: function(element, selector, condition) {
2076     if (isUndefined(condition)) {
2077       condition = !JQLiteHasClass(element, selector);
2078     }
2079     (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
2080   },
2081
2082   parent: function(element) {
2083     var parent = element.parentNode;
2084     return parent && parent.nodeType !== 11 ? parent : null;
2085   },
2086
2087   next: function(element) {
2088     return element.nextSibling;
2089   },
2090
2091   find: function(element, selector) {
2092     return element.getElementsByTagName(selector);
2093   },
2094
2095   clone: JQLiteClone
2096 }, function(fn, name){
2097   /**
2098    * chaining functions
2099    */
2100   JQLite.prototype[name] = function(arg1, arg2) {
2101     var value;
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);
2108         }
2109       } else {
2110         JQLiteAddNodes(value, fn(this[i], arg1, arg2));
2111       }
2112     }
2113     return value == undefined ? this : value;
2114   };
2115 });
2116
2117 /**
2118  * Computes a hash of an 'obj'.
2119  * Hash of a:
2120  *  string is string
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.
2124  *
2125  * @param obj
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.
2128  */
2129 function hashKey(obj) {
2130   var objType = typeof obj,
2131       key;
2132
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();
2139     }
2140   } else {
2141     key = obj;
2142   }
2143
2144   return objType + ':' + key;
2145 }
2146
2147 /**
2148  * HashMap which can use objects as keys
2149  */
2150 function HashMap(array){
2151   forEach(array, this.put, this);
2152 }
2153 HashMap.prototype = {
2154   /**
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
2158    */
2159   put: function(key, value) {
2160     this[hashKey(key)] = value;
2161   },
2162
2163   /**
2164    * @param key
2165    * @returns the value for the key
2166    */
2167   get: function(key) {
2168     return this[hashKey(key)];
2169   },
2170
2171   /**
2172    * Remove the key/value pair
2173    * @param key
2174    */
2175   remove: function(key) {
2176     var value = this[key = hashKey(key)];
2177     delete this[key];
2178     return value;
2179   }
2180 };
2181
2182 /**
2183  * A map where multiple values can be added to the same key such that they form a queue.
2184  * @returns {HashQueueMap}
2185  */
2186 function HashQueueMap() {}
2187 HashQueueMap.prototype = {
2188   /**
2189    * Same as array push, but using an array as the value for the hash
2190    */
2191   push: function(key, value) {
2192     var array = this[key = hashKey(key)];
2193     if (!array) {
2194       this[key] = [value];
2195     } else {
2196       array.push(value);
2197     }
2198   },
2199
2200   /**
2201    * Same as array shift, but using an array as the value for the hash
2202    */
2203   shift: function(key) {
2204     var array = this[key = hashKey(key)];
2205     if (array) {
2206       if (array.length == 1) {
2207         delete this[key];
2208         return array[0];
2209       } else {
2210         return array.shift();
2211       }
2212     }
2213   }
2214 };
2215
2216 /**
2217  * @ngdoc function
2218  * @name angular.injector
2219  * @function
2220  *
2221  * @description
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}).
2224  *
2225
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}.
2229  *
2230  * @example
2231  * Typical usage
2232  * <pre>
2233  *   // create an injector
2234  *   var $injector = angular.injector(['ng']);
2235  *
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();
2241  *   });
2242  * </pre>
2243  */
2244
2245
2246 /**
2247  * @ngdoc overview
2248  * @name AUTO
2249  * @description
2250  *
2251  * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
2252  */
2253
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) {
2259   var $inject,
2260       fnText,
2261       argDecl,
2262       last;
2263
2264   if (typeof fn == 'function') {
2265     if (!($inject = fn.$inject)) {
2266       $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){
2271           $inject.push(name);
2272         });
2273       });
2274       fn.$inject = $inject;
2275     }
2276   } else if (isArray(fn)) {
2277     last = fn.length - 1;
2278     assertArgFn(fn[last], 'fn')
2279     $inject = fn.slice(0, last);
2280   } else {
2281     assertArgFn(fn, 'fn', true);
2282   }
2283   return $inject;
2284 }
2285
2286 ///////////////////////////////////////
2287
2288 /**
2289  * @ngdoc object
2290  * @name AUTO.$injector
2291  * @function
2292  *
2293  * @description
2294  *
2295  * `$injector` is used to retrieve object instances as defined by
2296  * {@link AUTO.$provide provider}, instantiate types, invoke methods,
2297  * and load modules.
2298  *
2299  * The following always holds true:
2300  *
2301  * <pre>
2302  *   var $injector = angular.injector();
2303  *   expect($injector.get('$injector')).toBe($injector);
2304  *   expect($injector.invoke(function($injector){
2305  *     return $injector;
2306  *   }).toBe($injector);
2307  * </pre>
2308  *
2309  * # Injection Function Annotation
2310  *
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.
2313  *
2314  * <pre>
2315  *   // inferred (only works if code not minified/obfuscated)
2316  *   $inject.invoke(function(serviceA){});
2317  *
2318  *   // annotated
2319  *   function explicit(serviceA) {};
2320  *   explicit.$inject = ['serviceA'];
2321  *   $inject.invoke(explicit);
2322  *
2323  *   // inline
2324  *   $inject.invoke(['serviceA', function(serviceA){}]);
2325  * </pre>
2326  *
2327  * ## Inference
2328  *
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.
2332  *
2333  * ## `$inject` Annotation
2334  * By adding a `$inject` property onto a function the injection parameters can be specified.
2335  *
2336  * ## Inline
2337  * As an array of injection names, where the last item in the array is the function to call.
2338  */
2339
2340 /**
2341  * @ngdoc method
2342  * @name AUTO.$injector#get
2343  * @methodOf AUTO.$injector
2344  *
2345  * @description
2346  * Return an instance of the service.
2347  *
2348  * @param {string} name The name of the instance to retrieve.
2349  * @return {*} The instance.
2350  */
2351
2352 /**
2353  * @ngdoc method
2354  * @name AUTO.$injector#invoke
2355  * @methodOf AUTO.$injector
2356  *
2357  * @description
2358  * Invoke the method and supply the method arguments from the `$injector`.
2359  *
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.
2365  */
2366
2367 /**
2368  * @ngdoc method
2369  * @name AUTO.$injector#instantiate
2370  * @methodOf AUTO.$injector
2371  * @description
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.
2374  *
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`.
2379  */
2380
2381 /**
2382  * @ngdoc method
2383  * @name AUTO.$injector#annotate
2384  * @methodOf AUTO.$injector
2385  *
2386  * @description
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.
2390  *
2391  * # Argument names
2392  *
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.
2395  * <pre>
2396  *   // Given
2397  *   function MyController($scope, $route) {
2398  *     // ...
2399  *   }
2400  *
2401  *   // Then
2402  *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
2403  * </pre>
2404  *
2405  * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
2406  * are supported.
2407  *
2408  * # The `$injector` property
2409  *
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.
2412  * <pre>
2413  *   // Given
2414  *   var MyController = function(obfuscatedScope, obfuscatedRoute) {
2415  *     // ...
2416  *   }
2417  *   // Define function dependencies
2418  *   MyController.$inject = ['$scope', '$route'];
2419  *
2420  *   // Then
2421  *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
2422  * </pre>
2423  *
2424  * # The array notation
2425  *
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:
2429  *
2430  * <pre>
2431  *   // We wish to write this (not minification / obfuscation safe)
2432  *   injector.invoke(function($compile, $rootScope) {
2433  *     // ...
2434  *   });
2435  *
2436  *   // We are forced to write break inlining
2437  *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
2438  *     // ...
2439  *   };
2440  *   tmpFn.$inject = ['$compile', '$rootScope'];
2441  *   injector.invoke(tempFn);
2442  *
2443  *   // To better support inline function the inline annotation is supported
2444  *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
2445  *     // ...
2446  *   }]);
2447  *
2448  *   // Therefore
2449  *   expect(injector.annotate(
2450  *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
2451  *    ).toEqual(['$compile', '$rootScope']);
2452  * </pre>
2453  *
2454  * @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
2455  *   above.
2456  *
2457  * @returns {Array.<string>} The names of the services which the function requires.
2458  */
2459
2460
2461
2462
2463 /**
2464  * @ngdoc object
2465  * @name AUTO.$provide
2466  *
2467  * @description
2468  *
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.
2471  *
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.
2474  *
2475  * <pre>
2476  *   function GreetProvider() {
2477  *     var salutation = 'Hello';
2478  *
2479  *     this.salutation = function(text) {
2480  *       salutation = text;
2481  *     };
2482  *
2483  *     this.$get = function() {
2484  *       return function (name) {
2485  *         return salutation + ' ' + name + '!';
2486  *       };
2487  *     };
2488  *   }
2489  *
2490  *   describe('Greeter', function(){
2491  *
2492  *     beforeEach(module(function($provide) {
2493  *       $provide.provider('greet', GreetProvider);
2494  *     });
2495  *
2496  *     it('should greet', inject(function(greet) {
2497  *       expect(greet('angular')).toEqual('Hello angular!');
2498  *     }));
2499  *
2500  *     it('should allow configuration of salutation', function() {
2501  *       module(function(greetProvider) {
2502  *         greetProvider.salutation('Ahoj');
2503  *       });
2504  *       inject(function(greet) {
2505  *         expect(greet('angular')).toEqual('Ahoj angular!');
2506  *       });
2507  *     )};
2508  *
2509  *   });
2510  * </pre>
2511  */
2512
2513 /**
2514  * @ngdoc method
2515  * @name AUTO.$provide#provider
2516  * @methodOf AUTO.$provide
2517  * @description
2518  *
2519  * Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
2520  *
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:
2523  *
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`.
2528  *
2529  * @returns {Object} registered provider instance
2530  */
2531
2532 /**
2533  * @ngdoc method
2534  * @name AUTO.$provide#factory
2535  * @methodOf AUTO.$provide
2536  * @description
2537  *
2538  * A short hand for configuring services if only `$get` method is required.
2539  *
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
2544  */
2545
2546
2547 /**
2548  * @ngdoc method
2549  * @name AUTO.$provide#service
2550  * @methodOf AUTO.$provide
2551  * @description
2552  *
2553  * A short hand for registering service of given class.
2554  *
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
2558  */
2559
2560
2561 /**
2562  * @ngdoc method
2563  * @name AUTO.$provide#value
2564  * @methodOf AUTO.$provide
2565  * @description
2566  *
2567  * A short hand for configuring services if the `$get` method is a constant.
2568  *
2569  * @param {string} name The name of the instance.
2570  * @param {*} value The value.
2571  * @returns {Object} registered provider instance
2572  */
2573
2574
2575 /**
2576  * @ngdoc method
2577  * @name AUTO.$provide#constant
2578  * @methodOf AUTO.$provide
2579  * @description
2580  *
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}.
2584  *
2585  * @param {string} name The name of the constant.
2586  * @param {*} value The constant value.
2587  * @returns {Object} registered instance
2588  */
2589
2590
2591 /**
2592  * @ngdoc method
2593  * @name AUTO.$provide#decorator
2594  * @methodOf AUTO.$provide
2595  * @description
2596  *
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.
2600  *
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:
2605  *
2606  *    * `$delegate` - The original service instance, which can be monkey patched, configured,
2607  *      decorated or delegated to.
2608  */
2609
2610
2611 function createInjector(modulesToLoad) {
2612   var INSTANTIATING = {},
2613       providerSuffix = 'Provider',
2614       path = [],
2615       loadedModules = new HashMap(),
2616       providerCache = {
2617         $provide: {
2618             provider: supportObject(provider),
2619             factory: supportObject(factory),
2620             service: supportObject(service),
2621             value: supportObject(value),
2622             constant: supportObject(constant),
2623             decorator: decorator
2624           }
2625       },
2626       providerInjector = createInternalInjector(providerCache, function() {
2627         throw Error("Unknown provider: " + path.join(' <- '));
2628       }),
2629       instanceCache = {},
2630       instanceInjector = (instanceCache.$injector =
2631           createInternalInjector(instanceCache, function(servicename) {
2632             var provider = providerInjector.get(servicename + providerSuffix);
2633             return instanceInjector.invoke(provider.$get, provider);
2634           }));
2635
2636
2637   forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
2638
2639   return instanceInjector;
2640
2641   ////////////////////////////////////
2642   // $provider
2643   ////////////////////////////////////
2644
2645   function supportObject(delegate) {
2646     return function(key, value) {
2647       if (isObject(key)) {
2648         forEach(key, reverseParams(delegate));
2649       } else {
2650         return delegate(key, value);
2651       }
2652     }
2653   }
2654
2655   function provider(name, provider_) {
2656     if (isFunction(provider_)) {
2657       provider_ = providerInjector.instantiate(provider_);
2658     }
2659     if (!provider_.$get) {
2660       throw Error('Provider ' + name + ' must define $get factory method.');
2661     }
2662     return providerCache[name + providerSuffix] = provider_;
2663   }
2664
2665   function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
2666
2667   function service(name, constructor) {
2668     return factory(name, ['$injector', function($injector) {
2669       return $injector.instantiate(constructor);
2670     }]);
2671   }
2672
2673   function value(name, value) { return factory(name, valueFn(value)); }
2674
2675   function constant(name, value) {
2676     providerCache[name] = value;
2677     instanceCache[name] = value;
2678   }
2679
2680   function decorator(serviceName, decorFn) {
2681     var origProvider = providerInjector.get(serviceName + providerSuffix),
2682         orig$get = origProvider.$get;
2683
2684     origProvider.$get = function() {
2685       var origInstance = instanceInjector.invoke(orig$get, origProvider);
2686       return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
2687     };
2688   }
2689
2690   ////////////////////////////////////
2691   // Module Loading
2692   ////////////////////////////////////
2693   function loadModules(modulesToLoad){
2694     var runBlocks = [];
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);
2701
2702         try {
2703           for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
2704             var invokeArgs = invokeQueue[i],
2705                 provider = invokeArgs[0] == '$injector'
2706                     ? providerInjector
2707                     : providerInjector.get(invokeArgs[0]);
2708
2709             provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
2710           }
2711         } catch (e) {
2712           if (e.message) e.message += ' from ' + module;
2713           throw e;
2714         }
2715       } else if (isFunction(module)) {
2716         try {
2717           runBlocks.push(providerInjector.invoke(module));
2718         } catch (e) {
2719           if (e.message) e.message += ' from ' + module;
2720           throw e;
2721         }
2722       } else if (isArray(module)) {
2723         try {
2724           runBlocks.push(providerInjector.invoke(module));
2725         } catch (e) {
2726           if (e.message) e.message += ' from ' + String(module[module.length - 1]);
2727           throw e;
2728         }
2729       } else {
2730         assertArgFn(module, 'module');
2731       }
2732     });
2733     return runBlocks;
2734   }
2735
2736   ////////////////////////////////////
2737   // internal Injector
2738   ////////////////////////////////////
2739
2740   function createInternalInjector(cache, factory) {
2741
2742     function getService(serviceName) {
2743       if (typeof serviceName !== 'string') {
2744         throw Error('Service name expected');
2745       }
2746       if (cache.hasOwnProperty(serviceName)) {
2747         if (cache[serviceName] === INSTANTIATING) {
2748           throw Error('Circular dependency: ' + path.join(' <- '));
2749         }
2750         return cache[serviceName];
2751       } else {
2752         try {
2753           path.unshift(serviceName);
2754           cache[serviceName] = INSTANTIATING;
2755           return cache[serviceName] = factory(serviceName);
2756         } finally {
2757           path.shift();
2758         }
2759       }
2760     }
2761
2762     function invoke(fn, self, locals){
2763       var args = [],
2764           $inject = annotate(fn),
2765           length, i,
2766           key;
2767
2768       for(i = 0, length = $inject.length; i < length; i++) {
2769         key = $inject[i];
2770         args.push(
2771           locals && locals.hasOwnProperty(key)
2772           ? locals[key]
2773           : getService(key, path)
2774         );
2775       }
2776       if (!fn.$inject) {
2777         // this means that we must be an array.
2778         fn = fn[length];
2779       }
2780
2781
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);
2796       }
2797     }
2798
2799     function instantiate(Type, locals) {
2800       var Constructor = function() {},
2801           instance, returnedValue;
2802
2803       Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
2804       instance = new Constructor();
2805       returnedValue = invoke(Type, instance, locals);
2806
2807       return isObject(returnedValue) ? returnedValue : instance;
2808     }
2809
2810     return {
2811       invoke: invoke,
2812       instantiate: instantiate,
2813       get: getService,
2814       annotate: annotate
2815     };
2816   }
2817 }
2818 /**
2819  * @ngdoc function
2820  * @name ng.$anchorScroll
2821  * @requires $window
2822  * @requires $location
2823  * @requires $rootScope
2824  *
2825  * @description
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}.
2829  *
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()`.
2832  */
2833 function $AnchorScrollProvider() {
2834
2835   var autoScrollingEnabled = true;
2836
2837   this.disableAutoScrolling = function() {
2838     autoScrollingEnabled = false;
2839   };
2840
2841   this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
2842     var document = $window.document;
2843
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) {
2849       var result = null;
2850       forEach(list, function(element) {
2851         if (!result && lowercase(element.nodeName) === 'a') result = element;
2852       });
2853       return result;
2854     }
2855
2856     function scroll() {
2857       var hash = $location.hash(), elm;
2858
2859       // empty hash, scroll to the top of the page
2860       if (!hash) $window.scrollTo(0, 0);
2861
2862       // element with given id
2863       else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
2864
2865       // first anchor with given name :-D
2866       else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
2867
2868       // no element and hash == 'top', scroll to the top of the page
2869       else if (hash === 'top') $window.scrollTo(0, 0);
2870     }
2871
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);
2877       });
2878     }
2879
2880     return scroll;
2881   }];
2882 }
2883
2884 /**
2885  * ! This is a private undocumented service !
2886  *
2887  * @name ng.$browser
2888  * @requires $log
2889  * @description
2890  * This object has two goals:
2891  *
2892  * - hide all the global state in the browser caused by the window object
2893  * - abstract away all the browser specific features and inconsistencies
2894  *
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.
2898  */
2899 /**
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
2905  */
2906 function Browser(window, document, $log, $sniffer) {
2907   var self = this,
2908       rawDocument = document[0],
2909       location = window.location,
2910       history = window.history,
2911       setTimeout = window.setTimeout,
2912       clearTimeout = window.clearTimeout,
2913       pendingDeferIds = {};
2914
2915   self.isMock = false;
2916
2917   var outstandingRequestCount = 0;
2918   var outstandingRequestCallbacks = [];
2919
2920   // TODO(vojta): remove this temporary api
2921   self.$$completeOutstandingRequest = completeOutstandingRequest;
2922   self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
2923
2924   /**
2925    * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
2926    * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
2927    */
2928   function completeOutstandingRequest(fn) {
2929     try {
2930       fn.apply(null, sliceArgs(arguments, 1));
2931     } finally {
2932       outstandingRequestCount--;
2933       if (outstandingRequestCount === 0) {
2934         while(outstandingRequestCallbacks.length) {
2935           try {
2936             outstandingRequestCallbacks.pop()();
2937           } catch (e) {
2938             $log.error(e);
2939           }
2940         }
2941       }
2942     }
2943   }
2944
2945   /**
2946    * @private
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
2950    */
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(); });
2956
2957     if (outstandingRequestCount === 0) {
2958       callback();
2959     } else {
2960       outstandingRequestCallbacks.push(callback);
2961     }
2962   };
2963
2964   //////////////////////////////////////////////////////////////
2965   // Poll Watcher API
2966   //////////////////////////////////////////////////////////////
2967   var pollFns = [],
2968       pollTimeout;
2969
2970   /**
2971    * @name ng.$browser#addPollFn
2972    * @methodOf ng.$browser
2973    *
2974    * @param {function()} fn Poll function to add
2975    *
2976    * @description
2977    * Adds a function to the list of functions that poller periodically executes,
2978    * and starts polling if not started yet.
2979    *
2980    * @returns {function()} the added function
2981    */
2982   self.addPollFn = function(fn) {
2983     if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
2984     pollFns.push(fn);
2985     return fn;
2986   };
2987
2988   /**
2989    * @param {number} interval How often should browser call poll functions (ms)
2990    * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
2991    *
2992    * @description
2993    * Configures the poller to run in the specified intervals, using the specified
2994    * setTimeout fn and kicks it off.
2995    */
2996   function startPoller(interval, setTimeout) {
2997     (function check() {
2998       forEach(pollFns, function(pollFn){ pollFn(); });
2999       pollTimeout = setTimeout(check, interval);
3000     })();
3001   }
3002
3003   //////////////////////////////////////////////////////////////
3004   // URL API
3005   //////////////////////////////////////////////////////////////
3006
3007   var lastBrowserUrl = location.href,
3008       baseElement = document.find('base');
3009
3010   /**
3011    * @name ng.$browser#url
3012    * @methodOf ng.$browser
3013    *
3014    * @description
3015    * GETTER:
3016    * Without any argument, this method just returns current value of location.href.
3017    *
3018    * SETTER:
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
3023    *
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.
3026    *
3027    * @param {string} url New url (when used as setter)
3028    * @param {boolean=} replace Should new url replace current history record ?
3029    */
3030   self.url = function(url, replace) {
3031     // setter
3032     if (url) {
3033       if (lastBrowserUrl == url) return;
3034       lastBrowserUrl = url;
3035       if ($sniffer.history) {
3036         if (replace) history.replaceState(null, '', url);
3037         else {
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'));
3041         }
3042       } else {
3043         if (replace) location.replace(url);
3044         else location.href = url;
3045       }
3046       return self;
3047     // getter
3048     } else {
3049       // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
3050       return location.href.replace(/%27/g,"'");
3051     }
3052   };
3053
3054   var urlChangeListeners = [],
3055       urlChangeInit = false;
3056
3057   function fireUrlChange() {
3058     if (lastBrowserUrl == self.url()) return;
3059
3060     lastBrowserUrl = self.url();
3061     forEach(urlChangeListeners, function(listener) {
3062       listener(self.url());
3063     });
3064   }
3065
3066   /**
3067    * @name ng.$browser#onUrlChange
3068    * @methodOf ng.$browser
3069    * @TODO(vojta): refactor to use node's syntax for events
3070    *
3071    * @description
3072    * Register callback function that will be called, when url changes.
3073    *
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
3078    *
3079    * It's not called when url is changed by $browser.url() method
3080    *
3081    * The listener gets called with new url as parameter.
3082    *
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.
3085    *
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.
3088    */
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
3094
3095       // html5 history api - popstate event
3096       if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
3097       // hashchange event
3098       if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
3099       // polling
3100       else self.addPollFn(fireUrlChange);
3101
3102       urlChangeInit = true;
3103     }
3104
3105     urlChangeListeners.push(callback);
3106     return callback;
3107   };
3108
3109   //////////////////////////////////////////////////////////////
3110   // Misc API
3111   //////////////////////////////////////////////////////////////
3112
3113   /**
3114    * Returns current <base href>
3115    * (always relative - without domain)
3116    *
3117    * @returns {string=}
3118    */
3119   self.baseHref = function() {
3120     var href = baseElement.attr('href');
3121     return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href;
3122   };
3123
3124   //////////////////////////////////////////////////////////////
3125   // Cookies API
3126   //////////////////////////////////////////////////////////////
3127   var lastCookies = {};
3128   var lastCookieString = '';
3129   var cookiePath = self.baseHref();
3130
3131   /**
3132    * @name ng.$browser#cookies
3133    * @methodOf ng.$browser
3134    *
3135    * @param {string=} name Cookie name
3136    * @param {string=} value Cokkie value
3137    *
3138    * @description
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.
3141    *
3142    * The return values vary depending on the arguments that the method was called with as follows:
3143    * <ul>
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>
3147    * </ul>
3148    *
3149    * @returns {Object} Hash of all cookies (if called without any parameter)
3150    */
3151   self.cookies = function(name, value) {
3152     var cookieLength, cookieArray, cookie, i, index;
3153
3154     if (name) {
3155       if (value === undefined) {
3156         rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
3157       } else {
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)!");
3163           }
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 )");
3167           }
3168         }
3169       }
3170     } else {
3171       if (rawDocument.cookie !== lastCookieString) {
3172         lastCookieString = rawDocument.cookie;
3173         cookieArray = lastCookieString.split("; ");
3174         lastCookies = {};
3175
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));
3181           }
3182         }
3183       }
3184       return lastCookies;
3185     }
3186   };
3187
3188
3189   /**
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()`.
3195    *
3196    * @description
3197    * Executes a fn asynchroniously via `setTimeout(fn, delay)`.
3198    *
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()`.
3202    *
3203    */
3204   self.defer = function(fn, delay) {
3205     var timeoutId;
3206     outstandingRequestCount++;
3207     timeoutId = setTimeout(function() {
3208       delete pendingDeferIds[timeoutId];
3209       completeOutstandingRequest(fn);
3210     }, delay || 0);
3211     pendingDeferIds[timeoutId] = true;
3212     return timeoutId;
3213   };
3214
3215
3216   /**
3217    * @name ng.$browser#defer.cancel
3218    * @methodOf ng.$browser.defer
3219    *
3220    * @description
3221    * Cancels a defered task identified with `deferId`.
3222    *
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.
3225    */
3226   self.defer.cancel = function(deferId) {
3227     if (pendingDeferIds[deferId]) {
3228       delete pendingDeferIds[deferId];
3229       clearTimeout(deferId);
3230       completeOutstandingRequest(noop);
3231       return true;
3232     }
3233     return false;
3234   };
3235
3236 }
3237
3238 function $BrowserProvider(){
3239   this.$get = ['$window', '$log', '$sniffer', '$document',
3240       function( $window,   $log,   $sniffer,   $document){
3241         return new Browser($window, $document, $log, $sniffer);
3242       }];
3243 }
3244 /**
3245  * @ngdoc object
3246  * @name ng.$cacheFactory
3247  *
3248  * @description
3249  * Factory that constructs cache objects.
3250  *
3251  *
3252  * @param {string} cacheId Name or id of the newly created cache.
3253  * @param {object=} options Options object that specifies the cache behavior. Properties:
3254  *
3255  *   - `{number=}` `capacity` — turns the cache into LRU cache.
3256  *
3257  * @returns {object} Newly created cache object with the following set of methods:
3258  *
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.
3265  *
3266  */
3267 function $CacheFactoryProvider() {
3268
3269   this.$get = function() {
3270     var caches = {};
3271
3272     function cacheFactory(cacheId, options) {
3273       if (cacheId in caches) {
3274         throw Error('cacheId ' + cacheId + ' taken');
3275       }
3276
3277       var size = 0,
3278           stats = extend({}, options, {id: cacheId}),
3279           data = {},
3280           capacity = (options && options.capacity) || Number.MAX_VALUE,
3281           lruHash = {},
3282           freshEnd = null,
3283           staleEnd = null;
3284
3285       return caches[cacheId] = {
3286
3287         put: function(key, value) {
3288           var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
3289
3290           refresh(lruEntry);
3291
3292           if (isUndefined(value)) return;
3293           if (!(key in data)) size++;
3294           data[key] = value;
3295
3296           if (size > capacity) {
3297             this.remove(staleEnd.key);
3298           }
3299         },
3300
3301
3302         get: function(key) {
3303           var lruEntry = lruHash[key];
3304
3305           if (!lruEntry) return;
3306
3307           refresh(lruEntry);
3308
3309           return data[key];
3310         },
3311
3312
3313         remove: function(key) {
3314           var lruEntry = lruHash[key];
3315
3316           if (lruEntry == freshEnd) freshEnd = lruEntry.p;
3317           if (lruEntry == staleEnd) staleEnd = lruEntry.n;
3318           link(lruEntry.n,lruEntry.p);
3319
3320           delete lruHash[key];
3321           delete data[key];
3322           size--;
3323         },
3324
3325
3326         removeAll: function() {
3327           data = {};
3328           size = 0;
3329           lruHash = {};
3330           freshEnd = staleEnd = null;
3331         },
3332
3333
3334         destroy: function() {
3335           data = null;
3336           stats = null;
3337           lruHash = null;
3338           delete caches[cacheId];
3339         },
3340
3341
3342         info: function() {
3343           return extend({}, stats, {size: size});
3344         }
3345       };
3346
3347
3348       /**
3349        * makes the `entry` the freshEnd of the LRU linked list
3350        */
3351       function refresh(entry) {
3352         if (entry != freshEnd) {
3353           if (!staleEnd) {
3354             staleEnd = entry;
3355           } else if (staleEnd == entry) {
3356             staleEnd = entry.n;
3357           }
3358
3359           link(entry.n, entry.p);
3360           link(entry, freshEnd);
3361           freshEnd = entry;
3362           freshEnd.n = null;
3363         }
3364       }
3365
3366
3367       /**
3368        * bidirectionally links two entries of the LRU linked list
3369        */
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
3374         }
3375       }
3376     }
3377
3378
3379     cacheFactory.info = function() {
3380       var info = {};
3381       forEach(caches, function(cache, cacheId) {
3382         info[cacheId] = cache.info();
3383       });
3384       return info;
3385     };
3386
3387
3388     cacheFactory.get = function(cacheId) {
3389       return caches[cacheId];
3390     };
3391
3392
3393     return cacheFactory;
3394   };
3395 }
3396
3397 /**
3398  * @ngdoc object
3399  * @name ng.$templateCache
3400  *
3401  * @description
3402  * Cache used for storing html templates.
3403  *
3404  * See {@link ng.$cacheFactory $cacheFactory}.
3405  *
3406  */
3407 function $TemplateCacheProvider() {
3408   this.$get = ['$cacheFactory', function($cacheFactory) {
3409     return $cacheFactory('templates');
3410   }];
3411 }
3412
3413 /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
3414  *
3415  * DOM-related variables:
3416  *
3417  * - "node" - DOM Node
3418  * - "element" - DOM Element or Node
3419  * - "$node" or "$element" - jqLite-wrapped node or element
3420  *
3421  *
3422  * Compiler related stuff:
3423  *
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)
3428  */
3429
3430
3431 var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
3432
3433
3434 /**
3435  * @ngdoc function
3436  * @name ng.$compile
3437  * @function
3438  *
3439  * @description
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.
3442  *
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.
3447  *
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.
3451  *
3452  <doc:example module="compile">
3453    <doc:source>
3454     <script>
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) {
3462             scope.$watch(
3463               function(scope) {
3464                  // watch the 'compile' expression for changes
3465                 return scope.$eval(attrs.compile);
3466               },
3467               function(value) {
3468                 // when the 'compile' expression changes
3469                 // assign it into the current DOM
3470                 element.html(value);
3471
3472                 // compile the new DOM and link it to the current
3473                 // scope.
3474                 // NOTE: we only compile .childNodes so that
3475                 // we don't get into infinite loop compiling ourselves
3476                 $compile(element.contents())(scope);
3477               }
3478             );
3479           };
3480         })
3481       });
3482
3483       function Ctrl($scope) {
3484         $scope.name = 'Angular';
3485         $scope.html = 'Hello {{name}}';
3486       }
3487     </script>
3488     <div ng-controller="Ctrl">
3489       <input ng-model="name"> <br>
3490       <textarea ng-model="html"></textarea> <br>
3491       <div compile="html"></div>
3492     </div>
3493    </doc:source>
3494    <doc:scenario>
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!');
3499      });
3500    </doc:scenario>
3501  </doc:example>
3502
3503  *
3504  *
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:
3511  *
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:
3517  *
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.
3520  *
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.
3523  *
3524  * After linking the view is not updated until after a call to $digest which typically is done by
3525  * Angular automatically.
3526  *
3527  * If you need access to the bound view, there are two ways to do it:
3528  *
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.
3531  *   <pre>
3532  *     var element = $compile('<p>{{total}}</p>')(scope);
3533  *   </pre>
3534  *
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:
3538  *   <pre>
3539  *     var templateHTML = angular.element('<p>{{total}}</p>'),
3540  *         scope = ....;
3541  *
3542  *     var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
3543  *       //attach the clone to DOM document at the right place
3544  *     });
3545  *
3546  *     //now we have reference to the cloned DOM via `clone`
3547  *   </pre>
3548  *
3549  *
3550  * For information on how the compiler works, see the
3551  * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
3552  */
3553
3554
3555 /**
3556  * @ngdoc service
3557  * @name ng.$compileProvider
3558  * @function
3559  *
3560  * @description
3561  */
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: ';
3569
3570
3571   /**
3572    * @ngdoc function
3573    * @name ng.$compileProvider#directive
3574    * @methodOf ng.$compileProvider
3575    * @function
3576    *
3577    * @description
3578    * Register a new directives with the compiler.
3579    *
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
3583    *                info.
3584    * @returns {ng.$compileProvider} Self for chaining.
3585    */
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) {
3595               try {
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);
3601                 }
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);
3607               } catch (e) {
3608                 $exceptionHandler(e);
3609               }
3610             });
3611             return directives;
3612           }]);
3613       }
3614       hasDirectives[name].push(directiveFactory);
3615     } else {
3616       forEach(name, reverseParams(registerDirective));
3617     }
3618     return this;
3619   };
3620
3621
3622   this.$get = [
3623             '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
3624             '$controller', '$rootScope',
3625     function($injector,   $interpolate,   $exceptionHandler,   $http,   $templateCache,   $parse,
3626              $controller,   $rootScope) {
3627
3628     var Attributes = function(element, attr) {
3629       this.$$element = element;
3630       this.$attr = attr || {};
3631     };
3632
3633     Attributes.prototype = {
3634       $normalize: directiveNormalize,
3635
3636
3637       /**
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.
3643        *     Defaults to true.
3644        * @param {string=} attrName Optional none normalized name. Defaults to key.
3645        */
3646       $set: function(key, value, writeAttr, attrName) {
3647         var booleanKey = getBooleanAttrName(this.$$element[0], key),
3648             $$observers = this.$$observers;
3649
3650         if (booleanKey) {
3651           this.$$element.prop(key, value);
3652           attrName = booleanKey;
3653         }
3654
3655         this[key] = value;
3656
3657         // translate normalized key to actual key
3658         if (attrName) {
3659           this.$attr[key] = attrName;
3660         } else {
3661           attrName = this.$attr[key];
3662           if (!attrName) {
3663             this.$attr[key] = attrName = snake_case(key, '-');
3664           }
3665         }
3666
3667         if (writeAttr !== false) {
3668           if (value === null || value === undefined) {
3669             this.$$element.removeAttr(attrName);
3670           } else {
3671             this.$$element.attr(attrName, value);
3672           }
3673         }
3674
3675         // fire observers
3676         $$observers && forEach($$observers[key], function(fn) {
3677           try {
3678             fn(value);
3679           } catch (e) {
3680             $exceptionHandler(e);
3681           }
3682         });
3683       },
3684
3685
3686       /**
3687        * Observe an interpolated attribute.
3688        * The observer will never be called, if given attribute is not interpolated.
3689        *
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.
3693        */
3694       $observe: function(key, fn) {
3695         var attrs = this,
3696             $$observers = (attrs.$$observers || (attrs.$$observers = {})),
3697             listeners = ($$observers[key] || ($$observers[key] = []));
3698
3699         listeners.push(fn);
3700         $rootScope.$evalAsync(function() {
3701           if (!listeners.$$inter) {
3702             // no one registered attribute interpolation function, so lets call it manually
3703             fn(attrs[key]);
3704           }
3705         });
3706         return fn;
3707       }
3708     };
3709
3710     var startSymbol = $interpolate.startSymbol(),
3711         endSymbol = $interpolate.endSymbol(),
3712         denormalizeTemplate = (startSymbol == '{{' || endSymbol  == '}}')
3713             ? identity
3714             : function denormalizeTemplate(template) {
3715               return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
3716             };
3717
3718
3719     return compile;
3720
3721     //================================
3722
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);
3727       }
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];
3733         }
3734       });
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!!!
3742           : $compileNode;
3743         $linkNode.data('$scope', scope);
3744         safeAddClass($linkNode, 'ng-scope');
3745         if (cloneConnectFn) cloneConnectFn($linkNode, scope);
3746         if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
3747         return $linkNode;
3748       };
3749     }
3750
3751     function wrongMode(localName, mode) {
3752       throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
3753     }
3754
3755     function safeAddClass($element, className) {
3756       try {
3757         $element.addClass(className);
3758       } catch(e) {
3759         // ignore, since it means that we are trying to set class on
3760         // SVG element, where class name is read-only.
3761       }
3762     }
3763
3764     /**
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.
3769      *
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.
3778      */
3779     function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) {
3780      var linkFns = [],
3781          nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
3782
3783      for(var i = 0; i < nodeList.length; i++) {
3784        attrs = new Attributes();
3785
3786        // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
3787        directives = collectDirectives(nodeList[i], [], attrs, maxPriority);
3788
3789        nodeLinkFn = (directives.length)
3790            ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
3791            : null;
3792
3793        childLinkFn = (nodeLinkFn && nodeLinkFn.terminal)
3794            ? null
3795            : compileNodes(nodeList[i].childNodes,
3796                 nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
3797
3798        linkFns.push(nodeLinkFn);
3799        linkFns.push(childLinkFn);
3800        linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
3801      }
3802
3803      // return a linking function if we have found anything, null otherwise
3804      return linkFnFound ? compositeLinkFn : null;
3805
3806      function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
3807        var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn;
3808
3809        for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
3810          node = nodeList[n];
3811          nodeLinkFn = linkFns[i++];
3812          childLinkFn = linkFns[i++];
3813
3814          if (nodeLinkFn) {
3815            if (nodeLinkFn.scope) {
3816              childScope = scope.$new(isObject(nodeLinkFn.scope));
3817              jqLite(node).data('$scope', childScope);
3818            } else {
3819              childScope = scope;
3820            }
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();
3827
3828                      return transcludeFn(transcludeScope, cloneFn).
3829                          bind('$destroy', bind(transcludeScope, transcludeScope.$destroy));
3830                     };
3831                   })(childTranscludeFn || transcludeFn)
3832              );
3833            } else {
3834              nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
3835            }
3836          } else if (childLinkFn) {
3837            childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
3838          }
3839        }
3840      }
3841    }
3842
3843
3844     /**
3845      * Looks for directives on the given node ands them to the directive collection which is sorted.
3846      *
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
3852      */
3853     function collectDirectives(node, directives, attrs, maxPriority) {
3854       var nodeType = node.nodeType,
3855           attrsMap = attrs.$attr,
3856           match,
3857           className;
3858
3859       switch(nodeType) {
3860         case 1: /* Element */
3861           // use the node name: <directive>
3862           addDirective(directives,
3863               directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
3864
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++) {
3868             attr = nAttrs[j];
3869             if (attr.specified) {
3870               name = attr.name;
3871               nName = directiveNormalize(name.toLowerCase());
3872               attrsMap[nName] = name;
3873               attrs[nName] = value = trim((msie && name == 'href')
3874                 ? decodeURIComponent(node.getAttribute(name, 2))
3875                 : attr.value);
3876               if (getBooleanAttrName(node, nName)) {
3877                 attrs[nName] = true; // presence means true
3878               }
3879               addAttrInterpolateDirective(node, directives, value, nName);
3880               addDirective(directives, nName, 'A', maxPriority);
3881             }
3882           }
3883
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]);
3891               }
3892               className = className.substr(match.index + match[0].length);
3893             }
3894           }
3895           break;
3896         case 3: /* Text Node */
3897           addTextInterpolateDirective(directives, node.nodeValue);
3898           break;
3899         case 8: /* Comment */
3900           try {
3901             match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
3902             if (match) {
3903               nName = directiveNormalize(match[1]);
3904               if (addDirective(directives, nName, 'M', maxPriority)) {
3905                 attrs[nName] = trim(match[2]);
3906               }
3907             }
3908           } catch (e) {
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.)
3911           }
3912           break;
3913       }
3914
3915       directives.sort(byPriority);
3916       return directives;
3917     }
3918
3919
3920     /**
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..
3924      *
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.
3933      * @returns linkFn
3934      */
3935     function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) {
3936       var terminalPriority = -Number.MAX_VALUE,
3937           preLinkFns = [],
3938           postLinkFns = [],
3939           newScopeDirective = null,
3940           newIsolatedScopeDirective = null,
3941           templateDirective = null,
3942           $compileNode = templateAttrs.$$element = jqLite(compileNode),
3943           directive,
3944           directiveName,
3945           $template,
3946           transcludeDirective,
3947           childTranscludeFn = transcludeFn,
3948           controllerDirectives,
3949           linkFn,
3950           directiveValue;
3951
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;
3956
3957         if (terminalPriority > directive.priority) {
3958           break; // prevent further processing of directives
3959         }
3960
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;
3966           }
3967           safeAddClass($compileNode, 'ng-scope');
3968           newScopeDirective = newScopeDirective || directive;
3969         }
3970
3971         directiveName = directive.name;
3972
3973         if (directiveValue = directive.controller) {
3974           controllerDirectives = controllerDirectives || {};
3975           assertNoDuplicate("'" + directiveName + "' controller",
3976               controllerDirectives[directiveName], directive, $compileNode);
3977           controllerDirectives[directiveName] = directive;
3978         }
3979
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);
3991           } else {
3992             $template = jqLite(JQLiteClone(compileNode)).contents();
3993             $compileNode.html(''); // clear contents
3994             childTranscludeFn = compile($template, transcludeFn);
3995           }
3996         }
3997
3998         if ((directiveValue = directive.template)) {
3999           assertNoDuplicate('template', templateDirective, directive, $compileNode);
4000           templateDirective = directive;
4001           directiveValue = denormalizeTemplate(directiveValue);
4002
4003           if (directive.replace) {
4004             $template = jqLite('<div>' +
4005                                  trim(directiveValue) +
4006                                '</div>').contents();
4007             compileNode = $template[0];
4008
4009             if ($template.length != 1 || compileNode.nodeType !== 1) {
4010               throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
4011             }
4012
4013             replaceWith($rootElement, $compileNode, compileNode);
4014
4015             var newTemplateAttrs = {$attr: {}};
4016
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(
4023                 collectDirectives(
4024                     compileNode,
4025                     directives.splice(i + 1, directives.length - (i + 1)),
4026                     newTemplateAttrs
4027                 )
4028             );
4029             mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
4030
4031             ii = directives.length;
4032           } else {
4033             $compileNode.html(directiveValue);
4034           }
4035         }
4036
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,
4042               childTranscludeFn);
4043           ii = directives.length;
4044         } else if (directive.compile) {
4045           try {
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);
4051             }
4052           } catch (e) {
4053             $exceptionHandler(e, startingTag($compileNode));
4054           }
4055         }
4056
4057         if (directive.terminal) {
4058           nodeLinkFn.terminal = true;
4059           terminalPriority = Math.max(terminalPriority, directive.priority);
4060         }
4061
4062       }
4063
4064       nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
4065       nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
4066
4067       // might be normal or delayed nodeLinkFn depending on if templateUrl is present
4068       return nodeLinkFn;
4069
4070       ////////////////////
4071
4072       function addLinkFns(pre, post) {
4073         if (pre) {
4074           pre.require = directive.require;
4075           preLinkFns.push(pre);
4076         }
4077         if (post) {
4078           post.require = directive.require;
4079           postLinkFns.push(post);
4080         }
4081       }
4082
4083
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);
4089             if (value == '^') {
4090               retrievalMethod = 'inheritedData';
4091             }
4092             optional = optional || value == '?';
4093           }
4094           value = $element[retrievalMethod]('$' + require + 'Controller');
4095           if (!value && !optional) {
4096             throw Error("No controller: " + require);
4097           }
4098           return value;
4099         } else if (isArray(require)) {
4100           value = [];
4101           forEach(require, function(require) {
4102             value.push(getControllers(require, $element));
4103           });
4104         }
4105         return value;
4106       }
4107
4108
4109       function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
4110         var attrs, $element, i, ii, linkFn, controller;
4111
4112         if (compileNode === linkNode) {
4113           attrs = templateAttrs;
4114         } else {
4115           attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
4116         }
4117         $element = attrs.$$element;
4118
4119         if (newScopeDirective && isObject(newScopeDirective.scope)) {
4120           var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/;
4121
4122           var parentScope = scope.$parent || scope;
4123
4124           forEach(newScopeDirective.scope, function(definiton, scopeName) {
4125             var match = definiton.match(LOCAL_REGEXP) || [],
4126                 attrName = match[2]|| scopeName,
4127                 mode = match[1], // @, =, or &
4128                 lastValue,
4129                 parentGet, parentSet;
4130
4131             switch (mode) {
4132
4133               case '@': {
4134                 attrs.$observe(attrName, function(value) {
4135                   scope[scopeName] = value;
4136                 });
4137                 attrs.$$observers[attrName].$$scope = parentScope;
4138                 break;
4139               }
4140
4141               case '=': {
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 + ')');
4148                 };
4149                 lastValue = scope[scopeName] = parentGet(parentScope);
4150                 scope.$watch(function() {
4151                   var parentValue = parentGet(parentScope);
4152
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;
4158                     } else {
4159                       // if the parent can be assigned then do so
4160                       parentSet(parentScope, lastValue = scope[scopeName]);
4161                     }
4162                   }
4163                   return parentValue;
4164                 });
4165                 break;
4166               }
4167
4168               case '&': {
4169                 parentGet = $parse(attrs[attrName]);
4170                 scope[scopeName] = function(locals) {
4171                   return parentGet(parentScope, locals);
4172                 }
4173                 break;
4174               }
4175
4176               default: {
4177                 throw Error('Invalid isolate scope definition for directive ' +
4178                     newScopeDirective.name + ': ' + definiton);
4179               }
4180             }
4181           });
4182         }
4183
4184         if (controllerDirectives) {
4185           forEach(controllerDirectives, function(directive) {
4186             var locals = {
4187               $scope: scope,
4188               $element: $element,
4189               $attrs: attrs,
4190               $transclude: boundTranscludeFn
4191             };
4192
4193             controller = directive.controller;
4194             if (controller == '@') {
4195               controller = attrs[directive.name];
4196             }
4197
4198             $element.data(
4199                 '$' + directive.name + 'Controller',
4200                 $controller(controller, locals));
4201           });
4202         }
4203
4204         // PRELINKING
4205         for(i = 0, ii = preLinkFns.length; i < ii; i++) {
4206           try {
4207             linkFn = preLinkFns[i];
4208             linkFn(scope, $element, attrs,
4209                 linkFn.require && getControllers(linkFn.require, $element));
4210           } catch (e) {
4211             $exceptionHandler(e, startingTag($element));
4212           }
4213         }
4214
4215         // RECURSION
4216         childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
4217
4218         // POSTLINKING
4219         for(i = 0, ii = postLinkFns.length; i < ii; i++) {
4220           try {
4221             linkFn = postLinkFns[i];
4222             linkFn(scope, $element, attrs,
4223                 linkFn.require && getControllers(linkFn.require, $element));
4224           } catch (e) {
4225             $exceptionHandler(e, startingTag($element));
4226           }
4227         }
4228       }
4229     }
4230
4231
4232     /**
4233      * looks up the directive and decorates it with exception handling and proper parameters. We
4234      * call this the boundDirective.
4235      *
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:
4239      *
4240      *   * `E`: element name
4241      *   * `A': attribute
4242      *   * `C`: class
4243      *   * `M`: comment
4244      * @returns true if directive was added.
4245      */
4246     function addDirective(tDirectives, name, location, maxPriority) {
4247       var match = false;
4248       if (hasDirectives.hasOwnProperty(name)) {
4249         for(var directive, directives = $injector.get(name + Suffix),
4250             i = 0, ii = directives.length; i<ii; i++) {
4251           try {
4252             directive = directives[i];
4253             if ( (maxPriority === undefined || maxPriority > directive.priority) &&
4254                  directive.restrict.indexOf(location) != -1) {
4255               tDirectives.push(directive);
4256               match = true;
4257             }
4258           } catch(e) { $exceptionHandler(e); }
4259         }
4260       }
4261       return match;
4262     }
4263
4264
4265     /**
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.
4269      *
4270      * @param {object} dst destination attributes (original DOM)
4271      * @param {object} src source attributes (from the directive template)
4272      */
4273     function mergeTemplateAttributes(dst, src) {
4274       var srcAttr = src.$attr,
4275           dstAttr = dst.$attr,
4276           $element = dst.$$element;
4277
4278       // reapply the old attributes to the new element
4279       forEach(dst, function(value, key) {
4280         if (key.charAt(0) != '$') {
4281           if (src[key]) {
4282             value += (key === 'style' ? ';' : ' ') + src[key];
4283           }
4284           dst.$set(key, value, true, srcAttr[key]);
4285         }
4286       });
4287
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)) {
4296           dst[key] = value;
4297           dstAttr[key] = srcAttr[key];
4298         }
4299       });
4300     }
4301
4302
4303     function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
4304         $rootElement, replace, childTranscludeFn) {
4305       var linkQueue = [],
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
4313           });
4314
4315       $compileNode.html('');
4316
4317       $http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
4318         success(function(content) {
4319           var compileNode, tempTemplateAttrs, $template;
4320
4321           content = denormalizeTemplate(content);
4322
4323           if (replace) {
4324             $template = jqLite('<div>' + trim(content) + '</div>').contents();
4325             compileNode = $template[0];
4326
4327             if ($template.length != 1 || compileNode.nodeType !== 1) {
4328               throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
4329             }
4330
4331             tempTemplateAttrs = {$attr: {}};
4332             replaceWith($rootElement, $compileNode, compileNode);
4333             collectDirectives(compileNode, directives, tempTemplateAttrs);
4334             mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
4335           } else {
4336             compileNode = beforeTemplateCompileNode;
4337             $compileNode.html(content);
4338           }
4339
4340           directives.unshift(derivedSyncDirective);
4341           afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn);
4342           afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn);
4343
4344
4345           while(linkQueue.length) {
4346             var controller = linkQueue.pop(),
4347                 linkRootElement = linkQueue.pop(),
4348                 beforeTemplateLinkNode = linkQueue.pop(),
4349                 scope = linkQueue.pop(),
4350                 linkNode = compileNode;
4351
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);
4356             }
4357
4358             afterTemplateNodeLinkFn(function() {
4359               beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
4360             }, scope, linkNode, $rootElement, controller);
4361           }
4362           linkQueue = null;
4363         }).
4364         error(function(response, code, headers, config) {
4365           throw Error('Failed to load template: ' + config.url);
4366         });
4367
4368       return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
4369         if (linkQueue) {
4370           linkQueue.push(scope);
4371           linkQueue.push(node);
4372           linkQueue.push(rootElement);
4373           linkQueue.push(controller);
4374         } else {
4375           afterTemplateNodeLinkFn(function() {
4376             beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
4377           }, scope, node, rootElement, controller);
4378         }
4379       };
4380     }
4381
4382
4383     /**
4384      * Sorting function for bound directives.
4385      */
4386     function byPriority(a, b) {
4387       return b.priority - a.priority;
4388     }
4389
4390
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));
4395       }
4396     }
4397
4398
4399     function addTextInterpolateDirective(directives, text) {
4400       var interpolateFn = $interpolate(text, true);
4401       if (interpolateFn) {
4402         directives.push({
4403           priority: 0,
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;
4411             });
4412           })
4413         });
4414       }
4415     }
4416
4417
4418     function addAttrInterpolateDirective(node, directives, value, name) {
4419       var interpolateFn = $interpolate(value, true);
4420
4421
4422       // no interpolation found -> ignore
4423       if (!interpolateFn) return;
4424
4425       directives.push({
4426         priority: 100,
4427         compile: valueFn(function(scope, element, attr) {
4428           var $$observers = (attr.$$observers || (attr.$$observers = {}));
4429
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);
4434           }
4435
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);
4441             });
4442         })
4443       });
4444     }
4445
4446
4447     /**
4448      * This is a special jqLite.replaceWith, which can replace items which
4449      * have no parents, provided that the containing jqLite collection is provided.
4450      *
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.
4456      */
4457     function replaceWith($rootElement, $element, newNode) {
4458       var oldNode = $element[0],
4459           parent = oldNode.parentNode,
4460           i, ii;
4461
4462       if ($rootElement) {
4463         for(i = 0, ii = $rootElement.length; i < ii; i++) {
4464           if ($rootElement[i] == oldNode) {
4465             $rootElement[i] = newNode;
4466             break;
4467           }
4468         }
4469       }
4470
4471       if (parent) {
4472         parent.replaceChild(newNode, oldNode);
4473       }
4474
4475       newNode[jqLite.expando] = oldNode[jqLite.expando];
4476       $element[0] = newNode;
4477     }
4478   }];
4479 }
4480
4481 var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
4482 /**
4483  * Converts all accepted directives format into proper directive name.
4484  * All of these will become 'myDirective':
4485  *   my:DiRective
4486  *   my-directive
4487  *   x-my-directive
4488  *   data-my:directive
4489  *
4490  * Also there is special case for Moz prefix starting with upper case letter.
4491  * @param name Name to normalize
4492  */
4493 function directiveNormalize(name) {
4494   return camelCase(name.replace(PREFIX_REGEXP, ''));
4495 }
4496
4497 /**
4498  * @ngdoc object
4499  * @name ng.$compile.directive.Attributes
4500  * @description
4501  *
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:
4505  *
4506  *          <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
4507  */
4508
4509 /**
4510  * @ngdoc property
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.
4515  */
4516
4517
4518 /**
4519  * @ngdoc function
4520  * @name ng.$compile.directive.Attributes#$set
4521  * @methodOf ng.$compile.directive.Attributes
4522  * @function
4523  *
4524  * @description
4525  * Set DOM element attribute value.
4526  *
4527  *
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.
4532  */
4533
4534
4535
4536 /**
4537  * Closure compiler type information
4538  */
4539
4540 function nodesetLinkingFn(
4541   /* angular.Scope */ scope,
4542   /* NodeList */ nodeList,
4543   /* Element */ rootElement,
4544   /* function(Function) */ boundTranscludeFn
4545 ){}
4546
4547 function directiveLinkingFn(
4548   /* nodesetLinkingFn */ nodesetLinkingFn,
4549   /* angular.Scope */ scope,
4550   /* Node */ node,
4551   /* Element */ rootElement,
4552   /* function(Function) */ boundTranscludeFn
4553 ){}
4554
4555 /**
4556  * @ngdoc object
4557  * @name ng.$controllerProvider
4558  * @description
4559  * The {@link ng.$controller $controller service} is used by Angular to create new
4560  * controllers.
4561  *
4562  * This provider allows controller registration via the
4563  * {@link ng.$controllerProvider#register register} method.
4564  */
4565 function $ControllerProvider() {
4566   var controllers = {};
4567
4568
4569   /**
4570    * @ngdoc function
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).
4576    */
4577   this.register = function(name, constructor) {
4578     if (isObject(name)) {
4579       extend(controllers, name)
4580     } else {
4581       controllers[name] = constructor;
4582     }
4583   };
4584
4585
4586   this.$get = ['$injector', '$window', function($injector, $window) {
4587
4588     /**
4589      * @ngdoc function
4590      * @name ng.$controller
4591      * @requires $injector
4592      *
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:
4596      *
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
4600      *
4601      * @param {Object} locals Injection locals for Controller.
4602      * @return {Object} Instance of given controller.
4603      *
4604      * @description
4605      * `$controller` service is responsible for instantiating controllers.
4606      *
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
4609      * BC version}.
4610      */
4611     return function(constructor, locals) {
4612       if(isString(constructor)) {
4613         var name = constructor;
4614         constructor = controllers.hasOwnProperty(name)
4615             ? controllers[name]
4616             : getter(locals.$scope, name, true) || getter($window, name, true);
4617
4618         assertArgFn(constructor, name, true);
4619       }
4620
4621       return $injector.instantiate(constructor, locals);
4622     };
4623   }];
4624 }
4625
4626 /**
4627  * @ngdoc object
4628  * @name ng.$document
4629  * @requires $window
4630  *
4631  * @description
4632  * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
4633  * element.
4634  */
4635 function $DocumentProvider(){
4636   this.$get = ['$window', function(window){
4637     return jqLite(window.document);
4638   }];
4639 }
4640
4641 /**
4642  * @ngdoc function
4643  * @name ng.$exceptionHandler
4644  * @requires $log
4645  *
4646  * @description
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.
4650  *
4651  * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
4652  * {@link ngMock.$exceptionHandler mock $exceptionHandler}
4653  *
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.
4657  */
4658 function $ExceptionHandlerProvider() {
4659   this.$get = ['$log', function($log){
4660     return function(exception, cause) {
4661       $log.error.apply($log, arguments);
4662     };
4663   }];
4664 }
4665
4666 /**
4667  * @ngdoc object
4668  * @name ng.$interpolateProvider
4669  * @function
4670  *
4671  * @description
4672  *
4673  * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
4674  */
4675 function $InterpolateProvider() {
4676   var startSymbol = '{{';
4677   var endSymbol = '}}';
4678
4679   /**
4680    * @ngdoc method
4681    * @name ng.$interpolateProvider#startSymbol
4682    * @methodOf ng.$interpolateProvider
4683    * @description
4684    * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
4685    *
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.
4688    */
4689   this.startSymbol = function(value){
4690     if (value) {
4691       startSymbol = value;
4692       return this;
4693     } else {
4694       return startSymbol;
4695     }
4696   };
4697
4698   /**
4699    * @ngdoc method
4700    * @name ng.$interpolateProvider#endSymbol
4701    * @methodOf ng.$interpolateProvider
4702    * @description
4703    * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
4704    *
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.
4707    */
4708   this.endSymbol = function(value){
4709     if (value) {
4710       endSymbol = value;
4711       return this;
4712     } else {
4713       return endSymbol;
4714     }
4715   };
4716
4717
4718   this.$get = ['$parse', function($parse) {
4719     var startSymbolLength = startSymbol.length,
4720         endSymbolLength = endSymbol.length;
4721
4722     /**
4723      * @ngdoc function
4724      * @name ng.$interpolate
4725      * @function
4726      *
4727      * @requires $parse
4728      *
4729      * @description
4730      *
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.
4735      *
4736      *
4737        <pre>
4738          var $interpolate = ...; // injected
4739          var exp = $interpolate('Hello {{name}}!');
4740          expect(exp({name:'Angular'}).toEqual('Hello Angular!');
4741        </pre>
4742      *
4743      *
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:
4750      *
4751      *    * `context`: an object against which any expressions embedded in the strings are evaluated
4752      *      against.
4753      *
4754      */
4755     function $interpolate(text, mustHaveExpression) {
4756       var startIndex,
4757           endIndex,
4758           index = 0,
4759           parts = [],
4760           length = text.length,
4761           hasInterpolation = false,
4762           fn,
4763           exp,
4764           concat = [];
4765
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)));
4771           fn.exp = exp;
4772           index = endIndex + endSymbolLength;
4773           hasInterpolation = true;
4774         } else {
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));
4777           index = length;
4778         }
4779       }
4780
4781       if (!(length = parts.length)) {
4782         // we added, nothing, must have been an empty string.
4783         parts.push('');
4784         length = 1;
4785       }
4786
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) {
4794                 part = '';
4795               } else if (typeof part != 'string') {
4796                 part = toJson(part);
4797               }
4798             }
4799             concat[i] = part;
4800           }
4801           return concat.join('');
4802         };
4803         fn.exp = text;
4804         fn.parts = parts;
4805         return fn;
4806       }
4807     }
4808
4809
4810     /**
4811      * @ngdoc method
4812      * @name ng.$interpolate#startSymbol
4813      * @methodOf ng.$interpolate
4814      * @description
4815      * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
4816      *
4817      * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
4818      * the symbol.
4819      *
4820      * @returns {string} start symbol.
4821      */
4822     $interpolate.startSymbol = function() {
4823       return startSymbol;
4824     }
4825
4826
4827     /**
4828      * @ngdoc method
4829      * @name ng.$interpolate#endSymbol
4830      * @methodOf ng.$interpolate
4831      * @description
4832      * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
4833      *
4834      * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
4835      * the symbol.
4836      *
4837      * @returns {string} start symbol.
4838      */
4839     $interpolate.endSymbol = function() {
4840       return endSymbol;
4841     }
4842
4843     return $interpolate;
4844   }];
4845 }
4846
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};
4851
4852
4853 /**
4854  * Encode path using encodeUriSegment, ignoring forward slashes
4855  *
4856  * @param {string} path Path to encode
4857  * @returns {string}
4858  */
4859 function encodePath(path) {
4860   var segments = path.split('/'),
4861       i = segments.length;
4862
4863   while (i--) {
4864     segments[i] = encodeUriSegment(segments[i]);
4865   }
4866
4867   return segments.join('/');
4868 }
4869
4870 function stripHash(url) {
4871   return url.split('#')[0];
4872 }
4873
4874
4875 function matchUrl(url, obj) {
4876   var match = URL_MATCH.exec(url);
4877
4878   match = {
4879       protocol: match[1],
4880       host: match[3],
4881       port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
4882       path: match[6] || '/',
4883       search: match[8],
4884       hash: match[10]
4885     };
4886
4887   if (obj) {
4888     obj.$$protocol = match.protocol;
4889     obj.$$host = match.host;
4890     obj.$$port = match.port;
4891   }
4892
4893   return match;
4894 }
4895
4896
4897 function composeProtocolHostPort(protocol, host, port) {
4898   return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
4899 }
4900
4901
4902 function pathPrefixFromBase(basePath) {
4903   return basePath.substr(0, basePath.lastIndexOf('/'));
4904 }
4905
4906
4907 function convertToHtml5Url(url, basePath, hashPrefix) {
4908   var match = matchUrl(url);
4909
4910   // already html5 url
4911   if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
4912       match.hash.indexOf(hashPrefix) !== 0) {
4913     return url;
4914   // convert hashbang url -> html5 url
4915   } else {
4916     return composeProtocolHostPort(match.protocol, match.host, match.port) +
4917            pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
4918   }
4919 }
4920
4921
4922 function convertToHashbangUrl(url, basePath, hashPrefix) {
4923   var match = matchUrl(url);
4924
4925   // already hashbang url
4926   if (decodeURIComponent(match.path) == basePath) {
4927     return url;
4928   // convert html5 url -> hashbang url
4929   } else {
4930     var search = match.search && '?' + match.search || '',
4931         hash = match.hash && '#' + match.hash || '',
4932         pathPrefix = pathPrefixFromBase(basePath),
4933         path = match.path.substr(pathPrefix.length);
4934
4935     if (match.path.indexOf(pathPrefix) !== 0) {
4936       throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
4937     }
4938
4939     return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
4940            '#' + hashPrefix + path + search + hash;
4941   }
4942 }
4943
4944
4945 /**
4946  * LocationUrl represents an url
4947  * This object is exposed as $location service when HTML5 mode is enabled and supported
4948  *
4949  * @constructor
4950  * @param {string} url HTML5 url
4951  * @param {string} pathPrefix
4952  */
4953 function LocationUrl(url, pathPrefix, appBaseUrl) {
4954   pathPrefix = pathPrefix || '';
4955
4956   /**
4957    * Parse given html5 (regular) url string into properties
4958    * @param {string} newAbsoluteUrl HTML5 url
4959    * @private
4960    */
4961   this.$$parse = function(newAbsoluteUrl) {
4962     var match = matchUrl(newAbsoluteUrl, this);
4963
4964     if (match.path.indexOf(pathPrefix) !== 0) {
4965       throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
4966     }
4967
4968     this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
4969     this.$$search = parseKeyValue(match.search);
4970     this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
4971
4972     this.$$compose();
4973   };
4974
4975   /**
4976    * Compose url and update `absUrl` property
4977    * @private
4978    */
4979   this.$$compose = function() {
4980     var search = toKeyValue(this.$$search),
4981         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
4982
4983     this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
4984     this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
4985                     pathPrefix + this.$$url;
4986   };
4987
4988
4989   this.$$rewriteAppUrl = function(absoluteLinkUrl) {
4990     if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
4991       return absoluteLinkUrl;
4992     }
4993   }
4994
4995
4996   this.$$parse(url);
4997 }
4998
4999
5000 /**
5001  * LocationHashbangUrl represents url
5002  * This object is exposed as $location service when html5 history api is disabled or not supported
5003  *
5004  * @constructor
5005  * @param {string} url Legacy url
5006  * @param {string} hashPrefix Prefix for hash part (containing path and search)
5007  */
5008 function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
5009   var basePath;
5010
5011   /**
5012    * Parse given hashbang url into properties
5013    * @param {string} url Hashbang url
5014    * @private
5015    */
5016   this.$$parse = function(url) {
5017     var match = matchUrl(url, this);
5018
5019
5020     if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
5021       throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
5022     }
5023
5024     basePath = match.path + (match.search ? '?' + match.search : '');
5025     match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
5026     if (match[1]) {
5027       this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
5028     } else {
5029       this.$$path = '';
5030     }
5031
5032     this.$$search = parseKeyValue(match[3]);
5033     this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
5034
5035     this.$$compose();
5036   };
5037
5038   /**
5039    * Compose hashbang url and update `absUrl` property
5040    * @private
5041    */
5042   this.$$compose = function() {
5043     var search = toKeyValue(this.$$search),
5044         hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
5045
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 : '');
5049   };
5050
5051   this.$$rewriteAppUrl = function(absoluteLinkUrl) {
5052     if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
5053       return absoluteLinkUrl;
5054     }
5055   }
5056
5057
5058   this.$$parse(url);
5059 }
5060
5061
5062 LocationUrl.prototype = {
5063
5064   /**
5065    * Has any change been replacing ?
5066    * @private
5067    */
5068   $$replace: false,
5069
5070   /**
5071    * @ngdoc method
5072    * @name ng.$location#absUrl
5073    * @methodOf ng.$location
5074    *
5075    * @description
5076    * This method is getter only.
5077    *
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}.
5080    *
5081    * @return {string} full url
5082    */
5083   absUrl: locationGetter('$$absUrl'),
5084
5085   /**
5086    * @ngdoc method
5087    * @name ng.$location#url
5088    * @methodOf ng.$location
5089    *
5090    * @description
5091    * This method is getter / setter.
5092    *
5093    * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
5094    *
5095    * Change path, search and hash, when called with parameter and return `$location`.
5096    *
5097    * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
5098    * @return {string} url
5099    */
5100   url: function(url, replace) {
5101     if (isUndefined(url))
5102       return this.$$url;
5103
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);
5108
5109     return this;
5110   },
5111
5112   /**
5113    * @ngdoc method
5114    * @name ng.$location#protocol
5115    * @methodOf ng.$location
5116    *
5117    * @description
5118    * This method is getter only.
5119    *
5120    * Return protocol of current url.
5121    *
5122    * @return {string} protocol of current url
5123    */
5124   protocol: locationGetter('$$protocol'),
5125
5126   /**
5127    * @ngdoc method
5128    * @name ng.$location#host
5129    * @methodOf ng.$location
5130    *
5131    * @description
5132    * This method is getter only.
5133    *
5134    * Return host of current url.
5135    *
5136    * @return {string} host of current url.
5137    */
5138   host: locationGetter('$$host'),
5139
5140   /**
5141    * @ngdoc method
5142    * @name ng.$location#port
5143    * @methodOf ng.$location
5144    *
5145    * @description
5146    * This method is getter only.
5147    *
5148    * Return port of current url.
5149    *
5150    * @return {Number} port
5151    */
5152   port: locationGetter('$$port'),
5153
5154   /**
5155    * @ngdoc method
5156    * @name ng.$location#path
5157    * @methodOf ng.$location
5158    *
5159    * @description
5160    * This method is getter / setter.
5161    *
5162    * Return path of current url when called without any parameter.
5163    *
5164    * Change path when called with parameter and return `$location`.
5165    *
5166    * Note: Path should always begin with forward slash (/), this method will add the forward slash
5167    * if it is missing.
5168    *
5169    * @param {string=} path New path
5170    * @return {string} path
5171    */
5172   path: locationGetterSetter('$$path', function(path) {
5173     return path.charAt(0) == '/' ? path : '/' + path;
5174   }),
5175
5176   /**
5177    * @ngdoc method
5178    * @name ng.$location#search
5179    * @methodOf ng.$location
5180    *
5181    * @description
5182    * This method is getter / setter.
5183    *
5184    * Return search part (as object) of current url when called without any parameter.
5185    *
5186    * Change search part when called with parameter and return `$location`.
5187    *
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.
5191    *
5192    * @return {string} search
5193    */
5194   search: function(search, paramValue) {
5195     if (isUndefined(search))
5196       return this.$$search;
5197
5198     if (isDefined(paramValue)) {
5199       if (paramValue === null) {
5200         delete this.$$search[search];
5201       } else {
5202         this.$$search[search] = paramValue;
5203       }
5204     } else {
5205       this.$$search = isString(search) ? parseKeyValue(search) : search;
5206     }
5207
5208     this.$$compose();
5209     return this;
5210   },
5211
5212   /**
5213    * @ngdoc method
5214    * @name ng.$location#hash
5215    * @methodOf ng.$location
5216    *
5217    * @description
5218    * This method is getter / setter.
5219    *
5220    * Return hash fragment when called without any parameter.
5221    *
5222    * Change hash fragment when called with parameter and return `$location`.
5223    *
5224    * @param {string=} hash New hash fragment
5225    * @return {string} hash
5226    */
5227   hash: locationGetterSetter('$$hash', identity),
5228
5229   /**
5230    * @ngdoc method
5231    * @name ng.$location#replace
5232    * @methodOf ng.$location
5233    *
5234    * @description
5235    * If called, all changes to $location during current `$digest` will be replacing current history
5236    * record, instead of adding new one.
5237    */
5238   replace: function() {
5239     this.$$replace = true;
5240     return this;
5241   }
5242 };
5243
5244 LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
5245
5246 function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
5247   LocationHashbangUrl.apply(this, arguments);
5248
5249
5250   this.$$rewriteAppUrl = function(absoluteLinkUrl) {
5251     if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
5252       return appBaseUrl + baseExtra + '#' + hashPrefix  + absoluteLinkUrl.substr(appBaseUrl.length);
5253     }
5254   }
5255 }
5256
5257 LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
5258
5259 function locationGetter(property) {
5260   return function() {
5261     return this[property];
5262   };
5263 }
5264
5265
5266 function locationGetterSetter(property, preprocess) {
5267   return function(value) {
5268     if (isUndefined(value))
5269       return this[property];
5270
5271     this[property] = preprocess(value);
5272     this.$$compose();
5273
5274     return this;
5275   };
5276 }
5277
5278
5279 /**
5280  * @ngdoc object
5281  * @name ng.$location
5282  *
5283  * @requires $browser
5284  * @requires $sniffer
5285  * @requires $rootElement
5286  *
5287  * @description
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.
5292  *
5293  * **The $location service:**
5294  *
5295  * - Exposes the current URL in the browser address bar, so you can
5296  *   - Watch and observe the URL.
5297  *   - Change 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).
5303  *
5304  * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
5305  * Services: Using $location}
5306  */
5307
5308 /**
5309  * @ngdoc object
5310  * @name ng.$locationProvider
5311  * @description
5312  * Use the `$locationProvider` to configure how the application deep linking paths are stored.
5313  */
5314 function $LocationProvider(){
5315   var hashPrefix = '',
5316       html5Mode = false;
5317
5318   /**
5319    * @ngdoc property
5320    * @name ng.$locationProvider#hashPrefix
5321    * @methodOf ng.$locationProvider
5322    * @description
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
5325    */
5326   this.hashPrefix = function(prefix) {
5327     if (isDefined(prefix)) {
5328       hashPrefix = prefix;
5329       return this;
5330     } else {
5331       return hashPrefix;
5332     }
5333   };
5334
5335   /**
5336    * @ngdoc property
5337    * @name ng.$locationProvider#html5Mode
5338    * @methodOf ng.$locationProvider
5339    * @description
5340    * @param {string=} mode Use HTML5 strategy if available.
5341    * @returns {*} current value if used as getter or itself (chaining) if used as setter
5342    */
5343   this.html5Mode = function(mode) {
5344     if (isDefined(mode)) {
5345       html5Mode = mode;
5346       return this;
5347     } else {
5348       return html5Mode;
5349     }
5350   };
5351
5352   this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
5353       function( $rootScope,   $browser,   $sniffer,   $rootElement) {
5354     var $location,
5355         basePath,
5356         pathPrefix,
5357         initUrl = $browser.url(),
5358         initUrlParts = matchUrl(initUrl),
5359         appBaseUrl;
5360
5361     if (html5Mode) {
5362       basePath = $browser.baseHref() || '/';
5363       pathPrefix = pathPrefixFromBase(basePath);
5364       appBaseUrl =
5365           composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
5366           pathPrefix + '/';
5367
5368       if ($sniffer.history) {
5369         $location = new LocationUrl(
5370           convertToHtml5Url(initUrl, basePath, hashPrefix),
5371           pathPrefix, appBaseUrl);
5372       } else {
5373         $location = new LocationHashbangInHtml5Url(
5374           convertToHashbangUrl(initUrl, basePath, hashPrefix),
5375           hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
5376       }
5377     } else {
5378       appBaseUrl =
5379           composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
5380           (initUrlParts.path || '') +
5381           (initUrlParts.search ? ('?' + initUrlParts.search) : '') +
5382           '#' + hashPrefix + '/';
5383
5384       $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
5385     }
5386
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
5390
5391       if (event.ctrlKey || event.metaKey || event.which == 2) return;
5392
5393       var elm = jqLite(event.target);
5394
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;
5399       }
5400
5401       var absHref = elm.prop('href'),
5402           rewrittenUrl = $location.$$rewriteAppUrl(absHref);
5403
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;
5411       }
5412     });
5413
5414
5415     // rewrite hashbang url <> html5 url
5416     if ($location.absUrl() != initUrl) {
5417       $browser.url($location.absUrl(), true);
5418     }
5419
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();
5425
5426           $location.$$parse(newUrl);
5427           afterLocationChange(oldUrl);
5428         });
5429         if (!$rootScope.$$phase) $rootScope.$digest();
5430       }
5431     });
5432
5433     // update browser
5434     var changeCounter = 0;
5435     $rootScope.$watch(function $locationWatch() {
5436       var oldUrl = $browser.url();
5437
5438       if (!changeCounter || oldUrl != $location.absUrl()) {
5439         changeCounter++;
5440         $rootScope.$evalAsync(function() {
5441           if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
5442               defaultPrevented) {
5443             $location.$$parse(oldUrl);
5444           } else {
5445             $browser.url($location.absUrl(), $location.$$replace);
5446             $location.$$replace = false;
5447             afterLocationChange(oldUrl);
5448           }
5449         });
5450       }
5451
5452       return changeCounter;
5453     });
5454
5455     return $location;
5456
5457     function afterLocationChange(oldUrl) {
5458       $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
5459     }
5460 }];
5461 }
5462
5463 /**
5464  * @ngdoc object
5465  * @name ng.$log
5466  * @requires $window
5467  *
5468  * @description
5469  * Simple service for logging. Default implementation writes the message
5470  * into the browser's console (if present).
5471  *
5472  * The main purpose of this service is to simplify debugging and troubleshooting.
5473  *
5474  * @example
5475    <example>
5476      <file name="script.js">
5477        function LogCtrl($scope, $log) {
5478          $scope.$log = $log;
5479          $scope.message = 'Hello World!';
5480        }
5481      </file>
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>
5485          Message:
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>
5491        </div>
5492      </file>
5493    </example>
5494  */
5495
5496 function $LogProvider(){
5497   this.$get = ['$window', function($window){
5498     return {
5499       /**
5500        * @ngdoc method
5501        * @name ng.$log#log
5502        * @methodOf ng.$log
5503        *
5504        * @description
5505        * Write a log message
5506        */
5507       log: consoleLog('log'),
5508
5509       /**
5510        * @ngdoc method
5511        * @name ng.$log#warn
5512        * @methodOf ng.$log
5513        *
5514        * @description
5515        * Write a warning message
5516        */
5517       warn: consoleLog('warn'),
5518
5519       /**
5520        * @ngdoc method
5521        * @name ng.$log#info
5522        * @methodOf ng.$log
5523        *
5524        * @description
5525        * Write an information message
5526        */
5527       info: consoleLog('info'),
5528
5529       /**
5530        * @ngdoc method
5531        * @name ng.$log#error
5532        * @methodOf ng.$log
5533        *
5534        * @description
5535        * Write an error message
5536        */
5537       error: consoleLog('error')
5538     };
5539
5540     function formatError(arg) {
5541       if (arg instanceof Error) {
5542         if (arg.stack) {
5543           arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
5544               ? 'Error: ' + arg.message + '\n' + arg.stack
5545               : arg.stack;
5546         } else if (arg.sourceURL) {
5547           arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
5548         }
5549       }
5550       return arg;
5551     }
5552
5553     function consoleLog(type) {
5554       var console = $window.console || {},
5555           logFn = console[type] || console.log || noop;
5556
5557       if (logFn.apply) {
5558         return function() {
5559           var args = [];
5560           forEach(arguments, function(arg) {
5561             args.push(formatError(arg));
5562           });
5563           return logFn.apply(console, args);
5564         };
5565       }
5566
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) {
5570         logFn(arg1, arg2);
5571       }
5572     }
5573   }];
5574 }
5575
5576 var OPERATORS = {
5577     'null':function(){return null;},
5578     'true':function(){return true;},
5579     'false':function(){return false;},
5580     undefined:noop,
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);},
5587     '=':noop,
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);}
5600 };
5601 var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
5602
5603 function lex(text, csp){
5604   var tokens = [],
5605       token,
5606       index = 0,
5607       json = [],
5608       ch,
5609       lastCh = ':'; // can start regexp
5610
5611   while (index < text.length) {
5612     ch = text.charAt(index);
5613     if (is('"\'')) {
5614       readString(ch);
5615     } else if (isNumber(ch) || is('.') && isNumber(peek())) {
5616       readNumber();
5617     } else if (isIdent(ch)) {
5618       readIdent();
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;
5623       }
5624     } else if (is('(){}[].,;:')) {
5625       tokens.push({
5626         index:index,
5627         text:ch,
5628         json:(was(':[,') && is('{[')) || is('}]:,')
5629       });
5630       if (is('{[')) json.unshift(ch);
5631       if (is('}]')) json.shift();
5632       index++;
5633     } else if (isWhitespace(ch)) {
5634       index++;
5635       continue;
5636     } else {
5637       var ch2 = ch + peek(),
5638           fn = OPERATORS[ch],
5639           fn2 = OPERATORS[ch2];
5640       if (fn2) {
5641         tokens.push({index:index, text:ch2, fn:fn2});
5642         index += 2;
5643       } else if (fn) {
5644         tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
5645         index += 1;
5646       } else {
5647         throwError("Unexpected next character ", index, index+1);
5648       }
5649     }
5650     lastCh = ch;
5651   }
5652   return tokens;
5653
5654   function is(chars) {
5655     return chars.indexOf(ch) != -1;
5656   }
5657
5658   function was(chars) {
5659     return chars.indexOf(lastCh) != -1;
5660   }
5661
5662   function peek() {
5663     return index + 1 < text.length ? text.charAt(index + 1) : false;
5664   }
5665   function isNumber(ch) {
5666     return '0' <= ch && ch <= '9';
5667   }
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
5671   }
5672   function isIdent(ch) {
5673     return 'a' <= ch && ch <= 'z' ||
5674            'A' <= ch && ch <= 'Z' ||
5675            '_' == ch || ch == '$';
5676   }
5677   function isExpOperator(ch) {
5678     return ch == '-' || ch == '+' || isNumber(ch);
5679   }
5680
5681   function throwError(error, start, end) {
5682     end = end || index;
5683     throw Error("Lexer Error: " + error + " at column" +
5684         (isDefined(start)
5685             ? "s " + start +  "-" + index + " [" + text.substring(start, end) + "]"
5686             : " " + end) +
5687         " in expression [" + text + "].");
5688   }
5689
5690   function readNumber() {
5691     var number = "";
5692     var start = index;
5693     while (index < text.length) {
5694       var ch = lowercase(text.charAt(index));
5695       if (ch == '.' || isNumber(ch)) {
5696         number += ch;
5697       } else {
5698         var peekCh = peek();
5699         if (ch == 'e' && isExpOperator(peekCh)) {
5700           number += ch;
5701         } else if (isExpOperator(ch) &&
5702             peekCh && isNumber(peekCh) &&
5703             number.charAt(number.length - 1) == 'e') {
5704           number += ch;
5705         } else if (isExpOperator(ch) &&
5706             (!peekCh || !isNumber(peekCh)) &&
5707             number.charAt(number.length - 1) == 'e') {
5708           throwError('Invalid exponent');
5709         } else {
5710           break;
5711         }
5712       }
5713       index++;
5714     }
5715     number = 1 * number;
5716     tokens.push({index:start, text:number, json:true,
5717       fn:function() {return number;}});
5718   }
5719   function readIdent() {
5720     var ident = "",
5721         start = index,
5722         lastDot, peekIndex, methodName;
5723
5724     while (index < text.length) {
5725       var ch = text.charAt(index);
5726       if (ch == '.' || isIdent(ch) || isNumber(ch)) {
5727         if (ch == '.') lastDot = index;
5728         ident += ch;
5729       } else {
5730         break;
5731       }
5732       index++;
5733     }
5734
5735     //check if this is not a method invocation and if it is back out to last dot
5736     if (lastDot) {
5737       peekIndex = index;
5738       while(peekIndex < text.length) {
5739         var ch = text.charAt(peekIndex);
5740         if (ch == '(') {
5741           methodName = ident.substr(lastDot - start + 1);
5742           ident = ident.substr(0, lastDot - start);
5743           index = peekIndex;
5744           break;
5745         }
5746         if(isWhitespace(ch)) {
5747           peekIndex++;
5748         } else {
5749           break;
5750         }
5751       }
5752     }
5753
5754
5755     var token = {
5756       index:start,
5757       text:ident
5758     };
5759
5760     if (OPERATORS.hasOwnProperty(ident)) {
5761       token.fn = token.json = OPERATORS[ident];
5762     } else {
5763       var getter = getterFn(ident, csp);
5764       token.fn = extend(function(self, locals) {
5765         return (getter(self, locals));
5766       }, {
5767         assign: function(self, value) {
5768           return setter(self, ident, value);
5769         }
5770       });
5771     }
5772
5773     tokens.push(token);
5774
5775     if (methodName) {
5776       tokens.push({
5777         index:lastDot,
5778         text: '.',
5779         json: false
5780       });
5781       tokens.push({
5782         index: lastDot + 1,
5783         text: methodName,
5784         json: false
5785       });
5786     }
5787   }
5788
5789   function readString(quote) {
5790     var start = index;
5791     index++;
5792     var string = "";
5793     var rawString = quote;
5794     var escape = false;
5795     while (index < text.length) {
5796       var ch = text.charAt(index);
5797       rawString += ch;
5798       if (escape) {
5799         if (ch == 'u') {
5800           var hex = text.substring(index + 1, index + 5);
5801           if (!hex.match(/[\da-f]{4}/i))
5802             throwError( "Invalid unicode escape [\\u" + hex + "]");
5803           index += 4;
5804           string += String.fromCharCode(parseInt(hex, 16));
5805         } else {
5806           var rep = ESCAPE[ch];
5807           if (rep) {
5808             string += rep;
5809           } else {
5810             string += ch;
5811           }
5812         }
5813         escape = false;
5814       } else if (ch == '\\') {
5815         escape = true;
5816       } else if (ch == quote) {
5817         index++;
5818         tokens.push({
5819           index:start,
5820           text:rawString,
5821           string:string,
5822           json:true,
5823           fn:function() { return string; }
5824         });
5825         return;
5826       } else {
5827         string += ch;
5828       }
5829       index++;
5830     }
5831     throwError("Unterminated quote", start);
5832   }
5833 }
5834
5835 /////////////////////////////////////////
5836
5837 function parser(text, json, $filter, csp){
5838   var ZERO = valueFn(0),
5839       value,
5840       tokens = lex(text, csp),
5841       assignment = _assignment,
5842       functionCall = _functionCall,
5843       fieldAccess = _fieldAccess,
5844       objectIndex = _objectIndex,
5845       filterChain = _filterChain;
5846
5847   if(json){
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;
5851     functionCall =
5852       fieldAccess =
5853       objectIndex =
5854       filterChain =
5855         function() { throwError("is not valid json", {text:text, index:0}); };
5856     value = primary();
5857   } else {
5858     value = statements();
5859   }
5860   if (tokens.length !== 0) {
5861     throwError("is an unexpected token", tokens[0]);
5862   }
5863   return value;
5864
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) + "].");
5871   }
5872
5873   function peekToken() {
5874     if (tokens.length === 0)
5875       throw Error("Unexpected end of expression: " + text);
5876     return tokens[0];
5877   }
5878
5879   function peek(e1, e2, e3, e4) {
5880     if (tokens.length > 0) {
5881       var token = tokens[0];
5882       var t = token.text;
5883       if (t==e1 || t==e2 || t==e3 || t==e4 ||
5884           (!e1 && !e2 && !e3 && !e4)) {
5885         return token;
5886       }
5887     }
5888     return false;
5889   }
5890
5891   function expect(e1, e2, e3, e4){
5892     var token = peek(e1, e2, e3, e4);
5893     if (token) {
5894       if (json && !token.json) {
5895         throwError("is not valid json", token);
5896       }
5897       tokens.shift();
5898       return token;
5899     }
5900     return false;
5901   }
5902
5903   function consume(e1){
5904     if (!expect(e1)) {
5905       throwError("is unexpected, expecting [" + e1 + "]", peek());
5906     }
5907   }
5908
5909   function unaryFn(fn, right) {
5910     return function(self, locals) {
5911       return fn(self, locals, right);
5912     };
5913   }
5914
5915   function binaryFn(left, fn, right) {
5916     return function(self, locals) {
5917       return fn(self, locals, left, right);
5918     };
5919   }
5920
5921   function statements() {
5922     var statements = [];
5923     while(true) {
5924       if (tokens.length > 0 && !peek('}', ')', ';', ']'))
5925         statements.push(filterChain());
5926       if (!expect(';')) {
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
5930           ? statements[0]
5931           : function(self, locals){
5932             var value;
5933             for ( var i = 0; i < statements.length; i++) {
5934               var statement = statements[i];
5935               if (statement)
5936                 value = statement(self, locals);
5937             }
5938             return value;
5939           };
5940       }
5941     }
5942   }
5943
5944   function _filterChain() {
5945     var left = expression();
5946     var token;
5947     while(true) {
5948       if ((token = expect('|'))) {
5949         left = binaryFn(left, token.fn, filter());
5950       } else {
5951         return left;
5952       }
5953     }
5954   }
5955
5956   function filter() {
5957     var token = expect();
5958     var fn = $filter(token.text);
5959     var argsFn = [];
5960     while(true) {
5961       if ((token = expect(':'))) {
5962         argsFn.push(expression());
5963       } else {
5964         var fnInvoke = function(self, locals, input){
5965           var args = [input];
5966           for ( var i = 0; i < argsFn.length; i++) {
5967             args.push(argsFn[i](self, locals));
5968           }
5969           return fn.apply(self, args);
5970         };
5971         return function() {
5972           return fnInvoke;
5973         };
5974       }
5975     }
5976   }
5977
5978   function expression() {
5979     return assignment();
5980   }
5981
5982   function _assignment() {
5983     var left = logicalOR();
5984     var right;
5985     var token;
5986     if ((token = expect('='))) {
5987       if (!left.assign) {
5988         throwError("implies assignment but [" +
5989           text.substring(0, token.index) + "] can not be assigned to", token);
5990       }
5991       right = logicalOR();
5992       return function(self, locals){
5993         return left.assign(self, right(self, locals), locals);
5994       };
5995     } else {
5996       return left;
5997     }
5998   }
5999
6000   function logicalOR() {
6001     var left = logicalAND();
6002     var token;
6003     while(true) {
6004       if ((token = expect('||'))) {
6005         left = binaryFn(left, token.fn, logicalAND());
6006       } else {
6007         return left;
6008       }
6009     }
6010   }
6011
6012   function logicalAND() {
6013     var left = equality();
6014     var token;
6015     if ((token = expect('&&'))) {
6016       left = binaryFn(left, token.fn, logicalAND());
6017     }
6018     return left;
6019   }
6020
6021   function equality() {
6022     var left = relational();
6023     var token;
6024     if ((token = expect('==','!='))) {
6025       left = binaryFn(left, token.fn, equality());
6026     }
6027     return left;
6028   }
6029
6030   function relational() {
6031     var left = additive();
6032     var token;
6033     if ((token = expect('<', '>', '<=', '>='))) {
6034       left = binaryFn(left, token.fn, relational());
6035     }
6036     return left;
6037   }
6038
6039   function additive() {
6040     var left = multiplicative();
6041     var token;
6042     while ((token = expect('+','-'))) {
6043       left = binaryFn(left, token.fn, multiplicative());
6044     }
6045     return left;
6046   }
6047
6048   function multiplicative() {
6049     var left = unary();
6050     var token;
6051     while ((token = expect('*','/','%'))) {
6052       left = binaryFn(left, token.fn, unary());
6053     }
6054     return left;
6055   }
6056
6057   function unary() {
6058     var token;
6059     if (expect('+')) {
6060       return primary();
6061     } else if ((token = expect('-'))) {
6062       return binaryFn(ZERO, token.fn, unary());
6063     } else if ((token = expect('!'))) {
6064       return unaryFn(token.fn, unary());
6065     } else {
6066       return primary();
6067     }
6068   }
6069
6070
6071   function primary() {
6072     var primary;
6073     if (expect('(')) {
6074       primary = filterChain();
6075       consume(')');
6076     } else if (expect('[')) {
6077       primary = arrayDeclaration();
6078     } else if (expect('{')) {
6079       primary = object();
6080     } else {
6081       var token = expect();
6082       primary = token.fn;
6083       if (!primary) {
6084         throwError("not a primary expression", token);
6085       }
6086     }
6087
6088     var next, context;
6089     while ((next = expect('(', '[', '.'))) {
6090       if (next.text === '(') {
6091         primary = functionCall(primary, context);
6092         context = null;
6093       } else if (next.text === '[') {
6094         context = primary;
6095         primary = objectIndex(primary);
6096       } else if (next.text === '.') {
6097         context = primary;
6098         primary = fieldAccess(primary);
6099       } else {
6100         throwError("IMPOSSIBLE");
6101       }
6102     }
6103     return primary;
6104   }
6105
6106   function _fieldAccess(object) {
6107     var field = expect().text;
6108     var getter = getterFn(field, csp);
6109     return extend(
6110         function(self, locals) {
6111           return getter(object(self, locals), locals);
6112         },
6113         {
6114           assign:function(self, value, locals) {
6115             return setter(object(self, locals), field, value);
6116           }
6117         }
6118     );
6119   }
6120
6121   function _objectIndex(obj) {
6122     var indexFn = expression();
6123     consume(']');
6124     return extend(
6125       function(self, locals){
6126         var o = obj(self, locals),
6127             i = indexFn(self, locals),
6128             v, p;
6129
6130         if (!o) return undefined;
6131         v = o[i];
6132         if (v && v.then) {
6133           p = v;
6134           if (!('$$v' in v)) {
6135             p.$$v = undefined;
6136             p.then(function(val) { p.$$v = val; });
6137           }
6138           v = v.$$v;
6139         }
6140         return v;
6141       }, {
6142         assign:function(self, value, locals){
6143           return obj(self, locals)[indexFn(self, locals)] = value;
6144         }
6145       });
6146   }
6147
6148   function _functionCall(fn, contextGetter) {
6149     var argsFn = [];
6150     if (peekToken().text != ')') {
6151       do {
6152         argsFn.push(expression());
6153       } while (expect(','));
6154     }
6155     consume(')');
6156     return function(self, locals){
6157       var args = [],
6158           context = contextGetter ? contextGetter(self, locals) : self;
6159
6160       for ( var i = 0; i < argsFn.length; i++) {
6161         args.push(argsFn[i](self, locals));
6162       }
6163       var fnPtr = fn(self, locals) || noop;
6164       // IE stupidity!
6165       return fnPtr.apply
6166           ? fnPtr.apply(context, args)
6167           : fnPtr(args[0], args[1], args[2], args[3], args[4]);
6168     };
6169   }
6170
6171   // This is used with json array declaration
6172   function arrayDeclaration () {
6173     var elementFns = [];
6174     if (peekToken().text != ']') {
6175       do {
6176         elementFns.push(expression());
6177       } while (expect(','));
6178     }
6179     consume(']');
6180     return function(self, locals){
6181       var array = [];
6182       for ( var i = 0; i < elementFns.length; i++) {
6183         array.push(elementFns[i](self, locals));
6184       }
6185       return array;
6186     };
6187   }
6188
6189   function object () {
6190     var keyValues = [];
6191     if (peekToken().text != '}') {
6192       do {
6193         var token = expect(),
6194         key = token.string || token.text;
6195         consume(":");
6196         var value = expression();
6197         keyValues.push({key:key, value:value});
6198       } while (expect(','));
6199     }
6200     consume('}');
6201     return function(self, locals){
6202       var object = {};
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;
6207       }
6208       return object;
6209     };
6210   }
6211 }
6212
6213 //////////////////////////////////////////////////
6214 // Parser helper functions
6215 //////////////////////////////////////////////////
6216
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];
6222     if (!propertyObj) {
6223       propertyObj = {};
6224       obj[key] = propertyObj;
6225     }
6226     obj = propertyObj;
6227   }
6228   obj[element.shift()] = setValue;
6229   return setValue;
6230 }
6231
6232 /**
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
6238  */
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('.');
6243   var key;
6244   var lastInstance = obj;
6245   var len = keys.length;
6246
6247   for (var i = 0; i < len; i++) {
6248     key = keys[i];
6249     if (obj) {
6250       obj = (lastInstance = obj)[key];
6251     }
6252   }
6253   if (!bindFnToScope && isFunction(obj)) {
6254     return bind(lastInstance, obj);
6255   }
6256   return obj;
6257 }
6258
6259 var getterFnCache = {};
6260
6261 /**
6262  * Implementation of the "Black Hole" variant from:
6263  * - http://jsperf.com/angularjs-parse-getter/4
6264  * - http://jsperf.com/path-evaluation-simplified/7
6265  */
6266 function cspSafeGetterFn(key0, key1, key2, key3, key4) {
6267   return function(scope, locals) {
6268     var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
6269         promise;
6270
6271     if (pathVal === null || pathVal === undefined) return pathVal;
6272
6273     pathVal = pathVal[key0];
6274     if (pathVal && pathVal.then) {
6275       if (!("$$v" in pathVal)) {
6276         promise = pathVal;
6277         promise.$$v = undefined;
6278         promise.then(function(val) { promise.$$v = val; });
6279       }
6280       pathVal = pathVal.$$v;
6281     }
6282     if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
6283
6284     pathVal = pathVal[key1];
6285     if (pathVal && pathVal.then) {
6286       if (!("$$v" in pathVal)) {
6287         promise = pathVal;
6288         promise.$$v = undefined;
6289         promise.then(function(val) { promise.$$v = val; });
6290       }
6291       pathVal = pathVal.$$v;
6292     }
6293     if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
6294
6295     pathVal = pathVal[key2];
6296     if (pathVal && pathVal.then) {
6297       if (!("$$v" in pathVal)) {
6298         promise = pathVal;
6299         promise.$$v = undefined;
6300         promise.then(function(val) { promise.$$v = val; });
6301       }
6302       pathVal = pathVal.$$v;
6303     }
6304     if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
6305
6306     pathVal = pathVal[key3];
6307     if (pathVal && pathVal.then) {
6308       if (!("$$v" in pathVal)) {
6309         promise = pathVal;
6310         promise.$$v = undefined;
6311         promise.then(function(val) { promise.$$v = val; });
6312       }
6313       pathVal = pathVal.$$v;
6314     }
6315     if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
6316
6317     pathVal = pathVal[key4];
6318     if (pathVal && pathVal.then) {
6319       if (!("$$v" in pathVal)) {
6320         promise = pathVal;
6321         promise.$$v = undefined;
6322         promise.then(function(val) { promise.$$v = val; });
6323       }
6324       pathVal = pathVal.$$v;
6325     }
6326     return pathVal;
6327   };
6328 };
6329
6330 function getterFn(path, csp) {
6331   if (getterFnCache.hasOwnProperty(path)) {
6332     return getterFnCache[path];
6333   }
6334
6335   var pathKeys = path.split('.'),
6336       pathKeysLength = pathKeys.length,
6337       fn;
6338
6339   if (csp) {
6340     fn = (pathKeysLength < 6)
6341         ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
6342         : function(scope, locals) {
6343           var i = 0, val
6344           do {
6345             val = cspSafeGetterFn(
6346                     pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
6347                   )(scope, locals);
6348
6349             locals = undefined; // clear after first iteration
6350             scope = val;
6351           } while (i < pathKeysLength);
6352           return val;
6353         }
6354   } else {
6355     var code = 'var l, fn, p;\n';
6356     forEach(pathKeys, function(key, index) {
6357       code += 'if(s === null || s === undefined) return s;\n' +
6358               'l=s;\n' +
6359               's='+ (index
6360                       // we simply dereference 's' on any .dot notation
6361                       ? 's'
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' +
6366                   ' p=s;\n' +
6367                   ' p.$$v = undefined;\n' +
6368                   ' p.then(function(v) {p.$$v=v;});\n' +
6369                   '}\n' +
6370                 ' s=s.$$v\n' +
6371               '}\n';
6372     });
6373     code += 'return s;';
6374     fn = Function('s', 'k', code); // s=scope, k=locals
6375     fn.toString = function() { return code; };
6376   }
6377
6378   return getterFnCache[path] = fn;
6379 }
6380
6381 ///////////////////////////////////
6382
6383 /**
6384  * @ngdoc function
6385  * @name ng.$parse
6386  * @function
6387  *
6388  * @description
6389  *
6390  * Converts Angular {@link guide/expression expression} into a function.
6391  *
6392  * <pre>
6393  *   var getter = $parse('user.name');
6394  *   var setter = getter.assign;
6395  *   var context = {user:{name:'angular'}};
6396  *   var locals = {user:{name:'local'}};
6397  *
6398  *   expect(getter(context)).toEqual('angular');
6399  *   setter(context, 'newValue');
6400  *   expect(context.user.name).toEqual('newValue');
6401  *   expect(getter(context, locals)).toEqual('local');
6402  * </pre>
6403  *
6404  *
6405  * @param {string} expression String expression to compile.
6406  * @returns {function(context, locals)} a function which represents the compiled expression:
6407  *
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`.
6411  *
6412  *    The return function also has an `assign` property, if the expression is assignable, which
6413  *    allows one to set values to expressions.
6414  *
6415  */
6416 function $ParseProvider() {
6417   var cache = {};
6418   this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
6419     return function(exp) {
6420       switch(typeof exp) {
6421         case 'string':
6422           return cache.hasOwnProperty(exp)
6423             ? cache[exp]
6424             : cache[exp] =  parser(exp, false, $filter, $sniffer.csp);
6425         case 'function':
6426           return exp;
6427         default:
6428           return noop;
6429       }
6430     };
6431   }];
6432 }
6433
6434 /**
6435  * @ngdoc service
6436  * @name ng.$q
6437  * @requires $rootScope
6438  *
6439  * @description
6440  * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
6441  *
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.
6445  *
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.
6448  *
6449  * <pre>
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).
6452  *
6453  *   function asyncGreet(name) {
6454  *     var deferred = $q.defer();
6455  *
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 + '!');
6462  *         } else {
6463  *           deferred.reject('Greeting ' + name + ' is not allowed.');
6464  *         }
6465  *       });
6466  *     }, 1000);
6467  *
6468  *     return deferred.promise;
6469  *   }
6470  *
6471  *   var promise = asyncGreet('Robin Hood');
6472  *   promise.then(function(greeting) {
6473  *     alert('Success: ' + greeting);
6474  *   }, function(reason) {
6475  *     alert('Failed: ' + reason);
6476  *   );
6477  * </pre>
6478  *
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).
6482  *
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.
6487  *
6488  *
6489  * # The Deferred API
6490  *
6491  * A new instance of deferred is constructed by calling `$q.defer()`.
6492  *
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.
6495  *
6496  * **Methods**
6497  *
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`.
6502  *
6503  * **Properties**
6504  *
6505  * - promise – `{Promise}` – promise object associated with this deferred.
6506  *
6507  *
6508  * # The Promise API
6509  *
6510  * A new promise instance is created when a deferred instance is created and can be retrieved by
6511  * calling `deferred.promise`.
6512  *
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.
6515  *
6516  * **Methods**
6517  *
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.
6521  *
6522  *   This method *returns a new promise* which is resolved or rejected via the return value of the
6523  *   `successCallback` or `errorCallback`.
6524  *
6525  *
6526  * # Chaining promises
6527  *
6528  * Because calling `then` api of a promise returns a new derived promise, it is easily possible
6529  * to create a chain of promises:
6530  *
6531  * <pre>
6532  *   promiseB = promiseA.then(function(result) {
6533  *     return result + 1;
6534  *   });
6535  *
6536  *   // promiseB will be resolved immediately after promiseA is resolved and it's value will be
6537  *   // the result of promiseA incremented by 1
6538  * </pre>
6539  *
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.
6544  *
6545  *
6546  * # Differences between Kris Kowal's Q and $q
6547  *
6548  *  There are three main differences:
6549  *
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.
6557  */
6558 function $QProvider() {
6559
6560   this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
6561     return qFactory(function(callback) {
6562       $rootScope.$evalAsync(callback);
6563     }, $exceptionHandler);
6564   }];
6565 }
6566
6567
6568 /**
6569  * Constructs a promise manager.
6570  *
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.
6575  */
6576 function qFactory(nextTick, exceptionHandler) {
6577
6578   /**
6579    * @ngdoc
6580    * @name ng.$q#defer
6581    * @methodOf ng.$q
6582    * @description
6583    * Creates a `Deferred` object which represents a task which will finish in the future.
6584    *
6585    * @returns {Deferred} Returns a new instance of deferred.
6586    */
6587   var defer = function() {
6588     var pending = [],
6589         value, deferred;
6590
6591     deferred = {
6592
6593       resolve: function(val) {
6594         if (pending) {
6595           var callbacks = pending;
6596           pending = undefined;
6597           value = ref(val);
6598
6599           if (callbacks.length) {
6600             nextTick(function() {
6601               var callback;
6602               for (var i = 0, ii = callbacks.length; i < ii; i++) {
6603                 callback = callbacks[i];
6604                 value.then(callback[0], callback[1]);
6605               }
6606             });
6607           }
6608         }
6609       },
6610
6611
6612       reject: function(reason) {
6613         deferred.resolve(reject(reason));
6614       },
6615
6616
6617       promise: {
6618         then: function(callback, errback) {
6619           var result = defer();
6620
6621           var wrappedCallback = function(value) {
6622             try {
6623               result.resolve((callback || defaultCallback)(value));
6624             } catch(e) {
6625               exceptionHandler(e);
6626               result.reject(e);
6627             }
6628           };
6629
6630           var wrappedErrback = function(reason) {
6631             try {
6632               result.resolve((errback || defaultErrback)(reason));
6633             } catch(e) {
6634               exceptionHandler(e);
6635               result.reject(e);
6636             }
6637           };
6638
6639           if (pending) {
6640             pending.push([wrappedCallback, wrappedErrback]);
6641           } else {
6642             value.then(wrappedCallback, wrappedErrback);
6643           }
6644
6645           return result.promise;
6646         }
6647       }
6648     };
6649
6650     return deferred;
6651   };
6652
6653
6654   var ref = function(value) {
6655     if (value && value.then) return value;
6656     return {
6657       then: function(callback) {
6658         var result = defer();
6659         nextTick(function() {
6660           result.resolve(callback(value));
6661         });
6662         return result.promise;
6663       }
6664     };
6665   };
6666
6667
6668   /**
6669    * @ngdoc
6670    * @name ng.$q#reject
6671    * @methodOf ng.$q
6672    * @description
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.
6676    *
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
6681    * `reject`.
6682    *
6683    * <pre>
6684    *   promiseB = promiseA.then(function(result) {
6685    *     // success: do something and resolve promiseB
6686    *     //          with the old or a new result
6687    *     return 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;
6695    *     }
6696    *     return $q.reject(reason);
6697    *   });
6698    * </pre>
6699    *
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`.
6702    */
6703   var reject = function(reason) {
6704     return {
6705       then: function(callback, errback) {
6706         var result = defer();
6707         nextTick(function() {
6708           result.resolve((errback || defaultErrback)(reason));
6709         });
6710         return result.promise;
6711       }
6712     };
6713   };
6714
6715
6716   /**
6717    * @ngdoc
6718    * @name ng.$q#when
6719    * @methodOf ng.$q
6720    * @description
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.
6724    *
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
6729    *   same rejection.
6730    */
6731   var when = function(value, callback, errback) {
6732     var result = defer(),
6733         done;
6734
6735     var wrappedCallback = function(value) {
6736       try {
6737         return (callback || defaultCallback)(value);
6738       } catch (e) {
6739         exceptionHandler(e);
6740         return reject(e);
6741       }
6742     };
6743
6744     var wrappedErrback = function(reason) {
6745       try {
6746         return (errback || defaultErrback)(reason);
6747       } catch (e) {
6748         exceptionHandler(e);
6749         return reject(e);
6750       }
6751     };
6752
6753     nextTick(function() {
6754       ref(value).then(function(value) {
6755         if (done) return;
6756         done = true;
6757         result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
6758       }, function(reason) {
6759         if (done) return;
6760         done = true;
6761         result.resolve(wrappedErrback(reason));
6762       });
6763     });
6764
6765     return result.promise;
6766   };
6767
6768
6769   function defaultCallback(value) {
6770     return value;
6771   }
6772
6773
6774   function defaultErrback(reason) {
6775     return reject(reason);
6776   }
6777
6778
6779   /**
6780    * @ngdoc
6781    * @name ng.$q#all
6782    * @methodOf ng.$q
6783    * @description
6784    * Combines multiple promises into a single promise that is resolved when all of the input
6785    * promises are resolved.
6786    *
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
6791    *   same rejection.
6792    */
6793   function all(promises) {
6794     var deferred = defer(),
6795         counter = promises.length,
6796         results = [];
6797
6798     if (counter) {
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);
6807         });
6808       });
6809     } else {
6810       deferred.resolve(results);
6811     }
6812
6813     return deferred.promise;
6814   }
6815
6816   return {
6817     defer: defer,
6818     reject: reject,
6819     when: when,
6820     all: all
6821   };
6822 }
6823
6824 /**
6825  * @ngdoc object
6826  * @name ng.$routeProvider
6827  * @function
6828  *
6829  * @description
6830  *
6831  * Used for configuring routes. See {@link ng.$route $route} for an example.
6832  */
6833 function $RouteProvider(){
6834   var routes = {};
6835
6836   /**
6837    * @ngdoc method
6838    * @name ng.$routeProvider#when
6839    * @methodOf ng.$routeProvider
6840    *
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
6844    *    route definition.
6845    * @param {Object} route Mapping information to be assigned to `$route.current` on route
6846    *    match.
6847    *
6848    *    Object properties:
6849    *
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:
6863    *
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.
6869    *
6870    *    - `redirectTo` – {(string|function())=} – value to update
6871    *      {@link ng.$location $location} path with and trigger route redirection.
6872    *
6873    *      If `redirectTo` is a function, it will be called with the following parameters:
6874    *
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()`
6879    *
6880    *      The custom `redirectTo` function is expected to return a string which will be used
6881    *      to update `$location.path()` and `$location.search()`.
6882    *
6883    *    - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
6884    *    changes.
6885    *
6886    *      If the option is set to `false` and url in the browser changes, then
6887    *      `$routeUpdate` event is broadcasted on the root scope.
6888    *
6889    * @returns {Object} self
6890    *
6891    * @description
6892    * Adds a new route definition to the `$route` service.
6893    */
6894   this.when = function(path, route) {
6895     routes[path] = extend({reloadOnSearch: true}, route);
6896
6897     // create redirection for trailing slashes
6898     if (path) {
6899       var redirectPath = (path[path.length-1] == '/')
6900           ? path.substr(0, path.length-1)
6901           : path +'/';
6902
6903       routes[redirectPath] = {redirectTo: path};
6904     }
6905
6906     return this;
6907   };
6908
6909   /**
6910    * @ngdoc method
6911    * @name ng.$routeProvider#otherwise
6912    * @methodOf ng.$routeProvider
6913    *
6914    * @description
6915    * Sets route definition that will be used on route change when no other route definition
6916    * is matched.
6917    *
6918    * @param {Object} params Mapping information to be assigned to `$route.current`.
6919    * @returns {Object} self
6920    */
6921   this.otherwise = function(params) {
6922     this.when(null, params);
6923     return this;
6924   };
6925
6926
6927   this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
6928       function( $rootScope,   $location,   $routeParams,   $q,   $injector,   $http,   $templateCache) {
6929
6930     /**
6931      * @ngdoc object
6932      * @name ng.$route
6933      * @requires $location
6934      * @requires $routeParams
6935      *
6936      * @property {Object} current Reference to the current route definition.
6937      * The route definition contains:
6938      *
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:
6943      *
6944      *     - `$scope` - The current route scope.
6945      *     - `$template` - The current route template HTML.
6946      *
6947      * @property {Array.<Object>} routes Array of all configured routes.
6948      *
6949      * @description
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.
6952      *
6953      * You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
6954      *
6955      * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
6956      * directive and the {@link ng.$routeParams $routeParams} service.
6957      *
6958      * @example
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.
6961
6962        Note that this example is using {@link ng.directive:script inlined templates}
6963        to get it working on jsfiddle as well.
6964
6965      <example module="ngView">
6966        <file name="index.html">
6967          <div ng-controller="MainCntl">
6968            Choose:
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/>
6974
6975            <div ng-view></div>
6976            <hr />
6977
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>
6983          </div>
6984        </file>
6985
6986        <file name="book.html">
6987          controller: {{name}}<br />
6988          Book Id: {{params.bookId}}<br />
6989        </file>
6990
6991        <file name="chapter.html">
6992          controller: {{name}}<br />
6993          Book Id: {{params.bookId}}<br />
6994          Chapter Id: {{params.chapterId}}
6995        </file>
6996
6997        <file name="script.js">
6998          angular.module('ngView', [], function($routeProvider, $locationProvider) {
6999            $routeProvider.when('/Book/:bookId', {
7000              templateUrl: 'book.html',
7001              controller: BookCntl,
7002              resolve: {
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;
7008                }
7009              }
7010            });
7011            $routeProvider.when('/Book/:bookId/ch/:chapterId', {
7012              templateUrl: 'chapter.html',
7013              controller: ChapterCntl
7014            });
7015
7016            // configure html5 to get links working on jsfiddle
7017            $locationProvider.html5Mode(true);
7018          });
7019
7020          function MainCntl($scope, $route, $routeParams, $location) {
7021            $scope.$route = $route;
7022            $scope.$location = $location;
7023            $scope.$routeParams = $routeParams;
7024          }
7025
7026          function BookCntl($scope, $routeParams) {
7027            $scope.name = "BookCntl";
7028            $scope.params = $routeParams;
7029          }
7030
7031          function ChapterCntl($scope, $routeParams) {
7032            $scope.name = "ChapterCntl";
7033            $scope.params = $routeParams;
7034          }
7035        </file>
7036
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/);
7044
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/);
7050          });
7051        </file>
7052      </example>
7053      */
7054
7055     /**
7056      * @ngdoc event
7057      * @name ng.$route#$routeChangeStart
7058      * @eventOf ng.$route
7059      * @eventType broadcast on root scope
7060      * @description
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.
7066      *
7067      * @param {Route} next Future route information.
7068      * @param {Route} current Current route information.
7069      */
7070
7071     /**
7072      * @ngdoc event
7073      * @name ng.$route#$routeChangeSuccess
7074      * @eventOf ng.$route
7075      * @eventType broadcast on root scope
7076      * @description
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.
7080      *
7081      * @param {Route} current Current route information.
7082      * @param {Route} previous Previous route information.
7083      */
7084
7085     /**
7086      * @ngdoc event
7087      * @name ng.$route#$routeChangeError
7088      * @eventOf ng.$route
7089      * @eventType broadcast on root scope
7090      * @description
7091      * Broadcasted if any of the resolve promises are rejected.
7092      *
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.
7096      */
7097
7098     /**
7099      * @ngdoc event
7100      * @name ng.$route#$routeUpdate
7101      * @eventOf ng.$route
7102      * @eventType broadcast on root scope
7103      * @description
7104      *
7105      * The `reloadOnSearch` property has been set to false, and we are reusing the same
7106      * instance of the Controller.
7107      */
7108
7109     var matcher = switchRouteMatcher,
7110         forceReload = false,
7111         $route = {
7112           routes: routes,
7113
7114           /**
7115            * @ngdoc method
7116            * @name ng.$route#reload
7117            * @methodOf ng.$route
7118            *
7119            * @description
7120            * Causes `$route` service to reload the current route even if
7121            * {@link ng.$location $location} hasn't changed.
7122            *
7123            * As a result of that, {@link ng.directive:ngView ngView}
7124            * creates new scope, reinstantiates the controller.
7125            */
7126           reload: function() {
7127             forceReload = true;
7128             $rootScope.$evalAsync(updateRoute);
7129           }
7130         };
7131
7132     $rootScope.$on('$locationChangeSuccess', updateRoute);
7133
7134     return $route;
7135
7136     /////////////////////////////////////////////////////
7137
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") + '$',
7142           params = [],
7143           dst = {};
7144       forEach(when.split(/\W/), function(param) {
7145         if (param) {
7146           var paramRegExp = new RegExp(":" + param + "([\\W])");
7147           if (regex.match(paramRegExp)) {
7148             regex = regex.replace(paramRegExp, "([^\\/]*)$1");
7149             params.push(param);
7150           }
7151         }
7152       });
7153       var match = on.match(new RegExp(regex));
7154       if (match) {
7155         forEach(params, function(name, index) {
7156           dst[name] = match[index + 1];
7157         });
7158       }
7159       return match ? dst : null;
7160     }
7161
7162     function updateRoute() {
7163       var next = parseRoute(),
7164           last = $route.current;
7165
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;
7175         if (next) {
7176           if (next.redirectTo) {
7177             if (isString(next.redirectTo)) {
7178               $location.path(interpolate(next.redirectTo, next.params)).search(next.params)
7179                        .replace();
7180             } else {
7181               $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
7182                        .replace();
7183             }
7184           }
7185         }
7186
7187         $q.when(next).
7188           then(function() {
7189             if (next) {
7190               var keys = [],
7191                   values = [],
7192                   template;
7193
7194               forEach(next.resolve || {}, function(value, key) {
7195                 keys.push(key);
7196                 values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value));
7197               });
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; });
7202               }
7203               if (isDefined(template)) {
7204                 keys.push('$template');
7205                 values.push(template);
7206               }
7207               return $q.all(values).then(function(values) {
7208                 var locals = {};
7209                 forEach(values, function(value, index) {
7210                   locals[keys[index]] = value;
7211                 });
7212                 return locals;
7213               });
7214             }
7215           }).
7216           // after route change
7217           then(function(locals) {
7218             if (next == $route.current) {
7219               if (next) {
7220                 next.locals = locals;
7221                 copy(next.params, $routeParams);
7222               }
7223               $rootScope.$broadcast('$routeChangeSuccess', next, last);
7224             }
7225           }, function(error) {
7226             if (next == $route.current) {
7227               $rootScope.$broadcast('$routeChangeError', next, last, error);
7228             }
7229           });
7230       }
7231     }
7232
7233
7234     /**
7235      * @returns the current active route, by matching it against the URL
7236      */
7237     function parseRoute() {
7238       // Match a route
7239       var params, match;
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;
7246         }
7247       });
7248       // No route matched; fallback to "otherwise" route
7249       return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
7250     }
7251
7252     /**
7253      * @returns interpolation of the redirect path with the parametrs
7254      */
7255     function interpolate(string, params) {
7256       var result = [];
7257       forEach((string||'').split(':'), function(segment, i) {
7258         if (i == 0) {
7259           result.push(segment);
7260         } else {
7261           var segmentMatch = segment.match(/(\w+)(.*)/);
7262           var key = segmentMatch[1];
7263           result.push(params[key]);
7264           result.push(segmentMatch[2] || '');
7265           delete params[key];
7266         }
7267       });
7268       return result.join('');
7269     }
7270   }];
7271 }
7272
7273 /**
7274  * @ngdoc object
7275  * @name ng.$routeParams
7276  * @requires $route
7277  *
7278  * @description
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.
7282  *
7283  * In case of parameter name collision, `path` params take precedence over `search` params.
7284  *
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.
7287  *
7288  * @example
7289  * <pre>
7290  *  // Given:
7291  *  // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
7292  *  // Route: /Chapter/:chapterId/Section/:sectionId
7293  *  //
7294  *  // Then
7295  *  $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
7296  * </pre>
7297  */
7298 function $RouteParamsProvider() {
7299   this.$get = valueFn({});
7300 }
7301
7302 /**
7303  * DESIGN NOTES
7304  *
7305  * The design decisions behind the scope ware heavily favored for speed and memory consumption.
7306  *
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.
7309  *
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
7314  *
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)
7318  *
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
7321  *
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.
7325  */
7326
7327
7328 /**
7329  * @ngdoc object
7330  * @name ng.$rootScopeProvider
7331  * @description
7332  *
7333  * Provider for the $rootScope service.
7334  */
7335
7336 /**
7337  * @ngdoc function
7338  * @name ng.$rootScopeProvider#digestTtl
7339  * @methodOf ng.$rootScopeProvider
7340  * @description
7341  *
7342  * Sets the number of digest iteration the scope should attempt to execute before giving up and
7343  * assuming that the model is unstable.
7344  *
7345  * The current default is 10 iterations.
7346  *
7347  * @param {number} limit The number of digest iterations.
7348  */
7349
7350
7351 /**
7352  * @ngdoc object
7353  * @name ng.$rootScope
7354  * @description
7355  *
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}.
7359  */
7360 function $RootScopeProvider(){
7361   var TTL = 10;
7362
7363   this.digestTtl = function(value) {
7364     if (arguments.length) {
7365       TTL = value;
7366     }
7367     return TTL;
7368   };
7369
7370   this.$get = ['$injector', '$exceptionHandler', '$parse',
7371       function( $injector,   $exceptionHandler,   $parse) {
7372
7373     /**
7374      * @ngdoc function
7375      * @name ng.$rootScope.Scope
7376      *
7377      * @description
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.)
7382      *
7383      * Here is a simple scope snippet to show how you can interact with the scope.
7384      * <pre>
7385         angular.injector(['ng']).invoke(function($rootScope) {
7386            var scope = $rootScope.$new();
7387            scope.salutation = 'Hello';
7388            scope.name = 'World';
7389
7390            expect(scope.greeting).toEqual(undefined);
7391
7392            scope.$watch('name', function() {
7393              this.greeting = this.salutation + ' ' + this.name + '!';
7394            }); // initialize the watch
7395
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);
7400
7401            scope.$digest(); // fire all  the watches
7402            expect(scope.greeting).toEqual('Hello Misko!');
7403         });
7404      * </pre>
7405      *
7406      * # Inheritance
7407      * A scope can inherit from a parent scope, as in this example:
7408      * <pre>
7409          var parent = $rootScope;
7410          var child = parent.$new();
7411
7412          parent.salutation = "Hello";
7413          child.name = "World";
7414          expect(child.salutation).toEqual('Hello');
7415
7416          child.salutation = "Welcome";
7417          expect(child.salutation).toEqual('Welcome');
7418          expect(parent.salutation).toEqual('Hello');
7419      * </pre>
7420      *
7421      *
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.
7428      *
7429      */
7430     function 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 = {};
7438     }
7439
7440     /**
7441      * @ngdoc property
7442      * @name ng.$rootScope.Scope#$id
7443      * @propertyOf ng.$rootScope.Scope
7444      * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
7445      *   debugging.
7446      */
7447
7448
7449     Scope.prototype = {
7450       /**
7451        * @ngdoc function
7452        * @name ng.$rootScope.Scope#$new
7453        * @methodOf ng.$rootScope.Scope
7454        * @function
7455        *
7456        * @description
7457        * Creates a new child {@link ng.$rootScope.Scope scope}.
7458        *
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()}.
7462        *
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.
7466        *
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
7470        *         state.
7471        *
7472        * @returns {Object} The newly created child scope.
7473        *
7474        */
7475       $new: function(isolate) {
7476         var Child,
7477             child;
7478
7479         if (isFunction(isolate)) {
7480           // TODO: remove at some point
7481           throw Error('API-CHANGE: Use $controller to instantiate controllers.');
7482         }
7483         if (isolate) {
7484           child = new Scope();
7485           child.$root = this.$root;
7486         } else {
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();
7493         }
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;
7503         } else {
7504           this.$$childHead = this.$$childTail = child;
7505         }
7506         return child;
7507       },
7508
7509       /**
7510        * @ngdoc function
7511        * @name ng.$rootScope.Scope#$watch
7512        * @methodOf ng.$rootScope.Scope
7513        * @function
7514        *
7515        * @description
7516        * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
7517        *
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.
7531        *
7532        *
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.)
7537        *
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.
7544        *
7545        *
7546        * # Example
7547        * <pre>
7548            // let's assume that scope was dependency injected as the $rootScope
7549            var scope = $rootScope;
7550            scope.name = 'misko';
7551            scope.counter = 0;
7552
7553            expect(scope.counter).toEqual(0);
7554            scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; });
7555            expect(scope.counter).toEqual(0);
7556
7557            scope.$digest();
7558            // no variable change
7559            expect(scope.counter).toEqual(0);
7560
7561            scope.name = 'adam';
7562            scope.$digest();
7563            expect(scope.counter).toEqual(1);
7564        * </pre>
7565        *
7566        *
7567        *
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`.
7571        *
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.
7576        *
7577        *    - `string`: Evaluated as {@link guide/expression expression}
7578        *    - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
7579        *
7580        * @param {boolean=} objectEquality Compare object for equality rather then for refference.
7581        * @returns {function()} Returns a deregistration function for this listener.
7582        */
7583       $watch: function(watchExp, listener, objectEquality) {
7584         var scope = this,
7585             get = compileToFn(watchExp, 'watch'),
7586             array = scope.$$watchers,
7587             watcher = {
7588               fn: listener,
7589               last: initWatchVal,
7590               get: get,
7591               exp: watchExp,
7592               eq: !!objectEquality
7593             };
7594
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);};
7599         }
7600
7601         if (!array) {
7602           array = scope.$$watchers = [];
7603         }
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);
7607
7608         return function() {
7609           arrayRemove(array, watcher);
7610         };
7611       },
7612
7613       /**
7614        * @ngdoc function
7615        * @name ng.$rootScope.Scope#$digest
7616        * @methodOf ng.$rootScope.Scope
7617        * @function
7618        *
7619        * @description
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.
7625        *
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()`.
7631        *
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`.
7635        *
7636        * You may have a need to call `$digest()` from within unit-tests, to simulate the scope
7637        * life-cycle.
7638        *
7639        * # Example
7640        * <pre>
7641            var scope = ...;
7642            scope.name = 'misko';
7643            scope.counter = 0;
7644
7645            expect(scope.counter).toEqual(0);
7646            scope.$watch('name', function(newValue, oldValue) {
7647              counter = counter + 1;
7648            });
7649            expect(scope.counter).toEqual(0);
7650
7651            scope.$digest();
7652            // no variable change
7653            expect(scope.counter).toEqual(0);
7654
7655            scope.name = 'adam';
7656            scope.$digest();
7657            expect(scope.counter).toEqual(1);
7658        * </pre>
7659        *
7660        */
7661       $digest: function() {
7662         var watch, value, last,
7663             watchers,
7664             asyncQueue,
7665             length,
7666             dirty, ttl = TTL,
7667             next, current, target = this,
7668             watchLog = [],
7669             logIdx, logMsg;
7670
7671         beginPhase('$digest');
7672
7673         do {
7674           dirty = false;
7675           current = target;
7676           do {
7677             asyncQueue = current.$$asyncQueue;
7678             while(asyncQueue.length) {
7679               try {
7680                 current.$eval(asyncQueue.shift());
7681               } catch (e) {
7682                 $exceptionHandler(e);
7683               }
7684             }
7685             if ((watchers = current.$$watchers)) {
7686               // process our watches
7687               length = watchers.length;
7688               while (length--) {
7689                 try {
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) &&
7694                       !(watch.eq
7695                           ? equals(value, last)
7696                           : (typeof value == 'number' && typeof last == 'number'
7697                              && isNaN(value) && isNaN(last)))) {
7698                     dirty = true;
7699                     watch.last = watch.eq ? copy(value) : value;
7700                     watch.fn(value, ((last === initWatchVal) ? value : last), current);
7701                     if (ttl < 5) {
7702                       logIdx = 4 - ttl;
7703                       if (!watchLog[logIdx]) watchLog[logIdx] = [];
7704                       logMsg = (isFunction(watch.exp))
7705                           ? 'fn: ' + (watch.exp.name || watch.exp.toString())
7706                           : watch.exp;
7707                       logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
7708                       watchLog[logIdx].push(logMsg);
7709                     }
7710                   }
7711                 } catch (e) {
7712                   $exceptionHandler(e);
7713                 }
7714               }
7715             }
7716
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;
7723               }
7724             }
7725           } while ((current = next));
7726
7727           if(dirty && !(ttl--)) {
7728             clearPhase();
7729             throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
7730                 'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
7731           }
7732         } while (dirty || asyncQueue.length);
7733
7734         clearPhase();
7735       },
7736
7737
7738       /**
7739        * @ngdoc event
7740        * @name ng.$rootScope.Scope#$destroy
7741        * @eventOf ng.$rootScope.Scope
7742        * @eventType broadcast on scope being destroyed
7743        *
7744        * @description
7745        * Broadcasted when a scope and its children are being destroyed.
7746        */
7747
7748       /**
7749        * @ngdoc function
7750        * @name ng.$rootScope.Scope#$destroy
7751        * @methodOf ng.$rootScope.Scope
7752        * @function
7753        *
7754        * @description
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.
7759        *
7760        * The `$destroy()` is usually used by directives such as
7761        * {@link ng.directive:ngRepeat ngRepeat} for managing the
7762        * unrolling of the loop.
7763        *
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.
7767        */
7768       $destroy: function() {
7769         if ($rootScope == this) return; // we can't remove the root node;
7770         var parent = this.$parent;
7771
7772         this.$broadcast('$destroy');
7773
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;
7778       },
7779
7780       /**
7781        * @ngdoc function
7782        * @name ng.$rootScope.Scope#$eval
7783        * @methodOf ng.$rootScope.Scope
7784        * @function
7785        *
7786        * @description
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.
7789        *
7790        * # Example
7791        * <pre>
7792            var scope = ng.$rootScope.Scope();
7793            scope.a = 1;
7794            scope.b = 2;
7795
7796            expect(scope.$eval('a+b')).toEqual(3);
7797            expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
7798        * </pre>
7799        *
7800        * @param {(string|function())=} expression An angular expression to be executed.
7801        *
7802        *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.
7803        *    - `function(scope)`: execute the function with the current `scope` parameter.
7804        *
7805        * @returns {*} The result of evaluating the expression.
7806        */
7807       $eval: function(expr, locals) {
7808         return $parse(expr)(this, locals);
7809       },
7810
7811       /**
7812        * @ngdoc function
7813        * @name ng.$rootScope.Scope#$evalAsync
7814        * @methodOf ng.$rootScope.Scope
7815        * @function
7816        *
7817        * @description
7818        * Executes the expression on the current scope at a later point in time.
7819        *
7820        * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
7821        *
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.
7825        *
7826        * Any exceptions from the execution of the expression are forwarded to the
7827        * {@link ng.$exceptionHandler $exceptionHandler} service.
7828        *
7829        * @param {(string|function())=} expression An angular expression to be executed.
7830        *
7831        *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.
7832        *    - `function(scope)`: execute the function with the current `scope` parameter.
7833        *
7834        */
7835       $evalAsync: function(expr) {
7836         this.$$asyncQueue.push(expr);
7837       },
7838
7839       /**
7840        * @ngdoc function
7841        * @name ng.$rootScope.Scope#$apply
7842        * @methodOf ng.$rootScope.Scope
7843        * @function
7844        *
7845        * @description
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}.
7851        *
7852        * ## Life cycle
7853        *
7854        * # Pseudo-Code of `$apply()`
7855        * <pre>
7856            function $apply(expr) {
7857              try {
7858                return $eval(expr);
7859              } catch (e) {
7860                $exceptionHandler(e);
7861              } finally {
7862                $root.$digest();
7863              }
7864            }
7865        * </pre>
7866        *
7867        *
7868        * Scope's `$apply()` method transitions through the following stages:
7869        *
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.
7876        *
7877        *
7878        * @param {(string|function())=} exp An angular expression to be executed.
7879        *
7880        *    - `string`: execute using the rules as defined in {@link guide/expression expression}.
7881        *    - `function(scope)`: execute the function with current `scope` parameter.
7882        *
7883        * @returns {*} The result of evaluating the expression.
7884        */
7885       $apply: function(expr) {
7886         try {
7887           beginPhase('$apply');
7888           return this.$eval(expr);
7889         } catch (e) {
7890           $exceptionHandler(e);
7891         } finally {
7892           clearPhase();
7893           try {
7894             $rootScope.$digest();
7895           } catch (e) {
7896             $exceptionHandler(e);
7897             throw e;
7898           }
7899         }
7900       },
7901
7902       /**
7903        * @ngdoc function
7904        * @name ng.$rootScope.Scope#$on
7905        * @methodOf ng.$rootScope.Scope
7906        * @function
7907        *
7908        * @description
7909        * Listen on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
7910        * event life cycle.
7911        *
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.
7915        *
7916        * The event listener function format is: `function(event, args...)`. The `event` object
7917        * passed into the listener has the following attributes:
7918        *
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.
7926        */
7927       $on: function(name, listener) {
7928         var namedListeners = this.$$listeners[name];
7929         if (!namedListeners) {
7930           this.$$listeners[name] = namedListeners = [];
7931         }
7932         namedListeners.push(listener);
7933
7934         return function() {
7935           arrayRemove(namedListeners, listener);
7936         };
7937       },
7938
7939
7940       /**
7941        * @ngdoc function
7942        * @name ng.$rootScope.Scope#$emit
7943        * @methodOf ng.$rootScope.Scope
7944        * @function
7945        *
7946        * @description
7947        * Dispatches an event `name` upwards through the scope hierarchy notifying the
7948        * registered {@link ng.$rootScope.Scope#$on} listeners.
7949        *
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.
7954        *
7955        * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
7956        * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
7957        *
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}
7961        */
7962       $emit: function(name, args) {
7963         var empty = [],
7964             namedListeners,
7965             scope = this,
7966             stopPropagation = false,
7967             event = {
7968               name: name,
7969               targetScope: scope,
7970               stopPropagation: function() {stopPropagation = true;},
7971               preventDefault: function() {
7972                 event.defaultPrevented = true;
7973               },
7974               defaultPrevented: false
7975             },
7976             listenerArgs = concat([event], arguments, 1),
7977             i, length;
7978
7979         do {
7980           namedListeners = scope.$$listeners[name] || empty;
7981           event.currentScope = scope;
7982           for (i=0, length=namedListeners.length; i<length; i++) {
7983             try {
7984               namedListeners[i].apply(null, listenerArgs);
7985               if (stopPropagation) return event;
7986             } catch (e) {
7987               $exceptionHandler(e);
7988             }
7989           }
7990           //traverse upwards
7991           scope = scope.$parent;
7992         } while (scope);
7993
7994         return event;
7995       },
7996
7997
7998       /**
7999        * @ngdoc function
8000        * @name ng.$rootScope.Scope#$broadcast
8001        * @methodOf ng.$rootScope.Scope
8002        * @function
8003        *
8004        * @description
8005        * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
8006        * registered {@link ng.$rootScope.Scope#$on} listeners.
8007        *
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.
8012        *
8013        * Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
8014        * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
8015        *
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}
8019        */
8020       $broadcast: function(name, args) {
8021         var target = this,
8022             current = target,
8023             next = target,
8024             event = {
8025               name: name,
8026               targetScope: target,
8027               preventDefault: function() {
8028                 event.defaultPrevented = true;
8029               },
8030               defaultPrevented: false
8031             },
8032             listenerArgs = concat([event], arguments, 1);
8033
8034         //down while you can, then up and next sibling or up and next sibling until back at root
8035         do {
8036           current = next;
8037           event.currentScope = current;
8038           forEach(current.$$listeners[name], function(listener) {
8039             try {
8040               listener.apply(null, listenerArgs);
8041             } catch(e) {
8042               $exceptionHandler(e);
8043             }
8044           });
8045
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;
8052             }
8053           }
8054         } while ((current = next));
8055
8056         return event;
8057       }
8058     };
8059
8060     var $rootScope = new Scope();
8061
8062     return $rootScope;
8063
8064
8065     function beginPhase(phase) {
8066       if ($rootScope.$$phase) {
8067         throw Error($rootScope.$$phase + ' already in progress');
8068       }
8069
8070       $rootScope.$$phase = phase;
8071     }
8072
8073     function clearPhase() {
8074       $rootScope.$$phase = null;
8075     }
8076
8077     function compileToFn(exp, name) {
8078       var fn = $parse(exp);
8079       assertArgFn(fn, name);
8080       return fn;
8081     }
8082
8083     /**
8084      * function used as an initial value for watchers.
8085      * because it's uniqueue we can easily tell it apart from other values
8086      */
8087     function initWatchVal() {}
8088   }];
8089 }
8090
8091 /**
8092  * !!! This is an undocumented "private" service !!!
8093  *
8094  * @name ng.$sniffer
8095  * @requires $window
8096  *
8097  * @property {boolean} history Does the browser support html5 history api ?
8098  * @property {boolean} hashchange Does the browser support hashchange event ?
8099  *
8100  * @description
8101  * This is very simple implementation of testing browser's features.
8102  */
8103 function $SnifferProvider() {
8104   this.$get = ['$window', function($window) {
8105     var eventSupport = {},
8106         android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
8107
8108     return {
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;
8122
8123         if (isUndefined(eventSupport[event])) {
8124           var divElm = $window.document.createElement('div');
8125           eventSupport[event] = 'on' + event in divElm;
8126         }
8127
8128         return eventSupport[event];
8129       },
8130       // TODO(i): currently there is no way to feature detect CSP without triggering alerts
8131       csp: false
8132     };
8133   }];
8134 }
8135
8136 /**
8137  * @ngdoc object
8138  * @name ng.$window
8139  *
8140  * @description
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.
8145  *
8146  * All expressions are evaluated with respect to current scope so they don't
8147  * suffer from window globality.
8148  *
8149  * @example
8150    <doc:example>
8151      <doc:source>
8152        <input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" />
8153        <button ng-click="$window.alert(greeting)">ALERT</button>
8154      </doc:source>
8155      <doc:scenario>
8156      </doc:scenario>
8157    </doc:example>
8158  */
8159 function $WindowProvider(){
8160   this.$get = valueFn(window);
8161 }
8162
8163 /**
8164  * Parse headers into key value object
8165  *
8166  * @param {string} headers Raw headers as a string
8167  * @returns {Object} Parsed headers as key value object
8168  */
8169 function parseHeaders(headers) {
8170   var parsed = {}, key, val, i;
8171
8172   if (!headers) return parsed;
8173
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));
8178
8179     if (key) {
8180       if (parsed[key]) {
8181         parsed[key] += ', ' + val;
8182       } else {
8183         parsed[key] = val;
8184       }
8185     }
8186   });
8187
8188   return parsed;
8189 }
8190
8191
8192 /**
8193  * Returns a function that provides access to parsed headers.
8194  *
8195  * Headers are lazy parsed when first requested.
8196  * @see parseHeaders
8197  *
8198  * @param {(string|Object)} headers Headers to provide access to.
8199  * @returns {function(string=)} Returns a getter function which if called with:
8200  *
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.
8203  */
8204 function headersGetter(headers) {
8205   var headersObj = isObject(headers) ? headers : undefined;
8206
8207   return function(name) {
8208     if (!headersObj) headersObj =  parseHeaders(headers);
8209
8210     if (name) {
8211       return headersObj[lowercase(name)] || null;
8212     }
8213
8214     return headersObj;
8215   };
8216 }
8217
8218
8219 /**
8220  * Chain all given functions
8221  *
8222  * This function is used for both request and response transforming
8223  *
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.
8228  */
8229 function transformData(data, headers, fns) {
8230   if (isFunction(fns))
8231     return fns(data, headers);
8232
8233   forEach(fns, function(fn) {
8234     data = fn(data, headers);
8235   });
8236
8237   return data;
8238 }
8239
8240
8241 function isSuccess(status) {
8242   return 200 <= status && status < 300;
8243 }
8244
8245
8246 function $HttpProvider() {
8247   var JSON_START = /^\s*(\[|\{[^\{])/,
8248       JSON_END = /[\}\]]\s*$/,
8249       PROTECTION_PREFIX = /^\)\]\}',?\n/;
8250
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);
8259       }
8260       return data;
8261     }],
8262
8263     // transform outgoing request data
8264     transformRequest: [function(d) {
8265       return isObject(d) && !isFile(d) ? toJson(d) : d;
8266     }],
8267
8268     // default headers
8269     headers: {
8270       common: {
8271         'Accept': 'application/json, text/plain, */*',
8272         'X-Requested-With': 'XMLHttpRequest'
8273       },
8274       post: {'Content-Type': 'application/json;charset=utf-8'},
8275       put:  {'Content-Type': 'application/json;charset=utf-8'}
8276     }
8277   };
8278
8279   var providerResponseInterceptors = this.responseInterceptors = [];
8280
8281   this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
8282       function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
8283
8284     var defaultCache = $cacheFactory('$http'),
8285         responseInterceptors = [];
8286
8287     forEach(providerResponseInterceptors, function(interceptor) {
8288       responseInterceptors.push(
8289           isString(interceptor)
8290               ? $injector.get(interceptor)
8291               : $injector.invoke(interceptor)
8292       );
8293     });
8294
8295
8296     /**
8297      * @ngdoc function
8298      * @name ng.$http
8299      * @requires $httpBacked
8300      * @requires $browser
8301      * @requires $cacheFactory
8302      * @requires $rootScope
8303      * @requires $q
8304      * @requires $injector
8305      *
8306      * @description
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}.
8310      *
8311      * For unit testing applications that use `$http` service, see
8312      * {@link ngMock.$httpBackend $httpBackend mock}.
8313      *
8314      * For a higher level of abstraction, please check out the {@link ngResource.$resource
8315      * $resource} service.
8316      *
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.
8320      *
8321      *
8322      * # General usage
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`.
8326      *
8327      * <pre>
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
8332      *     }).
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
8337      *     });
8338      * </pre>
8339      *
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
8343      * details.
8344      *
8345      *
8346      * # Shortcut methods
8347      *
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:
8351      *
8352      * <pre>
8353      *   $http.get('/someUrl').success(successCallback);
8354      *   $http.post('/someUrl', data).success(successCallback);
8355      * </pre>
8356      *
8357      * Complete list of shortcut methods:
8358      *
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}
8365      *
8366      *
8367      * # Setting HTTP Headers
8368      *
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:
8372      *
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`
8380      *
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'`.
8385      *
8386      * Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar
8387      * fassion as described above.
8388      *
8389      *
8390      * # Transforming Requests and Responses
8391      *
8392      * Both requests and responses can be transformed using transform functions. By default, Angular
8393      * applies these transformations:
8394      *
8395      * Request transformations:
8396      *
8397      * - if the `data` property of the request config object contains an object, serialize it into
8398      *   JSON format.
8399      *
8400      * Response transformations:
8401      *
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
8404      *
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`.
8409      *
8410      *
8411      * # Caching
8412      *
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.
8416      *
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.
8419      *
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.
8423      *
8424      *
8425      * # Response interceptors
8426      *
8427      * Before you start creating interceptors, be sure to understand the
8428      * {@link ng.$q $q and deferred/promise APIs}.
8429      *
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.
8435      *
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.
8440      *
8441      * <pre>
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
8451      *         }
8452      *         return $q.reject(response);
8453      *       });
8454      *     }
8455      *   });
8456      *
8457      *   $httpProvider.responseInterceptors.push('myHttpInterceptor');
8458      *
8459      *
8460      *   // register the interceptor via an anonymous factory
8461      *   $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
8462      *     return function(promise) {
8463      *       // same as above
8464      *     }
8465      *   });
8466      * </pre>
8467      *
8468      *
8469      * # Security Considerations
8470      *
8471      * When designing web applications, consider security threats from:
8472      *
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}
8476      *
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.
8480      *
8481      * ## JSON Vulnerability Protection
8482      *
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.
8488      *
8489      * For example if your server needs to return:
8490      * <pre>
8491      * ['one','two']
8492      * </pre>
8493      *
8494      * which is vulnerable to attack, your server can return:
8495      * <pre>
8496      * )]}',
8497      * ['one','two']
8498      * </pre>
8499      *
8500      * Angular will strip the prefix, before processing the JSON.
8501      *
8502      *
8503      * ## Cross Site Request Forgery (XSRF) Protection
8504      *
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.
8511      *
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}.
8519      *
8520      *
8521      * @param {object} config Object describing the request to be made and how it should be
8522      *    processed. The object has following properties:
8523      *
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
8539      *      caching.
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.
8544      *
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:
8552      *
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.
8557      *
8558      * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
8559      *   requests. This is primarily meant to be used for debugging purposes.
8560      *
8561      *
8562      * @example
8563       <example>
8564         <file name="index.html">
8565           <div ng-controller="FetchCtrl">
8566             <select ng-model="method">
8567               <option>GET</option>
8568               <option>JSONP</option>
8569             </select>
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>
8577           </div>
8578         </file>
8579         <file name="script.js">
8580           function FetchCtrl($scope, $http, $templateCache) {
8581             $scope.method = 'GET';
8582             $scope.url = 'http-hello.html';
8583
8584             $scope.fetch = function() {
8585               $scope.code = null;
8586               $scope.response = null;
8587
8588               $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
8589                 success(function(data, status) {
8590                   $scope.status = status;
8591                   $scope.data = data;
8592                 }).
8593                 error(function(data, status) {
8594                   $scope.data = data || "Request failed";
8595                   $scope.status = status;
8596               });
8597             };
8598
8599             $scope.updateModel = function(method, url) {
8600               $scope.method = method;
8601               $scope.url = url;
8602             };
8603           }
8604         </file>
8605         <file name="http-hello.html">
8606           Hello, $http!
8607         </file>
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!/);
8614           });
8615
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!/);
8621           });
8622
8623           it('should make JSONP request to invalid URL and invoke the error handler',
8624               function() {
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');
8629           });
8630         </file>
8631       </example>
8632      */
8633     function $http(config) {
8634       config.method = uppercase(config.method);
8635
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),
8642           promise;
8643
8644       // strip content-type if data is undefined
8645       if (isUndefined(config.data)) {
8646         delete reqHeaders['Content-Type'];
8647       }
8648
8649       // send request
8650       promise = sendReq(config, reqData, reqHeaders);
8651
8652
8653       // transform future response
8654       promise = promise.then(transformResponse, transformResponse);
8655
8656       // apply interceptors
8657       forEach(responseInterceptors, function(interceptor) {
8658         promise = interceptor(promise);
8659       });
8660
8661       promise.success = function(fn) {
8662         promise.then(function(response) {
8663           fn(response.data, response.status, response.headers, config);
8664         });
8665         return promise;
8666       };
8667
8668       promise.error = function(fn) {
8669         promise.then(null, function(response) {
8670           fn(response.data, response.status, response.headers, config);
8671         });
8672         return promise;
8673       };
8674
8675       return promise;
8676
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)
8681         });
8682         return (isSuccess(response.status))
8683           ? resp
8684           : $q.reject(resp);
8685       }
8686     }
8687
8688     $http.pendingRequests = [];
8689
8690     /**
8691      * @ngdoc method
8692      * @name ng.$http#get
8693      * @methodOf ng.$http
8694      *
8695      * @description
8696      * Shortcut method to perform `GET` request
8697      *
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
8701      */
8702
8703     /**
8704      * @ngdoc method
8705      * @name ng.$http#delete
8706      * @methodOf ng.$http
8707      *
8708      * @description
8709      * Shortcut method to perform `DELETE` request
8710      *
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
8714      */
8715
8716     /**
8717      * @ngdoc method
8718      * @name ng.$http#head
8719      * @methodOf ng.$http
8720      *
8721      * @description
8722      * Shortcut method to perform `HEAD` request
8723      *
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
8727      */
8728
8729     /**
8730      * @ngdoc method
8731      * @name ng.$http#jsonp
8732      * @methodOf ng.$http
8733      *
8734      * @description
8735      * Shortcut method to perform `JSONP` request
8736      *
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
8741      */
8742     createShortMethods('get', 'delete', 'head', 'jsonp');
8743
8744     /**
8745      * @ngdoc method
8746      * @name ng.$http#post
8747      * @methodOf ng.$http
8748      *
8749      * @description
8750      * Shortcut method to perform `POST` request
8751      *
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
8756      */
8757
8758     /**
8759      * @ngdoc method
8760      * @name ng.$http#put
8761      * @methodOf ng.$http
8762      *
8763      * @description
8764      * Shortcut method to perform `PUT` request
8765      *
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
8770      */
8771     createShortMethodsWithData('post', 'put');
8772
8773         /**
8774          * @ngdoc property
8775          * @name ng.$http#defaults
8776          * @propertyOf ng.$http
8777          *
8778          * @description
8779          * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
8780          * default headers as well as request and response transformations.
8781          *
8782          * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
8783          */
8784     $http.defaults = $config;
8785
8786
8787     return $http;
8788
8789
8790     function createShortMethods(names) {
8791       forEach(arguments, function(name) {
8792         $http[name] = function(url, config) {
8793           return $http(extend(config || {}, {
8794             method: name,
8795             url: url
8796           }));
8797         };
8798       });
8799     }
8800
8801
8802     function createShortMethodsWithData(name) {
8803       forEach(arguments, function(name) {
8804         $http[name] = function(url, data, config) {
8805           return $http(extend(config || {}, {
8806             method: name,
8807             url: url,
8808             data: data
8809           }));
8810         };
8811       });
8812     }
8813
8814
8815     /**
8816      * Makes the request
8817      *
8818      * !!! ACCESSES CLOSURE VARS:
8819      * $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
8820      */
8821     function sendReq(config, reqData, reqHeaders) {
8822       var deferred = $q.defer(),
8823           promise = deferred.promise,
8824           cache,
8825           cachedResp,
8826           url = buildUrl(config.url, config.params);
8827
8828       $http.pendingRequests.push(config);
8829       promise.then(removePendingReq, removePendingReq);
8830
8831
8832       if (config.cache && config.method == 'GET') {
8833         cache = isObject(config.cache) ? config.cache : defaultCache;
8834       }
8835
8836       if (cache) {
8837         cachedResp = cache.get(url);
8838         if (cachedResp) {
8839           if (cachedResp.then) {
8840             // cached request has already been sent, but there is no response yet
8841             cachedResp.then(removePendingReq, removePendingReq);
8842             return cachedResp;
8843           } else {
8844             // serving from cache
8845             if (isArray(cachedResp)) {
8846               resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
8847             } else {
8848               resolvePromise(cachedResp, 200, {});
8849             }
8850           }
8851         } else {
8852           // put the promise for the non-transformed response into cache as a placeholder
8853           cache.put(url, promise);
8854         }
8855       }
8856
8857       // if we won't have the response in cache, send the request to the backend
8858       if (!cachedResp) {
8859         $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
8860             config.withCredentials);
8861       }
8862
8863       return promise;
8864
8865
8866       /**
8867        * Callback registered to $httpBackend():
8868        *  - caches the response if desired
8869        *  - resolves the raw $http promise
8870        *  - calls $apply
8871        */
8872       function done(status, response, headersString) {
8873         if (cache) {
8874           if (isSuccess(status)) {
8875             cache.put(url, [status, response, parseHeaders(headersString)]);
8876           } else {
8877             // remove promise from the cache
8878             cache.remove(url);
8879           }
8880         }
8881
8882         resolvePromise(response, status, headersString);
8883         $rootScope.$apply();
8884       }
8885
8886
8887       /**
8888        * Resolves the raw $http promise.
8889        */
8890       function resolvePromise(response, status, headers) {
8891         // normalize internal statuses to 0
8892         status = Math.max(status, 0);
8893
8894         (isSuccess(status) ? deferred.resolve : deferred.reject)({
8895           data: response,
8896           status: status,
8897           headers: headersGetter(headers),
8898           config: config
8899         });
8900       }
8901
8902
8903       function removePendingReq() {
8904         var idx = indexOf($http.pendingRequests, config);
8905         if (idx !== -1) $http.pendingRequests.splice(idx, 1);
8906       }
8907     }
8908
8909
8910     function buildUrl(url, params) {
8911           if (!params) return url;
8912           var parts = [];
8913           forEachSorted(params, function(value, key) {
8914             if (value == null || value == undefined) return;
8915             if (isObject(value)) {
8916               value = toJson(value);
8917             }
8918             parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
8919           });
8920           return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
8921         }
8922
8923
8924   }];
8925 }
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.");
8931 };
8932
8933
8934 /**
8935  * @ngdoc object
8936  * @name ng.$httpBackend
8937  * @requires $browser
8938  * @requires $window
8939  * @requires $document
8940  *
8941  * @description
8942  * HTTP backend used by the {@link ng.$http service} that delegates to
8943  * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
8944  *
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}.
8947  *
8948  * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
8949  * $httpBackend} which can be trained with responses.
8950  */
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(':', ''));
8955   }];
8956 }
8957
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();
8963
8964     if (lowercase(method) == 'jsonp') {
8965       var callbackId = '_' + (callbacks.counter++).toString(36);
8966       callbacks[callbackId] = function(data) {
8967         callbacks[callbackId].data = data;
8968       };
8969
8970       jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
8971           function() {
8972         if (callbacks[callbackId].data) {
8973           completeRequest(callback, 200, callbacks[callbackId].data);
8974         } else {
8975           completeRequest(callback, -2);
8976         }
8977         delete callbacks[callbackId];
8978       });
8979     } else {
8980       var xhr = new XHR();
8981       xhr.open(method, url, true);
8982       forEach(headers, function(value, key) {
8983         if (value) xhr.setRequestHeader(key, value);
8984       });
8985
8986       var status;
8987
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
8990       // always async
8991       xhr.onreadystatechange = function() {
8992         if (xhr.readyState == 4) {
8993           completeRequest(
8994               callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders());
8995         }
8996       };
8997
8998       if (withCredentials) {
8999         xhr.withCredentials = true;
9000       }
9001
9002       xhr.send(post || '');
9003
9004       if (timeout > 0) {
9005         $browserDefer(function() {
9006           status = -1;
9007           xhr.abort();
9008         }, timeout);
9009       }
9010     }
9011
9012
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];
9016
9017       // fix status code for file protocol (it's always 0)
9018       status = (protocol == 'file') ? (response ? 200 : 404) : status;
9019
9020       // normalize IE bug (http://bugs.jquery.com/ticket/1450)
9021       status = status == 1223 ? 204 : status;
9022
9023       callback(status, response, headersString);
9024       $browser.$$completeOutstandingRequest(noop);
9025     }
9026   };
9027
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);
9035           if (done) done();
9036         };
9037
9038     script.type = 'text/javascript';
9039     script.src = url;
9040
9041     if (msie) {
9042       script.onreadystatechange = function() {
9043         if (/loaded|complete/.test(script.readyState)) doneWrapper();
9044       };
9045     } else {
9046       script.onload = script.onerror = doneWrapper;
9047     }
9048
9049     rawDocument.body.appendChild(script);
9050   }
9051 }
9052
9053 /**
9054  * @ngdoc object
9055  * @name ng.$locale
9056  *
9057  * @description
9058  * $locale service provides localization rules for various Angular components. As of right now the
9059  * only public api is:
9060  *
9061  * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
9062  */
9063 function $LocaleProvider(){
9064   this.$get = function() {
9065     return {
9066       id: 'en-us',
9067
9068       NUMBER_FORMATS: {
9069         DECIMAL_SEP: '.',
9070         GROUP_SEP: ',',
9071         PATTERNS: [
9072           { // Decimal Pattern
9073             minInt: 1,
9074             minFrac: 0,
9075             maxFrac: 3,
9076             posPre: '',
9077             posSuf: '',
9078             negPre: '-',
9079             negSuf: '',
9080             gSize: 3,
9081             lgSize: 3
9082           },{ //Currency Pattern
9083             minInt: 1,
9084             minFrac: 2,
9085             maxFrac: 2,
9086             posPre: '\u00A4',
9087             posSuf: '',
9088             negPre: '(\u00A4',
9089             negSuf: ')',
9090             gSize: 3,
9091             lgSize: 3
9092           }
9093         ],
9094         CURRENCY_SYM: '$'
9095       },
9096
9097       DATETIME_FORMATS: {
9098         MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
9099                 .split(','),
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(','),
9103         AMPMS: ['AM','PM'],
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',
9111         shortTime: 'h:mm a'
9112       },
9113
9114       pluralCat: function(num) {
9115         if (num === 1) {
9116           return 'one';
9117         }
9118         return 'other';
9119       }
9120     };
9121   };
9122 }
9123
9124 function $TimeoutProvider() {
9125   this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
9126        function($rootScope,   $browser,   $q,   $exceptionHandler) {
9127     var deferreds = {};
9128
9129
9130      /**
9131       * @ngdoc function
9132       * @name ng.$timeout
9133       * @requires $browser
9134       *
9135       * @description
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.
9139       *
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.
9142       *
9143       * To cancel a the timeout request, call `$timeout.cancel(promise)`.
9144       *
9145       * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
9146       * synchronously flush the queue of deferred functions.
9147       *
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.
9154       */
9155     function timeout(fn, delay, invokeApply) {
9156       var deferred = $q.defer(),
9157           promise = deferred.promise,
9158           skipApply = (isDefined(invokeApply) && !invokeApply),
9159           timeoutId, cleanup;
9160
9161       timeoutId = $browser.defer(function() {
9162         try {
9163           deferred.resolve(fn());
9164         } catch(e) {
9165           deferred.reject(e);
9166           $exceptionHandler(e);
9167         }
9168
9169         if (!skipApply) $rootScope.$apply();
9170       }, delay);
9171
9172       cleanup = function() {
9173         delete deferreds[promise.$$timeoutId];
9174       };
9175
9176       promise.$$timeoutId = timeoutId;
9177       deferreds[timeoutId] = deferred;
9178       promise.then(cleanup, cleanup);
9179
9180       return promise;
9181     }
9182
9183
9184      /**
9185       * @ngdoc function
9186       * @name ng.$timeout#cancel
9187       * @methodOf ng.$timeout
9188       *
9189       * @description
9190       * Cancels a task associated with the `promise`. As a result of this the promise will be
9191       * resolved with a rejection.
9192       *
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
9195       *   canceled.
9196       */
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);
9201       }
9202       return false;
9203     };
9204
9205     return timeout;
9206   }];
9207 }
9208
9209 /**
9210  * @ngdoc object
9211  * @name ng.$filterProvider
9212  * @description
9213  *
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.
9217  *
9218  * <pre>
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 + '!';
9224  *     });
9225  *
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;
9234  *       };
9235  *     });
9236  *   }
9237  * </pre>
9238  *
9239  * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
9240  * <pre>
9241  *   it('should be the same instance', inject(
9242  *     function($filterProvider) {
9243  *       $filterProvider.register('reverse', function(){
9244  *         return ...;
9245  *       });
9246  *     },
9247  *     function($filter, reverseFilter) {
9248  *       expect($filter('reverse')).toBe(reverseFilter);
9249  *     });
9250  * </pre>
9251  *
9252  *
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
9255  * Guide.
9256  */
9257 /**
9258  * @ngdoc method
9259  * @name ng.$filterProvider#register
9260  * @methodOf ng.$filterProvider
9261  * @description
9262  * Register filter factory function.
9263  *
9264  * @param {String} name Name of the filter.
9265  * @param {function} fn The filter factory function which is injectable.
9266  */
9267
9268
9269 /**
9270  * @ngdoc function
9271  * @name ng.$filter
9272  * @function
9273  * @description
9274  * Filters are used for formatting data displayed to the user.
9275  *
9276  * The general syntax in templates is as follows:
9277  *
9278  *         {{ expression | [ filter_name ] }}
9279  *
9280  * @param {String} name Name of the filter function to retrieve
9281  * @return {Function} the filter function
9282  */
9283 $FilterProvider.$inject = ['$provide'];
9284 function $FilterProvider($provide) {
9285   var suffix = 'Filter';
9286
9287   function register(name, factory) {
9288     return $provide.factory(name + suffix, factory);
9289   }
9290   this.register = register;
9291
9292   this.$get = ['$injector', function($injector) {
9293     return function(name) {
9294       return $injector.get(name + suffix);
9295     }
9296   }];
9297
9298   ////////////////////////////////////////
9299
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);
9309 }
9310
9311 /**
9312  * @ngdoc filter
9313  * @name ng.filter:filter
9314  * @function
9315  *
9316  * @description
9317  * Selects a subset of items from `array` and returns it as a new array.
9318  *
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.
9321  *
9322  * @param {Array} array The source array.
9323  * @param {string|Object|function()} expression The predicate to be used for selecting items from
9324  *   `array`.
9325  *
9326  *   Can be one of:
9327  *
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 `!`.
9331  *
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.
9338  *
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.
9342  *
9343  * @example
9344    <doc:example>
9345      <doc:source>
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>
9351
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>
9358          <tr>
9359        </table>
9360        <hr>
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>
9369          <tr>
9370        </table>
9371      </doc:source>
9372      <doc:scenario>
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']);
9377
9378          input('searchText').enter('76');
9379          expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
9380            toEqual(['John', 'Julie']);
9381        });
9382
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']);
9387        });
9388      </doc:scenario>
9389    </doc:example>
9390  */
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)) {
9398           return false;
9399         }
9400       }
9401       return true;
9402     };
9403     var search = function(obj, text){
9404       if (text.charAt(0) === '!') {
9405         return !search(obj, text.substr(1));
9406       }
9407       switch (typeof obj) {
9408         case "boolean":
9409         case "number":
9410         case "string":
9411           return ('' + obj).toLowerCase().indexOf(text) > -1;
9412         case "object":
9413           for ( var objKey in obj) {
9414             if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
9415               return true;
9416             }
9417           }
9418           return false;
9419         case "array":
9420           for ( var i = 0; i < obj.length; i++) {
9421             if (search(obj[i], text)) {
9422               return true;
9423             }
9424           }
9425           return false;
9426         default:
9427           return false;
9428       }
9429     };
9430     switch (typeof expression) {
9431       case "boolean":
9432       case "number":
9433       case "string":
9434         expression = {$:expression};
9435       case "object":
9436         for (var key in expression) {
9437           if (key == '$') {
9438             (function() {
9439               var text = (''+expression[key]).toLowerCase();
9440               if (!text) return;
9441               predicates.push(function(value) {
9442                 return search(value, text);
9443               });
9444             })();
9445           } else {
9446             (function() {
9447               var path = key;
9448               var text = (''+expression[key]).toLowerCase();
9449               if (!text) return;
9450               predicates.push(function(value) {
9451                 return search(getter(value, path), text);
9452               });
9453             })();
9454           }
9455         }
9456         break;
9457       case 'function':
9458         predicates.push(expression);
9459         break;
9460       default:
9461         return array;
9462     }
9463     var filtered = [];
9464     for ( var j = 0; j < array.length; j++) {
9465       var value = array[j];
9466       if (predicates.check(value)) {
9467         filtered.push(value);
9468       }
9469     }
9470     return filtered;
9471   }
9472 }
9473
9474 /**
9475  * @ngdoc filter
9476  * @name ng.filter:currency
9477  * @function
9478  *
9479  * @description
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.
9482  *
9483  * @param {number} amount Input to filter.
9484  * @param {string=} symbol Currency symbol or identifier to be displayed.
9485  * @returns {string} Formatted number.
9486  *
9487  *
9488  * @example
9489    <doc:example>
9490      <doc:source>
9491        <script>
9492          function Ctrl($scope) {
9493            $scope.amount = 1234.56;
9494          }
9495        </script>
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$"}}
9500        </div>
9501      </doc:source>
9502      <doc:scenario>
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');
9506        });
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)');
9511        });
9512      </doc:scenario>
9513    </doc:example>
9514  */
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);
9522   };
9523 }
9524
9525 /**
9526  * @ngdoc filter
9527  * @name ng.filter:number
9528  * @function
9529  *
9530  * @description
9531  * Formats a number as text.
9532  *
9533  * If the input is not a number an empty string is returned.
9534  *
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.
9538  *
9539  * @example
9540    <doc:example>
9541      <doc:source>
9542        <script>
9543          function Ctrl($scope) {
9544            $scope.val = 1234.56789;
9545          }
9546        </script>
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}}
9552        </div>
9553      </doc:source>
9554      <doc:scenario>
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');
9559        });
9560
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');
9566        });
9567      </doc:scenario>
9568    </doc:example>
9569  */
9570
9571
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,
9577       fractionSize);
9578   };
9579 }
9580
9581 var DECIMAL_SEP = '.';
9582 function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
9583   if (isNaN(number) || !isFinite(number)) return '';
9584
9585   var isNegative = number < 0;
9586   number = Math.abs(number);
9587   var numStr = number + '',
9588       formatedText = '',
9589       parts = [];
9590
9591   if (numStr.indexOf('e') !== -1) {
9592     formatedText = numStr;
9593   } else {
9594     var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
9595
9596     // determine fractionSize if it is not specified
9597     if (isUndefined(fractionSize)) {
9598       fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
9599     }
9600
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] || '';
9606
9607     var pos = 0,
9608         lgroup = pattern.lgSize,
9609         group = pattern.gSize;
9610
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;
9616         }
9617         formatedText += whole.charAt(i);
9618       }
9619     }
9620
9621     for (i = pos; i < whole.length; i++) {
9622       if ((whole.length - i)%lgroup === 0 && i !== 0) {
9623         formatedText += groupSep;
9624       }
9625       formatedText += whole.charAt(i);
9626     }
9627
9628     // format fraction part.
9629     while(fraction.length < fractionSize) {
9630       fraction += '0';
9631     }
9632
9633     if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize);
9634   }
9635
9636   parts.push(isNegative ? pattern.negPre : pattern.posPre);
9637   parts.push(formatedText);
9638   parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
9639   return parts.join('');
9640 }
9641
9642 function padNumber(num, digits, trim) {
9643   var neg = '';
9644   if (num < 0) {
9645     neg =  '-';
9646     num = -num;
9647   }
9648   num = '' + num;
9649   while(num.length < digits) num = '0' + num;
9650   if (trim)
9651     num = num.substr(num.length - digits);
9652   return neg + num;
9653 }
9654
9655
9656 function dateGetter(name, size, offset, trim) {
9657   return function(date) {
9658     var value = date['get' + name]();
9659     if (offset > 0 || value > -offset)
9660       value += offset;
9661     if (value === 0 && offset == -12 ) value = 12;
9662     return padNumber(value, size, trim);
9663   };
9664 }
9665
9666 function dateStrGetter(name, shortForm) {
9667   return function(date, formats) {
9668     var value = date['get' + name]();
9669     var get = uppercase(shortForm ? ('SHORT' + name) : name);
9670
9671     return formats[get][value];
9672   };
9673 }
9674
9675 function timeZoneGetter(date) {
9676   var offset = date.getTimezoneOffset();
9677   return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2);
9678 }
9679
9680 function ampmGetter(date, formats) {
9681   return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
9682 }
9683
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),
9704      a: ampmGetter,
9705      Z: timeZoneGetter
9706 };
9707
9708 var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
9709     NUMBER_STRING = /^\d+$/;
9710
9711 /**
9712  * @ngdoc filter
9713  * @name ng.filter:date
9714  * @function
9715  *
9716  * @description
9717  *   Formats `date` to a string based on the requested `format`.
9718  *
9719  *   `format` string can be composed of the following elements:
9720  *
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)
9742  *
9743  *   `format` string can also be one of the following predefined
9744  *   {@link guide/i18n localizable formats}:
9745  *
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)
9756  *
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"`).
9760  *
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.
9767  *
9768  * @example
9769    <doc:example>
9770      <doc:source>
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>
9777      </doc:source>
9778      <doc:scenario>
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)/);
9786        });
9787      </doc:scenario>
9788    </doc:example>
9789  */
9790 dateFilter.$inject = ['$locale'];
9791 function dateFilter($locale) {
9792
9793
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){
9796     var match;
9797     if (match = string.match(R_ISO8601_STR)) {
9798       var date = new Date(0),
9799           tzHour = 0,
9800           tzMin  = 0;
9801       if (match[9]) {
9802         tzHour = int(match[9] + match[10]);
9803         tzMin = int(match[9] + match[11]);
9804       }
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));
9807       return date;
9808     }
9809     return string;
9810   }
9811
9812
9813   return function(date, format) {
9814     var text = '',
9815         parts = [],
9816         fn, match;
9817
9818     format = format || 'mediumDate';
9819     format = $locale.DATETIME_FORMATS[format] || format;
9820     if (isString(date)) {
9821       if (NUMBER_STRING.test(date)) {
9822         date = int(date);
9823       } else {
9824         date = jsonStringToDate(date);
9825       }
9826     }
9827
9828     if (isNumber(date)) {
9829       date = new Date(date);
9830     }
9831
9832     if (!isDate(date)) {
9833       return date;
9834     }
9835
9836     while(format) {
9837       match = DATE_FORMATS_SPLIT.exec(format);
9838       if (match) {
9839         parts = concat(parts, match, 1);
9840         format = parts.pop();
9841       } else {
9842         parts.push(format);
9843         format = null;
9844       }
9845     }
9846
9847     forEach(parts, function(value){
9848       fn = DATE_FORMATS[value];
9849       text += fn ? fn(date, $locale.DATETIME_FORMATS)
9850                  : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
9851     });
9852
9853     return text;
9854   };
9855 }
9856
9857
9858 /**
9859  * @ngdoc filter
9860  * @name ng.filter:json
9861  * @function
9862  *
9863  * @description
9864  *   Allows you to convert a JavaScript object into JSON string.
9865  *
9866  *   This filter is mostly useful for debugging. When using the double curly {{value}} notation
9867  *   the binding is automatically converted to JSON.
9868  *
9869  * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
9870  * @returns {string} JSON string.
9871  *
9872  *
9873  * @example:
9874    <doc:example>
9875      <doc:source>
9876        <pre>{{ {'name':'value'} | json }}</pre>
9877      </doc:source>
9878      <doc:scenario>
9879        it('should jsonify filtered objects', function() {
9880          expect(binding("{'name':'value'}")).toMatch(/\{\n  "name": ?"value"\n}/);
9881        });
9882      </doc:scenario>
9883    </doc:example>
9884  *
9885  */
9886 function jsonFilter() {
9887   return function(object) {
9888     return toJson(object, true);
9889   };
9890 }
9891
9892
9893 /**
9894  * @ngdoc filter
9895  * @name ng.filter:lowercase
9896  * @function
9897  * @description
9898  * Converts string to lowercase.
9899  * @see angular.lowercase
9900  */
9901 var lowercaseFilter = valueFn(lowercase);
9902
9903
9904 /**
9905  * @ngdoc filter
9906  * @name ng.filter:uppercase
9907  * @function
9908  * @description
9909  * Converts string to uppercase.
9910  * @see angular.uppercase
9911  */
9912 var uppercaseFilter = valueFn(uppercase);
9913
9914 /**
9915  * @ngdoc function
9916  * @name ng.filter:limitTo
9917  * @function
9918  *
9919  * @description
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`.
9923  *
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.
9926  *
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`
9933  *     elements.
9934  *
9935  * @example
9936    <doc:example>
9937      <doc:source>
9938        <script>
9939          function Ctrl($scope) {
9940            $scope.numbers = [1,2,3,4,5,6,7,8,9];
9941            $scope.limit = 3;
9942          }
9943        </script>
9944        <div ng-controller="Ctrl">
9945          Limit {{numbers}} to: <input type="integer" ng-model="limit">
9946          <p>Output: {{ numbers | limitTo:limit }}</p>
9947        </div>
9948      </doc:source>
9949      <doc:scenario>
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]');
9953        });
9954
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]');
9958        });
9959
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]');
9963        });
9964      </doc:scenario>
9965    </doc:example>
9966  */
9967 function limitToFilter(){
9968   return function(array, limit) {
9969     if (!(array instanceof Array)) return array;
9970     limit = int(limit);
9971     var out = [],
9972       i, n;
9973
9974     // check that array is iterable
9975     if (!array || !(array instanceof Array))
9976       return out;
9977
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;
9983
9984     if (limit > 0) {
9985       i = 0;
9986       n = limit;
9987     } else {
9988       i = array.length + limit;
9989       n = array.length;
9990     }
9991
9992     for (; i<n; i++) {
9993       out.push(array[i]);
9994     }
9995
9996     return out;
9997   }
9998 }
9999
10000 /**
10001  * @ngdoc function
10002  * @name ng.filter:orderBy
10003  * @function
10004  *
10005  * @description
10006  * Orders a specified `array` by the `expression` predicate.
10007  *
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.
10010  *
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.
10014  *
10015  *    Can be one of:
10016  *
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.
10024  *
10025  * @param {boolean=} reverse Reverse the order the array.
10026  * @returns {Array} Sorted copy of the source array.
10027  *
10028  * @example
10029    <doc:example>
10030      <doc:source>
10031        <script>
10032          function Ctrl($scope) {
10033            $scope.friends =
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';
10040          }
10041        </script>
10042        <div ng-controller="Ctrl">
10043          <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
10044          <hr/>
10045          [ <a href="" ng-click="predicate=''">unsorted</a> ]
10046          <table class="friend">
10047            <tr>
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>
10052            <tr>
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>
10057            <tr>
10058          </table>
10059        </div>
10060      </doc:source>
10061      <doc:scenario>
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']);
10068        });
10069
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']);
10076
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']);
10082        });
10083      </doc:scenario>
10084    </doc:example>
10085  */
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);
10098         }
10099         get = $parse(predicate);
10100       }
10101       return reverseComparator(function(a,b){
10102         return compare(get(a),get(b));
10103       }, descending);
10104     });
10105     var arrayCopy = [];
10106     for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
10107     return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
10108
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;
10113       }
10114       return 0;
10115     }
10116     function reverseComparator(comp, descending) {
10117       return toBoolean(descending)
10118           ? function(a,b){return comp(b,a);}
10119           : comp;
10120     }
10121     function compare(v1, v2){
10122       var t1 = typeof v1;
10123       var t2 = typeof v2;
10124       if (t1 == t2) {
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;
10129       } else {
10130         return t1 < t2 ? -1 : 1;
10131       }
10132     }
10133   }
10134 }
10135
10136 function ngDirective(directive) {
10137   if (isFunction(directive)) {
10138     directive = {
10139       link: directive
10140     }
10141   }
10142   directive.restrict = directive.restrict || 'AC';
10143   return valueFn(directive);
10144 }
10145
10146 /**
10147  * @ngdoc directive
10148  * @name ng.directive:a
10149  * @restrict E
10150  *
10151  * @description
10152  * Modifies the default behavior of html A tag, so that the default action is prevented when href
10153  * attribute is empty.
10154  *
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>
10158  */
10159 var htmlAnchorDirective = valueFn({
10160   restrict: 'E',
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
10164     if (!attr.href) {
10165       attr.$set('href', '');
10166     }
10167
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();
10173         }
10174       });
10175     }
10176   }
10177 });
10178
10179 /**
10180  * @ngdoc directive
10181  * @name ng.directive:ngHref
10182  * @restrict A
10183  *
10184  * @description
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.
10190  *
10191  * The buggy way to write it:
10192  * <pre>
10193  * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
10194  * </pre>
10195  *
10196  * The correct way to write it:
10197  * <pre>
10198  * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
10199  * </pre>
10200  *
10201  * @element A
10202  * @param {template} ngHref any string which can contain `{{}}` markup.
10203  *
10204  * @example
10205  * This example uses `link` variable inside `href` attribute:
10206     <doc:example>
10207       <doc:source>
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)
10215       </doc:source>
10216       <doc:scenario>
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("");
10221         });
10222
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("");
10227         });
10228
10229         it('should execute ng-click and change url when ng-href specified', function() {
10230           expect(element('#link-3').attr('href')).toBe("/123");
10231
10232           element('#link-3').click();
10233           expect(browser().window().path()).toEqual('/123');
10234         });
10235
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('');
10240         });
10241
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('');
10246         });
10247
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');
10251
10252           element('#link-6').click();
10253           expect(browser().location().url()).toEqual('/6');
10254         });
10255       </doc:scenario>
10256     </doc:example>
10257  */
10258
10259 /**
10260  * @ngdoc directive
10261  * @name ng.directive:ngSrc
10262  * @restrict A
10263  *
10264  * @description
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.
10269  *
10270  * The buggy way to write it:
10271  * <pre>
10272  * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
10273  * </pre>
10274  *
10275  * The correct way to write it:
10276  * <pre>
10277  * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
10278  * </pre>
10279  *
10280  * @element IMG
10281  * @param {template} ngSrc any string which can contain `{{}}` markup.
10282  */
10283
10284 /**
10285  * @ngdoc directive
10286  * @name ng.directive:ngDisabled
10287  * @restrict A
10288  *
10289  * @description
10290  *
10291  * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
10292  * <pre>
10293  * <div ng-init="scope = { isDisabled: false }">
10294  *  <button disabled="{{scope.isDisabled}}">Disabled</button>
10295  * </div>
10296  * </pre>
10297  *
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.
10302  *
10303  * @example
10304     <doc:example>
10305       <doc:source>
10306         Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
10307         <button ng-model="button" ng-disabled="checked">Button</button>
10308       </doc:source>
10309       <doc:scenario>
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();
10314         });
10315       </doc:scenario>
10316     </doc:example>
10317  *
10318  * @element INPUT
10319  * @param {expression} ngDisabled Angular expression that will be evaluated.
10320  */
10321
10322
10323 /**
10324  * @ngdoc directive
10325  * @name ng.directive:ngChecked
10326  * @restrict A
10327  *
10328  * @description
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.
10333  * @example
10334     <doc:example>
10335       <doc:source>
10336         Check me to check both: <input type="checkbox" ng-model="master"><br/>
10337         <input id="checkSlave" type="checkbox" ng-checked="master">
10338       </doc:source>
10339       <doc:scenario>
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();
10344         });
10345       </doc:scenario>
10346     </doc:example>
10347  *
10348  * @element INPUT
10349  * @param {expression} ngChecked Angular expression that will be evaluated.
10350  */
10351
10352
10353 /**
10354  * @ngdoc directive
10355  * @name ng.directive:ngMultiple
10356  * @restrict A
10357  *
10358  * @description
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.
10363  *
10364  * @example
10365      <doc:example>
10366        <doc:source>
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>
10373          </select>
10374        </doc:source>
10375        <doc:scenario>
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();
10380          });
10381        </doc:scenario>
10382      </doc:example>
10383  *
10384  * @element SELECT
10385  * @param {expression} ngMultiple Angular expression that will be evaluated.
10386  */
10387
10388
10389 /**
10390  * @ngdoc directive
10391  * @name ng.directive:ngReadonly
10392  * @restrict A
10393  *
10394  * @description
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.
10399  * @example
10400     <doc:example>
10401       <doc:source>
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"/>
10404       </doc:source>
10405       <doc:scenario>
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();
10410         });
10411       </doc:scenario>
10412     </doc:example>
10413  *
10414  * @element INPUT
10415  * @param {string} expression Angular expression that will be evaluated.
10416  */
10417
10418
10419 /**
10420  * @ngdoc directive
10421  * @name ng.directive:ngSelected
10422  * @restrict A
10423  *
10424  * @description
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.
10429  * @example
10430     <doc:example>
10431       <doc:source>
10432         Check me to select: <input type="checkbox" ng-model="selected"><br/>
10433         <select>
10434           <option>Hello!</option>
10435           <option id="greet" ng-selected="selected">Greetings!</option>
10436         </select>
10437       </doc:source>
10438       <doc:scenario>
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();
10443         });
10444       </doc:scenario>
10445     </doc:example>
10446  *
10447  * @element OPTION
10448  * @param {string} expression Angular expression that will be evaluated.
10449  */
10450
10451
10452 var ngAttributeAliasDirectives = {};
10453
10454
10455 // boolean attrs are evaluated
10456 forEach(BOOLEAN_ATTR, function(propName, attrName) {
10457   var normalized = directiveNormalize('ng-' + attrName);
10458   ngAttributeAliasDirectives[normalized] = function() {
10459     return {
10460       priority: 100,
10461       compile: function() {
10462         return function(scope, element, attr) {
10463           scope.$watch(attr[normalized], function(value) {
10464             attr.$set(attrName, !!value);
10465           });
10466         };
10467       }
10468     };
10469   };
10470 });
10471
10472
10473 // ng-src, ng-href are interpolated
10474 forEach(['src', 'href'], function(attrName) {
10475   var normalized = directiveNormalize('ng-' + attrName);
10476   ngAttributeAliasDirectives[normalized] = function() {
10477     return {
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);
10482
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);
10487         });
10488       }
10489     };
10490   };
10491 });
10492
10493 var nullFormCtrl = {
10494   $addControl: noop,
10495   $removeControl: noop,
10496   $setValidity: noop,
10497   $setDirty: noop
10498 };
10499
10500 /**
10501  * @ngdoc object
10502  * @name ng.directive:form.FormController
10503  *
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.
10508  *
10509  * @property {Object} $error Is an object hash, containing references to all invalid controls or
10510  *  forms, where:
10511  *
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.
10514  *
10515  * @description
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.
10518  *
10519  * Each {@link ng.directive:form form} directive creates an instance
10520  * of `FormController`.
10521  *
10522  */
10523 //asks for $scope to fool the BC controller module
10524 FormController.$inject = ['$element', '$attrs', '$scope'];
10525 function FormController(element, attrs) {
10526   var form = this,
10527       parentForm = element.parent().controller('form') || nullFormCtrl,
10528       invalidCount = 0, // used to easily determine if we are valid
10529       errors = form.$error = {};
10530
10531   // init state
10532   form.$name = attrs.name;
10533   form.$dirty = false;
10534   form.$pristine = true;
10535   form.$valid = true;
10536   form.$invalid = false;
10537
10538   parentForm.$addControl(form);
10539
10540   // Setup initial state of the control
10541   element.addClass(PRISTINE_CLASS);
10542   toggleValidCss(true);
10543
10544   // convenience method for easy toggling of classes
10545   function toggleValidCss(isValid, validationErrorKey) {
10546     validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
10547     element.
10548       removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
10549       addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
10550   }
10551
10552   form.$addControl = function(control) {
10553     if (control.$name && !form.hasOwnProperty(control.$name)) {
10554       form[control.$name] = control;
10555     }
10556   };
10557
10558   form.$removeControl = function(control) {
10559     if (control.$name && form[control.$name] === control) {
10560       delete form[control.$name];
10561     }
10562     forEach(errors, function(queue, validationToken) {
10563       form.$setValidity(validationToken, true, control);
10564     });
10565   };
10566
10567   form.$setValidity = function(validationToken, isValid, control) {
10568     var queue = errors[validationToken];
10569
10570     if (isValid) {
10571       if (queue) {
10572         arrayRemove(queue, control);
10573         if (!queue.length) {
10574           invalidCount--;
10575           if (!invalidCount) {
10576             toggleValidCss(isValid);
10577             form.$valid = true;
10578             form.$invalid = false;
10579           }
10580           errors[validationToken] = false;
10581           toggleValidCss(true, validationToken);
10582           parentForm.$setValidity(validationToken, true, form);
10583         }
10584       }
10585
10586     } else {
10587       if (!invalidCount) {
10588         toggleValidCss(isValid);
10589       }
10590       if (queue) {
10591         if (includes(queue, control)) return;
10592       } else {
10593         errors[validationToken] = queue = [];
10594         invalidCount++;
10595         toggleValidCss(false, validationToken);
10596         parentForm.$setValidity(validationToken, false, form);
10597       }
10598       queue.push(control);
10599
10600       form.$valid = false;
10601       form.$invalid = true;
10602     }
10603   };
10604
10605   form.$setDirty = function() {
10606     element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
10607     form.$dirty = true;
10608     form.$pristine = false;
10609   };
10610
10611 }
10612
10613
10614 /**
10615  * @ngdoc directive
10616  * @name ng.directive:ngForm
10617  * @restrict EAC
10618  *
10619  * @description
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.
10623  *
10624  * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
10625  *                       related scope, under this name.
10626  *
10627  */
10628
10629  /**
10630  * @ngdoc directive
10631  * @name ng.directive:form
10632  * @restrict E
10633  *
10634  * @description
10635  * Directive that instantiates
10636  * {@link ng.directive:form.FormController FormController}.
10637  *
10638  * If `name` attribute is specified, the form controller is published onto the current scope under
10639  * this name.
10640  *
10641  * # Alias: {@link ng.directive:ngForm `ngForm`}
10642  *
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.
10647  *
10648  *
10649  * # CSS classes
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.
10654  *
10655  *
10656  * # Submitting a form and preventing default action
10657  *
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.
10662  *
10663  * For this reason, Angular prevents the default action (form submission to the server) unless the
10664  * `<form>` element has an `action` attribute specified.
10665  *
10666  * You can use one of the following two ways to specify what javascript method should be called when
10667  * a form is submitted:
10668  *
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])
10672  *
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:
10675  *
10676  * - If a form has only one input field then hitting enter in this field triggers form submit
10677  * (`ngSubmit`)
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`)
10683  *
10684  * @param {string=} name Name of the form. If specified, the form controller will be published into
10685  *                       related scope, under this name.
10686  *
10687  * @example
10688     <doc:example>
10689       <doc:source>
10690        <script>
10691          function Ctrl($scope) {
10692            $scope.userType = 'guest';
10693          }
10694        </script>
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>
10703         </form>
10704       </doc:source>
10705       <doc:scenario>
10706         it('should initialize to model', function() {
10707          expect(binding('userType')).toEqual('guest');
10708          expect(binding('myForm.input.$valid')).toEqual('true');
10709         });
10710
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');
10715         });
10716       </doc:scenario>
10717     </doc:example>
10718  */
10719 var formDirectiveFactory = function(isNgForm) {
10720   return ['$timeout', function($timeout) {
10721     var formDirective = {
10722       name: 'form',
10723       restrict: 'E',
10724       controller: FormController,
10725       compile: function() {
10726         return {
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
10731               //
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
10739               };
10740
10741               addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
10742
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);
10748                 }, 0, false);
10749               });
10750             }
10751
10752             var parentFormCtrl = formElement.parent().controller('form'),
10753                 alias = attr.name || attr.ngForm;
10754
10755             if (alias) {
10756               scope[alias] = controller;
10757             }
10758             if (parentFormCtrl) {
10759               formElement.bind('$destroy', function() {
10760                 parentFormCtrl.$removeControl(controller);
10761                 if (alias) {
10762                   scope[alias] = undefined;
10763                 }
10764                 extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
10765               });
10766             }
10767           }
10768         };
10769       }
10770     };
10771
10772     return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective;
10773   }];
10774 };
10775
10776 var formDirective = formDirectiveFactory();
10777 var ngFormDirective = formDirectiveFactory(true);
10778
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*$/;
10782
10783 var inputType = {
10784
10785   /**
10786    * @ngdoc inputType
10787    * @name ng.directive:input.text
10788    *
10789    * @description
10790    * Standard HTML text input with angular data binding.
10791    *
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
10796    *    minlength.
10797    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
10798    *    maxlength.
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.
10804    *
10805    * @example
10806       <doc:example>
10807         <doc:source>
10808          <script>
10809            function Ctrl($scope) {
10810              $scope.text = 'guest';
10811              $scope.word = /^\w*$/;
10812            }
10813          </script>
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">
10818              Required!</span>
10819            <span class="error" ng-show="myForm.input.$error.pattern">
10820              Single word only!</span>
10821
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/>
10827           </form>
10828         </doc:source>
10829         <doc:scenario>
10830           it('should initialize to model', function() {
10831             expect(binding('text')).toEqual('guest');
10832             expect(binding('myForm.input.$valid')).toEqual('true');
10833           });
10834
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');
10839           });
10840
10841           it('should be invalid if multi word', function() {
10842             input('text').enter('hello world');
10843             expect(binding('myForm.input.$valid')).toEqual('false');
10844           });
10845         </doc:scenario>
10846       </doc:example>
10847    */
10848   'text': textInputType,
10849
10850
10851   /**
10852    * @ngdoc inputType
10853    * @name ng.directive:input.number
10854    *
10855    * @description
10856    * Text input with number validation and transformation. Sets the `number` validation
10857    * error if not a valid number.
10858    *
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
10865    *    minlength.
10866    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
10867    *    maxlength.
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.
10873    *
10874    * @example
10875       <doc:example>
10876         <doc:source>
10877          <script>
10878            function Ctrl($scope) {
10879              $scope.value = 12;
10880            }
10881          </script>
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">
10886              Required!</span>
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/>
10894           </form>
10895         </doc:source>
10896         <doc:scenario>
10897           it('should initialize to model', function() {
10898            expect(binding('value')).toEqual('12');
10899            expect(binding('myForm.input.$valid')).toEqual('true');
10900           });
10901
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');
10906           });
10907
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');
10912           });
10913         </doc:scenario>
10914       </doc:example>
10915    */
10916   'number': numberInputType,
10917
10918
10919   /**
10920    * @ngdoc inputType
10921    * @name ng.directive:input.url
10922    *
10923    * @description
10924    * Text input with URL validation. Sets the `url` validation error key if the content is not a
10925    * valid URL.
10926    *
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
10931    *    minlength.
10932    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
10933    *    maxlength.
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.
10939    *
10940    * @example
10941       <doc:example>
10942         <doc:source>
10943          <script>
10944            function Ctrl($scope) {
10945              $scope.text = 'http://google.com';
10946            }
10947          </script>
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">
10951              Required!</span>
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/>
10960           </form>
10961         </doc:source>
10962         <doc:scenario>
10963           it('should initialize to model', function() {
10964             expect(binding('text')).toEqual('http://google.com');
10965             expect(binding('myForm.input.$valid')).toEqual('true');
10966           });
10967
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');
10972           });
10973
10974           it('should be invalid if not url', function() {
10975             input('text').enter('xxx');
10976             expect(binding('myForm.input.$valid')).toEqual('false');
10977           });
10978         </doc:scenario>
10979       </doc:example>
10980    */
10981   'url': urlInputType,
10982
10983
10984   /**
10985    * @ngdoc inputType
10986    * @name ng.directive:input.email
10987    *
10988    * @description
10989    * Text input with email validation. Sets the `email` validation error key if not a valid email
10990    * address.
10991    *
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
10996    *    minlength.
10997    * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
10998    *    maxlength.
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.
11002    *
11003    * @example
11004       <doc:example>
11005         <doc:source>
11006          <script>
11007            function Ctrl($scope) {
11008              $scope.text = 'me@example.com';
11009            }
11010          </script>
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">
11014                Required!</span>
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/>
11023            </form>
11024         </doc:source>
11025         <doc:scenario>
11026           it('should initialize to model', function() {
11027             expect(binding('text')).toEqual('me@example.com');
11028             expect(binding('myForm.input.$valid')).toEqual('true');
11029           });
11030
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');
11035           });
11036
11037           it('should be invalid if not email', function() {
11038             input('text').enter('xxx');
11039             expect(binding('myForm.input.$valid')).toEqual('false');
11040           });
11041         </doc:scenario>
11042       </doc:example>
11043    */
11044   'email': emailInputType,
11045
11046
11047   /**
11048    * @ngdoc inputType
11049    * @name ng.directive:input.radio
11050    *
11051    * @description
11052    * HTML radio button.
11053    *
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.
11059    *
11060    * @example
11061       <doc:example>
11062         <doc:source>
11063          <script>
11064            function Ctrl($scope) {
11065              $scope.color = 'blue';
11066            }
11067          </script>
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/>
11073           </form>
11074         </doc:source>
11075         <doc:scenario>
11076           it('should change state', function() {
11077             expect(binding('color')).toEqual('blue');
11078
11079             input('color').select('red');
11080             expect(binding('color')).toEqual('red');
11081           });
11082         </doc:scenario>
11083       </doc:example>
11084    */
11085   'radio': radioInputType,
11086
11087
11088   /**
11089    * @ngdoc inputType
11090    * @name ng.directive:input.checkbox
11091    *
11092    * @description
11093    * HTML checkbox.
11094    *
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.
11101    *
11102    * @example
11103       <doc:example>
11104         <doc:source>
11105          <script>
11106            function Ctrl($scope) {
11107              $scope.value1 = true;
11108              $scope.value2 = 'YES'
11109            }
11110          </script>
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/>
11117           </form>
11118         </doc:source>
11119         <doc:scenario>
11120           it('should change state', function() {
11121             expect(binding('value1')).toEqual('true');
11122             expect(binding('value2')).toEqual('YES');
11123
11124             input('value1').check();
11125             input('value2').check();
11126             expect(binding('value1')).toEqual('false');
11127             expect(binding('value2')).toEqual('NO');
11128           });
11129         </doc:scenario>
11130       </doc:example>
11131    */
11132   'checkbox': checkboxInputType,
11133
11134   'hidden': noop,
11135   'button': noop,
11136   'submit': noop,
11137   'reset': noop
11138 };
11139
11140
11141 function isEmpty(value) {
11142   return isUndefined(value) || value === '' || value === null || value !== value;
11143 }
11144
11145
11146 function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11147
11148   var listener = function() {
11149     var value = trim(element.val());
11150
11151     if (ctrl.$viewValue !== value) {
11152       scope.$apply(function() {
11153         ctrl.$setViewValue(value);
11154       });
11155     }
11156   };
11157
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);
11162   } else {
11163     var timeout;
11164
11165     element.bind('keydown', function(event) {
11166       var key = event.keyCode;
11167
11168       // ignore
11169       //    command            modifiers                   arrows
11170       if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
11171
11172       if (!timeout) {
11173         timeout = $browser.defer(function() {
11174           listener();
11175           timeout = null;
11176         });
11177       }
11178     });
11179
11180     // if user paste into input using mouse, we need "change" event to catch it
11181     element.bind('change', listener);
11182   }
11183
11184
11185   ctrl.$render = function() {
11186     element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
11187   };
11188
11189   // pattern validator
11190   var pattern = attr.ngPattern,
11191       patternValidator;
11192
11193   var validate = function(regexp, value) {
11194     if (isEmpty(value) || regexp.test(value)) {
11195       ctrl.$setValidity('pattern', true);
11196       return value;
11197     } else {
11198       ctrl.$setValidity('pattern', false);
11199       return undefined;
11200     }
11201   };
11202
11203   if (pattern) {
11204     if (pattern.match(/^\/(.*)\/$/)) {
11205       pattern = new RegExp(pattern.substr(1, pattern.length - 2));
11206       patternValidator = function(value) {
11207         return validate(pattern, value)
11208       };
11209     } else {
11210       patternValidator = function(value) {
11211         var patternObj = scope.$eval(pattern);
11212
11213         if (!patternObj || !patternObj.test) {
11214           throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
11215         }
11216         return validate(patternObj, value);
11217       };
11218     }
11219
11220     ctrl.$formatters.push(patternValidator);
11221     ctrl.$parsers.push(patternValidator);
11222   }
11223
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);
11230         return undefined;
11231       } else {
11232         ctrl.$setValidity('minlength', true);
11233         return value;
11234       }
11235     };
11236
11237     ctrl.$parsers.push(minLengthValidator);
11238     ctrl.$formatters.push(minLengthValidator);
11239   }
11240
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);
11247         return undefined;
11248       } else {
11249         ctrl.$setValidity('maxlength', true);
11250         return value;
11251       }
11252     };
11253
11254     ctrl.$parsers.push(maxLengthValidator);
11255     ctrl.$formatters.push(maxLengthValidator);
11256   }
11257 }
11258
11259 function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11260   textInputType(scope, element, attr, ctrl, $sniffer, $browser);
11261
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));
11267     } else {
11268       ctrl.$setValidity('number', false);
11269       return undefined;
11270     }
11271   });
11272
11273   ctrl.$formatters.push(function(value) {
11274     return isEmpty(value) ? '' : '' + value;
11275   });
11276
11277   if (attr.min) {
11278     var min = parseFloat(attr.min);
11279     var minValidator = function(value) {
11280       if (!isEmpty(value) && value < min) {
11281         ctrl.$setValidity('min', false);
11282         return undefined;
11283       } else {
11284         ctrl.$setValidity('min', true);
11285         return value;
11286       }
11287     };
11288
11289     ctrl.$parsers.push(minValidator);
11290     ctrl.$formatters.push(minValidator);
11291   }
11292
11293   if (attr.max) {
11294     var max = parseFloat(attr.max);
11295     var maxValidator = function(value) {
11296       if (!isEmpty(value) && value > max) {
11297         ctrl.$setValidity('max', false);
11298         return undefined;
11299       } else {
11300         ctrl.$setValidity('max', true);
11301         return value;
11302       }
11303     };
11304
11305     ctrl.$parsers.push(maxValidator);
11306     ctrl.$formatters.push(maxValidator);
11307   }
11308
11309   ctrl.$formatters.push(function(value) {
11310
11311     if (isEmpty(value) || isNumber(value)) {
11312       ctrl.$setValidity('number', true);
11313       return value;
11314     } else {
11315       ctrl.$setValidity('number', false);
11316       return undefined;
11317     }
11318   });
11319 }
11320
11321 function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11322   textInputType(scope, element, attr, ctrl, $sniffer, $browser);
11323
11324   var urlValidator = function(value) {
11325     if (isEmpty(value) || URL_REGEXP.test(value)) {
11326       ctrl.$setValidity('url', true);
11327       return value;
11328     } else {
11329       ctrl.$setValidity('url', false);
11330       return undefined;
11331     }
11332   };
11333
11334   ctrl.$formatters.push(urlValidator);
11335   ctrl.$parsers.push(urlValidator);
11336 }
11337
11338 function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11339   textInputType(scope, element, attr, ctrl, $sniffer, $browser);
11340
11341   var emailValidator = function(value) {
11342     if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
11343       ctrl.$setValidity('email', true);
11344       return value;
11345     } else {
11346       ctrl.$setValidity('email', false);
11347       return undefined;
11348     }
11349   };
11350
11351   ctrl.$formatters.push(emailValidator);
11352   ctrl.$parsers.push(emailValidator);
11353 }
11354
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());
11359   }
11360
11361   element.bind('click', function() {
11362     if (element[0].checked) {
11363       scope.$apply(function() {
11364         ctrl.$setViewValue(attr.value);
11365       });
11366     }
11367   });
11368
11369   ctrl.$render = function() {
11370     var value = attr.value;
11371     element[0].checked = (value == ctrl.$viewValue);
11372   };
11373
11374   attr.$observe('value', ctrl.$render);
11375 }
11376
11377 function checkboxInputType(scope, element, attr, ctrl) {
11378   var trueValue = attr.ngTrueValue,
11379       falseValue = attr.ngFalseValue;
11380
11381   if (!isString(trueValue)) trueValue = true;
11382   if (!isString(falseValue)) falseValue = false;
11383
11384   element.bind('click', function() {
11385     scope.$apply(function() {
11386       ctrl.$setViewValue(element[0].checked);
11387     });
11388   });
11389
11390   ctrl.$render = function() {
11391     element[0].checked = ctrl.$viewValue;
11392   };
11393
11394   ctrl.$formatters.push(function(value) {
11395     return value === trueValue;
11396   });
11397
11398   ctrl.$parsers.push(function(value) {
11399     return value ? trueValue : falseValue;
11400   });
11401 }
11402
11403
11404 /**
11405  * @ngdoc directive
11406  * @name ng.directive:textarea
11407  * @restrict E
11408  *
11409  * @description
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}.
11413  *
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
11418  *    minlength.
11419  * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
11420  *    maxlength.
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.
11426  */
11427
11428
11429 /**
11430  * @ngdoc directive
11431  * @name ng.directive:input
11432  * @restrict E
11433  *
11434  * @description
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.
11437  *
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
11442  *    minlength.
11443  * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
11444  *    maxlength.
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.
11450  *
11451  * @example
11452     <doc:example>
11453       <doc:source>
11454        <script>
11455          function Ctrl($scope) {
11456            $scope.user = {name: 'guest', last: 'visitor'};
11457          }
11458        </script>
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">
11467              Too short!</span>
11468            <span class="error" ng-show="myForm.lastName.$error.maxlength">
11469              Too long!</span><br>
11470          </form>
11471          <hr>
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>
11481        </div>
11482       </doc:source>
11483       <doc:scenario>
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');
11488         });
11489
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');
11495         });
11496
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');
11502         });
11503
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');
11510         });
11511
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');
11519         });
11520       </doc:scenario>
11521     </doc:example>
11522  */
11523 var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
11524   return {
11525     restrict: 'E',
11526     require: '?ngModel',
11527     link: function(scope, element, attr, ctrl) {
11528       if (ctrl) {
11529         (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
11530                                                             $browser);
11531       }
11532     }
11533   };
11534 }];
11535
11536 var VALID_CLASS = 'ng-valid',
11537     INVALID_CLASS = 'ng-invalid',
11538     PRISTINE_CLASS = 'ng-pristine',
11539     DIRTY_CLASS = 'ng-dirty';
11540
11541 /**
11542  * @ngdoc object
11543  * @name ng.directive:ngModel.NgModelController
11544  *
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.
11549  *
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.
11552  *
11553  * @property {Object} $error An bject hash with all errors as keys.
11554  *
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.
11559  *
11560  * @description
11561  *
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.
11567  *
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.
11571  *
11572  * <example module="customControl">
11573     <file name="style.css">
11574       [contenteditable] {
11575         border: 1px solid black;
11576         background-color: white;
11577         min-height: 20px;
11578       }
11579
11580       .ng-invalid {
11581         border: 1px solid red;
11582       }
11583
11584     </file>
11585     <file name="script.js">
11586       angular.module('customControl', []).
11587         directive('contenteditable', function() {
11588           return {
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
11593
11594               // Specify how UI should be updated
11595               ngModel.$render = function() {
11596                 element.html(ngModel.$viewValue || '');
11597               };
11598
11599               // Listen for change events to enable binding
11600               element.bind('blur keyup change', function() {
11601                 scope.$apply(read);
11602               });
11603               read(); // initialize
11604
11605               // Write data to the model
11606               function read() {
11607                 ngModel.$setViewValue(element.html());
11608               }
11609             }
11610           };
11611         });
11612     </file>
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>
11619        <hr>
11620        <textarea ng-model="userContent"></textarea>
11621       </form>
11622     </file>
11623     <file name="scenario.js">
11624       it('should data-bind and become invalid', function() {
11625         var contentEditable = element('[contenteditable]');
11626
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/);
11631       });
11632     </file>
11633  * </example>
11634  *
11635  */
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;
11648
11649   var ngModelGet = $parse($attr.ngModel),
11650       ngModelSet = ngModelGet.assign;
11651
11652   if (!ngModelSet) {
11653     throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
11654         ' (' + startingTag($element) + ')');
11655   }
11656
11657   /**
11658    * @ngdoc function
11659    * @name ng.directive:ngModel.NgModelController#$render
11660    * @methodOf ng.directive:ngModel.NgModelController
11661    *
11662    * @description
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.
11665    */
11666   this.$render = noop;
11667
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
11671
11672
11673   // Setup initial state of the control
11674   $element.addClass(PRISTINE_CLASS);
11675   toggleValidCss(true);
11676
11677   // convenience method for easy toggling of classes
11678   function toggleValidCss(isValid, validationErrorKey) {
11679     validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
11680     $element.
11681       removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
11682       addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
11683   }
11684
11685   /**
11686    * @ngdoc function
11687    * @name ng.directive:ngModel.NgModelController#$setValidity
11688    * @methodOf ng.directive:ngModel.NgModelController
11689    *
11690    * @description
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).
11693    *
11694    * This method should be called by validators - i.e. the parser or formatter functions.
11695    *
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).
11702    */
11703   this.$setValidity = function(validationErrorKey, isValid) {
11704     if ($error[validationErrorKey] === !isValid) return;
11705
11706     if (isValid) {
11707       if ($error[validationErrorKey]) invalidCount--;
11708       if (!invalidCount) {
11709         toggleValidCss(true);
11710         this.$valid = true;
11711         this.$invalid = false;
11712       }
11713     } else {
11714       toggleValidCss(false);
11715       this.$invalid = true;
11716       this.$valid = false;
11717       invalidCount++;
11718     }
11719
11720     $error[validationErrorKey] = !isValid;
11721     toggleValidCss(isValid, validationErrorKey);
11722
11723     parentForm.$setValidity(validationErrorKey, isValid, this);
11724   };
11725
11726
11727   /**
11728    * @ngdoc function
11729    * @name ng.directive:ngModel.NgModelController#$setViewValue
11730    * @methodOf ng.directive:ngModel.NgModelController
11731    *
11732    * @description
11733    * Read a value from view.
11734    *
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.
11738    *
11739    * It internally calls all `formatters` and if resulted value is valid, updates the model and
11740    * calls all registered change listeners.
11741    *
11742    * @param {string} value Value from the view.
11743    */
11744   this.$setViewValue = function(value) {
11745     this.$viewValue = value;
11746
11747     // change to dirty
11748     if (this.$pristine) {
11749       this.$dirty = true;
11750       this.$pristine = false;
11751       $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
11752       parentForm.$setDirty();
11753     }
11754
11755     forEach(this.$parsers, function(fn) {
11756       value = fn(value);
11757     });
11758
11759     if (this.$modelValue !== value) {
11760       this.$modelValue = value;
11761       ngModelSet($scope, value);
11762       forEach(this.$viewChangeListeners, function(listener) {
11763         try {
11764           listener();
11765         } catch(e) {
11766           $exceptionHandler(e);
11767         }
11768       })
11769     }
11770   };
11771
11772   // model -> value
11773   var ctrl = this;
11774   $scope.$watch(ngModelGet, function(value) {
11775
11776     // ignore change from view
11777     if (ctrl.$modelValue === value) return;
11778
11779     var formatters = ctrl.$formatters,
11780         idx = formatters.length;
11781
11782     ctrl.$modelValue = value;
11783     while(idx--) {
11784       value = formatters[idx](value);
11785     }
11786
11787     if (ctrl.$viewValue !== value) {
11788       ctrl.$viewValue = value;
11789       ctrl.$render();
11790     }
11791   });
11792 }];
11793
11794
11795 /**
11796  * @ngdoc directive
11797  * @name ng.directive:ngModel
11798  *
11799  * @element input
11800  *
11801  * @description
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.
11804  *
11805  * `ngModel` is responsible for:
11806  *
11807  * - binding the view into the model, which other directives such as `input`, `textarea` or `select`
11808  *   require,
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}.
11813  *
11814  * For basic examples, how to use `ngModel`, see:
11815  *
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}
11825  *
11826  */
11827 var ngModelDirective = function() {
11828   return {
11829     require: ['ngModel', '^?form'],
11830     controller: NgModelController,
11831     link: function(scope, element, attr, ctrls) {
11832       // notify others, especially parent forms
11833
11834       var modelCtrl = ctrls[0],
11835           formCtrl = ctrls[1] || nullFormCtrl;
11836
11837       formCtrl.$addControl(modelCtrl);
11838
11839       element.bind('$destroy', function() {
11840         formCtrl.$removeControl(modelCtrl);
11841       });
11842     }
11843   };
11844 };
11845
11846
11847 /**
11848  * @ngdoc directive
11849  * @name ng.directive:ngChange
11850  * @restrict E
11851  *
11852  * @description
11853  * Evaluate given expression when user changes the input.
11854  * The expression is not evaluated when the value change is coming from the model.
11855  *
11856  * Note, this directive requires `ngModel` to be present.
11857  *
11858  * @element input
11859  *
11860  * @example
11861  * <doc:example>
11862  *   <doc:source>
11863  *     <script>
11864  *       function Controller($scope) {
11865  *         $scope.counter = 0;
11866  *         $scope.change = function() {
11867  *           $scope.counter++;
11868  *         };
11869  *       }
11870  *     </script>
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}}
11877  *     </div>
11878  *   </doc:source>
11879  *   <doc:scenario>
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');
11885  *     });
11886  *
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');
11891  *     });
11892  *   </doc:scenario>
11893  * </doc:example>
11894  */
11895 var ngChangeDirective = valueFn({
11896   require: 'ngModel',
11897   link: function(scope, element, attr, ctrl) {
11898     ctrl.$viewChangeListeners.push(function() {
11899       scope.$eval(attr.ngChange);
11900     });
11901   }
11902 });
11903
11904
11905 var requiredDirective = function() {
11906   return {
11907     require: '?ngModel',
11908     link: function(scope, elm, attr, ctrl) {
11909       if (!ctrl) return;
11910       attr.required = true; // force truthy in case we are on non input element
11911
11912       var validator = function(value) {
11913         if (attr.required && (isEmpty(value) || value === false)) {
11914           ctrl.$setValidity('required', false);
11915           return;
11916         } else {
11917           ctrl.$setValidity('required', true);
11918           return value;
11919         }
11920       };
11921
11922       ctrl.$formatters.push(validator);
11923       ctrl.$parsers.unshift(validator);
11924
11925       attr.$observe('required', function() {
11926         validator(ctrl.$viewValue);
11927       });
11928     }
11929   };
11930 };
11931
11932
11933 /**
11934  * @ngdoc directive
11935  * @name ng.directive:ngList
11936  *
11937  * @description
11938  * Text input that converts between comma-seperated string into an array of strings.
11939  *
11940  * @element input
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.
11943  *
11944  * @example
11945     <doc:example>
11946       <doc:source>
11947        <script>
11948          function Ctrl($scope) {
11949            $scope.names = ['igor', 'misko', 'vojta'];
11950          }
11951        </script>
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">
11955            Required!</span>
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/>
11961         </form>
11962       </doc:source>
11963       <doc:scenario>
11964         it('should initialize to model', function() {
11965           expect(binding('names')).toEqual('["igor","misko","vojta"]');
11966           expect(binding('myForm.namesInput.$valid')).toEqual('true');
11967         });
11968
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');
11973         });
11974       </doc:scenario>
11975     </doc:example>
11976  */
11977 var ngListDirective = function() {
11978   return {
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 || ',';
11983
11984       var parse = function(viewValue) {
11985         var list = [];
11986
11987         if (viewValue) {
11988           forEach(viewValue.split(separator), function(value) {
11989             if (value) list.push(trim(value));
11990           });
11991         }
11992
11993         return list;
11994       };
11995
11996       ctrl.$parsers.push(parse);
11997       ctrl.$formatters.push(function(value) {
11998         if (isArray(value)) {
11999           return value.join(', ');
12000         }
12001
12002         return undefined;
12003       });
12004     }
12005   };
12006 };
12007
12008
12009 var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
12010
12011 var ngValueDirective = function() {
12012   return {
12013     priority: 100,
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));
12018         };
12019       } else {
12020         return function(scope, elm, attr) {
12021           scope.$watch(attr.ngValue, function(value) {
12022             attr.$set('value', value, false);
12023           });
12024         };
12025       }
12026     }
12027   };
12028 };
12029
12030 /**
12031  * @ngdoc directive
12032  * @name ng.directive:ngBind
12033  *
12034  * @description
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.
12038  *
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.
12041  *
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.
12046  *
12047  * An alternative solution to this problem would be using the
12048  * {@link ng.directive:ngCloak ngCloak} directive.
12049  *
12050  *
12051  * @element ANY
12052  * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
12053  *
12054  * @example
12055  * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
12056    <doc:example>
12057      <doc:source>
12058        <script>
12059          function Ctrl($scope) {
12060            $scope.name = 'Whirled';
12061          }
12062        </script>
12063        <div ng-controller="Ctrl">
12064          Enter name: <input type="text" ng-model="name"><br>
12065          Hello <span ng-bind="name"></span>!
12066        </div>
12067      </doc:source>
12068      <doc:scenario>
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');
12073        });
12074      </doc:scenario>
12075    </doc:example>
12076  */
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);
12081   });
12082 });
12083
12084
12085 /**
12086  * @ngdoc directive
12087  * @name ng.directive:ngBindTemplate
12088  *
12089  * @description
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.)
12095  *
12096  * @element ANY
12097  * @param {string} ngBindTemplate template of form
12098  *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
12099  *
12100  * @example
12101  * Try it here: enter text in text box and watch the greeting change.
12102    <doc:example>
12103      <doc:source>
12104        <script>
12105          function Ctrl($scope) {
12106            $scope.salutation = 'Hello';
12107            $scope.name = 'World';
12108          }
12109        </script>
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>
12114        </div>
12115      </doc:source>
12116      <doc:scenario>
12117        it('should check ng-bind', function() {
12118          expect(using('.doc-example-live').binding('salutation')).
12119            toBe('Hello');
12120          expect(using('.doc-example-live').binding('name')).
12121            toBe('World');
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')).
12125            toBe('Greetings');
12126          expect(using('.doc-example-live').binding('name')).
12127            toBe('user');
12128        });
12129      </doc:scenario>
12130    </doc:example>
12131  */
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);
12139     });
12140   }
12141 }];
12142
12143
12144 /**
12145  * @ngdoc directive
12146  * @name ng.directive:ngBindHtmlUnsafe
12147  *
12148  * @description
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.
12153  *
12154  * See {@link ngSanitize.$sanitize $sanitize} docs for examples.
12155  *
12156  * @element ANY
12157  * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
12158  */
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 || '');
12164     });
12165   };
12166 }];
12167
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);
12177          }
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);      }
12181     }, true);
12182   });
12183 }
12184
12185 /**
12186  * @ngdoc directive
12187  * @name ng.directive:ngClass
12188  *
12189  * @description
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.
12192  *
12193  * The directive won't add duplicate classes if a particular class was already set.
12194  *
12195  * When the expression changes, the previously added classes are removed and only then the classes
12196  * new classes are added.
12197  *
12198  * @element ANY
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.
12202  *
12203  * @example
12204    <example>
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=''">
12208       <br>
12209       <span ng-class="myVar">Sample Text</span>
12210      </file>
12211      <file name="style.css">
12212        .my-class {
12213          color: red;
12214        }
12215      </file>
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/);
12220
12221          using('.doc-example-live').element(':button:first').click();
12222
12223          expect(element('.doc-example-live span').prop('className')).
12224            toMatch(/my-class/);
12225
12226          using('.doc-example-live').element(':button:last').click();
12227
12228          expect(element('.doc-example-live span').prop('className')).not().
12229            toMatch(/my-class/);
12230        });
12231      </file>
12232    </example>
12233  */
12234 var ngClassDirective = classDirective('', true);
12235
12236 /**
12237  * @ngdoc directive
12238  * @name ng.directive:ngClassOdd
12239  *
12240  * @description
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.
12244  *
12245  * This directive can be applied only within a scope of an
12246  * {@link ng.directive:ngRepeat ngRepeat}.
12247  *
12248  * @element ANY
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.
12251  *
12252  * @example
12253    <example>
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'">
12258              {{name}}
12259            </span>
12260           </li>
12261         </ol>
12262      </file>
12263      <file name="style.css">
12264        .odd {
12265          color: red;
12266        }
12267        .even {
12268          color: blue;
12269        }
12270      </file>
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')).
12274            toMatch(/odd/);
12275          expect(element('.doc-example-live li:last span').prop('className')).
12276            toMatch(/even/);
12277        });
12278      </file>
12279    </example>
12280  */
12281 var ngClassOddDirective = classDirective('Odd', 0);
12282
12283 /**
12284  * @ngdoc directive
12285  * @name ng.directive:ngClassEven
12286  *
12287  * @description
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.
12291  *
12292  * This directive can be applied only within a scope of an
12293  * {@link ng.directive:ngRepeat ngRepeat}.
12294  *
12295  * @element ANY
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.
12298  *
12299  * @example
12300    <example>
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}} &nbsp; &nbsp; &nbsp;
12306            </span>
12307           </li>
12308         </ol>
12309      </file>
12310      <file name="style.css">
12311        .odd {
12312          color: red;
12313        }
12314        .even {
12315          color: blue;
12316        }
12317      </file>
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')).
12321            toMatch(/odd/);
12322          expect(element('.doc-example-live li:last span').prop('className')).
12323            toMatch(/even/);
12324        });
12325      </file>
12326    </example>
12327  */
12328 var ngClassEvenDirective = classDirective('Even', 1);
12329
12330 /**
12331  * @ngdoc directive
12332  * @name ng.directive:ngCloak
12333  *
12334  * @description
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.
12338  *
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.
12341  *
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:
12344  *
12345  * <pre>
12346  * [ng\:cloak], [ng-cloak], .ng-cloak {
12347  *   display: none;
12348  * }
12349  * </pre>
12350  *
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.
12355  *
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
12358  * application.
12359  *
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.
12363  *
12364  * @element ANY
12365  *
12366  * @example
12367    <doc:example>
12368      <doc:source>
12369         <div id="template1" ng-cloak>{{ 'hello' }}</div>
12370         <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
12371      </doc:source>
12372      <doc:scenario>
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();
12378        });
12379      </doc:scenario>
12380    </doc:example>
12381  *
12382  */
12383 var ngCloakDirective = ngDirective({
12384   compile: function(element, attr) {
12385     attr.$set('ngCloak', undefined);
12386     element.removeClass('ng-cloak');
12387   }
12388 });
12389
12390 /**
12391  * @ngdoc directive
12392  * @name ng.directive:ngController
12393  *
12394  * @description
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.
12397  *
12398  * MVC components in angular:
12399  *
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.
12404  *
12405  * Note that an alternative way to define controllers is via the `{@link ng.$route}`
12406  * service.
12407  *
12408  * @element ANY
12409  * @scope
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.
12413  *
12414  * @example
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.
12421    <doc:example>
12422      <doc:source>
12423       <script>
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'} ];
12429
12430           $scope.greet = function() {
12431            alert(this.name);
12432           };
12433
12434           $scope.addContact = function() {
12435            this.contacts.push({type:'email', value:'yourname@example.org'});
12436           };
12437
12438           $scope.removeContact = function(contactToRemove) {
12439            var index = this.contacts.indexOf(contactToRemove);
12440            this.contacts.splice(index, 1);
12441           };
12442
12443           $scope.clearContact = function(contact) {
12444            contact.type = 'phone';
12445            contact.value = '';
12446           };
12447         }
12448       </script>
12449       <div ng-controller="SettingsController">
12450         Name: <input type="text" ng-model="name"/>
12451         [ <a href="" ng-click="greet()">greet</a> ]<br/>
12452         Contact:
12453         <ul>
12454           <li ng-repeat="contact in contacts">
12455             <select ng-model="contact.type">
12456                <option>phone</option>
12457                <option>email</option>
12458             </select>
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> ]
12462           </li>
12463           <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
12464        </ul>
12465       </div>
12466      </doc:source>
12467      <doc:scenario>
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');
12474
12475          element('.doc-example-live li:first a:contains("clear")').click();
12476          expect(element('.doc-example-live li:first input').val()).toBe('');
12477
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');
12481        });
12482      </doc:scenario>
12483    </doc:example>
12484  */
12485 var ngControllerDirective = [function() {
12486   return {
12487     scope: true,
12488     controller: '@'
12489   };
12490 }];
12491
12492 /**
12493  * @ngdoc directive
12494  * @name ng.directive:ngCsp
12495  * @priority 1000
12496  *
12497  * @description
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}
12501  * directive).
12502  *
12503  * If enabled the performance of template expression evaluator will suffer slightly, so don't enable
12504  * this mode unless you need it.
12505  *
12506  * @element html
12507  */
12508
12509 var ngCspDirective = ['$sniffer', function($sniffer) {
12510   return {
12511     priority: 1000,
12512     compile: function() {
12513       $sniffer.csp = true;
12514     }
12515   };
12516 }];
12517
12518 /**
12519  * @ngdoc directive
12520  * @name ng.directive:ngClick
12521  *
12522  * @description
12523  * The ngClick allows you to specify custom behavior when
12524  * element is clicked.
12525  *
12526  * @element ANY
12527  * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
12528  * click. (Event object is available as `$event`)
12529  *
12530  * @example
12531    <doc:example>
12532      <doc:source>
12533       <button ng-click="count = count + 1" ng-init="count=0">
12534         Increment
12535       </button>
12536       count: {{count}}
12537      </doc:source>
12538      <doc:scenario>
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');
12543        });
12544      </doc:scenario>
12545    </doc:example>
12546  */
12547 /*
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.
12550  *
12551  * Events that are handled via these handler are always configured not to propagate further.
12552  */
12553 var ngEventDirectives = {};
12554 forEach(
12555   'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '),
12556   function(name) {
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});
12564           });
12565         });
12566       };
12567     }];
12568   }
12569 );
12570
12571 /**
12572  * @ngdoc directive
12573  * @name ng.directive:ngDblclick
12574  *
12575  * @description
12576  * The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
12577  *
12578  * @element ANY
12579  * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
12580  * dblclick. (Event object is available as `$event`)
12581  *
12582  * @example
12583  * See {@link ng.directive:ngClick ngClick}
12584  */
12585
12586
12587 /**
12588  * @ngdoc directive
12589  * @name ng.directive:ngMousedown
12590  *
12591  * @description
12592  * The ngMousedown directive allows you to specify custom behavior on mousedown event.
12593  *
12594  * @element ANY
12595  * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
12596  * mousedown. (Event object is available as `$event`)
12597  *
12598  * @example
12599  * See {@link ng.directive:ngClick ngClick}
12600  */
12601
12602
12603 /**
12604  * @ngdoc directive
12605  * @name ng.directive:ngMouseup
12606  *
12607  * @description
12608  * Specify custom behavior on mouseup event.
12609  *
12610  * @element ANY
12611  * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
12612  * mouseup. (Event object is available as `$event`)
12613  *
12614  * @example
12615  * See {@link ng.directive:ngClick ngClick}
12616  */
12617
12618 /**
12619  * @ngdoc directive
12620  * @name ng.directive:ngMouseover
12621  *
12622  * @description
12623  * Specify custom behavior on mouseover event.
12624  *
12625  * @element ANY
12626  * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
12627  * mouseover. (Event object is available as `$event`)
12628  *
12629  * @example
12630  * See {@link ng.directive:ngClick ngClick}
12631  */
12632
12633
12634 /**
12635  * @ngdoc directive
12636  * @name ng.directive:ngMouseenter
12637  *
12638  * @description
12639  * Specify custom behavior on mouseenter event.
12640  *
12641  * @element ANY
12642  * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
12643  * mouseenter. (Event object is available as `$event`)
12644  *
12645  * @example
12646  * See {@link ng.directive:ngClick ngClick}
12647  */
12648
12649
12650 /**
12651  * @ngdoc directive
12652  * @name ng.directive:ngMouseleave
12653  *
12654  * @description
12655  * Specify custom behavior on mouseleave event.
12656  *
12657  * @element ANY
12658  * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
12659  * mouseleave. (Event object is available as `$event`)
12660  *
12661  * @example
12662  * See {@link ng.directive:ngClick ngClick}
12663  */
12664
12665
12666 /**
12667  * @ngdoc directive
12668  * @name ng.directive:ngMousemove
12669  *
12670  * @description
12671  * Specify custom behavior on mousemove event.
12672  *
12673  * @element ANY
12674  * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
12675  * mousemove. (Event object is available as `$event`)
12676  *
12677  * @example
12678  * See {@link ng.directive:ngClick ngClick}
12679  */
12680
12681
12682 /**
12683  * @ngdoc directive
12684  * @name ng.directive:ngSubmit
12685  *
12686  * @description
12687  * Enables binding angular expressions to onsubmit events.
12688  *
12689  * Additionally it prevents the default action (which for form means sending the request to the
12690  * server and reloading the current page).
12691  *
12692  * @element form
12693  * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
12694  *
12695  * @example
12696    <doc:example>
12697      <doc:source>
12698       <script>
12699         function Ctrl($scope) {
12700           $scope.list = [];
12701           $scope.text = 'hello';
12702           $scope.submit = function() {
12703             if (this.text) {
12704               this.list.push(this.text);
12705               this.text = '';
12706             }
12707           };
12708         }
12709       </script>
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>
12715       </form>
12716      </doc:source>
12717      <doc:scenario>
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('');
12723        });
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"]');
12729        });
12730      </doc:scenario>
12731    </doc:example>
12732  */
12733 var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
12734   element.bind('submit', function() {
12735     scope.$apply(attrs.ngSubmit);
12736   });
12737 });
12738
12739 /**
12740  * @ngdoc directive
12741  * @name ng.directive:ngInclude
12742  * @restrict ECA
12743  *
12744  * @description
12745  * Fetches, compiles and includes an external HTML fragment.
12746  *
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).
12750  *
12751  * @scope
12752  *
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.
12756  *
12757  * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
12758  *                  $anchorScroll} to scroll the viewport after the content is loaded.
12759  *
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.
12763  *
12764  * @example
12765   <example>
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>
12770        </select>
12771        url of the template: <tt>{{template.url}}</tt>
12772        <hr/>
12773        <div ng-include src="template.url"></div>
12774      </div>
12775     </file>
12776     <file name="script.js">
12777       function Ctrl($scope) {
12778         $scope.templates =
12779           [ { name: 'template1.html', url: 'template1.html'}
12780           , { name: 'template2.html', url: 'template2.html'} ];
12781         $scope.template = $scope.templates[0];
12782       }
12783      </file>
12784     <file name="template1.html">
12785       Content of template1.html
12786     </file>
12787     <file name="template2.html">
12788       Content of template2.html
12789     </file>
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/);
12794       });
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/);
12799       });
12800       it('should change to blank', function() {
12801        select('template').option('');
12802        expect(element('.doc-example-live [ng-include]').text()).toEqual('');
12803       });
12804     </file>
12805   </example>
12806  */
12807
12808
12809 /**
12810  * @ngdoc event
12811  * @name ng.directive:ngInclude#$includeContentLoaded
12812  * @eventOf ng.directive:ngInclude
12813  * @eventType emit on the current ngInclude scope
12814  * @description
12815  * Emitted every time the ngInclude content is reloaded.
12816  */
12817 var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile',
12818                   function($http,   $templateCache,   $anchorScroll,   $compile) {
12819   return {
12820     restrict: 'ECA',
12821     terminal: true,
12822     compile: function(element, attr) {
12823       var srcExp = attr.ngInclude || attr.src,
12824           onloadExp = attr.onload || '',
12825           autoScrollExp = attr.autoscroll;
12826
12827       return function(scope, element) {
12828         var changeCounter = 0,
12829             childScope;
12830
12831         var clearContent = function() {
12832           if (childScope) {
12833             childScope.$destroy();
12834             childScope = null;
12835           }
12836
12837           element.html('');
12838         };
12839
12840         scope.$watch(srcExp, function(src) {
12841           var thisChangeId = ++changeCounter;
12842
12843           if (src) {
12844             $http.get(src, {cache: $templateCache}).success(function(response) {
12845               if (thisChangeId !== changeCounter) return;
12846
12847               if (childScope) childScope.$destroy();
12848               childScope = scope.$new();
12849
12850               element.html(response);
12851               $compile(element.contents())(childScope);
12852
12853               if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
12854                 $anchorScroll();
12855               }
12856
12857               childScope.$emit('$includeContentLoaded');
12858               scope.$eval(onloadExp);
12859             }).error(function() {
12860               if (thisChangeId === changeCounter) clearContent();
12861             });
12862           } else clearContent();
12863         });
12864       };
12865     }
12866   };
12867 }];
12868
12869 /**
12870  * @ngdoc directive
12871  * @name ng.directive:ngInit
12872  *
12873  * @description
12874  * The `ngInit` directive specifies initialization tasks to be executed
12875  *  before the template enters execution mode during bootstrap.
12876  *
12877  * @element ANY
12878  * @param {expression} ngInit {@link guide/expression Expression} to eval.
12879  *
12880  * @example
12881    <doc:example>
12882      <doc:source>
12883     <div ng-init="greeting='Hello'; person='World'">
12884       {{greeting}} {{person}}!
12885     </div>
12886      </doc:source>
12887      <doc:scenario>
12888        it('should check greeting', function() {
12889          expect(binding('greeting')).toBe('Hello');
12890          expect(binding('person')).toBe('World');
12891        });
12892      </doc:scenario>
12893    </doc:example>
12894  */
12895 var ngInitDirective = ngDirective({
12896   compile: function() {
12897     return {
12898       pre: function(scope, element, attrs) {
12899         scope.$eval(attrs.ngInit);
12900       }
12901     }
12902   }
12903 });
12904
12905 /**
12906  * @ngdoc directive
12907  * @name ng.directive:ngNonBindable
12908  * @priority 1000
12909  *
12910  * @description
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.
12913  *
12914  * @element ANY
12915  *
12916  * @example
12917  * In this example there are two location where a simple binding (`{{}}`) is present, but the one
12918  * wrapped in `ngNonBindable` is left alone.
12919  *
12920  * @example
12921     <doc:example>
12922       <doc:source>
12923         <div>Normal: {{1 + 2}}</div>
12924         <div ng-non-bindable>Ignored: {{1 + 2}}</div>
12925       </doc:source>
12926       <doc:scenario>
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()).
12930            toMatch(/1 \+ 2/);
12931        });
12932       </doc:scenario>
12933     </doc:example>
12934  */
12935 var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
12936
12937 /**
12938  * @ngdoc directive
12939  * @name ng.directive:ngPluralize
12940  * @restrict EA
12941  *
12942  * @description
12943  * # Overview
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.
12950  *
12951  * # Plural categories and explicit number rules
12952  * There are two
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".
12955  *
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.
12960  *
12961  * # Configuring ngPluralize
12962  * You configure ngPluralize by providing 2 attributes: `count` and `when`.
12963  * You can also provide an optional attribute, `offset`.
12964  *
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.
12967  *
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.
12971  *
12972  * The following example shows how to configure ngPluralize:
12973  *
12974  * <pre>
12975  * <ng-pluralize count="personCount"
12976                  when="{'0': 'Nobody is viewing.',
12977  *                      'one': '1 person is viewing.',
12978  *                      'other': '{} people are viewing.'}">
12979  * </ng-pluralize>
12980  *</pre>
12981  *
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".
12987  *
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>.
12992  *
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:
12999  *
13000  * <pre>
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.'}">
13007  * </ng-pluralize>
13008  * </pre>
13009  *
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"
13016  * is shown.
13017  *
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".
13022  *
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.
13026  *
13027  * @example
13028     <doc:example>
13029       <doc:source>
13030         <script>
13031           function Ctrl($scope) {
13032             $scope.person1 = 'Igor';
13033             $scope.person2 = 'Misko';
13034             $scope.personCount = 1;
13035           }
13036         </script>
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/>
13041
13042           <!--- Example with simple pluralization rules for en locale --->
13043           Without Offset:
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>
13049
13050           <!--- Example with offset --->
13051           With Offset(2):
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.'}">
13058           </ng-pluralize>
13059         </div>
13060       </doc:source>
13061       <doc:scenario>
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.');
13067
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.');
13073
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.');
13079
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.');
13085
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.');
13091         });
13092
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.');
13097
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.');
13102         });
13103       </doc:scenario>
13104     </doc:example>
13105  */
13106 var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
13107   var BRACE = /{}/g;
13108   return {
13109     restrict: 'EA',
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),
13115           whensExpFns = {},
13116           startSymbol = $interpolate.startSymbol(),
13117           endSymbol = $interpolate.endSymbol();
13118
13119       forEach(whens, function(expression, key) {
13120         whensExpFns[key] =
13121           $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
13122             offset + endSymbol));
13123       });
13124
13125       scope.$watch(function() {
13126         var value = parseFloat(scope.$eval(numberExp));
13127
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);
13133         } else {
13134           return '';
13135         }
13136       }, function(newVal) {
13137         element.text(newVal);
13138       });
13139     }
13140   };
13141 }];
13142
13143 /**
13144  * @ngdoc directive
13145  * @name ng.directive:ngRepeat
13146  *
13147  * @description
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.
13151  *
13152  * Special properties are exposed on the local scope of each template instance, including:
13153  *
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.
13158  *
13159  *
13160  * @element ANY
13161  * @scope
13162  * @priority 1000
13163  * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
13164  *   formats are currently supported:
13165  *
13166  *   * `variable in expression` – where variable is the user defined loop variable and `expression`
13167  *     is a scope expression giving the collection to enumerate.
13168  *
13169  *     For example: `track in cd.tracks`.
13170  *
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.
13173  *
13174  *     For example: `(name, age) in {'adam':10, 'amalie':12}`.
13175  *
13176  * @example
13177  * This example initializes the scope to a list of names and
13178  * then uses `ngRepeat` to display every person:
13179     <doc:example>
13180       <doc:source>
13181         <div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
13182           I have {{friends.length}} friends. They are:
13183           <ul>
13184             <li ng-repeat="friend in friends">
13185               [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
13186             </li>
13187           </ul>
13188         </div>
13189       </doc:source>
13190       <doc:scenario>
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"]);
13196          });
13197       </doc:scenario>
13198     </doc:example>
13199  */
13200 var ngRepeatDirective = ngDirective({
13201   transclude: 'element',
13202   priority: 1000,
13203   terminal: true,
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;
13209       if (! match) {
13210         throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
13211           expression + "'.");
13212       }
13213       lhs = match[1];
13214       rhs = match[2];
13215       match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
13216       if (!match) {
13217         throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
13218             lhs + "'.");
13219       }
13220       valueIdent = match[3] || match[1];
13221       keyIdent = match[2];
13222
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){
13232         var index, length,
13233             collection = scope.$eval(rhs),
13234             collectionLength = size(collection, true),
13235             childScope,
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
13242
13243         if (!isArray(collection)) {
13244           // if object, extract keys, sort them and use to determine order of iteration over obj props
13245           array = [];
13246           for(key in collection) {
13247             if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
13248               array.push(key);
13249             }
13250           }
13251           array.sort();
13252         } else {
13253           array = collection || [];
13254         }
13255
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);
13261           if (last) {
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);
13266
13267             if (index === last.index) {
13268               // do nothing
13269               cursor = last.element;
13270             } else {
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;
13278             }
13279           } else {
13280             // new item which we don't know about
13281             childScope = scope.$new();
13282           }
13283
13284           childScope[valueIdent] = value;
13285           if (keyIdent) childScope[keyIdent] = key;
13286           childScope.$index = index;
13287
13288           childScope.$first = (index === 0);
13289           childScope.$last = (index === (collectionLength - 1));
13290           childScope.$middle = !(childScope.$first || childScope.$last);
13291
13292           if (!last) {
13293             linker(childScope, function(clone){
13294               cursor.after(clone);
13295               last = {
13296                   scope: childScope,
13297                   element: (cursor = clone),
13298                   index: index
13299                 };
13300               nextOrder.push(value, last);
13301             });
13302           }
13303         }
13304
13305         //shrink children
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();
13313             }
13314           }
13315         }
13316
13317         lastOrder = nextOrder;
13318       });
13319     };
13320   }
13321 });
13322
13323 /**
13324  * @ngdoc directive
13325  * @name ng.directive:ngShow
13326  *
13327  * @description
13328  * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
13329  * conditionally.
13330  *
13331  * @element ANY
13332  * @param {expression} ngShow If the {@link guide/expression expression} is truthy
13333  *     then the element is shown or hidden respectively.
13334  *
13335  * @example
13336    <doc:example>
13337      <doc:source>
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>
13341      </doc:source>
13342      <doc:scenario>
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);
13346
13347          input('checked').check();
13348
13349          expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
13350          expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
13351        });
13352      </doc:scenario>
13353    </doc:example>
13354  */
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');
13359   });
13360 });
13361
13362
13363 /**
13364  * @ngdoc directive
13365  * @name ng.directive:ngHide
13366  *
13367  * @description
13368  * The `ngHide` and `ngShow` directives hide or show a portion
13369  * of the HTML conditionally.
13370  *
13371  * @element ANY
13372  * @param {expression} ngHide If the {@link guide/expression expression} truthy then
13373  *     the element is shown or hidden respectively.
13374  *
13375  * @example
13376    <doc:example>
13377      <doc:source>
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>
13381      </doc:source>
13382      <doc:scenario>
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);
13386
13387          input('checked').check();
13388
13389          expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
13390          expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
13391        });
13392      </doc:scenario>
13393    </doc:example>
13394  */
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' : '');
13399   });
13400 });
13401
13402 /**
13403  * @ngdoc directive
13404  * @name ng.directive:ngStyle
13405  *
13406  * @description
13407  * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
13408  *
13409  * @element ANY
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
13412  *      keys.
13413  *
13414  * @example
13415    <example>
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={}">
13419         <br/>
13420         <span ng-style="myStyle">Sample Text</span>
13421         <pre>myStyle={{myStyle}}</pre>
13422      </file>
13423      <file name="style.css">
13424        span {
13425          color: black;
13426        }
13427      </file>
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)');
13435        });
13436      </file>
13437    </example>
13438  */
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, '');});
13443     }
13444     if (newStyles) element.css(newStyles);
13445   }, true);
13446 });
13447
13448 /**
13449  * @ngdoc directive
13450  * @name ng.directive:ngSwitch
13451  * @restrict EA
13452  *
13453  * @description
13454  * Conditionally change the DOM structure.
13455  *
13456  * @usageContent
13457  * <ANY ng-switch-when="matchValue1">...</ANY>
13458  *   <ANY ng-switch-when="matchValue2">...</ANY>
13459  *   ...
13460  *   <ANY ng-switch-default>...</ANY>
13461  *
13462  * @scope
13463  * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
13464  * @paramDescription
13465  * On child elments add:
13466  *
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.
13470  *
13471  * @example
13472     <doc:example>
13473       <doc:source>
13474         <script>
13475           function Ctrl($scope) {
13476             $scope.items = ['settings', 'home', 'other'];
13477             $scope.selection = $scope.items[0];
13478           }
13479         </script>
13480         <div ng-controller="Ctrl">
13481           <select ng-model="selection" ng-options="item for item in items">
13482           </select>
13483           <tt>selection={{selection}}</tt>
13484           <hr/>
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>
13489           </div>
13490         </div>
13491       </doc:source>
13492       <doc:scenario>
13493         it('should start in settings', function() {
13494          expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
13495         });
13496         it('should change to home', function() {
13497          select('selection').option('home');
13498          expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
13499         });
13500         it('should select deafault', function() {
13501          select('selection').option('other');
13502          expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
13503         });
13504       </doc:scenario>
13505     </doc:example>
13506  */
13507 var NG_SWITCH = 'ng-switch';
13508 var ngSwitchDirective = valueFn({
13509   restrict: 'EA',
13510   compile: function(element, attr) {
13511     var watchExpr = attr.ngSwitch || attr.on,
13512         cases = {};
13513
13514     element.data(NG_SWITCH, cases);
13515     return function(scope, element){
13516       var selectedTransclude,
13517           selectedElement,
13518           selectedScope;
13519
13520       scope.$watch(watchExpr, function(value) {
13521         if (selectedElement) {
13522           selectedScope.$destroy();
13523           selectedElement.remove();
13524           selectedElement = selectedScope = null;
13525         }
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);
13532           });
13533         }
13534       });
13535     };
13536   }
13537 });
13538
13539 var ngSwitchWhenDirective = ngDirective({
13540   transclude: 'element',
13541   priority: 500,
13542   compile: function(element, attrs, transclude) {
13543     var cases = element.inheritedData(NG_SWITCH);
13544     assertArg(cases);
13545     cases['!' + attrs.ngSwitchWhen] = transclude;
13546   }
13547 });
13548
13549 var ngSwitchDefaultDirective = ngDirective({
13550   transclude: 'element',
13551   priority: 500,
13552   compile: function(element, attrs, transclude) {
13553     var cases = element.inheritedData(NG_SWITCH);
13554     assertArg(cases);
13555     cases['?'] = transclude;
13556   }
13557 });
13558
13559 /**
13560  * @ngdoc directive
13561  * @name ng.directive:ngTransclude
13562  *
13563  * @description
13564  * Insert the transcluded DOM here.
13565  *
13566  * @element ANY
13567  *
13568  * @example
13569    <doc:example module="transclude">
13570      <doc:source>
13571        <script>
13572          function Ctrl($scope) {
13573            $scope.title = 'Lorem Ipsum';
13574            $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
13575          }
13576
13577          angular.module('transclude', [])
13578           .directive('pane', function(){
13579              return {
13580                restrict: 'E',
13581                transclude: true,
13582                scope: 'isolate',
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>' +
13587                          '</div>'
13588              };
13589          });
13590        </script>
13591        <div ng-controller="Ctrl">
13592          <input ng-model="title"><br>
13593          <textarea ng-model="text"></textarea> <br/>
13594          <pane title="{{title}}">{{text}}</pane>
13595        </div>
13596      </doc:source>
13597      <doc:scenario>
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');
13603         });
13604      </doc:scenario>
13605    </doc:example>
13606  *
13607  */
13608 var ngTranscludeDirective = ngDirective({
13609   controller: ['$transclude', '$element', function($transclude, $element) {
13610     $transclude(function(clone) {
13611       $element.append(clone);
13612     });
13613   }]
13614 });
13615
13616 /**
13617  * @ngdoc directive
13618  * @name ng.directive:ngView
13619  * @restrict ECA
13620  *
13621  * @description
13622  * # Overview
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.
13627  *
13628  * @scope
13629  * @example
13630     <example module="ngView">
13631       <file name="index.html">
13632         <div ng-controller="MainCntl">
13633           Choose:
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/>
13639
13640           <div ng-view></div>
13641           <hr />
13642
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>
13648         </div>
13649       </file>
13650
13651       <file name="book.html">
13652         controller: {{name}}<br />
13653         Book Id: {{params.bookId}}<br />
13654       </file>
13655
13656       <file name="chapter.html">
13657         controller: {{name}}<br />
13658         Book Id: {{params.bookId}}<br />
13659         Chapter Id: {{params.chapterId}}
13660       </file>
13661
13662       <file name="script.js">
13663         angular.module('ngView', [], function($routeProvider, $locationProvider) {
13664           $routeProvider.when('/Book/:bookId', {
13665             templateUrl: 'book.html',
13666             controller: BookCntl
13667           });
13668           $routeProvider.when('/Book/:bookId/ch/:chapterId', {
13669             templateUrl: 'chapter.html',
13670             controller: ChapterCntl
13671           });
13672
13673           // configure html5 to get links working on jsfiddle
13674           $locationProvider.html5Mode(true);
13675         });
13676
13677         function MainCntl($scope, $route, $routeParams, $location) {
13678           $scope.$route = $route;
13679           $scope.$location = $location;
13680           $scope.$routeParams = $routeParams;
13681         }
13682
13683         function BookCntl($scope, $routeParams) {
13684           $scope.name = "BookCntl";
13685           $scope.params = $routeParams;
13686         }
13687
13688         function ChapterCntl($scope, $routeParams) {
13689           $scope.name = "ChapterCntl";
13690           $scope.params = $routeParams;
13691         }
13692       </file>
13693
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/);
13701
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/);
13706         });
13707       </file>
13708     </example>
13709  */
13710
13711
13712 /**
13713  * @ngdoc event
13714  * @name ng.directive:ngView#$viewContentLoaded
13715  * @eventOf ng.directive:ngView
13716  * @eventType emit on the current ngView scope
13717  * @description
13718  * Emitted every time the ngView content is reloaded.
13719  */
13720 var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
13721                        '$controller',
13722                function($http,   $templateCache,   $route,   $anchorScroll,   $compile,
13723                         $controller) {
13724   return {
13725     restrict: 'ECA',
13726     terminal: true,
13727     link: function(scope, element, attr) {
13728       var lastScope,
13729           onloadExp = attr.onload || '';
13730
13731       scope.$on('$routeChangeSuccess', update);
13732       update();
13733
13734
13735       function destroyLastScope() {
13736         if (lastScope) {
13737           lastScope.$destroy();
13738           lastScope = null;
13739         }
13740       }
13741
13742       function clearContent() {
13743         element.html('');
13744         destroyLastScope();
13745       }
13746
13747       function update() {
13748         var locals = $route.current && $route.current.locals,
13749             template = locals && locals.$template;
13750
13751         if (template) {
13752           element.html(template);
13753           destroyLastScope();
13754
13755           var link = $compile(element.contents()),
13756               current = $route.current,
13757               controller;
13758
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);
13764           }
13765
13766           link(lastScope);
13767           lastScope.$emit('$viewContentLoaded');
13768           lastScope.$eval(onloadExp);
13769
13770           // $anchorScroll might listen on event...
13771           $anchorScroll();
13772         } else {
13773           clearContent();
13774         }
13775       }
13776     }
13777   };
13778 }];
13779
13780 /**
13781  * @ngdoc directive
13782  * @name ng.directive:script
13783  *
13784  * @description
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.
13787  *
13788  * @restrict E
13789  * @param {'text/ng-template'} type must be set to `'text/ng-template'`
13790  *
13791  * @example
13792   <doc:example>
13793     <doc:source>
13794       <script type="text/ng-template" id="/tpl.html">
13795         Content of the template.
13796       </script>
13797
13798       <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
13799       <div id="tpl-content" ng-include src="currentTpl"></div>
13800     </doc:source>
13801     <doc:scenario>
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/);
13805       });
13806     </doc:scenario>
13807   </doc:example>
13808  */
13809 var scriptDirective = ['$templateCache', function($templateCache) {
13810   return {
13811     restrict: 'E',
13812     terminal: true,
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;
13818
13819         $templateCache.put(templateUrl, text);
13820       }
13821     }
13822   };
13823 }];
13824
13825 /**
13826  * @ngdoc directive
13827  * @name ng.directive:select
13828  * @restrict E
13829  *
13830  * @description
13831  * HTML `SELECT` element with angular data-binding.
13832  *
13833  * # `ngOptions`
13834  *
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.
13838  *˝˝
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.
13842  *
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.
13846  *
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.
13851  *
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:
13855  *
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`
13867  *
13868  * Where:
13869  *
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>`
13879  *      DOM element.
13880  *
13881  * @example
13882     <doc:example>
13883       <doc:source>
13884         <script>
13885         function MyCntrl($scope) {
13886           $scope.colors = [
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'}
13892           ];
13893           $scope.color = $scope.colors[2]; // red
13894         }
13895         </script>
13896         <div ng-controller="MyCntrl">
13897           <ul>
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>]
13901             </li>
13902             <li>
13903               [<a href ng-click="colors.push({})">add</a>]
13904             </li>
13905           </ul>
13906           <hr/>
13907           Color (null not allowed):
13908           <select ng-model="color" ng-options="c.name for c in colors"></select><br>
13909
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>
13914             </select>
13915           </span><br/>
13916
13917           Color grouped by shade:
13918           <select ng-model="color" ng-options="c.name group by c.shade for c in colors">
13919           </select><br/>
13920
13921
13922           Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
13923           <hr/>
13924           Currently selected: {{ {selected_color:color}  }}
13925           <div style="border:solid 1px black; height:20px"
13926                ng-style="{'background-color':color.name}">
13927           </div>
13928         </div>
13929       </doc:source>
13930       <doc:scenario>
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');
13937          });
13938       </doc:scenario>
13939     </doc:example>
13940  */
13941
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};
13947
13948   return {
13949     restrict: 'E',
13950     require: ['select', '?ngModel'],
13951     controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
13952       var self = this,
13953           optionsMap = {},
13954           ngModelCtrl = nullModelCtrl,
13955           nullOption,
13956           unknownOption;
13957
13958
13959       self.databound = $attrs.ngModel;
13960
13961
13962       self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
13963         ngModelCtrl = ngModelCtrl_;
13964         nullOption = nullOption_;
13965         unknownOption = unknownOption_;
13966       }
13967
13968
13969       self.addOption = function(value) {
13970         optionsMap[value] = true;
13971
13972         if (ngModelCtrl.$viewValue == value) {
13973           $element.val(value);
13974           if (unknownOption.parent()) unknownOption.remove();
13975         }
13976       };
13977
13978
13979       self.removeOption = function(value) {
13980         if (this.hasOption(value)) {
13981           delete optionsMap[value];
13982           if (ngModelCtrl.$viewValue == value) {
13983             this.renderUnknownOption(value);
13984           }
13985         }
13986       };
13987
13988
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
13995       }
13996
13997
13998       self.hasOption = function(value) {
13999         return optionsMap.hasOwnProperty(value);
14000       }
14001
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;
14005       });
14006     }],
14007
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;
14011
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)
14017           emptyOption,
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();
14023
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);
14028           break;
14029         }
14030       }
14031
14032       selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
14033
14034       // required validator
14035       if (multiple && (attr.required || attr.ngRequired)) {
14036         var requiredValidator = function(value) {
14037           ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
14038           return value;
14039         };
14040
14041         ngModelCtrl.$parsers.push(requiredValidator);
14042         ngModelCtrl.$formatters.unshift(requiredValidator);
14043
14044         attr.$observe('required', function() {
14045           requiredValidator(ngModelCtrl.$viewValue);
14046         });
14047       }
14048
14049       if (optionsExp) Options(scope, element, ngModelCtrl);
14050       else if (multiple) Multiple(scope, element, ngModelCtrl);
14051       else Single(scope, element, ngModelCtrl, selectCtrl);
14052
14053
14054       ////////////////////////////
14055
14056
14057
14058       function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
14059         ngModelCtrl.$render = function() {
14060           var viewValue = ngModelCtrl.$viewValue;
14061
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
14066           } else {
14067             if (isUndefined(viewValue) && emptyOption) {
14068               selectElement.val('');
14069             } else {
14070               selectCtrl.renderUnknownOption(viewValue);
14071             }
14072           }
14073         };
14074
14075         selectElement.bind('change', function() {
14076           scope.$apply(function() {
14077             if (unknownOption.parent()) unknownOption.remove();
14078             ngModelCtrl.$setViewValue(selectElement.val());
14079           });
14080         });
14081       }
14082
14083       function Multiple(scope, selectElement, ctrl) {
14084         var lastView;
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));
14089           });
14090         };
14091
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);
14097             ctrl.$render();
14098           }
14099         });
14100
14101         selectElement.bind('change', function() {
14102           scope.$apply(function() {
14103             var array = [];
14104             forEach(selectElement.children(), function(option) {
14105               if (option.selected) {
14106                 array.push(option.value);
14107               }
14108             });
14109             ctrl.$setViewValue(array);
14110           });
14111         });
14112       }
14113
14114       function Options(scope, selectElement, ctrl) {
14115         var match;
14116
14117         if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
14118           throw Error(
14119             "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
14120             " but got '" + optionsExp + "'.");
14121         }
14122
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:''}]];
14133
14134         if (nullOption) {
14135           // compile the element since there might be bindings in it
14136           $compile(nullOption)(scope);
14137
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');
14141
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();
14145         }
14146
14147         // clear contents, we'll add what's needed based on the model
14148         selectElement.html('');
14149
14150         selectElement.bind('change', function() {
14151           scope.$apply(function() {
14152             var optionGroup,
14153                 collection = valuesFn(scope) || [],
14154                 locals = {},
14155                 key, value, optionElement, index, groupIndex, length, groupLength;
14156
14157             if (multiple) {
14158               value = [];
14159               for (groupIndex = 0, groupLength = optionGroupsCache.length;
14160                    groupIndex < groupLength;
14161                    groupIndex++) {
14162                 // list of options for that group. (first item has the parent)
14163                 optionGroup = optionGroupsCache[groupIndex];
14164
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));
14171                   }
14172                 }
14173               }
14174             } else {
14175               key = selectElement.val();
14176               if (key == '?') {
14177                 value = undefined;
14178               } else if (key == ''){
14179                 value = null;
14180               } else {
14181                 locals[valueName] = collection[key];
14182                 if (keyName) locals[keyName] = key;
14183                 value = valueFn(scope, locals);
14184               }
14185             }
14186             ctrl.$setViewValue(value);
14187           });
14188         });
14189
14190         ctrl.$render = render;
14191
14192         // TODO(vojta): can't we optimize this ?
14193         scope.$watch(render);
14194
14195         function render() {
14196           var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
14197               optionGroupNames = [''],
14198               optionGroupName,
14199               optionGroup,
14200               option,
14201               existingParent, existingOptions, existingOption,
14202               modelValue = ctrl.$modelValue,
14203               values = valuesFn(scope) || [],
14204               keys = keyName ? sortedKeys(values) : values,
14205               groupLength, length,
14206               groupIndex, index,
14207               locals = {},
14208               selected,
14209               selectedSet = false, // nothing is selected yet
14210               lastElement,
14211               element;
14212
14213           if (multiple) {
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;
14219           }
14220
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);
14228             }
14229             if (multiple) {
14230               selected = selectedSet.remove(valueFn(scope, locals)) != undefined;
14231             } else {
14232               selected = modelValue === valueFn(scope, locals);
14233               selectedSet = selectedSet || selected; // see if at least one item is selected
14234             }
14235             optionGroup.push({
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
14239             });
14240           }
14241           if (!multiple && !selectedSet) {
14242             // nothing was selected, we have to insert the undefined item
14243             optionGroups[''].unshift({id:'?', label:'', selected:true});
14244           }
14245
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;
14249                groupIndex++) {
14250             // current option group name or '' if no group
14251             optionGroupName = optionGroupNames[groupIndex];
14252
14253             // list of options for that group. (first item has the parent)
14254             optionGroup = optionGroups[optionGroupName];
14255
14256             if (optionGroupsCache.length <= groupIndex) {
14257               // we need to grow the optionGroups
14258               existingParent = {
14259                 element: optGroupTemplate.clone().attr('label', optionGroupName),
14260                 label: optionGroup.label
14261               };
14262               existingOptions = [existingParent];
14263               optionGroupsCache.push(existingOptions);
14264               selectElement.append(existingParent.element);
14265             } else {
14266               existingOptions = optionGroupsCache[groupIndex];
14267               existingParent = existingOptions[0];  // either SELECT (no group) or OPTGROUP element
14268
14269               // update the OPTGROUP label if not the same.
14270               if (existingParent.label != optionGroupName) {
14271                 existingParent.element.attr('label', existingParent.label = optionGroupName);
14272               }
14273             }
14274
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])) {
14279                 // reuse elements
14280                 lastElement = existingOption.element;
14281                 if (existingOption.label !== option.label) {
14282                   lastElement.text(existingOption.label = option.label);
14283                 }
14284                 if (existingOption.id !== option.id) {
14285                   lastElement.val(existingOption.id = option.id);
14286                 }
14287                 if (existingOption.element.selected !== option.selected) {
14288                   lastElement.prop('selected', (existingOption.selected = option.selected));
14289                 }
14290               } else {
14291                 // grow elements
14292
14293                 // if it's a null option
14294                 if (option.id === '' && nullOption) {
14295                   // put back the pre-compiled element
14296                   element = nullOption;
14297                 } else {
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())
14302                       .val(option.id)
14303                       .attr('selected', option.selected)
14304                       .text(option.label);
14305                 }
14306
14307                 existingOptions.push(existingOption = {
14308                     element: element,
14309                     label: option.label,
14310                     id: option.id,
14311                     selected: option.selected
14312                 });
14313                 if (lastElement) {
14314                   lastElement.after(element);
14315                 } else {
14316                   existingParent.element.append(element);
14317                 }
14318                 lastElement = element;
14319               }
14320             }
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();
14325             }
14326           }
14327           // remove any excessive OPTGROUPs from select
14328           while(optionGroupsCache.length > groupIndex) {
14329             optionGroupsCache.pop()[0].element.remove();
14330           }
14331         }
14332       }
14333     }
14334   }
14335 }];
14336
14337 var optionDirective = ['$interpolate', function($interpolate) {
14338   var nullSelectCtrl = {
14339     addOption: noop,
14340     removeOption: noop
14341   };
14342
14343   return {
14344     restrict: 'E',
14345     priority: 100,
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());
14351         }
14352       }
14353
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
14359
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);
14364         } else {
14365           selectCtrl = nullSelectCtrl;
14366         }
14367
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);
14373           });
14374         } else {
14375           selectCtrl.addOption(attr.value);
14376         }
14377
14378         element.bind('$destroy', function() {
14379           selectCtrl.removeOption(attr.value);
14380         });
14381       };
14382     }
14383   }
14384 }];
14385
14386 var styleDirective = valueFn({
14387   restrict: 'E',
14388   terminal: true
14389 });
14390   //try to bind to jquery now so that one can write angular.element().read()
14391   //but we will rebind on bootstrap again.
14392   bindJQuery();
14393
14394   publishExternalAPI(angular);
14395
14396   jqLite(document).ready(function() {
14397     angularInit(document, bootstrap);
14398   });
14399
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>');