vendor: 4,642 bytes, lines 1-131
1/** 2 * @license AngularJS v1.7.3 3 * (c) 2010-2018 Google, Inc. http://angularjs.org 4 * License: MIT 5 */ 6(function(window) {'use strict'; 7 8/* exported 9 minErrConfig, 10 errorHandlingConfig, 11 isValidObjectMaxDepth 12*/ 13 14var minErrConfig = { 15 objectMaxDepth: 5, 16 urlErrorParamsEnabled: true 17}; 18 19/** 20 * @ngdoc function 21 * @name angular.errorHandlingConfig 22 * @module ng 23 * @kind function 24 * 25 * @description 26 * Configure several aspects of error handling in AngularJS if used as a setter or return the 27 * current configuration if used as a getter. The following options are supported: 28 * 29 * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages. 30 * 31 * Omitted or undefined options will leave the corresponding configuration values unchanged. 32 * 33 * @param {Object=} config - The configuration object. May only contain the options that need to be 34 * updated. Supported keys: 35 * 36 * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a 37 * non-positive or non-numeric value, removes the max depth limit. 38 * Default: 5 39 * 40 * * `urlErrorParamsEnabled` **{Boolean}** - Specifies wether the generated error url will 41 * contain the parameters of the thrown error. Disabling the parameters can be useful if the 42 * generated error url is very long. 43 * 44 * Default: true. When used without argument, it returns the current value. 45 */ 46function errorHandlingConfig(config) { 47 if (isObject(config)) { 48 if (isDefined(config.objectMaxDepth)) { 49 minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN; 50 } 51 if (isDefined(config.urlErrorParamsEnabled) && isBoolean(config.urlErrorParamsEnabled)) { 52 minErrConfig.urlErrorParamsEnabled = config.urlErrorParamsEnabled; 53 } 54 } else { 55 return minErrConfig; 56 } 57} 58 59/** 60 * @private 61 * @param {Number} maxDepth 62 * @return {boolean} 63 */ 64function isValidObjectMaxDepth(maxDepth) { 65 return isNumber(maxDepth) && maxDepth > 0; 66} 67 68 69/** 70 * @description 71 * 72 * This object provides a utility for producing rich Error messages within 73 * AngularJS. It can be called as follows: 74 * 75 * var exampleMinErr = minErr('example'); 76 * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); 77 * 78 * The above creates an instance of minErr in the example namespace. The 79 * resulting error will have a namespaced error code of example.one. The 80 * resulting error will replace {0} with the value of foo, and {1} with the 81 * value of bar. The object is not restricted in the number of arguments it can 82 * take. 83 * 84 * If fewer arguments are specified than necessary for interpolation, the extra 85 * interpolation markers will be preserved in the final string. 86 * 87 * Since data will be parsed statically during a build step, some restrictions 88 * are applied with respect to how minErr instances are created and called. 89 * Instances should have names of the form namespaceMinErr for a minErr created 90 * using minErr('namespace') . Error codes, namespaces and template strings 91 * should all be static strings, not variables or general expressions. 92 * 93 * @param {string} module The namespace to use for the new minErr instance. 94 * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning 95 * error from returned function, for cases when a particular type of error is useful. 96 * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance 97 */ 98 99function minErr(module, ErrorConstructor) { 100 ErrorConstructor = ErrorConstructor || Error; 101 102 var url = 'https://errors.angularjs.org/1.7.3/'; 103 var regex = url.replace('.', '\\.') + '[\\s\\S]*'; 104 var errRegExp = new RegExp(regex, 'g'); 105 106 return function() { 107 var code = arguments[0], 108 template = arguments[1], 109 message = '[' + (module ? module + ':' : '') + code + '] ', 110 templateArgs = sliceArgs(arguments, 2).map(function(arg) { 111 return toDebugString(arg, minErrConfig.objectMaxDepth); 112 }), 113 paramPrefix, i; 114 115 // A minErr message has two parts: the message itself and the url that contains the 116 // encoded message. 117 // The message's parameters can contain other error messages which also include error urls. 118 // To prevent the messages from getting too long, we strip the error urls from the parameters. 119 120 message += template.replace(/\{\d+\}/g, function(match) { 121 var index = +match.slice(1, -1); 122 123 if (index < templateArgs.length) { 124 return templateArgs[index].replace(errRegExp, ''); 125 } 126 127 return match; 128 }); 129 130 message += '\n' + url + (module ? module + '/' : '') + code; 131
132 if (minErrConfig.urlErrorParamsEnabled) { 133 for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { 134 message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]); 135 } 136 } 137 138 return new ErrorConstructor(message); 139 }; 140} 141 142/* We need to tell ESLint what variables are being exported */ 143/* exported 144 angular, 145 msie, 146 jqLite, 147 jQuery, 148 slice, 149 splice, 150 push, 151 toString, 152 minErrConfig, 153 errorHandlingConfig, 154 isValidObjectMaxDepth, 155 ngMinErr, 156 angularModule, 157 uid, 158 REGEX_STRING_REGEXP, 159 VALIDITY_STATE_PROPERTY, 160 161 lowercase, 162 uppercase, 163 nodeName_, 164 isArrayLike, 165 forEach, 166 forEachSorted, 167 reverseParams, 168 nextUid, 169 setHashKey, 170 extend, 171 toInt, 172 inherit, 173 merge, 174 noop, 175 identity, 176 valueFn, 177 isUndefined, 178 isDefined, 179 isObject, 180 isBlankObject, 181 isString, 182 isNumber, 183 isNumberNaN, 184 isDate, 185 isError, 186 isArray, 187 isFunction, 188 isRegExp, 189 isWindow, 190 isScope, 191 isFile, 192 isFormData, 193 isBlob, 194 isBoolean, 195 isPromiseLike, 196 trim, 197 escapeForRegexp, 198 isElement, 199 makeMap, 200 includes, 201 arrayRemove, 202 copy, 203 simpleCompare, 204 equals, 205 csp, 206 jq, 207 concat, 208 sliceArgs, 209 bind, 210 toJsonReplacer, 211 toJson, 212 fromJson, 213 convertTimezoneToLocal, 214 timezoneToOffset, 215 addDateMinutes, 216 startingTag, 217 tryDecodeURIComponent, 218 parseKeyValue, 219 toKeyValue, 220 encodeUriSegment, 221 encodeUriQuery, 222 angularInit, 223 bootstrap, 224 getTestability, 225 snake_case, 226 bindJQuery, 227 assertArg, 228 assertArgFn, 229 assertNotHasOwnProperty, 230 getter, 231 getBlockNodes, 232 hasOwnProperty, 233 createMap, 234 stringify
vendor: 7,900 bytes, lines 234-484
234, 235 236 NODE_TYPE_ELEMENT, 237 NODE_TYPE_ATTRIBUTE, 238 NODE_TYPE_TEXT, 239 NODE_TYPE_COMMENT, 240 NODE_TYPE_DOCUMENT, 241 NODE_TYPE_DOCUMENT_FRAGMENT 242*/ 243 244//////////////////////////////////// 245 246/** 247 * @ngdoc module 248 * @name ng 249 * @module ng 250 * @installation 251 * @description 252 * 253 * The ng module is loaded by default when an AngularJS application is started. The module itself 254 * contains the essential components for an AngularJS application to function. The table below 255 * lists a high level breakdown of each of the services/factories, filters, directives and testing 256 * components available within this core module. 257 * 258 */ 259 260var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; 261 262// The name of a form control's ValidityState property. 263// This is used so that it's possible for internal tests to create mock ValidityStates. 264var VALIDITY_STATE_PROPERTY = 'validity'; 265 266 267var hasOwnProperty = Object.prototype.hasOwnProperty; 268 269/** 270 * @private 271 * 272 * @description Converts the specified string to lowercase. 273 * @param {string} string String to be converted to lowercase. 274 * @returns {string} Lowercased string. 275 */ 276var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;}; 277 278/** 279 * @private 280 * 281 * @description Converts the specified string to uppercase. 282 * @param {string} string String to be converted to uppercase. 283 * @returns {string} Uppercased string. 284 */ 285var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;}; 286 287 288var 289 msie, // holds major version number for IE, or NaN if UA is not IE. 290 jqLite, // delay binding since jQuery could be loaded after us. 291 jQuery, // delay binding 292 slice = [].slice, 293 splice = [].splice, 294 push = [].push, 295 toString = Object.prototype.toString, 296 getPrototypeOf = Object.getPrototypeOf, 297 ngMinErr = minErr('ng'), 298 299 /** @name angular */ 300 angular = window.angular || (window.angular = {}), 301 angularModule, 302 uid = 0; 303 304// Support: IE 9-11 only 305/** 306 * documentMode is an IE-only property 307 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx 308 */ 309msie = window.document.documentMode; 310 311 312/** 313 * @private 314 * @param {*} obj 315 * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, 316 * String ...) 317 */ 318function isArrayLike(obj) { 319 320 // `null`, `undefined` and `window` are not array-like 321 if (obj == null || isWindow(obj)) return false; 322 323 // arrays, strings and jQuery/jqLite objects are array like 324 // * jqLite is either the jQuery or jqLite constructor function 325 // * we have to check the existence of jqLite first as this method is called 326 // via the forEach method when constructing the jqLite object in the first place 327 if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true; 328 329 // Support: iOS 8.2 (not reproducible in simulator) 330 // "length" in obj used to prevent JIT error (gh-11508) 331 var length = 'length' in Object(obj) && obj.length; 332 333 // NodeList objects (with `item` method) and 334 // other objects with suitable length characteristics are array-like 335 return isNumber(length) && (length >= 0 && (length - 1) in obj || typeof obj.item === 'function'); 336 337} 338 339/** 340 * @ngdoc function 341 * @name angular.forEach 342 * @module ng 343 * @kind function 344 * 345 * @description 346 * Invokes the `iterator` function once for each item in `obj` collection, which can be either an 347 * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value` 348 * is the value of an object property or an array element, `key` is the object property key or 349 * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional. 350 * 351 * It is worth noting that `.forEach` does not iterate over inherited properties because it filters 352 * using the `hasOwnProperty` method. 353 * 354 * Unlike ES262's 355 * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18), 356 * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just 357 * return the value provided. 358 * 359 ```js 360 var values = {name: 'misko', gender: 'male'}; 361 var log = []; 362 angular.forEach(values, function(value, key) { 363 this.push(key + ': ' + value); 364 }, log); 365 expect(log).toEqual(['name: misko', 'gender: male']); 366 ``` 367 * 368 * @param {Object|Array} obj Object to iterate over. 369 * @param {Function} iterator Iterator function. 370 * @param {Object=} context Object to become context (`this`) for the iterator function. 371 * @returns {Object|Array} Reference to `obj`. 372 */ 373 374function forEach(obj, iterator, context) { 375 var key, length; 376 if (obj) { 377 if (isFunction(obj)) { 378 for (key in obj) { 379 if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) { 380 iterator.call(context, obj[key], key, obj); 381 } 382 } 383 } else if (isArray(obj) || isArrayLike(obj)) { 384 var isPrimitive = typeof obj !== 'object'; 385 for (key = 0, length = obj.length; key < length; key++) { 386 if (isPrimitive || key in obj) { 387 iterator.call(context, obj[key], key, obj); 388 } 389 } 390 } else if (obj.forEach && obj.forEach !== forEach) { 391 obj.forEach(iterator, context, obj); 392 } else if (isBlankObject(obj)) { 393 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty 394 for (key in obj) { 395 iterator.call(context, obj[key], key, obj); 396 } 397 } else if (typeof obj.hasOwnProperty === 'function') { 398 // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed 399 for (key in obj) { 400 if (obj.hasOwnProperty(key)) { 401 iterator.call(context, obj[key], key, obj); 402 } 403 } 404 } else { 405 // Slow path for objects which do not have a method `hasOwnProperty` 406 for (key in obj) { 407 if (hasOwnProperty.call(obj, key)) { 408 iterator.call(context, obj[key], key, obj); 409 } 410 } 411 } 412 } 413 return obj; 414} 415 416function forEachSorted(obj, iterator, context) { 417 var keys = Object.keys(obj).sort(); 418 for (var i = 0; i < keys.length; i++) { 419 iterator.call(context, obj[keys[i]], keys[i]); 420 } 421 return keys; 422} 423 424 425/** 426 * when using forEach the params are value, key, but it is often useful to have key, value. 427 * @param {function(string, *)} iteratorFn 428 * @returns {function(*, string)} 429 */ 430function reverseParams(iteratorFn) { 431 return function(value, key) {iteratorFn(key, value);}; 432} 433 434/** 435 * A consistent way of creating unique IDs in angular. 436 * 437 * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before 438 * we hit number precision issues in JavaScript. 439 * 440 * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M 441 * 442 * @returns {number} an unique alpha-numeric string 443 */ 444function nextUid() { 445 return ++uid; 446} 447 448 449/** 450 * Set or clear the hashkey for an object. 451 * @param obj object 452 * @param h the hashkey (!truthy to delete the hashkey) 453 */ 454function setHashKey(obj, h) { 455 if (h) { 456 obj.$$hashKey = h; 457 } else { 458 delete obj.$$hashKey; 459 } 460} 461 462 463function baseExtend(dst, objs, deep) { 464 var h = dst.$$hashKey; 465 466 for (var i = 0, ii = objs.length; i < ii; ++i) { 467 var obj = objs[i]; 468 if (!isObject(obj) && !isFunction(obj)) continue; 469 var keys = Object.keys(obj); 470 for (var j = 0, jj = keys.length; j < jj; j++) { 471 var key = keys[j]; 472 var src = obj[key]; 473 474 if (deep && isObject(src)) { 475 if (isDate(src)) { 476 dst[key] = new Date(src.valueOf()); 477 } else if (isRegExp(src)) { 478 dst[key] = new RegExp(src); 479 } else if (src.nodeName) { 480 dst[key] = src.cloneNode(true); 481 } else if (isElement(src)) { 482 dst[key] = src.clone(); 483 } else { 484 if (
vendor: 11,575 bytes, lines 484-942
484!isObject(dst[key])) dst[key] = isArray(src) ? [] : {}; 485 baseExtend(dst[key], [src], true); 486 } 487 } else { 488 dst[key] = src; 489 } 490 } 491 } 492 493 setHashKey(dst, h); 494 return dst; 495} 496 497/** 498 * @ngdoc function 499 * @name angular.extend 500 * @module ng 501 * @kind function 502 * 503 * @description 504 * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) 505 * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so 506 * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`. 507 * 508 * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use 509 * {@link angular.merge} for this. 510 * 511 * @param {Object} dst Destination object. 512 * @param {...Object} src Source object(s). 513 * @returns {Object} Reference to `dst`. 514 */ 515function extend(dst) { 516 return baseExtend(dst, slice.call(arguments, 1), false); 517} 518 519 520/** 521* @ngdoc function 522* @name angular.merge 523* @module ng 524* @kind function 525* 526* @description 527* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s) 528* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so 529* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`. 530* 531* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source 532* objects, performing a deep copy. 533* 534* @deprecated 535* sinceVersion="1.6.5" 536* This function is deprecated, but will not be removed in the 1.x lifecycle. 537* There are edge cases (see {@link angular.merge#known-issues known issues}) that are not 538* supported by this function. We suggest 539* using [lodash's merge()](https://lodash.com/docs/4.17.4#merge) instead. 540* 541* @knownIssue 542* This is a list of (known) object types that are not handled correctly by this function: 543* - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) 544* - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream) 545* - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient) 546* - AngularJS {@link $rootScope.Scope scopes}; 547* 548* @param {Object} dst Destination object. 549* @param {...Object} src Source object(s). 550* @returns {Object} Reference to `dst`. 551*/ 552function merge(dst) { 553 return baseExtend(dst, slice.call(arguments, 1), true); 554} 555 556 557 558function toInt(str) { 559 return parseInt(str, 10); 560} 561 562var isNumberNaN = Number.isNaN || function isNumberNaN(num) { 563 // eslint-disable-next-line no-self-compare 564 return num !== num; 565}; 566 567 568function inherit(parent, extra) { 569 return extend(Object.create(parent), extra); 570} 571 572/** 573 * @ngdoc function 574 * @name angular.noop 575 * @module ng 576 * @kind function 577 * 578 * @description 579 * A function that performs no operations. This function can be useful when writing code in the 580 * functional style. 581 ```js 582 function foo(callback) { 583 var result = calculateResult(); 584 (callback || angular.noop)(result); 585 } 586 ``` 587 */ 588function noop() {} 589noop.$inject = []; 590 591 592/** 593 * @ngdoc function 594 * @name angular.identity 595 * @module ng 596 * @kind function 597 * 598 * @description 599 * A function that returns its first argument. This function is useful when writing code in the 600 * functional style. 601 * 602 ```js 603 function transformer(transformationFn, value) { 604 return (transformationFn || angular.identity)(value); 605 }; 606 607 // E.g. 608 function getResult(fn, input) { 609 return (fn || angular.identity)(input); 610 }; 611 612 getResult(function(n) { return n * 2; }, 21); // returns 42 613 getResult(null, 21); // returns 21 614 getResult(undefined, 21); // returns 21 615 ``` 616 * 617 * @param {*} value to be returned. 618 * @returns {*} the value passed in. 619 */ 620function identity($) {return $;} 621identity.$inject = []; 622 623 624function valueFn(value) {return function valueRef() {return value;};} 625 626function hasCustomToString(obj) { 627 return isFunction(obj.toString) && obj.toString !== toString; 628} 629 630 631/** 632 * @ngdoc function 633 * @name angular.isUndefined 634 * @module ng 635 * @kind function 636 * 637 * @description 638 * Determines if a reference is undefined. 639 * 640 * @param {*} value Reference to check. 641 * @returns {boolean} True if `value` is undefined. 642 */ 643function isUndefined(value) {return typeof value === 'undefined';} 644 645 646/** 647 * @ngdoc function 648 * @name angular.isDefined 649 * @module ng 650 * @kind function 651 * 652 * @description 653 * Determines if a reference is defined. 654 * 655 * @param {*} value Reference to check. 656 * @returns {boolean} True if `value` is defined. 657 */ 658function isDefined(value) {return typeof value !== 'undefined';} 659 660 661/** 662 * @ngdoc function 663 * @name angular.isObject 664 * @module ng 665 * @kind function 666 * 667 * @description 668 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not 669 * considered to be objects. Note that JavaScript arrays are objects. 670 * 671 * @param {*} value Reference to check. 672 * @returns {boolean} True if `value` is an `Object` but not `null`. 673 */ 674function isObject(value) { 675 // http://jsperf.com/isobject4 676 return value !== null && typeof value === 'object'; 677} 678 679 680/** 681 * Determine if a value is an object with a null prototype 682 * 683 * @returns {boolean} True if `value` is an `Object` with a null prototype 684 */ 685function isBlankObject(value) { 686 return value !== null && typeof value === 'object' && !getPrototypeOf(value); 687} 688 689 690/** 691 * @ngdoc function 692 * @name angular.isString 693 * @module ng 694 * @kind function 695 * 696 * @description 697 * Determines if a reference is a `String`. 698 * 699 * @param {*} value Reference to check. 700 * @returns {boolean} True if `value` is a `String`. 701 */ 702function isString(value) {return typeof value === 'string';} 703 704 705/** 706 * @ngdoc function 707 * @name angular.isNumber 708 * @module ng 709 * @kind function 710 * 711 * @description 712 * Determines if a reference is a `Number`. 713 * 714 * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`. 715 * 716 * If you wish to exclude these then you can use the native 717 * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) 718 * method. 719 * 720 * @param {*} value Reference to check. 721 * @returns {boolean} True if `value` is a `Number`. 722 */ 723function isNumber(value) {return typeof value === 'number';} 724 725 726/** 727 * @ngdoc function 728 * @name angular.isDate 729 * @module ng 730 * @kind function 731 * 732 * @description 733 * Determines if a value is a date. 734 * 735 * @param {*} value Reference to check. 736 * @returns {boolean} True if `value` is a `Date`. 737 */ 738function isDate(value) { 739 return toString.call(value) === '[object Date]'; 740} 741 742 743/** 744 * @ngdoc function 745 * @name angular.isArray 746 * @module ng 747 * @kind function 748 * 749 * @description 750 * Determines if a reference is an `Array`. 751 * 752 * @param {*} value Reference to check. 753 * @returns {boolean} True if `value` is an `Array`. 754 */ 755function isArray(arr) { 756 return Array.isArray(arr) || arr instanceof Array; 757} 758 759/** 760 * @description 761 * Determines if a reference is an `Error`. 762 * Loosely based on https://www.npmjs.com/package/iserror 763 * 764 * @param {*} value Reference to check. 765 * @returns {boolean} True if `value` is an `Error`. 766 */ 767function isError(value) { 768 var tag = toString.call(value); 769 switch (tag) { 770 case '[object Error]': return true; 771 case '[object Exception]': return true; 772 case '[object DOMException]': return true; 773 default: return value instanceof Error; 774 } 775} 776 777/** 778 * @ngdoc function 779 * @name angular.isFunction 780 * @module ng 781 * @kind function 782 * 783 * @description 784 * Determines if a reference is a `Function`. 785 * 786 * @param {*} value Reference to check. 787 * @returns {boolean} True if `value` is a `Function`. 788 */ 789function isFunction(value) {return typeof value === 'function';} 790 791 792/** 793 * Determines if a value is a regular expression object. 794 * 795 * @private 796 * @param {*} value Reference to check. 797 * @returns {boolean} True if `value` is a `RegExp`. 798 */ 799function isRegExp(value) { 800 return toString.call(value) === '[object RegExp]'; 801} 802 803 804/** 805 * Checks if `obj` is a window object. 806 * 807 * @private 808 * @param {*} obj Object to check 809 * @returns {boolean} True if `obj` is a window obj. 810 */ 811function isWindow(obj) { 812 return obj && obj.window === obj; 813} 814 815 816function isScope(obj) { 817 return obj && obj.$evalAsync && obj.$watch; 818} 819 820 821function isFile(obj) { 822 return toString.call(obj) === '[object File]'; 823} 824 825 826function isFormData(obj) { 827 return toString.call(obj) === '[object FormData]'; 828} 829 830 831function isBlob(obj) { 832 return toString.call(obj) === '[object Blob]'; 833} 834 835 836function isBoolean(value) { 837 return typeof value === 'boolean'; 838} 839 840 841function isPromiseLike(obj) { 842 return obj && isFunction(obj.then); 843} 844 845 846var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/; 847function isTypedArray(value) { 848 return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value)); 849} 850 851function isArrayBuffer(obj) { 852 return toString.call(obj) === '[object ArrayBuffer]'; 853} 854 855 856var trim = function(value) { 857 return isString(value) ? value.trim() : value; 858}; 859 860// Copied from: 861// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021 862// Prereq: s is a string. 863var escapeForRegexp = function(s) { 864 return s 865 .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1') 866 // eslint-disable-next-line no-control-regex 867 .replace(/\x08/g, '\\x08'); 868}; 869 870 871/** 872 * @ngdoc function 873 * @name angular.isElement 874 * @module ng 875 * @kind function 876 * 877 * @description 878 * Determines if a reference is a DOM element (or wrapped jQuery element). 879 * 880 * @param {*} value Reference to check. 881 * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). 882 */ 883function isElement(node) { 884 return !!(node && 885 (node.nodeName // We are a direct element. 886 || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API. 887} 888 889/** 890 * @param str 'key1,key2,...' 891 * @returns {object} in the form of {key1:true, key2:true, ...} 892 */ 893function makeMap(str) { 894 var obj = {}, items = str.split(','), i; 895 for (i = 0; i < items.length; i++) { 896 obj[items[i]] = true; 897 } 898 return obj; 899} 900 901 902function nodeName_(element) { 903 return lowercase(element.nodeName || (element[0] && element[0].nodeName)); 904} 905 906function includes(array, obj) { 907 return Array.prototype.indexOf.call(array, obj) !== -1; 908} 909 910function arrayRemove(array, value) { 911 var index = array.indexOf(value); 912 if (index >= 0) { 913 array.splice(index, 1); 914 } 915 return index; 916} 917 918/** 919 * @ngdoc function 920 * @name angular.copy 921 * @module ng 922 * @kind function 923 * 924 * @description 925 * Creates a deep copy of `source`, which should be an object or an array. 926 * 927 * * If no destination is supplied, a copy of the object or array is created. 928 * * If a destination is provided, all of its elements (for arrays) or properties (for objects) 929 * are deleted and then all elements/properties from the source are copied to it. 930 * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. 931 * * If `source` is identical to `destination` an exception will be thrown. 932 * 933 * <br /> 934 * <div class="alert alert-warning"> 935 * Only enumerable properties are taken into account. Non-enumerable properties (both on `source` 936 * and on `destination`) will be ignored. 937 * </div> 938 * 939 * @param {*} source The source that will be used to make a copy. 940 * Can be any type, including primitives, `null`, and `undefined`. 941 * @param {(Object|Array)=} destination Destination into which the source is copied. If 942 * provided,
vendor: 21,649 bytes, lines 942-1647
942 must be of the same type as `source`. 943 * @returns {*} The copy or updated `destination`, if `destination` was specified. 944 * 945 * @example 946 <example module="copyExample" name="angular-copy"> 947 <file name="index.html"> 948 <div ng-controller="ExampleController"> 949 <form novalidate class="simple-form"> 950 <label>Name: <input type="text" ng-model="user.name" /></label><br /> 951 <label>Age: <input type="number" ng-model="user.age" /></label><br /> 952 Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label> 953 <label><input type="radio" ng-model="user.gender" value="female" />female</label><br /> 954 <button ng-click="reset()">RESET</button> 955 <button ng-click="update(user)">SAVE</button> 956 </form> 957 <pre>form = {{user | json}}</pre> 958 <pre>leader = {{leader | json}}</pre> 959 </div> 960 </file> 961 <file name="script.js"> 962 // Module: copyExample 963 angular. 964 module('copyExample', []). 965 controller('ExampleController', ['$scope', function($scope) { 966 $scope.leader = {}; 967 968 $scope.reset = function() { 969 // Example with 1 argument 970 $scope.user = angular.copy($scope.leader); 971 }; 972 973 $scope.update = function(user) { 974 // Example with 2 arguments 975 angular.copy(user, $scope.leader); 976 }; 977 978 $scope.reset(); 979 }]); 980 </file> 981 </example> 982 */ 983function copy(source, destination, maxDepth) { 984 var stackSource = []; 985 var stackDest = []; 986 maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN; 987 988 if (destination) { 989 if (isTypedArray(destination) || isArrayBuffer(destination)) { 990 throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.'); 991 } 992 if (source === destination) { 993 throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.'); 994 } 995 996 // Empty the destination object 997 if (isArray(destination)) { 998 destination.length = 0; 999 } else { 1000 forEach(destination, function(value, key) { 1001 if (key !== '$$hashKey') { 1002 delete destination[key]; 1003 } 1004 }); 1005 } 1006 1007 stackSource.push(source); 1008 stackDest.push(destination); 1009 return copyRecurse(source, destination, maxDepth); 1010 } 1011 1012 return copyElement(source, maxDepth); 1013 1014 function copyRecurse(source, destination, maxDepth) { 1015 maxDepth--; 1016 if (maxDepth < 0) { 1017 return '...'; 1018 } 1019 var h = destination.$$hashKey; 1020 var key; 1021 if (isArray(source)) { 1022 for (var i = 0, ii = source.length; i < ii; i++) { 1023 destination.push(copyElement(source[i], maxDepth)); 1024 } 1025 } else if (isBlankObject(source)) { 1026 // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty 1027 for (key in source) { 1028 destination[key] = copyElement(source[key], maxDepth); 1029 } 1030 } else if (source && typeof source.hasOwnProperty === 'function') { 1031 // Slow path, which must rely on hasOwnProperty 1032 for (key in source) { 1033 if (source.hasOwnProperty(key)) { 1034 destination[key] = copyElement(source[key], maxDepth); 1035 } 1036 } 1037 } else { 1038 // Slowest path --- hasOwnProperty can't be called as a method 1039 for (key in source) { 1040 if (hasOwnProperty.call(source, key)) { 1041 destination[key] = copyElement(source[key], maxDepth); 1042 } 1043 } 1044 } 1045 setHashKey(destination, h); 1046 return destination; 1047 } 1048 1049 function copyElement(source, maxDepth) { 1050 // Simple values 1051 if (!isObject(source)) { 1052 return source; 1053 } 1054 1055 // Already copied values 1056 var index = stackSource.indexOf(source); 1057 if (index !== -1) { 1058 return stackDest[index]; 1059 } 1060 1061 if (isWindow(source) || isScope(source)) { 1062 throw ngMinErr('cpws', 1063 'Can\'t copy! Making copies of Window or Scope instances is not supported.'); 1064 } 1065 1066 var needsRecurse = false; 1067 var destination = copyType(source); 1068 1069 if (destination === undefined) { 1070 destination = isArray(source) ? [] : Object.create(getPrototypeOf(source)); 1071 needsRecurse = true; 1072 } 1073 1074 stackSource.push(source); 1075 stackDest.push(destination); 1076 1077 return needsRecurse 1078 ? copyRecurse(source, destination, maxDepth) 1079 : destination; 1080 } 1081 1082 function copyType(source) { 1083 switch (toString.call(source)) { 1084 case '[object Int8Array]': 1085 case '[object Int16Array]': 1086 case '[object Int32Array]': 1087 case '[object Float32Array]': 1088 case '[object Float64Array]': 1089 case '[object Uint8Array]': 1090 case '[object Uint8ClampedArray]': 1091 case '[object Uint16Array]': 1092 case '[object Uint32Array]': 1093 return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length); 1094 1095 case '[object ArrayBuffer]': 1096 // Support: IE10 1097 if (!source.slice) { 1098 // If we're in this case we know the environment supports ArrayBuffer 1099 /* eslint-disable no-undef */ 1100 var copied = new ArrayBuffer(source.byteLength); 1101 new Uint8Array(copied).set(new Uint8Array(source)); 1102 /* eslint-enable */ 1103 return copied; 1104 } 1105 return source.slice(0); 1106 1107 case '[object Boolean]': 1108 case '[object Number]': 1109 case '[object String]': 1110 case '[object Date]': 1111 return new source.constructor(source.valueOf()); 1112 1113 case '[object RegExp]': 1114 var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]); 1115 re.lastIndex = source.lastIndex; 1116 return re; 1117 1118 case '[object Blob]': 1119 return new source.constructor([source], {type: source.type}); 1120 } 1121 1122 if (isFunction(source.cloneNode)) { 1123 return source.cloneNode(true); 1124 } 1125 } 1126} 1127 1128 1129// eslint-disable-next-line no-self-compare 1130function simpleCompare(a, b) { return a === b || (a !== a && b !== b); } 1131 1132 1133/** 1134 * @ngdoc function 1135 * @name angular.equals 1136 * @module ng 1137 * @kind function 1138 * 1139 * @description 1140 * Determines if two objects or two values are equivalent. Supports value types, regular 1141 * expressions, arrays and objects. 1142 * 1143 * Two objects or values are considered equivalent if at least one of the following is true: 1144 * 1145 * * Both objects or values pass `===` comparison. 1146 * * Both objects or values are of the same type and all of their properties are equal by 1147 * comparing them with `angular.equals`. 1148 * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) 1149 * * Both values represent the same regular expression (In JavaScript, 1150 * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual 1151 * representation matches). 1152 * 1153 * During a property comparison, properties of `function` type and properties with names 1154 * that begin with `$` are ignored. 1155 * 1156 * Scope and DOMWindow objects are being compared only by identify (`===`). 1157 * 1158 * @param {*} o1 Object or value to compare. 1159 * @param {*} o2 Object or value to compare. 1160 * @returns {boolean} True if arguments are equal. 1161 * 1162 * @example 1163 <example module="equalsExample" name="equalsExample"> 1164 <file name="index.html"> 1165 <div ng-controller="ExampleController"> 1166 <form novalidate> 1167 <h3>User 1</h3> 1168 Name: <input type="text" ng-model="user1.name"> 1169 Age: <input type="number" ng-model="user1.age"> 1170 1171 <h3>User 2</h3> 1172 Name: <input type="text" ng-model="user2.name"> 1173 Age: <input type="number" ng-model="user2.age"> 1174 1175 <div> 1176 <br/> 1177 <input type="button" value="Compare" ng-click="compare()"> 1178 </div> 1179 User 1: <pre>{{user1 | json}}</pre> 1180 User 2: <pre>{{user2 | json}}</pre> 1181 Equal: <pre>{{result}}</pre> 1182 </form> 1183 </div> 1184 </file> 1185 <file name="script.js"> 1186 angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) { 1187 $scope.user1 = {}; 1188 $scope.user2 = {}; 1189 $scope.compare = function() { 1190 $scope.result = angular.equals($scope.user1, $scope.user2); 1191 }; 1192 }]); 1193 </file> 1194 </example> 1195 */ 1196function equals(o1, o2) { 1197 if (o1 === o2) return true; 1198 if (o1 === null || o2 === null) return false; 1199 // eslint-disable-next-line no-self-compare 1200 if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN 1201 var t1 = typeof o1, t2 = typeof o2, length, key, keySet; 1202 if (t1 === t2 && t1 === 'object') { 1203 if (isArray(o1)) { 1204 if (!isArray(o2)) return false; 1205 if ((length = o1.length) === o2.length) { 1206 for (key = 0; key < length; key++) { 1207 if (!equals(o1[key], o2[key])) return false; 1208 } 1209 return true; 1210 } 1211 } else if (isDate(o1)) { 1212 if (!isDate(o2)) return false; 1213 return simpleCompare(o1.getTime(), o2.getTime()); 1214 } else if (isRegExp(o1)) { 1215 if (!isRegExp(o2)) return false; 1216 return o1.toString() === o2.toString(); 1217 } else { 1218 if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || 1219 isArray(o2) || isDate(o2) || isRegExp(o2)) return false; 1220 keySet = createMap(); 1221 for (key in o1) { 1222 if (key.charAt(0) === '$' || isFunction(o1[key])) continue; 1223 if (!equals(o1[key], o2[key])) return false; 1224 keySet[key] = true; 1225 } 1226 for (key in o2) { 1227 if (!(key in keySet) && 1228 key.charAt(0) !== '$' && 1229 isDefined(o2[key]) && 1230 !isFunction(o2[key])) return false; 1231 } 1232 return true; 1233 } 1234 } 1235 return false; 1236} 1237 1238var csp = function() { 1239 if (!isDefined(csp.rules)) { 1240 1241 1242 var ngCspElement = (window.document.querySelector('[ng-csp]') || 1243 window.document.querySelector('[data-ng-csp]')); 1244 1245 if (ngCspElement) { 1246 var ngCspAttribute = ngCspElement.getAttribute('ng-csp') || 1247 ngCspElement.getAttribute('data-ng-csp'); 1248 csp.rules = { 1249 noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1), 1250 noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1) 1251 }; 1252 } else { 1253 csp.rules = { 1254 noUnsafeEval: noUnsafeEval(), 1255 noInlineStyle: false 1256 }; 1257 } 1258 } 1259 1260 return csp.rules; 1261 1262 function noUnsafeEval() { 1263 try { 1264 // eslint-disable-next-line no-new, no-new-func 1265 new Function(''); 1266 return false; 1267 } catch (e) { 1268 return true; 1269 } 1270 } 1271}; 1272 1273/** 1274 * @ngdoc directive 1275 * @module ng 1276 * @name ngJq 1277 * 1278 * @element ANY 1279 * @param {string=} ngJq the name of the library available under `window` 1280 * to be used for angular.element 1281 * @description 1282 * Use this directive to force the angular.element library. This should be 1283 * used to force either jqLite by leaving ng-jq blank or setting the name of 1284 * the jquery variable under window (eg. jQuery). 1285 * 1286 * Since AngularJS looks for this directive when it is loaded (doesn't wait for the 1287 * DOMContentLoaded event), it must be placed on an element that comes before the script 1288 * which loads angular. Also, only the first instance of `ng-jq` will be used and all 1289 * others ignored. 1290 * 1291 * @example 1292 * This example shows how to force jqLite using the `ngJq` directive to the `html` tag. 1293 ```html 1294 <!doctype html> 1295 <html ng-app ng-jq> 1296 ... 1297 ... 1298 </html> 1299 ``` 1300 * @example 1301 * This example shows how to use a jQuery based library of a different name. 1302 * The library name must be available at the top most 'window'. 1303 ```html 1304 <!doctype html> 1305 <html ng-app ng-jq="jQueryLib"> 1306 ... 1307 ... 1308 </html> 1309 ``` 1310 */ 1311var jq = function() { 1312 if (isDefined(jq.name_)) return jq.name_; 1313 var el; 1314 var i, ii = ngAttrPrefixes.length, prefix, name; 1315 for (i = 0; i < ii; ++i) { 1316 prefix = ngAttrPrefixes[i]; 1317 el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]'); 1318 if (el) { 1319 name = el.getAttribute(prefix + 'jq'); 1320 break; 1321 } 1322 } 1323 1324 return (jq.name_ = name); 1325}; 1326 1327function concat(array1, array2, index) { 1328 return array1.concat(slice.call(array2, index)); 1329} 1330 1331function sliceArgs(args, startIndex) { 1332 return slice.call(args, startIndex || 0); 1333} 1334 1335 1336/** 1337 * @ngdoc function 1338 * @name angular.bind 1339 * @module ng 1340 * @kind function 1341 * 1342 * @description 1343 * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for 1344 * `fn`). You can supply optional `args` that are prebound to the function. This feature is also 1345 * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as 1346 * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application). 1347 * 1348 * @param {Object} self Context which `fn` should be evaluated in. 1349 * @param {function()} fn Function to be bound. 1350 * @param {...*} args Optional arguments to be prebound to the `fn` function call. 1351 * @returns {function()} Function that wraps the `fn` with all the specified bindings. 1352 */ 1353function bind(self, fn) { 1354 var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; 1355 if (isFunction(fn) && !(fn instanceof RegExp)) { 1356 return curryArgs.length 1357 ? function() { 1358 return arguments.length 1359 ? fn.apply(self, concat(curryArgs, arguments, 0)) 1360 : fn.apply(self, curryArgs); 1361 } 1362 : function() { 1363 return arguments.length 1364 ? fn.apply(self, arguments) 1365 : fn.call(self); 1366 }; 1367 } else { 1368 // In IE, native methods are not functions so they cannot be bound (note: they don't need to be). 1369 return fn; 1370 } 1371} 1372 1373 1374function toJsonReplacer(key, value) { 1375 var val = value; 1376 1377 if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { 1378 val = undefined; 1379 } else if (isWindow(value)) { 1380 val = '$WINDOW'; 1381 } else if (value && window.document === value) { 1382 val = '$DOCUMENT'; 1383 } else if (isScope(value)) { 1384 val = '$SCOPE'; 1385 } 1386 1387 return val; 1388} 1389 1390 1391/** 1392 * @ngdoc function 1393 * @name angular.toJson 1394 * @module ng 1395 * @kind function 1396 * 1397 * @description 1398 * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be 1399 * stripped since AngularJS uses this notation internally. 1400 * 1401 * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON. 1402 * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace. 1403 * If set to an integer, the JSON output will contain that many spaces per indentation. 1404 * @returns {string|undefined} JSON-ified string representing `obj`. 1405 * @knownIssue 1406 * 1407 * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date` 1408 * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the 1409 * `Date.prototype.toJSON` method as follows: 1410 * 1411 * ``` 1412 * var _DatetoJSON = Date.prototype.toJSON; 1413 * Date.prototype.toJSON = function() { 1414 * try { 1415 * return _DatetoJSON.call(this); 1416 * } catch(e) { 1417 * if (e instanceof RangeError) { 1418 * return null; 1419 * } 1420 * throw e; 1421 * } 1422 * }; 1423 * ``` 1424 * 1425 * See https://github.com/angular/angular.js/pull/14221 for more information. 1426 */ 1427function toJson(obj, pretty) { 1428 if (isUndefined(obj)) return undefined; 1429 if (!isNumber(pretty)) { 1430 pretty = pretty ? 2 : null; 1431 } 1432 return JSON.stringify(obj, toJsonReplacer, pretty); 1433} 1434 1435 1436/** 1437 * @ngdoc function 1438 * @name angular.fromJson 1439 * @module ng 1440 * @kind function 1441 * 1442 * @description 1443 * Deserializes a JSON string. 1444 * 1445 * @param {string} json JSON string to deserialize. 1446 * @returns {Object|Array|string|number} Deserialized JSON string. 1447 */ 1448function fromJson(json) { 1449 return isString(json) 1450 ? JSON.parse(json) 1451 : json; 1452} 1453 1454 1455var ALL_COLONS = /:/g; 1456function timezoneToOffset(timezone, fallback) { 1457 // Support: IE 9-11 only, Edge 13-15+ 1458 // IE/Edge do not "understand" colon (`:`) in timezone 1459 timezone = timezone.replace(ALL_COLONS, ''); 1460 var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; 1461 return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; 1462} 1463 1464 1465function addDateMinutes(date, minutes) { 1466 date = new Date(date.getTime()); 1467 date.setMinutes(date.getMinutes() + minutes); 1468 return date; 1469} 1470 1471 1472function convertTimezoneToLocal(date, timezone, reverse) { 1473 reverse = reverse ? -1 : 1; 1474 var dateTimezoneOffset = date.getTimezoneOffset(); 1475 var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); 1476 return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset)); 1477} 1478 1479 1480/** 1481 * @returns {string} Returns the string representation of the element. 1482 */ 1483function startingTag(element) { 1484 element = jqLite(element).clone().empty(); 1485 var elemHtml = jqLite('<div></div>').append(element).html(); 1486 try { 1487 return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : 1488 elemHtml. 1489 match(/^(<[^>]+>)/)[1]. 1490 replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);}); 1491 } catch (e) { 1492 return lowercase(elemHtml); 1493 } 1494 1495} 1496 1497 1498///////////////////////////////////////////////// 1499 1500/** 1501 * Tries to decode the URI component without throwing an exception. 1502 * 1503 * @private 1504 * @param str value potential URI component to check. 1505 * @returns {boolean} True if `value` can be decoded 1506 * with the decodeURIComponent function. 1507 */ 1508function tryDecodeURIComponent(value) { 1509 try { 1510 return decodeURIComponent(value); 1511 } catch (e) { 1512 // Ignore any invalid uri component. 1513 } 1514} 1515 1516 1517/** 1518 * Parses an escaped url query string into key-value pairs. 1519 * @returns {Object.<string,boolean|Array>} 1520 */ 1521function parseKeyValue(/**string*/keyValue) { 1522 var obj = {}; 1523 forEach((keyValue || '').split('&'), function(keyValue) { 1524 var splitPoint, key, val; 1525 if (keyValue) { 1526 key = keyValue = keyValue.replace(/\+/g,'%20'); 1527 splitPoint = keyValue.indexOf('='); 1528 if (splitPoint !== -1) { 1529 key = keyValue.substring(0, splitPoint); 1530 val = keyValue.substring(splitPoint + 1); 1531 } 1532 key = tryDecodeURIComponent(key); 1533 if (isDefined(key)) { 1534 val = isDefined(val) ? tryDecodeURIComponent(val) : true; 1535 if (!hasOwnProperty.call(obj, key)) { 1536 obj[key] = val; 1537 } else if (isArray(obj[key])) { 1538 obj[key].push(val); 1539 } else { 1540 obj[key] = [obj[key],val]; 1541 } 1542 } 1543 } 1544 }); 1545 return obj; 1546} 1547 1548function toKeyValue(obj) { 1549 var parts = []; 1550 forEach(obj, function(value, key) { 1551 if (isArray(value)) { 1552 forEach(value, function(arrayValue) { 1553 parts.push(encodeUriQuery(key, true) + 1554 (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true))); 1555 }); 1556 } else { 1557 parts.push(encodeUriQuery(key, true) + 1558 (value === true ? '' : '=' + encodeUriQuery(value, true))); 1559 } 1560 }); 1561 return parts.length ? parts.join('&') : ''; 1562} 1563 1564 1565/** 1566 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow 1567 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path 1568 * segments: 1569 * segment = *pchar 1570 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" 1571 * pct-encoded = "%" HEXDIG HEXDIG 1572 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" 1573 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" 1574 * / "*" / "+" / "," / ";" / "=" 1575 */ 1576function encodeUriSegment(val) { 1577 return encodeUriQuery(val, true). 1578 replace(/%26/gi, '&'). 1579 replace(/%3D/gi, '='). 1580 replace(/%2B/gi, '+'); 1581} 1582 1583 1584/** 1585 * This method is intended for encoding *key* or *value* parts of query component. We need a custom 1586 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be 1587 * encoded per http://tools.ietf.org/html/rfc3986: 1588 * query = *( pchar / "/" / "?" ) 1589 * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" 1590 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" 1591 * pct-encoded = "%" HEXDIG HEXDIG 1592 * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" 1593 * / "*" / "+" / "," / ";" / "=" 1594 */ 1595function encodeUriQuery(val, pctEncodeSpaces) { 1596 return encodeURIComponent(val). 1597 replace(/%40/gi, '@'). 1598 replace(/%3A/gi, ':'). 1599 replace(/%24/g, '$'). 1600 replace(/%2C/gi, ','). 1601 replace(/%3B/gi, ';'). 1602 replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); 1603} 1604 1605var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; 1606 1607function getNgAttribute(element, ngAttr) { 1608 var attr, i, ii = ngAttrPrefixes.length; 1609 for (i = 0; i < ii; ++i) { 1610 attr = ngAttrPrefixes[i] + ngAttr; 1611 if (isString(attr = element.getAttribute(attr))) { 1612 return attr; 1613 } 1614 } 1615 return null; 1616} 1617 1618function allowAutoBootstrap(document) { 1619 var script = document.currentScript; 1620 1621 if (!script) { 1622 // Support: IE 9-11 only 1623 // IE does not have `document.currentScript` 1624 return true; 1625 } 1626 1627 // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack 1628 if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) { 1629 return false; 1630 } 1631 1632 var attributes = script.attributes; 1633 var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')]; 1634 1635 return srcs.every(function(src) { 1636 if (!src) { 1637 return true; 1638 } 1639 if (!src.value) { 1640 return false; 1641 } 1642 1643 var link = document.createElement('a'); 1644 link.href = src.value; 1645 1646 if (document.location.origin === link.origin) { 1647 // Same-origin resources are always allowed, even for
1647non-whitelisted schemes. 1648 return true; 1649 } 1650 // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web. 1651 // This is to prevent angular.js bundled with browser extensions from being used to bypass the 1652 // content security policy in web pages and other browser extensions. 1653 switch (link.protocol) { 1654 case 'http:': 1655 case 'https:': 1656 case 'ftp:': 1657 case 'blob:': 1658 case 'file:': 1659 case 'data:': 1660 return true; 1661 default: 1662 return false; 1663 } 1664 }); 1665} 1666 1667// Cached as it has to run during loading so that document.currentScript is available. 1668var isAutoBootstrapAllowed = allowAutoBootstrap(window.document); 1669 1670/** 1671 * @ngdoc directive 1672 * @name ngApp 1673 * @module ng 1674 * 1675 * @element ANY 1676 * @param {angular.Module} ngApp an optional application 1677 * {@link angular.module module} name to load. 1678 * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be 1679 * created in "strict-di" mode. This means that the application will fail to invoke functions which 1680 * do not use explicit function annotation (and are thus unsuitable for minification), as described 1681 * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in 1682 * tracking down the root of these bugs. 1683 * 1684 * @description 1685 * 1686 * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive 1687 * designates the **root element** of the application and is typically placed near the root element 1688 * of the page - e.g. on the `<body>` or `<html>` tags. 1689 * 1690 * There are a few things to keep in mind when using `ngApp`: 1691 * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` 1692 * found in the document will be used to define the root element to auto-bootstrap as an 1693 * application. To run multiple applications in an HTML document you must manually bootstrap them using 1694 * {@link angular.bootstrap} instead. 1695 * - AngularJS applications cannot be nested within each other. 1696 * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`. 1697 * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and 1698 * {@link ngRoute.ngView `ngView`}. 1699 * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector}, 1700 * causing animations to stop working and making the injector inaccessible from outside the app. 1701 * 1702 * You can specify an **AngularJS module** to be used as the root module for the application. This 1703 * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It 1704 * should contain the application code needed or have dependencies on other modules that will 1705 * contain the code. See {@link angular.module} for more information. 1706 * 1707 * In the example below if the `ngApp` directive were not placed on the `html` element then the 1708 * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` 1709 * would not be resolved to `3`. 1710 * 1711 * @example 1712 * 1713 * ### Simple Usage 1714 * 1715 * `ngApp` is the easiest, and most common way to bootstrap an application. 1716 * 1717 <example module="ngAppDemo" name="ng-app"> 1718 <file name="index.html"> 1719 <div ng-controller="ngAppDemoController"> 1720 I can add: {{a}} + {{b}} = {{ a+b }} 1721 </div> 1722 </file> 1723 <file name="script.js"> 1724 angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { 1725 $scope.a = 1; 1726 $scope.b = 2; 1727 }); 1728 </file> 1729 </example> 1730 * 1731 * @example 1732 * 1733 * ### With `ngStrictDi` 1734 * 1735 * Using `ngStrictDi`, you would see something like this: 1736 * 1737 <example ng-app-included="true" name="strict-di"> 1738 <file name="index.html"> 1739 <div ng-app="ngAppStrictDemo" ng-strict-di> 1740 <div ng-controller="GoodController1"> 1741 I can add: {{a}} + {{b}} = {{ a+b }} 1742 1743 <p>This renders because the controller does not fail to 1744 instantiate, by using explicit annotation style (see 1745 script.js for details) 1746 </p> 1747 </div> 1748 1749 <div ng-controller="GoodController2"> 1750 Name: <input ng-model="name"><br /> 1751 Hello, {{name}}! 1752 1753 <p>This renders because the controller does not fail to 1754 instantiate, by using explicit annotation style 1755 (see script.js for details) 1756 </p> 1757 </div> 1758 1759 <div ng-controller="BadController"> 1760 I can add: {{a}} + {{b}} = {{ a+b }} 1761 1762 <p>The controller could not be instantiated, due to relying 1763 on automatic function annotations (which are disabled in
1764 strict mode). As such, the content of this section is not 1765 interpolated, and there should be an error in your web console. 1766 </p> 1767 </div> 1768 </div> 1769 </file> 1770 <file name="script.js"> 1771 angular.module('ngAppStrictDemo', []) 1772 // BadController will fail to instantiate, due to relying on automatic function annotation, 1773 // rather than an explicit annotation 1774 .controller('BadController', function($scope) { 1775 $scope.a = 1; 1776 $scope.b = 2; 1777 }) 1778 // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated, 1779 // due to using explicit annotations using the array style and $inject property, respectively. 1780 .controller('GoodController1', ['$scope', function($scope) { 1781 $scope.a = 1; 1782 $scope.b = 2; 1783 }]) 1784 .controller('GoodController2', GoodController2); 1785 function GoodController2($scope) { 1786 $scope.name = 'World'; 1787 } 1788 GoodController2.$inject = ['$scope']; 1789 </file> 1790 <file name="style.css"> 1791 div[ng-controller] { 1792 margin-bottom: 1em; 1793 -webkit-border-radius: 4px; 1794 border-radius: 4px; 1795 border: 1px solid; 1796 padding: .5em; 1797 } 1798 div[ng-controller^=Good] { 1799 border-color: #d6e9c6; 1800 background-color: #dff0d8; 1801 color: #3c763d; 1802 } 1803 div[ng-controller^=Bad] { 1804 border-color: #ebccd1; 1805 background-color: #f2dede; 1806 color: #a94442; 1807 margin-bottom: 0; 1808 } 1809 </file> 1810 </example> 1811 */ 1812function angularInit(element, bootstrap) { 1813 var appElement, 1814 module, 1815 config = {}; 1816 1817 // The element `element` has priority over any other element. 1818 forEach(ngAttrPrefixes, function(prefix) { 1819 var name = prefix + 'app'; 1820 1821 if (!appElement && element.hasAttribute && element.hasAttribute(name)) { 1822 appElement = element; 1823 module = element.getAttribute(name); 1824 } 1825 }); 1826 forEach(ngAttrPrefixes, function(prefix) { 1827 var name = prefix + 'app'; 1828 var candidate; 1829 1830 if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) { 1831 appElement = candidate; 1832 module = candidate.getAttribute(name); 1833 } 1834 }); 1835 if (appElement) { 1836 if (!isAutoBootstrapAllowed) {
vendor: 7,945 bytes, lines 1837-2067
1837 try { 1838 window.console.error('AngularJS: disabling automatic bootstrap. <script> protocol indicates ' + 1839 'an extension, document.location.href does not match.'); 1840 } catch (e) { 1841 // Support: Safari 11 w/ Webdriver 1842 // The console.error will throw and make the test fail 1843 } 1844 return; 1845 } 1846 config.strictDi = getNgAttribute(appElement, 'strict-di') !== null; 1847 bootstrap(appElement, module ? [module] : [], config); 1848 } 1849} 1850 1851/** 1852 * @ngdoc function 1853 * @name angular.bootstrap 1854 * @module ng 1855 * @description 1856 * Use this function to manually start up AngularJS application. 1857 * 1858 * For more information, see the {@link guide/bootstrap Bootstrap guide}. 1859 * 1860 * AngularJS will detect if it has been loaded into the browser more than once and only allow the 1861 * first loaded script to be bootstrapped and will report a warning to the browser console for 1862 * each of the subsequent scripts. This prevents strange results in applications, where otherwise 1863 * multiple instances of AngularJS try to work on the DOM. 1864 * 1865 * <div class="alert alert-warning"> 1866 * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually. 1867 * They must use {@link ng.directive:ngApp ngApp}. 1868 * </div> 1869 * 1870 * <div class="alert alert-warning"> 1871 * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion}, 1872 * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}. 1873 * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector}, 1874 * causing animations to stop working and making the injector inaccessible from outside the app. 1875 * </div> 1876 * 1877 * ```html 1878 * <!doctype html> 1879 * <html> 1880 * <body> 1881 * <div ng-controller="WelcomeController"> 1882 * {{greeting}} 1883 * </div> 1884 * 1885 * <script src="angular.js"></script> 1886 * <script> 1887 * var app = angular.module('demo', []) 1888 * .controller('WelcomeController', function($scope) { 1889 * $scope.greeting = 'Welcome!'; 1890 * }); 1891 * angular.bootstrap(document, ['demo']); 1892 * </script> 1893 * </body> 1894 * </html> 1895 * ``` 1896 * 1897 * @param {DOMElement} element DOM element which is the root of AngularJS application. 1898 * @param {Array<String|Function|Array>=} modules an array of modules to load into the application. 1899 * Each item in the array should be the name of a predefined module or a (DI annotated) 1900 * function that will be invoked by the injector as a `config` block. 1901 * See: {@link angular.module modules} 1902 * @param {Object=} config an object for defining configuration options for the application. The 1903 * following keys are supported: 1904 * 1905 * * `strictDi` - disable automatic function annotation for the application. This is meant to 1906 * assist in finding bugs which break minified code. Defaults to `false`. 1907 * 1908 * @returns {auto.$injector} Returns the newly created injector for this app. 1909 */ 1910function bootstrap(element, modules, config) { 1911 if (!isObject(config)) config = {}; 1912 var defaultConfig = { 1913 strictDi: false 1914 }; 1915 config = extend(defaultConfig, config); 1916 var doBootstrap = function() { 1917 element = jqLite(element); 1918 1919 if (element.injector()) { 1920 var tag = (element[0] === window.document) ? 'document' : startingTag(element); 1921 // Encode angle brackets to prevent input from being sanitized to empty string #8683. 1922 throw ngMinErr( 1923 'btstrpd', 1924 'App already bootstrapped with this element \'{0}\'', 1925 tag.replace(/</,'<').replace(/>/,'>')); 1926 } 1927 1928 modules = modules || []; 1929 modules.unshift(['$provide', function($provide) { 1930 $provide.value('$rootElement', element); 1931 }]); 1932 1933 if (config.debugInfoEnabled) { 1934 // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`. 1935 modules.push(['$compileProvider', function($compileProvider) { 1936 $compileProvider.debugInfoEnabled(true); 1937 }]); 1938 } 1939 1940 modules.unshift('ng'); 1941 var injector = createInjector(modules, config.strictDi); 1942 injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', 1943 function bootstrapApply(scope, element, compile, injector) { 1944 scope.$apply(function() { 1945 element.data('$injector', injector); 1946 compile(element)(scope); 1947 }); 1948 }] 1949 ); 1950 return injector; 1951 }; 1952 1953 var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/; 1954 var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; 1955 1956 if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) { 1957 config.debugInfoEnabled = true; 1958 window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, ''); 1959 } 1960 1961 if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { 1962 return doBootstrap(); 1963 } 1964 1965 window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); 1966 angular.resumeBootstrap = function(extraModules) { 1967 forEach(extraModules, function(module) { 1968 modules.push(module); 1969 }); 1970 return doBootstrap(); 1971 }; 1972 1973 if (isFunction(angular.resumeDeferredBootstrap)) { 1974 angular.resumeDeferredBootstrap(); 1975 } 1976} 1977 1978/** 1979 * @ngdoc function 1980 * @name angular.reloadWithDebugInfo 1981 * @module ng 1982 * @description 1983 * Use this function to reload the current application with debug information turned on. 1984 * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`. 1985 * 1986 * See {@link ng.$compileProvider#debugInfoEnabled} for more. 1987 */ 1988function reloadWithDebugInfo() { 1989 window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; 1990 window.location.reload(); 1991} 1992 1993/** 1994 * @name angular.getTestability 1995 * @module ng 1996 * @description 1997 * Get the testability service for the instance of AngularJS on the given 1998 * element. 1999 * @param {DOMElement} element DOM element which is the root of AngularJS application. 2000 */ 2001function getTestability(rootElement) { 2002 var injector = angular.element(rootElement).injector(); 2003 if (!injector) { 2004 throw ngMinErr('test', 2005 'no injector found for element argument to getTestability'); 2006 } 2007 return injector.get('$$testability'); 2008} 2009 2010var SNAKE_CASE_REGEXP = /[A-Z]/g; 2011function snake_case(name, separator) { 2012 separator = separator || '_'; 2013 return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { 2014 return (pos ? separator : '') + letter.toLowerCase(); 2015 }); 2016} 2017 2018var bindJQueryFired = false; 2019function bindJQuery() { 2020 var originalCleanData; 2021 2022 if (bindJQueryFired) { 2023 return; 2024 } 2025 2026 // bind to jQuery if present; 2027 var jqName = jq(); 2028 jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present) 2029 !jqName ? undefined : // use jqLite 2030 window[jqName]; // use jQuery specified by `ngJq` 2031 2032 // Use jQuery if it exists with proper functionality, otherwise default to us. 2033 // AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support. 2034 // AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older 2035 // versions. It will not work for sure with jQuery <1.7, though. 2036 if (jQuery && jQuery.fn.on) { 2037 jqLite = jQuery; 2038 extend(jQuery.fn, { 2039 scope: JQLitePrototype.scope, 2040 isolateScope: JQLitePrototype.isolateScope, 2041 controller: /** @type {?} */ (JQLitePrototype).controller, 2042 injector: JQLitePrototype.injector, 2043 inheritedData: JQLitePrototype.inheritedData 2044 }); 2045 } else { 2046 jqLite = JQLite; 2047 } 2048 2049 // All nodes removed from the DOM via various jqLite/jQuery APIs like .remove() 2050 // are passed through jqLite/jQuery.cleanData. Monkey-patch this method to fire 2051 // the $destroy event on all removed nodes. 2052 originalCleanData = jqLite.cleanData; 2053 jqLite.cleanData = function(elems) { 2054 var events; 2055 for (var i = 0, elem; (elem = elems[i]) != null; i++) { 2056 events = (jqLite._data(elem) || {}).events; 2057 if (events && events.$destroy) { 2058 jqLite(elem).triggerHandler('$destroy'); 2059 } 2060 } 2061 originalCleanData(elems); 2062 }; 2063 2064 angular.element = jqLite; 2065 2066 // Prevent double-proxying. 2067 bindJQueryFired
vendor: 20,525 bytes, lines 2067-2677
2067 = true; 2068} 2069 2070/** 2071 * throw error if the argument is falsy. 2072 */ 2073function assertArg(arg, name, reason) { 2074 if (!arg) { 2075 throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required')); 2076 } 2077 return arg; 2078} 2079 2080function assertArgFn(arg, name, acceptArrayAnnotation) { 2081 if (acceptArrayAnnotation && isArray(arg)) { 2082 arg = arg[arg.length - 1]; 2083 } 2084 2085 assertArg(isFunction(arg), name, 'not a function, got ' + 2086 (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); 2087 return arg; 2088} 2089 2090/** 2091 * throw error if the name given is hasOwnProperty 2092 * @param {String} name the name to test 2093 * @param {String} context the context in which the name is used, such as module or directive 2094 */ 2095function assertNotHasOwnProperty(name, context) { 2096 if (name === 'hasOwnProperty') { 2097 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); 2098 } 2099} 2100 2101/** 2102 * Return the value accessible from the object by path. Any undefined traversals are ignored 2103 * @param {Object} obj starting object 2104 * @param {String} path path to traverse 2105 * @param {boolean} [bindFnToScope=true] 2106 * @returns {Object} value as accessible by path 2107 */ 2108//TODO(misko): this function needs to be removed 2109function getter(obj, path, bindFnToScope) { 2110 if (!path) return obj; 2111 var keys = path.split('.'); 2112 var key; 2113 var lastInstance = obj; 2114 var len = keys.length; 2115 2116 for (var i = 0; i < len; i++) { 2117 key = keys[i]; 2118 if (obj) { 2119 obj = (lastInstance = obj)[key]; 2120 } 2121 } 2122 if (!bindFnToScope && isFunction(obj)) { 2123 return bind(lastInstance, obj); 2124 } 2125 return obj; 2126} 2127 2128/** 2129 * Return the DOM siblings between the first and last node in the given array. 2130 * @param {Array} array like object 2131 * @returns {Array} the inputted object or a jqLite collection containing the nodes 2132 */ 2133function getBlockNodes(nodes) { 2134 // TODO(perf): update `nodes` instead of creating a new object? 2135 var node = nodes[0]; 2136 var endNode = nodes[nodes.length - 1]; 2137 var blockNodes; 2138 2139 for (var i = 1; node !== endNode && (node = node.nextSibling); i++) { 2140 if (blockNodes || nodes[i] !== node) { 2141 if (!blockNodes) { 2142 blockNodes = jqLite(slice.call(nodes, 0, i)); 2143 } 2144 blockNodes.push(node); 2145 } 2146 } 2147 2148 return blockNodes || nodes; 2149} 2150 2151 2152/** 2153 * Creates a new object without a prototype. This object is useful for lookup without having to 2154 * guard against prototypically inherited properties via hasOwnProperty. 2155 * 2156 * Related micro-benchmarks: 2157 * - http://jsperf.com/object-create2 2158 * - http://jsperf.com/proto-map-lookup/2 2159 * - http://jsperf.com/for-in-vs-object-keys2 2160 * 2161 * @returns {Object} 2162 */ 2163function createMap() { 2164 return Object.create(null); 2165} 2166 2167function stringify(value) { 2168 if (value == null) { // null || undefined 2169 return ''; 2170 } 2171 switch (typeof value) { 2172 case 'string': 2173 break; 2174 case 'number': 2175 value = '' + value; 2176 break; 2177 default: 2178 if (hasCustomToString(value) && !isArray(value) && !isDate(value)) { 2179 value = value.toString(); 2180 } else { 2181 value = toJson(value); 2182 } 2183 } 2184 2185 return value; 2186} 2187 2188var NODE_TYPE_ELEMENT = 1; 2189var NODE_TYPE_ATTRIBUTE = 2; 2190var NODE_TYPE_TEXT = 3; 2191var NODE_TYPE_COMMENT = 8; 2192var NODE_TYPE_DOCUMENT = 9; 2193var NODE_TYPE_DOCUMENT_FRAGMENT = 11; 2194 2195/** 2196 * @ngdoc type 2197 * @name angular.Module 2198 * @module ng 2199 * @description 2200 * 2201 * Interface for configuring AngularJS {@link angular.module modules}. 2202 */ 2203 2204function setupModuleLoader(window) { 2205 2206 var $injectorMinErr = minErr('$injector'); 2207 var ngMinErr = minErr('ng'); 2208 2209 function ensure(obj, name, factory) { 2210 return obj[name] || (obj[name] = factory()); 2211 } 2212 2213 var angular = ensure(window, 'angular', Object); 2214 2215 // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap 2216 angular.$$minErr = angular.$$minErr || minErr; 2217 2218 return ensure(angular, 'module', function() { 2219 /** @type {Object.<string, angular.Module>} */ 2220 var modules = {}; 2221 2222 /** 2223 * @ngdoc function 2224 * @name angular.module 2225 * @module ng 2226 * @description 2227 * 2228 * The `angular.module` is a global place for creating, registering and retrieving AngularJS 2229 * modules. 2230 * All modules (AngularJS core or 3rd party) that should be available to an application must be 2231 * registered using this mechanism. 2232 * 2233 * Passing one argument retrieves an existing {@link angular.Module}, 2234 * whereas passing more than one argument creates a new {@link angular.Module} 2235 * 2236 * 2237 * # Module 2238 * 2239 * A module is a collection of services, directives, controllers, filters, and configuration information. 2240 * `angular.module` is used to configure the {@link auto.$injector $injector}. 2241 * 2242 * ```js 2243 * // Create a new module 2244 * var myModule = angular.module('myModule', []); 2245 * 2246 * // register a new service 2247 * myModule.value('appName', 'MyCoolApp'); 2248 * 2249 * // configure existing services inside initialization blocks. 2250 * myModule.config(['$locationProvider', function($locationProvider) { 2251 * // Configure existing providers 2252 * $locationProvider.hashPrefix('!'); 2253 * }]); 2254 * ``` 2255 * 2256 * Then you can create an injector and load your modules like this: 2257 * 2258 * ```js 2259 * var injector = angular.injector(['ng', 'myModule']) 2260 * ``` 2261 * 2262 * However it's more likely that you'll just use 2263 * {@link ng.directive:ngApp ngApp} or 2264 * {@link angular.bootstrap} to simplify this process for you. 2265 * 2266 * @param {!string} name The name of the module to create or retrieve. 2267 * @param {!Array.<string>=} requires If specified then new module is being created. If 2268 * unspecified then the module is being retrieved for further configuration. 2269 * @param {Function=} configFn Optional configuration function for the module. Same as 2270 * {@link angular.Module#config Module#config()}. 2271 * @returns {angular.Module} new module with the {@link angular.Module} api. 2272 */ 2273 return function module(name, requires, configFn) { 2274 2275 var info = {}; 2276 2277 var assertNotHasOwnProperty = function(name, context) { 2278 if (name === 'hasOwnProperty') { 2279 throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); 2280 } 2281 }; 2282 2283 assertNotHasOwnProperty(name, 'module'); 2284 if (requires && modules.hasOwnProperty(name)) { 2285 modules[name] = null; 2286 } 2287 return ensure(modules, name, function() { 2288 if (!requires) { 2289 throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' + 2290 'the module name or forgot to load it. If registering a module ensure that you ' + 2291 'specify the dependencies as the second argument.', name); 2292 } 2293 2294 /** @type {!Array.<Array.<*>>} */ 2295 var invokeQueue = []; 2296 2297 /** @type {!Array.<Function>} */ 2298 var configBlocks = []; 2299 2300 /** @type {!Array.<Function>} */ 2301 var runBlocks = []; 2302 2303 var config = invokeLater('$injector', 'invoke', 'push', configBlocks); 2304 2305 /** @type {angular.Module} */ 2306 var moduleInstance = { 2307 // Private state 2308 _invokeQueue: invokeQueue, 2309 _configBlocks: configBlocks, 2310 _runBlocks: runBlocks, 2311 2312 /** 2313 * @ngdoc method 2314 * @name angular.Module#info 2315 * @module ng 2316 * 2317 * @param {Object=} info Information about the module 2318 * @returns {Object|Module} The current info object for this module if called as a getter, 2319 * or `this` if called as a setter. 2320 * 2321 * @description 2322 * Read and write custom information about this module. 2323 * For example you could put the version of the module in here. 2324 * 2325 * ```js 2326 * angular.module('myModule', []).info({ version: '1.0.0' }); 2327 * ``` 2328 * 2329 * The version could then be read back out by accessing the module elsewhere: 2330 * 2331 * ``` 2332 * var version = angular.module('myModule').info().version; 2333 * ``` 2334 * 2335 * You can also retrieve this information during runtime via the 2336 * {@link $injector#modules `$injector.modules`} property: 2337 * 2338 * ```js 2339 * var version = $injector.modules['myModule'].info().version; 2340 * ``` 2341 */ 2342 info: function(value) { 2343 if (isDefined(value)) { 2344 if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value'); 2345 info = value; 2346 return this; 2347 } 2348 return info; 2349 }, 2350 2351 /** 2352 * @ngdoc property 2353 * @name angular.Module#requires 2354 * @module ng 2355 * 2356 * @description 2357 * Holds the list of modules which the injector will load before the current module is 2358 * loaded. 2359 */ 2360 requires: requires, 2361 2362 /** 2363 * @ngdoc property 2364 * @name angular.Module#name 2365 * @module ng 2366 * 2367 * @description 2368 * Name of the module. 2369 */ 2370 name: name, 2371 2372 2373 /** 2374 * @ngdoc method 2375 * @name angular.Module#provider 2376 * @module ng 2377 * @param {string} name service name 2378 * @param {Function} providerType Construction function for creating new instance of the 2379 * service. 2380 * @description 2381 * See {@link auto.$provide#provider $provide.provider()}. 2382 */ 2383 provider: invokeLaterAndSetModuleName('$provide', 'provider'), 2384 2385 /** 2386 * @ngdoc method 2387 * @name angular.Module#factory 2388 * @module ng 2389 * @param {string} name service name 2390 * @param {Function} providerFunction Function for creating new instance of the service. 2391 * @description 2392 * See {@link auto.$provide#factory $provide.factory()}. 2393 */ 2394 factory: invokeLaterAndSetModuleName('$provide', 'factory'), 2395 2396 /** 2397 * @ngdoc method 2398 * @name angular.Module#service 2399 * @module ng 2400 * @param {string} name service name 2401 * @param {Function} constructor A constructor function that will be instantiated. 2402 * @description 2403 * See {@link auto.$provide#service $provide.service()}. 2404 */ 2405 service: invokeLaterAndSetModuleName('$provide', 'service'), 2406 2407 /** 2408 * @ngdoc method 2409 * @name angular.Module#value 2410 * @module ng 2411 * @param {string} name service name 2412 * @param {*} object Service instance object. 2413 * @description 2414 * See {@link auto.$provide#value $provide.value()}. 2415 */ 2416 value: invokeLater('$provide', 'value'), 2417 2418 /** 2419 * @ngdoc method 2420 * @name angular.Module#constant 2421 * @module ng 2422 * @param {string} name constant name 2423 * @param {*} object Constant value. 2424 * @description 2425 * Because the constants are fixed, they get applied before other provide methods. 2426 * See {@link auto.$provide#constant $provide.constant()}. 2427 */ 2428 constant: invokeLater('$provide', 'constant', 'unshift'), 2429 2430 /** 2431 * @ngdoc method 2432 * @name angular.Module#decorator 2433 * @module ng 2434 * @param {string} name The name of the service to decorate. 2435 * @param {Function} decorFn This function will be invoked when the service needs to be 2436 * instantiated and should return the decorated service instance. 2437 * @description 2438 * See {@link auto.$provide#decorator $provide.decorator()}. 2439 */ 2440 decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks), 2441 2442 /** 2443 * @ngdoc method 2444 * @name angular.Module#animation 2445 * @module ng 2446 * @param {string} name animation name 2447 * @param {Function} animationFactory Factory function for creating new instance of an 2448 * animation. 2449 * @description 2450 * 2451 * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. 2452 * 2453 * 2454 * Defines an animation hook that can be later used with 2455 * {@link $animate $animate} service and directives that use this service. 2456 * 2457 * ```js 2458 * module.animation('.animation-name', function($inject1, $inject2) { 2459 * return { 2460 * eventName : function(element, done) { 2461 * //code to run the animation 2462 * //once complete, then run done() 2463 * return function cancellationFunction(element) { 2464 * //code to cancel the animation 2465 * } 2466 * } 2467 * } 2468 * }) 2469 * ``` 2470 * 2471 * See {@link ng.$animateProvider#register $animateProvider.register()} and 2472 * {@link ngAnimate ngAnimate module} for more information. 2473 */ 2474 animation: invokeLaterAndSetModuleName('$animateProvider', 'register'), 2475 2476 /** 2477 * @ngdoc method 2478 * @name angular.Module#filter 2479 * @module ng 2480 * @param {string} name Filter name - this must be a valid AngularJS expression identifier 2481 * @param {Function} filterFactory Factory function for creating new instance of filter. 2482 * @description 2483 * See {@link ng.$filterProvider#register $filterProvider.register()}. 2484 * 2485 * <div class="alert alert-warning"> 2486 * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. 2487 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace 2488 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores 2489 * (`myapp_subsection_filterx`). 2490 * </div> 2491 */ 2492 filter: invokeLaterAndSetModuleName('$filterProvider', 'register'), 2493 2494 /** 2495 * @ngdoc method 2496 * @name angular.Module#controller 2497 * @module ng 2498 * @param {string|Object} name Controller name, or an object map of controllers where the 2499 * keys are the names and the values are the constructors. 2500 * @param {Function} constructor Controller constructor function. 2501 * @description 2502 * See {@link ng.$controllerProvider#register $controllerProvider.register()}. 2503 */ 2504 controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'), 2505 2506 /** 2507 * @ngdoc method 2508 * @name angular.Module#directive 2509 * @module ng 2510 * @param {string|Object} name Directive name, or an object map of directives where the 2511 * keys are the names and the values are the factories. 2512 * @param {Function} directiveFactory Factory function for creating new instance of 2513 * directives. 2514 * @description 2515 * See {@link ng.$compileProvider#directive $compileProvider.directive()}. 2516 */ 2517 directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'), 2518 2519 /** 2520 * @ngdoc method 2521 * @name angular.Module#component 2522 * @module ng 2523 * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`), 2524 * or an object map of components where the keys are the names and the values are the component definition objects. 2525 * @param {Object} options Component definition object (a simplified 2526 * {@link ng.$compile#directive-definition-object directive definition object}) 2527 * 2528 * @description 2529 * See {@link ng.$compileProvider#component $compileProvider.component()}. 2530 */ 2531 component: invokeLaterAndSetModuleName('$compileProvider', 'component'), 2532 2533 /** 2534 * @ngdoc method 2535 * @name angular.Module#config 2536 * @module ng 2537 * @param {Function} configFn Execute this function on module load. Useful for service 2538 * configuration. 2539 * @description 2540 * Use this method to configure services by injecting their 2541 * {@link angular.Module#provider `providers`}, e.g. for adding routes to the 2542 * {@link ngRoute.$routeProvider $routeProvider}. 2543 * 2544 * Note that you can only inject {@link angular.Module#provider `providers`} and 2545 * {@link angular.Module#constant `constants`} into this function. 2546 * 2547 * For more about how to configure services, see 2548 * {@link providers#provider-recipe Provider Recipe}. 2549 */ 2550 config: config, 2551 2552 /** 2553 * @ngdoc method 2554 * @name angular.Module#run 2555 * @module ng 2556 * @param {Function} initializationFn Execute this function after injector creation. 2557 * Useful for application initialization. 2558 * @description 2559 * Use this method to register work which should be performed when the injector is done 2560 * loading all modules. 2561 */ 2562 run: function(block) { 2563 runBlocks.push(block); 2564 return this; 2565 } 2566 }; 2567 2568 if (configFn) { 2569 config(configFn); 2570 } 2571 2572 return moduleInstance; 2573 2574 /** 2575 * @param {string} provider 2576 * @param {string} method 2577 * @param {String=} insertMethod 2578 * @returns {angular.Module} 2579 */ 2580 function invokeLater(provider, method, insertMethod, queue) { 2581 if (!queue) queue = invokeQueue; 2582 return function() { 2583 queue[insertMethod || 'push']([provider, method, arguments]); 2584 return moduleInstance; 2585 }; 2586 } 2587 2588 /** 2589 * @param {string} provider 2590 * @param {string} method 2591 * @returns {angular.Module} 2592 */ 2593 function invokeLaterAndSetModuleName(provider, method, queue) { 2594 if (!queue) queue = invokeQueue; 2595 return function(recipeName, factoryFunction) { 2596 if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name; 2597 queue.push([provider, method, arguments]); 2598 return moduleInstance; 2599 }; 2600 } 2601 }); 2602 }; 2603 }); 2604 2605} 2606 2607/* global shallowCopy: true */ 2608 2609/** 2610 * Creates a shallow copy of an object, an array or a primitive. 2611 * 2612 * Assumes that there are no proto properties for objects. 2613 */ 2614function shallowCopy(src, dst) { 2615 if (isArray(src)) { 2616 dst = dst || []; 2617 2618 for (var i = 0, ii = src.length; i < ii; i++) { 2619 dst[i] = src[i]; 2620 } 2621 } else if (isObject(src)) { 2622 dst = dst || {}; 2623 2624 for (var key in src) { 2625 if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { 2626 dst[key] = src[key]; 2627 } 2628 } 2629 } 2630 2631 return dst || src; 2632} 2633 2634/* exported toDebugString */ 2635 2636function serializeObject(obj, maxDepth) { 2637 var seen = []; 2638 2639 // There is no direct way to stringify object until reaching a specific depth 2640 // and a very deep object can cause a performance issue, so we copy the object 2641 // based on this specific depth and then stringify it. 2642 if (isValidObjectMaxDepth(maxDepth)) { 2643 // This file is also included in `angular-loader`, so `copy()` might not always be available in 2644 // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed. 2645 obj = angular.copy(obj, null, maxDepth); 2646 } 2647 return JSON.stringify(obj, function(key, val) { 2648 val = toJsonReplacer(key, val); 2649 if (isObject(val)) { 2650 2651 if (seen.indexOf(val) >= 0) return '...'; 2652 2653 seen.push(val); 2654 } 2655 return val; 2656 }); 2657} 2658 2659function toDebugString(obj, maxDepth) { 2660 if (typeof obj === 'function') { 2661 return obj.toString().replace(/ \{[\s\S]*$/, ''); 2662 } else if (isUndefined(obj)) { 2663 return 'undefined'; 2664 } else if (typeof obj !== 'string') { 2665 return serializeObject(obj, maxDepth); 2666 } 2667 return obj; 2668} 2669 2670/* global angularModule: true, 2671 version: true, 2672 2673 $CompileProvider, 2674 2675 htmlAnchorDirective, 2676 inputDirective, 2677
2677inputDirective, 2678 formDirective, 2679 scriptDirective, 2680 selectDirective, 2681 optionDirective, 2682 ngBindDirective, 2683 ngBindHtmlDirective, 2684 ngBindTemplateDirective, 2685 ngClassDirective, 2686 ngClassEvenDirective, 2687 ngClassOddDirective, 2688 ngCloakDirective, 2689 ngControllerDirective, 2690 ngFormDirective, 2691 ngHideDirective, 2692 ngIfDirective, 2693 ngIncludeDirective, 2694 ngIncludeFillContentDirective, 2695 ngInitDirective, 2696 ngNonBindableDirective, 2697 ngPluralizeDirective, 2698 ngRefDirective, 2699 ngRepeatDirective, 2700 ngShowDirective, 2701 ngStyleDirective, 2702 ngSwitchDirective, 2703 ngSwitchWhenDirective, 2704 ngSwitchDefaultDirective, 2705 ngOptionsDirective, 2706 ngTranscludeDirective, 2707 ngModelDirective, 2708 ngListDirective, 2709 ngChangeDirective, 2710 patternDirective, 2711 patternDirective, 2712 requiredDirective, 2713 requiredDirective, 2714 minlengthDirective, 2715 minlengthDirective, 2716 maxlengthDirective, 2717 maxlengthDirective, 2718 ngValueDirective, 2719 ngModelOptionsDirective, 2720 ngAttributeAliasDirectives, 2721 ngEventDirectives, 2722 2723 $AnchorScrollProvider, 2724 $AnimateProvider, 2725 $CoreAnimateCssProvider,
vendor: 5,332 bytes, lines 2726-2898
2726 $$CoreAnimateJsProvider, 2727 $$CoreAnimateQueueProvider, 2728 $$AnimateRunnerFactoryProvider, 2729 $$AnimateAsyncRunFactoryProvider, 2730 $BrowserProvider, 2731 $CacheFactoryProvider, 2732 $ControllerProvider, 2733 $DateProvider, 2734 $DocumentProvider, 2735 $$IsDocumentHiddenProvider, 2736 $ExceptionHandlerProvider, 2737 $FilterProvider, 2738 $$ForceReflowProvider, 2739 $InterpolateProvider, 2740 $$IntervalFactoryProvider, 2741 $IntervalProvider, 2742 $HttpProvider, 2743 $HttpParamSerializerProvider, 2744 $HttpParamSerializerJQLikeProvider, 2745 $HttpBackendProvider, 2746 $xhrFactoryProvider, 2747 $jsonpCallbacksProvider, 2748 $LocationProvider, 2749 $LogProvider, 2750 $$MapProvider, 2751 $ParseProvider, 2752 $RootScopeProvider, 2753 $QProvider, 2754 $$QProvider, 2755 $$SanitizeUriProvider, 2756 $SceProvider, 2757 $SceDelegateProvider, 2758 $SnifferProvider, 2759 $$TaskTrackerFactoryProvider, 2760 $TemplateCacheProvider, 2761 $TemplateRequestProvider, 2762 $$TestabilityProvider, 2763 $TimeoutProvider, 2764 $$RAFProvider, 2765 $WindowProvider, 2766 $$jqLiteProvider, 2767 $$CookieReaderProvider 2768*/ 2769 2770 2771/** 2772 * @ngdoc object 2773 * @name angular.version 2774 * @module ng 2775 * @description 2776 * An object that contains information about the current AngularJS version. 2777 * 2778 * This object has the following properties: 2779 * 2780 * - `full` – `{string}` – Full version string, such as "0.9.18". 2781 * - `major` – `{number}` – Major version number, such as "0". 2782 * - `minor` – `{number}` – Minor version number, such as "9". 2783 * - `dot` – `{number}` – Dot version number, such as "18". 2784 * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". 2785 */ 2786var version = { 2787 // These placeholder strings will be replaced by grunt's `build` task. 2788 // They need to be double- or single-quoted. 2789 full: '1.7.3', 2790 major: 1, 2791 minor: 7, 2792 dot: 3, 2793 codeName: 'eventful-proposal' 2794}; 2795 2796 2797function publishExternalAPI(angular) { 2798 extend(angular, { 2799 'errorHandlingConfig': errorHandlingConfig, 2800 'bootstrap': bootstrap, 2801 'copy': copy, 2802 'extend': extend, 2803 'merge': merge, 2804 'equals': equals, 2805 'element': jqLite, 2806 'forEach': forEach, 2807 'injector': createInjector, 2808 'noop': noop, 2809 'bind': bind, 2810 'toJson': toJson, 2811 'fromJson': fromJson, 2812 'identity': identity, 2813 'isUndefined': isUndefined, 2814 'isDefined': isDefined, 2815 'isString': isString, 2816 'isFunction': isFunction, 2817 'isObject': isObject, 2818 'isNumber': isNumber, 2819 'isElement': isElement, 2820 'isArray': isArray, 2821 'version': version, 2822 'isDate': isDate, 2823 'callbacks': {$$counter: 0}, 2824 'getTestability': getTestability, 2825 'reloadWithDebugInfo': reloadWithDebugInfo, 2826 '$$minErr': minErr, 2827 '$$csp': csp, 2828 '$$encodeUriSegment': encodeUriSegment, 2829 '$$encodeUriQuery': encodeUriQuery, 2830 '$$lowercase': lowercase, 2831 '$$stringify': stringify, 2832 '$$uppercase': uppercase 2833 }); 2834 2835 angularModule = setupModuleLoader(window); 2836 2837 angularModule('ng', ['ngLocale'], ['$provide', 2838 function ngModule($provide) { 2839 // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it. 2840 $provide.provider({ 2841 $$sanitizeUri: $$SanitizeUriProvider 2842 }); 2843 $provide.provider('$compile', $CompileProvider). 2844 directive({ 2845 a: htmlAnchorDirective, 2846 input: inputDirective, 2847 textarea: inputDirective, 2848 form: formDirective, 2849 script: scriptDirective, 2850 select: selectDirective, 2851 option: optionDirective, 2852 ngBind: ngBindDirective, 2853 ngBindHtml: ngBindHtmlDirective, 2854 ngBindTemplate: ngBindTemplateDirective, 2855 ngClass: ngClassDirective, 2856 ngClassEven: ngClassEvenDirective, 2857 ngClassOdd: ngClassOddDirective, 2858 ngCloak: ngCloakDirective, 2859 ngController: ngControllerDirective, 2860 ngForm: ngFormDirective, 2861 ngHide: ngHideDirective, 2862 ngIf: ngIfDirective, 2863 ngInclude: ngIncludeDirective, 2864 ngInit: ngInitDirective, 2865 ngNonBindable: ngNonBindableDirective, 2866 ngPluralize: ngPluralizeDirective, 2867 ngRef: ngRefDirective, 2868 ngRepeat: ngRepeatDirective, 2869 ngShow: ngShowDirective, 2870 ngStyle: ngStyleDirective, 2871 ngSwitch: ngSwitchDirective, 2872 ngSwitchWhen: ngSwitchWhenDirective, 2873 ngSwitchDefault: ngSwitchDefaultDirective, 2874 ngOptions: ngOptionsDirective, 2875 ngTransclude: ngTranscludeDirective, 2876 ngModel: ngModelDirective, 2877 ngList: ngListDirective, 2878 ngChange: ngChangeDirective, 2879 pattern: patternDirective, 2880 ngPattern: patternDirective, 2881 required: requiredDirective, 2882 ngRequired: requiredDirective, 2883 minlength: minlengthDirective, 2884 ngMinlength: minlengthDirective, 2885 maxlength: maxlengthDirective, 2886 ngMaxlength: maxlengthDirective, 2887 ngValue: ngValueDirective, 2888 ngModelOptions: ngModelOptionsDirective 2889 }). 2890 directive({ 2891 ngInclude: ngIncludeFillContentDirective 2892 }). 2893 directive(ngAttributeAliasDirectives). 2894 directive(ngEventDirectives); 2895 $provide.provider({ 2896 $anchorScroll: $AnchorScrollProvider, 2897 $animate: $AnimateProvider, 2898 $animateCss: $CoreAnimateCssProvider,
2899 $$animateJs: $$CoreAnimateJsProvider, 2900 $$animateQueue: $$CoreAnimateQueueProvider, 2901 $$AnimateRunner: $$AnimateRunnerFactoryProvider, 2902 $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider, 2903 $browser: $BrowserProvider, 2904 $cacheFactory: $CacheFactoryProvider, 2905 $controller: $ControllerProvider, 2906 $document: $DocumentProvider, 2907 $$isDocumentHidden: $$IsDocumentHiddenProvider, 2908 $exceptionHandler: $ExceptionHandlerProvider, 2909 $filter: $FilterProvider, 2910 $$forceReflow: $$ForceReflowProvider, 2911 $interpolate: $InterpolateProvider, 2912 $interval: $IntervalProvider, 2913 $$intervalFactory: $$IntervalFactoryProvider, 2914 $http: $HttpProvider, 2915 $httpParamSerializer: $HttpParamSerializerProvider, 2916 $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider, 2917 $httpBackend: $HttpBackendProvider, 2918 $xhrFactory: $xhrFactoryProvider, 2919 $jsonpCallbacks: $jsonpCallbacksProvider, 2920 $location: $LocationProvider, 2921 $log: $LogProvider, 2922 $parse: $ParseProvider, 2923 $rootScope: $RootScopeProvider, 2924 $q: $QProvider, 2925 $$q: $$QProvider, 2926 $sce: $SceProvider, 2927 $sceDelegate: $SceDelegateProvider, 2928 $sniffer: $SnifferProvider, 2929 $$taskTrackerFactory: $$TaskTrackerFactoryProvider, 2930 $templateCache: $TemplateCacheProvider, 2931 $templateRequest: $TemplateRequestProvider, 2932 $$testability: $$TestabilityProvider, 2933 $timeout: $TimeoutProvider, 2934 $window: $WindowProvider, 2935 $$rAF: $$RAFProvider, 2936 $$jqLite: $$jqLiteProvider, 2937 $$Map: $$MapProvider, 2938 $$cookieReader: $$CookieReaderProvider 2939 }); 2940 } 2941 ]) 2942 .info({ angularVersion: '1.7.3' }); 2943} 2944 2945/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 2946 * Any commits to this file should be reviewed with security in mind. * 2947 * Changes to this file can potentially create security vulnerabilities. * 2948 * An approval from 2 Core members with history of modifying * 2949 * this file is required. * 2950 * * 2951 * Does the change somehow allow for arbitrary javascript to be executed? * 2952 * Or allows for someone to change the prototype of built-in objects? * 2953 * Or gives undesired access to variables likes document or window? * 2954 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 2955 2956/* global 2957 JQLitePrototype: true, 2958 BOOLEAN_ATTR: true, 2959 ALIASED_ATTR: true 2960*/ 2961 2962////////////////////////////////// 2963//JQLite 2964////////////////////////////////// 2965 2966/** 2967 * @ngdoc function 2968 * @name angular.element 2969 * @module ng 2970 * @kind function 2971 * 2972 * @description 2973 * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. 2974 * 2975 * If jQuery is available, `angular.element` is an alias for the 2976 * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` 2977 * delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or **jqLite**. 2978 * 2979 * jqLite is a tiny, API-compatible subset of jQuery that allows 2980 * AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most 2981 * commonly needed functionality with the goal of having a very small footprint. 2982 * 2983 * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the 2984 * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a 2985 * specific version of jQuery if multiple versions exist on the page. 2986 * 2987 * <div class="alert alert-info">**Note:** All element references in AngularJS are always wrapped with jQuery or 2988 * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div> 2989 * 2990 * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements 2991 * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)` 2992 * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div> 2993 * 2994 * ## AngularJS's jqLite 2995 * jqLite provides only the following jQuery methods: 2996 * 2997 * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument 2998 * - [`after()`](http://api.jquery.com/after/) 2999 * - [`append()`](http://api.jquery.com/append/) - Contrary to jQuery, this doesn't clone elements
3000 * so will not work correctly when invoked on a jqLite object containing more than one DOM node 3001 * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters 3002 * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData 3003 * - [`children()`](http://api.jquery.com/children/) - Does not support selectors 3004 * - [`clone()`](http://api.jquery.com/clone/) 3005 * - [`contents()`](http://api.jquery.com/contents/) 3006 * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. 3007 * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing. 3008 * - [`data()`](http://api.jquery.com/data/) 3009 * - [`detach()`](http://api.jquery.com/detach/) 3010 * - [`empty()`](http://api.jquery.com/empty/) 3011 * - [`eq()`](http://api.jquery.com/eq/) 3012 * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name 3013 * - [`hasClass()`](http://api.jquery.com/hasClass/) 3014 * - [`html()`](http://api.jquery.com/html/) 3015 * - [`next()`](http://api.jquery.com/next/) - Does not support selectors 3016 * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData 3017 * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter 3018 * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors 3019 * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors 3020 * - [`prepend()`](http://api.jquery.com/prepend/) 3021 * - [`prop()`](http://api.jquery.com/prop/) 3022 * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`) 3023 * - [`remove()`](http://api.jquery.com/remove/) 3024 * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes 3025 * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument 3026 * - [`removeData()`](http://api.jquery.com/removeData/) 3027 * - [`replaceWith()`](http://api.jquery.com/replaceWith/) 3028 * - [`text()`](http://api.jquery.com/text/) 3029 * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument 3030 * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers 3031 * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter 3032 * - [`val()`](http://api.jquery.com/val/) 3033 * - [`wrap()`](http://api.jquery.com/wrap/) 3034 * 3035 * ## jQuery/jqLite Extras 3036 * AngularJS also provides the following additional methods and events to both jQuery and jqLite: 3037 * 3038 * ### Events 3039 * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event 3040 * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM 3041 * element before it is removed. 3042 * 3043 * ### Methods 3044 * - `controller(name)` - retrieves the controller of the current element or its parent. By default 3045 * retrieves controller associated with the `ngController` directive. If `name` is provided as 3046 * camelCase directive name, then the controller for this directive will be retrieved (e.g. 3047 * `'ngModel'`). 3048 * - `injector()` - retrieves the injector of the current element or its parent. 3049 * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current 3050 * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to 3051 * be enabled. 3052 * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the 3053 * current element. This getter should be used only on elements that contain a directive which starts a new isolate 3054 * scope. Calling `scope()` on this element always returns the original non-isolate scope. 3055 * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled. 3056 * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top 3057 * parent element is reached. 3058 * 3059 * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See 3060 * https://github.com/angular/angular.js/issues/14251 for more information. 3061 * 3062 * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. 3063 * @returns {Object} jQuery object. 3064 */ 3065 3066JQLite.expando = 'ng339'; 3067 3068var jqCache = JQLite.cache = {}, 3069 jqId = 1; 3070 3071/* 3072 * !!! This is an undocumented "private" function !!! 3073 */ 3074JQLite._data = function(node) { 3075 //jQuery always returns an object on cache miss 3076 return this.cache[node[this.expando]] || {}; 3077}; 3078 3079function jqNextId() { return ++jqId; } 3080 3081 3082var DASH_LOWERCASE_REGEXP = /-([a-z])/g; 3083var MS_HACK_REGEXP = /^-ms-/; 3084var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' }; 3085var jqLiteMinErr = minErr('jqLite'); 3086 3087/** 3088 * Converts kebab-case to camelCase. 3089 * There is also a special case for the ms prefix starting with a lowercase letter. 3090 * @param name Name to normalize 3091 */ 3092function cssKebabToCamel(name) { 3093 return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-')); 3094} 3095 3096function fnCamelCaseReplace(all, letter) { 3097 return letter.toUpperCase(); 3098} 3099 3100/** 3101 * Converts kebab-case to camelCase. 3102 * @param name Name to normalize 3103 */ 3104function kebabToCamel(name) { 3105 return name 3106 .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace); 3107} 3108 3109var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
3110var HTML_REGEXP = /<|&#?\w+;/; 3111var TAG_NAME_REGEXP = /<([\w:-]+)/; 3112var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi; 3113 3114var wrapMap = { 3115 'option': [1, '<select multiple="multiple">', '</select>'], 3116 3117 'thead': [1, '<table>', '</table>'], 3118 'col': [2, '<table><colgroup>', '</colgroup></table>'], 3119 'tr': [2, '<table><tbody>', '</tbody></table>'], 3120 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'], 3121 '_default': [0, '', ''] 3122}; 3123 3124wrapMap.optgroup = wrapMap.option; 3125wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; 3126wrapMap.th = wrapMap.td; 3127 3128 3129function jqLiteIsTextNode(html) { 3130 return !HTML_REGEXP.test(html); 3131} 3132 3133function jqLiteAcceptsData(node) { 3134 // The window object can accept data but has no nodeType 3135 // Otherwise we are only interested in elements (1) and documents (9) 3136 var nodeType = node.nodeType; 3137 return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT; 3138} 3139 3140function jqLiteHasData(node) { 3141 for (var key in jqCache[node.ng339]) { 3142 return true; 3143 } 3144 return false; 3145} 3146 3147function jqLiteBuildFragment(html, context) { 3148 var tmp, tag, wrap, 3149 fragment = context.createDocumentFragment(), 3150 nodes = [], i; 3151 3152 if (jqLiteIsTextNode(html)) { 3153 // Convert non-html into a text node 3154 nodes.push(context.createTextNode(html)); 3155 } else { 3156 // Convert html into DOM nodes 3157 tmp = fragment.appendChild(context.createElement('div')); 3158 tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase(); 3159 wrap = wrapMap[tag] || wrapMap._default; 3160 tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2]; 3161 3162 // Descend through wrappers to the right content 3163 i = wrap[0]; 3164 while (i--) { 3165 tmp = tmp.lastChild
vendor: 168,082 bytes, lines 3165-7763
3165; 3166 } 3167 3168 nodes = concat(nodes, tmp.childNodes); 3169 3170 tmp = fragment.firstChild; 3171 tmp.textContent = ''; 3172 } 3173 3174 // Remove wrapper from fragment 3175 fragment.textContent = ''; 3176 fragment.innerHTML = ''; // Clear inner HTML 3177 forEach(nodes, function(node) { 3178 fragment.appendChild(node); 3179 }); 3180 3181 return fragment; 3182} 3183 3184function jqLiteParseHTML(html, context) { 3185 context = context || window.document; 3186 var parsed; 3187 3188 if ((parsed = SINGLE_TAG_REGEXP.exec(html))) { 3189 return [context.createElement(parsed[1])]; 3190 } 3191 3192 if ((parsed = jqLiteBuildFragment(html, context))) { 3193 return parsed.childNodes; 3194 } 3195 3196 return []; 3197} 3198 3199function jqLiteWrapNode(node, wrapper) { 3200 var parent = node.parentNode; 3201 3202 if (parent) { 3203 parent.replaceChild(wrapper, node); 3204 } 3205 3206 wrapper.appendChild(node); 3207} 3208 3209 3210// IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259. 3211var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) { 3212 // eslint-disable-next-line no-bitwise 3213 return !!(this.compareDocumentPosition(arg) & 16); 3214}; 3215 3216///////////////////////////////////////////// 3217function JQLite(element) { 3218 if (element instanceof JQLite) { 3219 return element; 3220 } 3221 3222 var argIsString; 3223 3224 if (isString(element)) { 3225 element = trim(element); 3226 argIsString = true; 3227 } 3228 if (!(this instanceof JQLite)) { 3229 if (argIsString && element.charAt(0) !== '<') { 3230 throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element'); 3231 } 3232 return new JQLite(element); 3233 } 3234 3235 if (argIsString) { 3236 jqLiteAddNodes(this, jqLiteParseHTML(element)); 3237 } else if (isFunction(element)) { 3238 jqLiteReady(element); 3239 } else { 3240 jqLiteAddNodes(this, element); 3241 } 3242} 3243 3244function jqLiteClone(element) { 3245 return element.cloneNode(true); 3246} 3247 3248function jqLiteDealoc(element, onlyDescendants) { 3249 if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]); 3250 3251 if (element.querySelectorAll) { 3252 jqLite.cleanData(element.querySelectorAll('*')); 3253 } 3254} 3255 3256function isEmptyObject(obj) { 3257 var name; 3258 3259 for (name in obj) { 3260 return false; 3261 } 3262 return true; 3263} 3264 3265function removeIfEmptyData(element) { 3266 var expandoId = element.ng339; 3267 var expandoStore = expandoId && jqCache[expandoId]; 3268 3269 var events = expandoStore && expandoStore.events; 3270 var data = expandoStore && expandoStore.data; 3271 3272 if ((!data || isEmptyObject(data)) && (!events || isEmptyObject(events))) { 3273 delete jqCache[expandoId]; 3274 element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it 3275 } 3276} 3277 3278function jqLiteOff(element, type, fn, unsupported) { 3279 if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument'); 3280 3281 var expandoStore = jqLiteExpandoStore(element); 3282 var events = expandoStore && expandoStore.events; 3283 var handle = expandoStore && expandoStore.handle; 3284 3285 if (!handle) return; //no listeners registered 3286 3287 if (!type) { 3288 for (type in events) { 3289 if (type !== '$destroy') { 3290 element.removeEventListener(type, handle); 3291 } 3292 delete events[type]; 3293 } 3294 } else { 3295 3296 var removeHandler = function(type) { 3297 var listenerFns = events[type]; 3298 if (isDefined(fn)) { 3299 arrayRemove(listenerFns || [], fn); 3300 } 3301 if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) { 3302 element.removeEventListener(type, handle); 3303 delete events[type]; 3304 } 3305 }; 3306 3307 forEach(type.split(' '), function(type) { 3308 removeHandler(type); 3309 if (MOUSE_EVENT_MAP[type]) { 3310 removeHandler(MOUSE_EVENT_MAP[type]); 3311 } 3312 }); 3313 } 3314 3315 removeIfEmptyData(element); 3316} 3317 3318function jqLiteRemoveData(element, name) { 3319 var expandoId = element.ng339; 3320 var expandoStore = expandoId && jqCache[expandoId]; 3321 3322 if (expandoStore) { 3323 if (name) { 3324 delete expandoStore.data[name]; 3325 } else { 3326 expandoStore.data = {}; 3327 } 3328 3329 removeIfEmptyData(element); 3330 } 3331} 3332 3333 3334function jqLiteExpandoStore(element, createIfNecessary) { 3335 var expandoId = element.ng339, 3336 expandoStore = expandoId && jqCache[expandoId]; 3337 3338 if (createIfNecessary && !expandoStore) { 3339 element.ng339 = expandoId = jqNextId(); 3340 expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined}; 3341 } 3342 3343 return expandoStore; 3344} 3345 3346 3347function jqLiteData(element, key, value) { 3348 if (jqLiteAcceptsData(element)) { 3349 var prop; 3350 3351 var isSimpleSetter = isDefined(value); 3352 var isSimpleGetter = !isSimpleSetter && key && !isObject(key); 3353 var massGetter = !key; 3354 var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter); 3355 var data = expandoStore && expandoStore.data; 3356 3357 if (isSimpleSetter) { // data('key', value) 3358 data[kebabToCamel(key)] = value; 3359 } else { 3360 if (massGetter) { // data() 3361 return data; 3362 } else { 3363 if (isSimpleGetter) { // data('key') 3364 // don't force creation of expandoStore if it doesn't exist yet 3365 return data && data[kebabToCamel(key)]; 3366 } else { // mass-setter: data({key1: val1, key2: val2}) 3367 for (prop in key) { 3368 data[kebabToCamel(prop)] = key[prop]; 3369 } 3370 } 3371 } 3372 } 3373 } 3374} 3375 3376function jqLiteHasClass(element, selector) { 3377 if (!element.getAttribute) return false; 3378 return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' '). 3379 indexOf(' ' + selector + ' ') > -1); 3380} 3381 3382function jqLiteRemoveClass(element, cssClasses) { 3383 if (cssClasses && element.setAttribute) { 3384 var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') 3385 .replace(/[\n\t]/g, ' '); 3386 var newClasses = existingClasses; 3387 3388 forEach(cssClasses.split(' '), function(cssClass) { 3389 cssClass = trim(cssClass); 3390 newClasses = newClasses.replace(' ' + cssClass + ' ', ' '); 3391 }); 3392 3393 if (newClasses !== existingClasses) { 3394 element.setAttribute('class', trim(newClasses)); 3395 } 3396 } 3397} 3398 3399function jqLiteAddClass(element, cssClasses) { 3400 if (cssClasses && element.setAttribute) { 3401 var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') 3402 .replace(/[\n\t]/g, ' '); 3403 var newClasses = existingClasses; 3404 3405 forEach(cssClasses.split(' '), function(cssClass) { 3406 cssClass = trim(cssClass); 3407 if (newClasses.indexOf(' ' + cssClass + ' ') === -1) { 3408 newClasses += cssClass + ' '; 3409 } 3410 }); 3411 3412 if (newClasses !== existingClasses) { 3413 element.setAttribute('class', trim(newClasses)); 3414 } 3415 } 3416} 3417 3418 3419function jqLiteAddNodes(root, elements) { 3420 // THIS CODE IS VERY HOT. Don't make changes without benchmarking. 3421 3422 if (elements) { 3423 3424 // if a Node (the most common case) 3425 if (elements.nodeType) { 3426 root[root.length++] = elements; 3427 } else { 3428 var length = elements.length; 3429 3430 // if an Array or NodeList and not a Window 3431 if (typeof length === 'number' && elements.window !== elements) { 3432 if (length) { 3433 for (var i = 0; i < length; i++) { 3434 root[root.length++] = elements[i]; 3435 } 3436 } 3437 } else { 3438 root[root.length++] = elements; 3439 } 3440 } 3441 } 3442} 3443 3444 3445function jqLiteController(element, name) { 3446 return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller'); 3447} 3448 3449function jqLiteInheritedData(element, name, value) { 3450 // if element is the document object work with the html element instead 3451 // this makes $(document).scope() possible 3452 if (element.nodeType === NODE_TYPE_DOCUMENT) { 3453 element = element.documentElement; 3454 } 3455 var names = isArray(name) ? name : [name]; 3456 3457 while (element) { 3458 for (var i = 0, ii = names.length; i < ii; i++) { 3459 if (isDefined(value = jqLite.data(element, names[i]))) return value; 3460 } 3461 3462 // If dealing with a document fragment node with a host element, and no parent, use the host 3463 // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM 3464 // to lookup parent controllers. 3465 element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host); 3466 } 3467} 3468 3469function jqLiteEmpty(element) { 3470 jqLiteDealoc(element, true); 3471 while (element.firstChild) { 3472 element.removeChild(element.firstChild); 3473 } 3474} 3475 3476function jqLiteRemove(element, keepData) { 3477 if (!keepData) jqLiteDealoc(element); 3478 var parent = element.parentNode; 3479 if (parent) parent.removeChild(element); 3480} 3481 3482 3483function jqLiteDocumentLoaded(action, win) { 3484 win = win || window; 3485 if (win.document.readyState === 'complete') { 3486 // Force the action to be run async for consistent behavior 3487 // from the action's point of view 3488 // i.e. it will definitely not be in a $apply 3489 win.setTimeout(action); 3490 } else { 3491 // No need to unbind this handler as load is only ever called once 3492 jqLite(win).on('load', action); 3493 } 3494} 3495 3496function jqLiteReady(fn) { 3497 function trigger() { 3498 window.document.removeEventListener('DOMContentLoaded', trigger); 3499 window.removeEventListener('load', trigger); 3500 fn(); 3501 } 3502 3503 // check if document is already loaded 3504 if (window.document.readyState === 'complete') { 3505 window.setTimeout(fn); 3506 } else { 3507 // We can not use jqLite since we are not done loading and jQuery could be loaded later. 3508 3509 // Works for modern browsers and IE9 3510 window.document.addEventListener('DOMContentLoaded', trigger); 3511 3512 // Fallback to window.onload for others 3513 window.addEventListener('load', trigger); 3514 } 3515} 3516 3517////////////////////////////////////////// 3518// Functions which are declared directly. 3519////////////////////////////////////////// 3520var JQLitePrototype = JQLite.prototype = { 3521 ready: jqLiteReady, 3522 toString: function() { 3523 var value = []; 3524 forEach(this, function(e) { value.push('' + e);}); 3525 return '[' + value.join(', ') + ']'; 3526 }, 3527 3528 eq: function(index) { 3529 return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); 3530 }, 3531 3532 length: 0, 3533 push: push, 3534 sort: [].sort, 3535 splice: [].splice 3536}; 3537 3538////////////////////////////////////////// 3539// Functions iterating getter/setters. 3540// these functions return self on setter and 3541// value on get. 3542////////////////////////////////////////// 3543var BOOLEAN_ATTR = {}; 3544forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { 3545 BOOLEAN_ATTR[lowercase(value)] = value; 3546}); 3547var BOOLEAN_ELEMENTS = {}; 3548forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { 3549 BOOLEAN_ELEMENTS[value] = true; 3550}); 3551var ALIASED_ATTR = { 3552 'ngMinlength': 'minlength', 3553 'ngMaxlength': 'maxlength', 3554 'ngMin': 'min', 3555 'ngMax': 'max', 3556 'ngPattern': 'pattern', 3557 'ngStep': 'step' 3558}; 3559 3560function getBooleanAttrName(element, name) { 3561 // check dom last since we will most likely fail on name 3562 var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; 3563 3564 // booleanAttr is here twice to minimize DOM access 3565 return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr; 3566} 3567 3568function getAliasedAttrName(name) { 3569 return ALIASED_ATTR[name]; 3570} 3571 3572forEach({ 3573 data: jqLiteData, 3574 removeData: jqLiteRemoveData, 3575 hasData: jqLiteHasData, 3576 cleanData: function jqLiteCleanData(nodes) { 3577 for (var i = 0, ii = nodes.length; i < ii; i++) { 3578 jqLiteRemoveData(nodes[i]); 3579 jqLiteOff(nodes[i]); 3580 } 3581 } 3582}, function(fn, name) { 3583 JQLite[name] = fn; 3584}); 3585 3586forEach({ 3587 data: jqLiteData, 3588 inheritedData: jqLiteInheritedData, 3589 3590 scope: function(element) { 3591 // Can't use jqLiteData here directly so we stay compatible with jQuery! 3592 return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); 3593 }, 3594 3595 isolateScope: function(element) { 3596 // Can't use jqLiteData here directly so we stay compatible with jQuery! 3597 return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); 3598 }, 3599 3600 controller: jqLiteController, 3601 3602 injector: function(element) { 3603 return jqLiteInheritedData(element, '$injector'); 3604 }, 3605 3606 removeAttr: function(element, name) { 3607 element.removeAttribute(name); 3608 }, 3609 3610 hasClass: jqLiteHasClass, 3611 3612 css: function(element, name, value) { 3613 name = cssKebabToCamel(name); 3614 3615 if (isDefined(value)) { 3616 element.style[name] = value; 3617 } else { 3618 return element.style[name]; 3619 } 3620 }, 3621 3622 attr: function(element, name, value) { 3623 var ret; 3624 var nodeType = element.nodeType; 3625 if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT || 3626 !element.getAttribute) { 3627 return; 3628 } 3629 3630 var lowercasedName = lowercase(name); 3631 var isBooleanAttr = BOOLEAN_ATTR[lowercasedName]; 3632 3633 if (isDefined(value)) { 3634 // setter 3635 3636 if (value === null || (value === false && isBooleanAttr)) { 3637 element.removeAttribute(name); 3638 } else { 3639 element.setAttribute(name, isBooleanAttr ? lowercasedName : value); 3640 } 3641 } else { 3642 // getter 3643 3644 ret = element.getAttribute(name); 3645 3646 if (isBooleanAttr && ret !== null) { 3647 ret = lowercasedName; 3648 } 3649 // Normalize non-existing attributes to undefined (as jQuery). 3650 return ret === null ? undefined : ret; 3651 } 3652 }, 3653 3654 prop: function(element, name, value) { 3655 if (isDefined(value)) { 3656 element[name] = value; 3657 } else { 3658 return element[name]; 3659 } 3660 }, 3661 3662 text: (function() { 3663 getText.$dv = ''; 3664 return getText; 3665 3666 function getText(element, value) { 3667 if (isUndefined(value)) { 3668 var nodeType = element.nodeType; 3669 return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : ''; 3670 } 3671 element.textContent = value; 3672 } 3673 })(), 3674 3675 val: function(element, value) { 3676 if (isUndefined(value)) { 3677 if (element.multiple && nodeName_(element) === 'select') { 3678 var result = []; 3679 forEach(element.options, function(option) { 3680 if (option.selected) { 3681 result.push(option.value || option.text); 3682 } 3683 }); 3684 return result; 3685 } 3686 return element.value; 3687 } 3688 element.value = value; 3689 }, 3690 3691 html: function(element, value) { 3692 if (isUndefined(value)) { 3693 return element.innerHTML; 3694 } 3695 jqLiteDealoc(element, true); 3696 element.innerHTML = value; 3697 }, 3698 3699 empty: jqLiteEmpty 3700}, function(fn, name) { 3701 /** 3702 * Properties: writes return selection, reads return first value 3703 */ 3704 JQLite.prototype[name] = function(arg1, arg2) { 3705 var i, key; 3706 var nodeCount = this.length; 3707 3708 // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it 3709 // in a way that survives minification. 3710 // jqLiteEmpty takes no arguments but is a setter. 3711 if (fn !== jqLiteEmpty && 3712 (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) { 3713 if (isObject(arg1)) { 3714 3715 // we are a write, but the object properties are the key/values 3716 for (i = 0; i < nodeCount; i++) { 3717 if (fn === jqLiteData) { 3718 // data() takes the whole object in jQuery 3719 fn(this[i], arg1); 3720 } else { 3721 for (key in arg1) { 3722 fn(this[i], key, arg1[key]); 3723 } 3724 } 3725 } 3726 // return self for chaining 3727 return this; 3728 } else { 3729 // we are a read, so read the first child. 3730 // TODO: do we still need this? 3731 var value = fn.$dv; 3732 // Only if we have $dv do we iterate over all, otherwise it is just the first element. 3733 var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount; 3734 for (var j = 0; j < jj; j++) { 3735 var nodeValue = fn(this[j], arg1, arg2); 3736 value = value ? value + nodeValue : nodeValue; 3737 } 3738 return value; 3739 } 3740 } else { 3741 // we are a write, so apply to all children 3742 for (i = 0; i < nodeCount; i++) { 3743 fn(this[i], arg1, arg2); 3744 } 3745 // return self for chaining 3746 return this; 3747 } 3748 }; 3749}); 3750 3751function createEventHandler(element, events) { 3752 var eventHandler = function(event, type) { 3753 // jQuery specific api 3754 event.isDefaultPrevented = function() { 3755 return event.defaultPrevented; 3756 }; 3757 3758 var eventFns = events[type || event.type]; 3759 var eventFnsLength = eventFns ? eventFns.length : 0; 3760 3761 if (!eventFnsLength) return; 3762 3763 if (isUndefined(event.immediatePropagationStopped)) { 3764 var originalStopImmediatePropagation = event.stopImmediatePropagation; 3765 event.stopImmediatePropagation = function() { 3766 event.immediatePropagationStopped = true; 3767 3768 if (event.stopPropagation) { 3769 event.stopPropagation(); 3770 } 3771 3772 if (originalStopImmediatePropagation) { 3773 originalStopImmediatePropagation.call(event); 3774 } 3775 }; 3776 } 3777 3778 event.isImmediatePropagationStopped = function() { 3779 return event.immediatePropagationStopped === true; 3780 }; 3781 3782 // Some events have special handlers that wrap the real handler 3783 var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper; 3784 3785 // Copy event handlers in case event handlers array is modified during execution. 3786 if ((eventFnsLength > 1)) { 3787 eventFns = shallowCopy(eventFns); 3788 } 3789 3790 for (var i = 0; i < eventFnsLength; i++) { 3791 if (!event.isImmediatePropagationStopped()) { 3792 handlerWrapper(element, event, eventFns[i]); 3793 } 3794 } 3795 }; 3796 3797 // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all 3798 // events on `element` 3799 eventHandler.elem = element; 3800 return eventHandler; 3801} 3802 3803function defaultHandlerWrapper(element, event, handler) { 3804 handler.call(element, event); 3805} 3806 3807function specialMouseHandlerWrapper(target, event, handler) { 3808 // Refer to jQuery's implementation of mouseenter & mouseleave 3809 // Read about mouseenter and mouseleave: 3810 // http://www.quirksmode.org/js/events_mouse.html#link8 3811 var related = event.relatedTarget; 3812 // For mousenter/leave call the handler if related is outside the target. 3813 // NB: No relatedTarget if the mouse left/entered the browser window 3814 if (!related || (related !== target && !jqLiteContains.call(target, related))) { 3815 handler.call(target, event); 3816 } 3817} 3818 3819////////////////////////////////////////// 3820// Functions iterating traversal. 3821// These functions chain results into a single 3822// selector. 3823////////////////////////////////////////// 3824forEach({ 3825 removeData: jqLiteRemoveData, 3826 3827 on: function jqLiteOn(element, type, fn, unsupported) { 3828 if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); 3829 3830 // Do not add event handlers to non-elements because they will not be cleaned up. 3831 if (!jqLiteAcceptsData(element)) { 3832 return; 3833 } 3834 3835 var expandoStore = jqLiteExpandoStore(element, true); 3836 var events = expandoStore.events; 3837 var handle = expandoStore.handle; 3838 3839 if (!handle) { 3840 handle = expandoStore.handle = createEventHandler(element, events); 3841 } 3842 3843 // http://jsperf.com/string-indexof-vs-split 3844 var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type]; 3845 var i = types.length; 3846 3847 var addHandler = function(type, specialHandlerWrapper, noEventListener) { 3848 var eventFns = events[type]; 3849 3850 if (!eventFns) { 3851 eventFns = events[type] = []; 3852 eventFns.specialHandlerWrapper = specialHandlerWrapper; 3853 if (type !== '$destroy' && !noEventListener) { 3854 element.addEventListener(type, handle); 3855 } 3856 } 3857 3858 eventFns.push(fn); 3859 }; 3860 3861 while (i--) { 3862 type = types[i]; 3863 if (MOUSE_EVENT_MAP[type]) { 3864 addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper); 3865 addHandler(type, undefined, true); 3866 } else { 3867 addHandler(type); 3868 } 3869 } 3870 }, 3871 3872 off: jqLiteOff, 3873 3874 one: function(element, type, fn) { 3875 element = jqLite(element); 3876 3877 //add the listener twice so that when it is called 3878 //you can remove the original function and still be 3879 //able to call element.off(ev, fn) normally 3880 element.on(type, function onFn() { 3881 element.off(type, fn); 3882 element.off(type, onFn); 3883 }); 3884 element.on(type, fn); 3885 }, 3886 3887 replaceWith: function(element, replaceNode) { 3888 var index, parent = element.parentNode; 3889 jqLiteDealoc(element); 3890 forEach(new JQLite(replaceNode), function(node) { 3891 if (index) { 3892 parent.insertBefore(node, index.nextSibling); 3893 } else { 3894 parent.replaceChild(node, element); 3895 } 3896 index = node; 3897 }); 3898 }, 3899 3900 children: function(element) { 3901 var children = []; 3902 forEach(element.childNodes, function(element) { 3903 if (element.nodeType === NODE_TYPE_ELEMENT) { 3904 children.push(element); 3905 } 3906 }); 3907 return children; 3908 }, 3909 3910 contents: function(element) { 3911 return element.contentDocument || element.childNodes || []; 3912 }, 3913 3914 append: function(element, node) { 3915 var nodeType = element.nodeType; 3916 if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return; 3917 3918 node = new JQLite(node); 3919 3920 for (var i = 0, ii = node.length; i < ii; i++) { 3921 var child = node[i]; 3922 element.appendChild(child); 3923 } 3924 }, 3925 3926 prepend: function(element, node) { 3927 if (element.nodeType === NODE_TYPE_ELEMENT) { 3928 var index = element.firstChild; 3929 forEach(new JQLite(node), function(child) { 3930 element.insertBefore(child, index); 3931 }); 3932 } 3933 }, 3934 3935 wrap: function(element, wrapNode) { 3936 jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]); 3937 }, 3938 3939 remove: jqLiteRemove, 3940 3941 detach: function(element) { 3942 jqLiteRemove(element, true); 3943 }, 3944 3945 after: function(element, newElement) { 3946 var index = element, parent = element.parentNode; 3947 3948 if (parent) { 3949 newElement = new JQLite(newElement); 3950 3951 for (var i = 0, ii = newElement.length; i < ii; i++) { 3952 var node = newElement[i]; 3953 parent.insertBefore(node, index.nextSibling); 3954 index = node; 3955 } 3956 } 3957 }, 3958 3959 addClass: jqLiteAddClass, 3960 removeClass: jqLiteRemoveClass, 3961 3962 toggleClass: function(element, selector, condition) { 3963 if (selector) { 3964 forEach(selector.split(' '), function(className) { 3965 var classCondition = condition; 3966 if (isUndefined(classCondition)) { 3967 classCondition = !jqLiteHasClass(element, className); 3968 } 3969 (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className); 3970 }); 3971 } 3972 }, 3973 3974 parent: function(element) { 3975 var parent = element.parentNode; 3976 return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null; 3977 }, 3978 3979 next: function(element) { 3980 return element.nextElementSibling; 3981 }, 3982 3983 find: function(element, selector) { 3984 if (element.getElementsByTagName) { 3985 return element.getElementsByTagName(selector); 3986 } else { 3987 return []; 3988 } 3989 }, 3990 3991 clone: jqLiteClone, 3992 3993 triggerHandler: function(element, event, extraParameters) { 3994 3995 var dummyEvent, eventFnsCopy, handlerArgs; 3996 var eventName = event.type || event; 3997 var expandoStore = jqLiteExpandoStore(element); 3998 var events = expandoStore && expandoStore.events; 3999 var eventFns = events && events[eventName]; 4000 4001 if (eventFns) { 4002 // Create a dummy event to pass to the handlers 4003 dummyEvent = { 4004 preventDefault: function() { this.defaultPrevented = true; }, 4005 isDefaultPrevented: function() { return this.defaultPrevented === true; }, 4006 stopImmediatePropagation: function() { this.immediatePropagationStopped = true; }, 4007 isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; }, 4008 stopPropagation: noop, 4009 type: eventName, 4010 target: element 4011 }; 4012 4013 // If a custom event was provided then extend our dummy event with it 4014 if (event.type) { 4015 dummyEvent = extend(dummyEvent, event); 4016 } 4017 4018 // Copy event handlers in case event handlers array is modified during execution. 4019 eventFnsCopy = shallowCopy(eventFns); 4020 handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; 4021 4022 forEach(eventFnsCopy, function(fn) { 4023 if (!dummyEvent.isImmediatePropagationStopped()) { 4024 fn.apply(element, handlerArgs); 4025 } 4026 }); 4027 } 4028 } 4029}, function(fn, name) { 4030 /** 4031 * chaining functions 4032 */ 4033 JQLite.prototype[name] = function(arg1, arg2, arg3) { 4034 var value; 4035 4036 for (var i = 0, ii = this.length; i < ii; i++) { 4037 if (isUndefined(value)) { 4038 value = fn(this[i], arg1, arg2, arg3); 4039 if (isDefined(value)) { 4040 // any function which returns a value needs to be wrapped 4041 value = jqLite(value); 4042 } 4043 } else { 4044 jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3)); 4045 } 4046 } 4047 return isDefined(value) ? value : this; 4048 }; 4049}); 4050 4051// bind legacy bind/unbind to on/off 4052JQLite.prototype.bind = JQLite.prototype.on; 4053JQLite.prototype.unbind = JQLite.prototype.off; 4054 4055 4056// Provider for private $$jqLite service 4057/** @this */ 4058function $$jqLiteProvider() { 4059 this.$get = function $$jqLite() { 4060 return extend(JQLite, { 4061 hasClass: function(node, classes) { 4062 if (node.attr) node = node[0]; 4063 return jqLiteHasClass(node, classes); 4064 }, 4065 addClass: function(node, classes) { 4066 if (node.attr) node = node[0]; 4067 return jqLiteAddClass(node, classes); 4068 }, 4069 removeClass: function(node, classes) { 4070 if (node.attr) node = node[0]; 4071 return jqLiteRemoveClass(node, classes); 4072 } 4073 }); 4074 }; 4075} 4076 4077/** 4078 * Computes a hash of an 'obj'. 4079 * Hash of a: 4080 * string is string 4081 * number is number as string 4082 * object is either result of calling $$hashKey function on the object or uniquely generated id, 4083 * that is also assigned to the $$hashKey property of the object. 4084 * 4085 * @param obj 4086 * @returns {string} hash string such that the same input will have the same hash string. 4087 * The resulting string key is in 'type:hashKey' format. 4088 */ 4089function hashKey(obj, nextUidFn) { 4090 var key = obj && obj.$$hashKey; 4091 4092 if (key) { 4093 if (typeof key === 'function') { 4094 key = obj.$$hashKey(); 4095 } 4096 return key; 4097 } 4098 4099 var objType = typeof obj; 4100 if (objType === 'function' || (objType === 'object' && obj !== null)) { 4101 key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)(); 4102 } else { 4103 key = objType + ':' + obj; 4104 } 4105 4106 return key; 4107} 4108 4109// A minimal ES2015 Map implementation. 4110// Should be bug/feature equivalent to the native implementations of supported browsers 4111// (for the features required in Angular). 4112// See https://kangax.github.io/compat-table/es6/#test-Map 4113var nanKey = Object.create(null); 4114function NgMapShim() { 4115 this._keys = []; 4116 this._values = []; 4117 this._lastKey = NaN; 4118 this._lastIndex = -1; 4119} 4120NgMapShim.prototype = { 4121 _idx: function(key) { 4122 if (key !== this._lastKey) { 4123 this._lastKey = key; 4124 this._lastIndex = this._keys.indexOf(key); 4125 } 4126 return this._lastIndex; 4127 }, 4128 _transformKey: function(key) { 4129 return isNumberNaN(key) ? nanKey : key; 4130 }, 4131 get: function(key) { 4132 key = this._transformKey(key); 4133 var idx = this._idx(key); 4134 if (idx !== -1) { 4135 return this._values[idx]; 4136 } 4137 }, 4138 has: function(key) { 4139 key = this._transformKey(key); 4140 var idx = this._idx(key); 4141 return idx !== -1; 4142 }, 4143 set: function(key, value) { 4144 key = this._transformKey(key); 4145 var idx = this._idx(key); 4146 if (idx === -1) { 4147 idx = this._lastIndex = this._keys.length; 4148 } 4149 this._keys[idx] = key; 4150 this._values[idx] = value; 4151 4152 // Support: IE11 4153 // Do not `return this` to simulate the partial IE11 implementation 4154 }, 4155 delete: function(key) { 4156 key = this._transformKey(key); 4157 var idx = this._idx(key); 4158 if (idx === -1) { 4159 return false; 4160 } 4161 this._keys.splice(idx, 1); 4162 this._values.splice(idx, 1); 4163 this._lastKey = NaN; 4164 this._lastIndex = -1; 4165 return true; 4166 } 4167}; 4168 4169// For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations 4170// are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map` 4171// implementations get more stable, we can reconsider switching to `window.Map` (when available). 4172var NgMap = NgMapShim; 4173 4174var $$MapProvider = [/** @this */function() { 4175 this.$get = [function() { 4176 return NgMap; 4177 }]; 4178}]; 4179 4180/** 4181 * @ngdoc function 4182 * @module ng 4183 * @name angular.injector 4184 * @kind function 4185 * 4186 * @description 4187 * Creates an injector object that can be used for retrieving services as well as for 4188 * dependency injection (see {@link guide/di dependency injection}). 4189 * 4190 * @param {Array.<string|Function>} modules A list of module functions or their aliases. See 4191 * {@link angular.module}. The `ng` module must be explicitly added. 4192 * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which 4193 * disallows argument name annotation inference. 4194 * @returns {injector} Injector object. See {@link auto.$injector $injector}. 4195 * 4196 * @example 4197 * Typical usage 4198 * ```js 4199 * // create an injector 4200 * var $injector = angular.injector(['ng']); 4201 * 4202 * // use the injector to kick off your application 4203 * // use the type inference to auto inject arguments, or use implicit injection 4204 * $injector.invoke(function($rootScope, $compile, $document) { 4205 * $compile($document)($rootScope); 4206 * $rootScope.$digest(); 4207 * }); 4208 * ``` 4209 * 4210 * Sometimes you want to get access to the injector of a currently running AngularJS app 4211 * from outside AngularJS. Perhaps, you want to inject and compile some markup after the 4212 * application has been bootstrapped. You can do this using the extra `injector()` added 4213 * to JQuery/jqLite elements. See {@link angular.element}. 4214 * 4215 * *This is fairly rare but could be the case if a third party library is injecting the 4216 * markup.* 4217 * 4218 * In the following example a new block of HTML containing a `ng-controller` 4219 * directive is added to the end of the document body by JQuery. We then compile and link 4220 * it into the current AngularJS scope. 4221 * 4222 * ```js 4223 * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); 4224 * $(document.body).append($div); 4225 * 4226 * angular.element(document).injector().invoke(function($compile) { 4227 * var scope = angular.element($div).scope(); 4228 * $compile($div)(scope); 4229 * }); 4230 * ``` 4231 */ 4232 4233 4234/** 4235 * @ngdoc module 4236 * @name auto 4237 * @installation 4238 * @description 4239 * 4240 * Implicit module which gets automatically added to each {@link auto.$injector $injector}. 4241 */ 4242 4243var ARROW_ARG = /^([^(]+?)=>/; 4244var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m; 4245var FN_ARG_SPLIT = /,/; 4246var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; 4247var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; 4248var $injectorMinErr = minErr('$injector'); 4249 4250function stringifyFn(fn) { 4251 return Function.prototype.toString.call(fn); 4252} 4253 4254function extractArgs(fn) { 4255 var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''), 4256 args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS); 4257 return args; 4258} 4259 4260function anonFn(fn) { 4261 // For anonymous functions, showing at the very least the function signature can help in 4262 // debugging. 4263 var args = extractArgs(fn); 4264 if (args) { 4265 return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; 4266 } 4267 return 'fn'; 4268} 4269 4270function annotate(fn, strictDi, name) { 4271 var $inject, 4272 argDecl, 4273 last; 4274 4275 if (typeof fn === 'function') { 4276 if (!($inject = fn.$inject)) { 4277 $inject = []; 4278 if (fn.length) { 4279 if (strictDi) { 4280 if (!isString(name) || !name) { 4281 name = fn.name || anonFn(fn); 4282 } 4283 throw $injectorMinErr('strictdi', 4284 '{0} is not using explicit annotation and cannot be invoked in strict mode', name); 4285 } 4286 argDecl = extractArgs(fn); 4287 forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { 4288 arg.replace(FN_ARG, function(all, underscore, name) { 4289 $inject.push(name); 4290 }); 4291 }); 4292 } 4293 fn.$inject = $inject; 4294 } 4295 } else if (isArray(fn)) { 4296 last = fn.length - 1; 4297 assertArgFn(fn[last], 'fn'); 4298 $inject = fn.slice(0, last); 4299 } else { 4300 assertArgFn(fn, 'fn', true); 4301 } 4302 return $inject; 4303} 4304 4305/////////////////////////////////////// 4306 4307/** 4308 * @ngdoc service 4309 * @name $injector 4310 * 4311 * @description 4312 * 4313 * `$injector` is used to retrieve object instances as defined by 4314 * {@link auto.$provide provider}, instantiate types, invoke methods, 4315 * and load modules. 4316 * 4317 * The following always holds true: 4318 * 4319 * ```js 4320 * var $injector = angular.injector(); 4321 * expect($injector.get('$injector')).toBe($injector); 4322 * expect($injector.invoke(function($injector) { 4323 * return $injector; 4324 * })).toBe($injector); 4325 * ``` 4326 * 4327 * ## Injection Function Annotation 4328 * 4329 * JavaScript does not have annotations, and annotations are needed for dependency injection. The 4330 * following are all valid ways of annotating function with injection arguments and are equivalent. 4331 * 4332 * ```js 4333 * // inferred (only works if code not minified/obfuscated) 4334 * $injector.invoke(function(serviceA){}); 4335 * 4336 * // annotated 4337 * function explicit(serviceA) {}; 4338 * explicit.$inject = ['serviceA']; 4339 * $injector.invoke(explicit); 4340 * 4341 * // inline 4342 * $injector.invoke(['serviceA', function(serviceA){}]); 4343 * ``` 4344 * 4345 * ### Inference 4346 * 4347 * In JavaScript calling `toString()` on a function returns the function definition. The definition 4348 * can then be parsed and the function arguments can be extracted. This method of discovering 4349 * annotations is disallowed when the injector is in strict mode. 4350 * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the 4351 * argument names. 4352 * 4353 * ### `$inject` Annotation 4354 * By adding an `$inject` property onto a function the injection parameters can be specified. 4355 * 4356 * ### Inline 4357 * As an array of injection names, where the last item in the array is the function to call. 4358 */ 4359 4360/** 4361 * @ngdoc property 4362 * @name $injector#modules 4363 * @type {Object} 4364 * @description 4365 * A hash containing all the modules that have been loaded into the 4366 * $injector. 4367 * 4368 * You can use this property to find out information about a module via the 4369 * {@link angular.Module#info `myModule.info(...)`} method. 4370 * 4371 * For example: 4372 * 4373 * ``` 4374 * var info = $injector.modules['ngAnimate'].info(); 4375 * ``` 4376 * 4377 * **Do not use this property to attempt to modify the modules after the application 4378 * has been bootstrapped.** 4379 */ 4380 4381 4382/** 4383 * @ngdoc method 4384 * @name $injector#get 4385 * 4386 * @description 4387 * Return an instance of the service. 4388 * 4389 * @param {string} name The name of the instance to retrieve. 4390 * @param {string=} caller An optional string to provide the origin of the function call for error messages. 4391 * @return {*} The instance. 4392 */ 4393 4394/** 4395 * @ngdoc method 4396 * @name $injector#invoke 4397 * 4398 * @description 4399 * Invoke the method and supply the method arguments from the `$injector`. 4400 * 4401 * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are 4402 * injected according to the {@link guide/di $inject Annotation} rules. 4403 * @param {Object=} self The `this` for the invoked method. 4404 * @param {Object=} locals Optional object. If preset then any argument names are read from this 4405 * object first, before the `$injector` is consulted. 4406 * @returns {*} the value returned by the invoked `fn` function. 4407 */ 4408 4409/** 4410 * @ngdoc method 4411 * @name $injector#has 4412 * 4413 * @description 4414 * Allows the user to query if the particular service exists. 4415 * 4416 * @param {string} name Name of the service to query. 4417 * @returns {boolean} `true` if injector has given service. 4418 */ 4419 4420/** 4421 * @ngdoc method 4422 * @name $injector#instantiate 4423 * @description 4424 * Create a new instance of JS type. The method takes a constructor function, invokes the new 4425 * operator, and supplies all of the arguments to the constructor function as specified by the 4426 * constructor annotation. 4427 * 4428 * @param {Function} Type Annotated constructor function. 4429 * @param {Object=} locals Optional object. If preset then any argument names are read from this 4430 * object first, before the `$injector` is consulted. 4431 * @returns {Object} new instance of `Type`. 4432 */ 4433 4434/** 4435 * @ngdoc method 4436 * @name $injector#annotate 4437 * 4438 * @description 4439 * Returns an array of service names which the function is requesting for injection. This API is 4440 * used by the injector to determine which services need to be injected into the function when the 4441 * function is invoked. There are three ways in which the function can be annotated with the needed 4442 * dependencies. 4443 * 4444 * #### Argument names 4445 * 4446 * The simplest form is to extract the dependencies from the arguments of the function. This is done 4447 * by converting the function into a string using `toString()` method and extracting the argument 4448 * names. 4449 * ```js 4450 * // Given 4451 * function MyController($scope, $route) { 4452 * // ... 4453 * } 4454 * 4455 * // Then 4456 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); 4457 * ``` 4458 * 4459 * You can disallow this method by using strict injection mode. 4460 * 4461 * This method does not work with code minification / obfuscation. For this reason the following 4462 * annotation strategies are supported. 4463 * 4464 * #### The `$inject` property 4465 * 4466 * If a function has an `$inject` property and its value is an array of strings, then the strings 4467 * represent names of services to be injected into the function. 4468 * ```js 4469 * // Given 4470 * var MyController = function(obfuscatedScope, obfuscatedRoute) { 4471 * // ... 4472 * } 4473 * // Define function dependencies 4474 * MyController['$inject'] = ['$scope', '$route']; 4475 * 4476 * // Then 4477 * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); 4478 * ``` 4479 * 4480 * #### The array notation 4481 * 4482 * It is often desirable to inline Injected functions and that's when setting the `$inject` property 4483 * is very inconvenient. In these situations using the array notation to specify the dependencies in 4484 * a way that survives minification is a better choice: 4485 * 4486 * ```js 4487 * // We wish to write this (not minification / obfuscation safe) 4488 * injector.invoke(function($compile, $rootScope) { 4489 * // ... 4490 * }); 4491 * 4492 * // We are forced to write break inlining 4493 * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { 4494 * // ... 4495 * }; 4496 * tmpFn.$inject = ['$compile', '$rootScope']; 4497 * injector.invoke(tmpFn); 4498 * 4499 * // To better support inline function the inline annotation is supported 4500 * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { 4501 * // ... 4502 * }]); 4503 * 4504 * // Therefore 4505 * expect(injector.annotate( 4506 * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) 4507 * ).toEqual(['$compile', '$rootScope']); 4508 * ``` 4509 * 4510 * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to 4511 * be retrieved as described above. 4512 * 4513 * @param {boolean=} [strictDi=false] Disallow argument name annotation inference. 4514 * 4515 * @returns {Array.<string>} The names of the services which the function requires. 4516 */ 4517/** 4518 * @ngdoc method 4519 * @name $injector#loadNewModules 4520 * 4521 * @description 4522 * 4523 * **This is a dangerous API, which you use at your own risk!** 4524 * 4525 * Add the specified modules to the current injector. 4526 * 4527 * This method will add each of the injectables to the injector and execute all of the config and run 4528 * blocks for each module passed to the method. 4529 * 4530 * If a module has already been loaded into the injector then it will not be loaded again. 4531 * 4532 * * The application developer is responsible for loading the code containing the modules; and for 4533 * ensuring that lazy scripts are not downloaded and executed more often that desired. 4534 * * Previously compiled HTML will not be affected by newly loaded directives, filters and components. 4535 * * Modules cannot be unloaded. 4536 * 4537 * You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded 4538 * into the injector, which may indicate whether the script has been executed already. 4539 * 4540 * @example 4541 * Here is an example of loading a bundle of modules, with a utility method called `getScript`: 4542 * 4543 * ```javascript 4544 * app.factory('loadModule', function($injector) { 4545 * return function loadModule(moduleName, bundleUrl) { 4546 * return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); }); 4547 * }; 4548 * }) 4549 * ``` 4550 * 4551 * @param {Array<String|Function|Array>=} mods an array of modules to load into the application. 4552 * Each item in the array should be the name of a predefined module or a (DI annotated) 4553 * function that will be invoked by the injector as a `config` block. 4554 * See: {@link angular.module modules} 4555 */ 4556 4557 4558/** 4559 * @ngdoc service 4560 * @name $provide 4561 * 4562 * @description 4563 * 4564 * The {@link auto.$provide $provide} service has a number of methods for registering components 4565 * with the {@link auto.$injector $injector}. Many of these functions are also exposed on 4566 * {@link angular.Module}. 4567 * 4568 * An AngularJS **service** is a singleton object created by a **service factory**. These **service 4569 * factories** are functions which, in turn, are created by a **service provider**. 4570 * The **service providers** are constructor functions. When instantiated they must contain a 4571 * property called `$get`, which holds the **service factory** function. 4572 * 4573 * When you request a service, the {@link auto.$injector $injector} is responsible for finding the 4574 * correct **service provider**, instantiating it and then calling its `$get` **service factory** 4575 * function to get the instance of the **service**. 4576 * 4577 * Often services have no configuration options and there is no need to add methods to the service 4578 * provider. The provider will be no more than a constructor function with a `$get` property. For 4579 * these cases the {@link auto.$provide $provide} service has additional helper methods to register 4580 * services without specifying a provider. 4581 * 4582 * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the 4583 * {@link auto.$injector $injector} 4584 * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by 4585 * providers and services. 4586 * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by 4587 * services, not providers. 4588 * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function** 4589 * that will be wrapped in a **service provider** object, whose `$get` property will contain the 4590 * given factory function. 4591 * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function** 4592 * that will be wrapped in a **service provider** object, whose `$get` property will instantiate 4593 * a new object using the given constructor function. 4594 * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that 4595 * will be able to modify or replace the implementation of another service. 4596 * 4597 * See the individual methods for more information and examples. 4598 */ 4599 4600/** 4601 * @ngdoc method 4602 * @name $provide#provider 4603 * @description 4604 * 4605 * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions 4606 * are constructor functions, whose instances are responsible for "providing" a factory for a 4607 * service. 4608 * 4609 * Service provider names start with the name of the service they provide followed by `Provider`. 4610 * For example, the {@link ng.$log $log} service has a provider called 4611 * {@link ng.$logProvider $logProvider}. 4612 * 4613 * Service provider objects can have additional methods which allow configuration of the provider 4614 * and its service. Importantly, you can configure what kind of service is created by the `$get` 4615 * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a 4616 * method {@link ng.$logProvider#debugEnabled debugEnabled} 4617 * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the 4618 * console or not. 4619 * 4620 * It is possible to inject other providers into the provider function, 4621 * but the injected provider must have been defined before the one that requires it. 4622 * 4623 * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 4624 'Provider'` key. 4625 * @param {(Object|function())} provider If the provider is: 4626 * 4627 * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using 4628 * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. 4629 * - `Constructor`: a new instance of the provider will be created using 4630 * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. 4631 * 4632 * @returns {Object} registered provider instance 4633 4634 * @example 4635 * 4636 * The following example shows how to create a simple event tracking service and register it using 4637 * {@link auto.$provide#provider $provide.provider()}. 4638 * 4639 * ```js 4640 * // Define the eventTracker provider 4641 * function EventTrackerProvider() { 4642 * var trackingUrl = '/track'; 4643 * 4644 * // A provider method for configuring where the tracked events should been saved 4645 * this.setTrackingUrl = function(url) { 4646 * trackingUrl = url; 4647 * }; 4648 * 4649 * // The service factory function 4650 * this.$get = ['$http', function($http) { 4651 * var trackedEvents = {}; 4652 * return { 4653 * // Call this to track an event 4654 * event: function(event) { 4655 * var count = trackedEvents[event] || 0; 4656 * count += 1; 4657 * trackedEvents[event] = count; 4658 * return count; 4659 * }, 4660 * // Call this to save the tracked events to the trackingUrl 4661 * save: function() { 4662 * $http.post(trackingUrl, trackedEvents); 4663 * } 4664 * }; 4665 * }]; 4666 * } 4667 * 4668 * describe('eventTracker', function() { 4669 * var postSpy; 4670 * 4671 * beforeEach(module(function($provide) { 4672 * // Register the eventTracker provider 4673 * $provide.provider('eventTracker', EventTrackerProvider); 4674 * })); 4675 * 4676 * beforeEach(module(function(eventTrackerProvider) { 4677 * // Configure eventTracker provider 4678 * eventTrackerProvider.setTrackingUrl('/custom-track'); 4679 * })); 4680 * 4681 * it('tracks events', inject(function(eventTracker) { 4682 * expect(eventTracker.event('login')).toEqual(1); 4683 * expect(eventTracker.event('login')).toEqual(2); 4684 * })); 4685 * 4686 * it('saves to the tracking url', inject(function(eventTracker, $http) { 4687 * postSpy = spyOn($http, 'post'); 4688 * eventTracker.event('login'); 4689 * eventTracker.save(); 4690 * expect(postSpy).toHaveBeenCalled(); 4691 * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); 4692 * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); 4693 * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); 4694 * })); 4695 * }); 4696 * ``` 4697 */ 4698 4699/** 4700 * @ngdoc method 4701 * @name $provide#factory 4702 * @description 4703 * 4704 * Register a **service factory**, which will be called to return the service instance. 4705 * This is short for registering a service where its provider consists of only a `$get` property, 4706 * which is the given service factory function. 4707 * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to 4708 * configure your service in a provider. 4709 * 4710 * @param {string} name The name of the instance. 4711 * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation. 4712 * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`. 4713 * @returns {Object} registered provider instance 4714 * 4715 * @example 4716 * Here is an example of registering a service 4717 * ```js 4718 * $provide.factory('ping', ['$http', function($http) { 4719 * return function ping() { 4720 * return $http.send('/ping'); 4721 * }; 4722 * }]); 4723 * ``` 4724 * You would then inject and use this service like this: 4725 * ```js 4726 * someModule.controller('Ctrl', ['ping', function(ping) { 4727 * ping(); 4728 * }]); 4729 * ``` 4730 */ 4731 4732 4733/** 4734 * @ngdoc method 4735 * @name $provide#service 4736 * @description 4737 * 4738 * Register a **service constructor**, which will be invoked with `new` to create the service 4739 * instance. 4740 * This is short for registering a service where its provider's `$get` property is a factory 4741 * function that returns an instance instantiated by the injector from the service constructor 4742 * function. 4743 * 4744 * Internally it looks a bit like this: 4745 * 4746 * ``` 4747 * { 4748 * $get: function() { 4749 * return $injector.instantiate(constructor); 4750 * } 4751 * } 4752 * ``` 4753 * 4754 * 4755 * You should use {@link auto.$provide#service $provide.service(class)} if you define your service 4756 * as a type/class. 4757 * 4758 * @param {string} name The name of the instance. 4759 * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function) 4760 * that will be instantiated. 4761 * @returns {Object} registered provider instance 4762 * 4763 * @example 4764 * Here is an example of registering a service using 4765 * {@link auto.$provide#service $provide.service(class)}. 4766 * ```js 4767 * var Ping = function($http) { 4768 * this.$http = $http; 4769 * }; 4770 * 4771 * Ping.$inject = ['$http']; 4772 * 4773 * Ping.prototype.send = function() { 4774 * return this.$http.get('/ping'); 4775 * }; 4776 * $provide.service('ping', Ping); 4777 * ``` 4778 * You would then inject and use this service like this: 4779 * ```js 4780 * someModule.controller('Ctrl', ['ping', function(ping) { 4781 * ping.send(); 4782 * }]); 4783 * ``` 4784 */ 4785 4786 4787/** 4788 * @ngdoc method 4789 * @name $provide#value 4790 * @description 4791 * 4792 * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a 4793 * number, an array, an object or a function. This is short for registering a service where its 4794 * provider's `$get` property is a factory function that takes no arguments and returns the **value 4795 * service**. That also means it is not possible to inject other services into a value service. 4796 * 4797 * Value services are similar to constant services, except that they cannot be injected into a 4798 * module configuration function (see {@link angular.Module#config}) but they can be overridden by 4799 * an AngularJS {@link auto.$provide#decorator decorator}. 4800 * 4801 * @param {string} name The name of the instance. 4802 * @param {*} value The value. 4803 * @returns {Object} registered provider instance 4804 * 4805 * @example 4806 * Here are some examples of creating value services. 4807 * ```js 4808 * $provide.value('ADMIN_USER', 'admin'); 4809 * 4810 * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); 4811 * 4812 * $provide.value('halfOf', function(value) { 4813 * return value / 2; 4814 * }); 4815 * ``` 4816 */ 4817 4818 4819/** 4820 * @ngdoc method 4821 * @name $provide#constant 4822 * @description 4823 * 4824 * Register a **constant service** with the {@link auto.$injector $injector}, such as a string, 4825 * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not 4826 * possible to inject other services into a constant. 4827 * 4828 * But unlike {@link auto.$provide#value value}, a constant can be 4829 * injected into a module configuration function (see {@link angular.Module#config}) and it cannot 4830 * be overridden by an AngularJS {@link auto.$provide#decorator decorator}. 4831 * 4832 * @param {string} name The name of the constant. 4833 * @param {*} value The constant value. 4834 * @returns {Object} registered instance 4835 * 4836 * @example 4837 * Here a some examples of creating constants: 4838 * ```js 4839 * $provide.constant('SHARD_HEIGHT', 306); 4840 * 4841 * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); 4842 * 4843 * $provide.constant('double', function(value) { 4844 * return value * 2; 4845 * }); 4846 * ``` 4847 */ 4848 4849 4850/** 4851 * @ngdoc method 4852 * @name $provide#decorator 4853 * @description 4854 * 4855 * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function 4856 * intercepts the creation of a service, allowing it to override or modify the behavior of the 4857 * service. The return value of the decorator function may be the original service, or a new service 4858 * that replaces (or wraps and delegates to) the original service. 4859 * 4860 * You can find out more about using decorators in the {@link guide/decorators} guide. 4861 * 4862 * @param {string} name The name of the service to decorate. 4863 * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be 4864 * provided and should return the decorated service instance. The function is called using 4865 * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. 4866 * Local injection arguments: 4867 * 4868 * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured, 4869 * decorated or delegated to. 4870 * 4871 * @example 4872 * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting 4873 * calls to {@link ng.$log#error $log.warn()}. 4874 * ```js 4875 * $provide.decorator('$log', ['$delegate', function($delegate) { 4876 * $delegate.warn = $delegate.error; 4877 * return $delegate; 4878 * }]); 4879 * ``` 4880 */ 4881 4882 4883function createInjector(modulesToLoad, strictDi) { 4884 strictDi = (strictDi === true); 4885 var INSTANTIATING = {}, 4886 providerSuffix = 'Provider', 4887 path = [], 4888 loadedModules = new NgMap(), 4889 providerCache = { 4890 $provide: { 4891 provider: supportObject(provider), 4892 factory: supportObject(factory), 4893 service: supportObject(service), 4894 value: supportObject(value), 4895 constant: supportObject(constant), 4896 decorator: decorator 4897 } 4898 }, 4899 providerInjector = (providerCache.$injector = 4900 createInternalInjector(providerCache, function(serviceName, caller) { 4901 if (angular.isString(caller)) { 4902 path.push(caller); 4903 } 4904 throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- ')); 4905 })), 4906 instanceCache = {}, 4907 protoInstanceInjector = 4908 createInternalInjector(instanceCache, function(serviceName, caller) { 4909 var provider = providerInjector.get(serviceName + providerSuffix, caller); 4910 return instanceInjector.invoke( 4911 provider.$get, provider, undefined, serviceName); 4912 }), 4913 instanceInjector = protoInstanceInjector; 4914 4915 providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) }; 4916 instanceInjector.modules = providerInjector.modules = createMap(); 4917 var runBlocks = loadModules(modulesToLoad); 4918 instanceInjector = protoInstanceInjector.get('$injector'); 4919 instanceInjector.strictDi = strictDi; 4920 forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); }); 4921 4922 instanceInjector.loadNewModules = function(mods) { 4923 forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); }); 4924 }; 4925 4926 4927 return instanceInjector; 4928 4929 //////////////////////////////////// 4930 // $provider 4931 //////////////////////////////////// 4932 4933 function supportObject(delegate) { 4934 return function(key, value) { 4935 if (isObject(key)) { 4936 forEach(key, reverseParams(delegate)); 4937 } else { 4938 return delegate(key, value); 4939 } 4940 }; 4941 } 4942 4943 function provider(name, provider_) { 4944 assertNotHasOwnProperty(name, 'service'); 4945 if (isFunction(provider_) || isArray(provider_)) { 4946 provider_ = providerInjector.instantiate(provider_); 4947 } 4948 if (!provider_.$get) { 4949 throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name); 4950 } 4951 return (providerCache[name + providerSuffix] = provider_); 4952 } 4953 4954 function enforceReturnValue(name, factory) { 4955 return /** @this */ function enforcedReturnValue() { 4956 var result = instanceInjector.invoke(factory, this); 4957 if (isUndefined(result)) { 4958 throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name); 4959 } 4960 return result; 4961 }; 4962 } 4963 4964 function factory(name, factoryFn, enforce) { 4965 return provider(name, { 4966 $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn 4967 }); 4968 } 4969 4970 function service(name, constructor) { 4971 return factory(name, ['$injector', function($injector) { 4972 return $injector.instantiate(constructor); 4973 }]); 4974 } 4975 4976 function value(name, val) { return factory(name, valueFn(val), false); } 4977 4978 function constant(name, value) { 4979 assertNotHasOwnProperty(name, 'constant'); 4980 providerCache[name] = value; 4981 instanceCache[name] = value; 4982 } 4983 4984 function decorator(serviceName, decorFn) { 4985 var origProvider = providerInjector.get(serviceName + providerSuffix), 4986 orig$get = origProvider.$get; 4987 4988 origProvider.$get = function() { 4989 var origInstance = instanceInjector.invoke(orig$get, origProvider); 4990 return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); 4991 }; 4992 } 4993 4994 //////////////////////////////////// 4995 // Module Loading 4996 //////////////////////////////////// 4997 function loadModules(modulesToLoad) { 4998 assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array'); 4999 var runBlocks = [], moduleFn; 5000 forEach(modulesToLoad, function(module) { 5001 if (loadedModules.get(module)) return; 5002 loadedModules.set(module, true); 5003 5004 function runInvokeQueue(queue) { 5005 var i, ii; 5006 for (i = 0, ii = queue.length; i < ii; i++) { 5007 var invokeArgs = queue[i], 5008 provider = providerInjector.get(invokeArgs[0]); 5009 5010 provider[invokeArgs[1]].apply(provider, invokeArgs[2]); 5011 } 5012 } 5013 5014 try { 5015 if (isString(module)) { 5016 moduleFn = angularModule(module); 5017 instanceInjector.modules[module] = moduleFn; 5018 runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); 5019 runInvokeQueue(moduleFn._invokeQueue); 5020 runInvokeQueue(moduleFn._configBlocks); 5021 } else if (isFunction(module)) { 5022 runBlocks.push(providerInjector.invoke(module)); 5023 } else if (isArray(module)) { 5024 runBlocks.push(providerInjector.invoke(module)); 5025 } else { 5026 assertArgFn(module, 'module'); 5027 } 5028 } catch (e) { 5029 if (isArray(module)) { 5030 module = module[module.length - 1]; 5031 } 5032 if (e.message && e.stack && e.stack.indexOf(e.message) === -1) { 5033 // Safari & FF's stack traces don't contain error.message content 5034 // unlike those of Chrome and IE 5035 // So if stack doesn't contain message, we create a new string that contains both. 5036 // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. 5037 // eslint-disable-next-line no-ex-assign 5038 e = e.message + '\n' + e.stack; 5039 } 5040 throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}', 5041 module, e.stack || e.message || e); 5042 } 5043 }); 5044 return runBlocks; 5045 } 5046 5047 //////////////////////////////////// 5048 // internal Injector 5049 //////////////////////////////////// 5050 5051 function createInternalInjector(cache, factory) { 5052 5053 function getService(serviceName, caller) { 5054 if (cache.hasOwnProperty(serviceName)) { 5055 if (cache[serviceName] === INSTANTIATING) { 5056 throw $injectorMinErr('cdep', 'Circular dependency found: {0}', 5057 serviceName + ' <- ' + path.join(' <- ')); 5058 } 5059 return cache[serviceName]; 5060 } else { 5061 try { 5062 path.unshift(serviceName); 5063 cache[serviceName] = INSTANTIATING; 5064 cache[serviceName] = factory(serviceName, caller); 5065 return cache[serviceName]; 5066 } catch (err) { 5067 if (cache[serviceName] === INSTANTIATING) { 5068 delete cache[serviceName]; 5069 } 5070 throw err; 5071 } finally { 5072 path.shift(); 5073 } 5074 } 5075 } 5076 5077 5078 function injectionArgs(fn, locals, serviceName) { 5079 var args = [], 5080 $inject = createInjector.$$annotate(fn, strictDi, serviceName); 5081 5082 for (var i = 0, length = $inject.length; i < length; i++) { 5083 var key = $inject[i]; 5084 if (typeof key !== 'string') { 5085 throw $injectorMinErr('itkn', 5086 'Incorrect injection token! Expected service name as string, got {0}', key); 5087 } 5088 args.push(locals && locals.hasOwnProperty(key) ? locals[key] : 5089 getService(key, serviceName)); 5090 } 5091 return args; 5092 } 5093 5094 function isClass(func) { 5095 // Support: IE 9-11 only 5096 // IE 9-11 do not support classes and IE9 leaks with the code below. 5097 if (msie || typeof func !== 'function') { 5098 return false; 5099 } 5100 var result = func.$$ngIsClass; 5101 if (!isBoolean(result)) { 5102 result = func.$$ngIsClass = /^class\b/.test(stringifyFn(func)); 5103 } 5104 return result; 5105 } 5106 5107 function invoke(fn, self, locals, serviceName) { 5108 if (typeof locals === 'string') { 5109 serviceName = locals; 5110 locals = null; 5111 } 5112 5113 var args = injectionArgs(fn, locals, serviceName); 5114 if (isArray(fn)) { 5115 fn = fn[fn.length - 1]; 5116 } 5117 5118 if (!isClass(fn)) { 5119 // http://jsperf.com/angularjs-invoke-apply-vs-switch 5120 // #5388 5121 return fn.apply(self, args); 5122 } else { 5123 args.unshift(null); 5124 return new (Function.prototype.bind.apply(fn, args))(); 5125 } 5126 } 5127 5128 5129 function instantiate(Type, locals, serviceName) { 5130 // Check if Type is annotated and use just the given function at n-1 as parameter 5131 // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); 5132 var ctor = (isArray(Type) ? Type[Type.length - 1] : Type); 5133 var args = injectionArgs(Type, locals, serviceName); 5134 // Empty object at position 0 is ignored for invocation with `new`, but required. 5135 args.unshift(null); 5136 return new (Function.prototype.bind.apply(ctor, args))(); 5137 } 5138 5139 5140 return { 5141 invoke: invoke, 5142 instantiate: instantiate, 5143 get: getService, 5144 annotate: createInjector.$$annotate, 5145 has: function(name) { 5146 return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); 5147 } 5148 }; 5149 } 5150} 5151 5152createInjector.$$annotate = annotate; 5153 5154/** 5155 * @ngdoc provider 5156 * @name $anchorScrollProvider 5157 * @this 5158 * 5159 * @description 5160 * Use `$anchorScrollProvider` to disable automatic scrolling whenever 5161 * {@link ng.$location#hash $location.hash()} changes. 5162 */ 5163function $AnchorScrollProvider() { 5164 5165 var autoScrollingEnabled = true; 5166 5167 /** 5168 * @ngdoc method 5169 * @name $anchorScrollProvider#disableAutoScrolling 5170 * 5171 * @description 5172 * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to 5173 * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br /> 5174 * Use this method to disable automatic scrolling. 5175 * 5176 * If automatic scrolling is disabled, one must explicitly call 5177 * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the 5178 * current hash. 5179 */ 5180 this.disableAutoScrolling = function() { 5181 autoScrollingEnabled = false; 5182 }; 5183 5184 /** 5185 * @ngdoc service 5186 * @name $anchorScroll 5187 * @kind function 5188 * @requires $window 5189 * @requires $location 5190 * @requires $rootScope 5191 * 5192 * @description 5193 * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the 5194 * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified 5195 * in the 5196 * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document). 5197 * 5198 * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to 5199 * match any anchor whenever it changes. This can be disabled by calling 5200 * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}. 5201 * 5202 * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a 5203 * vertical scroll-offset (either fixed or dynamic). 5204 * 5205 * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of 5206 * {@link ng.$location#hash $location.hash()} will be used. 5207 * 5208 * @property {(number|function|jqLite)} yOffset 5209 * If set, specifies a vertical scroll-offset. This is often useful when there are fixed 5210 * positioned elements at the top of the page, such as navbars, headers etc. 5211 * 5212 * `yOffset` can be specified in various ways: 5213 * - **number**: A fixed number of pixels to be used as offset.<br /><br /> 5214 * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return 5215 * a number representing the offset (in pixels).<br /><br /> 5216 * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from 5217 * the top of the page to the element's bottom will be used as offset.<br /> 5218 * **Note**: The element will be taken into account only as long as its `position` is set to 5219 * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust 5220 * their height and/or positioning according to the viewport's size. 5221 * 5222 * <br /> 5223 * <div class="alert alert-warning"> 5224 * In order for `yOffset` to work properly, scrolling should take place on the document's root and 5225 * not some child element. 5226 * </div> 5227 * 5228 * @example 5229 <example module="anchorScrollExample" name="anchor-scroll"> 5230 <file name="index.html"> 5231 <div id="scrollArea" ng-controller="ScrollController"> 5232 <a ng-click="gotoBottom()">Go to bottom</a> 5233 <a id="bottom"></a> You're at the bottom! 5234 </div> 5235 </file> 5236 <file name="script.js"> 5237 angular.module('anchorScrollExample', []) 5238 .controller('ScrollController', ['$scope', '$location', '$anchorScroll', 5239 function($scope, $location, $anchorScroll) { 5240 $scope.gotoBottom = function() { 5241 // set the location.hash to the id of 5242 // the element you wish to scroll to. 5243 $location.hash('bottom'); 5244 5245 // call $anchorScroll() 5246 $anchorScroll(); 5247 }; 5248 }]); 5249 </file> 5250 <file name="style.css"> 5251 #scrollArea { 5252 height: 280px; 5253 overflow: auto; 5254 } 5255 5256 #bottom { 5257 display: block; 5258 margin-top: 2000px; 5259 } 5260 </file> 5261 </example> 5262 * 5263 * <hr /> 5264 * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). 5265 * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details. 5266 * 5267 * @example 5268 <example module="anchorScrollOffsetExample" name="anchor-scroll-offset"> 5269 <file name="index.html"> 5270 <div class="fixed-header" ng-controller="headerCtrl"> 5271 <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]"> 5272 Go to anchor {{x}} 5273 </a> 5274 </div> 5275 <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]"> 5276 Anchor {{x}} of 5 5277 </div> 5278 </file> 5279 <file name="script.js"> 5280 angular.module('anchorScrollOffsetExample', []) 5281 .run(['$anchorScroll', function($anchorScroll) { 5282 $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels 5283 }]) 5284 .controller('headerCtrl', ['$anchorScroll', '$location', '$scope', 5285 function($anchorScroll, $location, $scope) { 5286 $scope.gotoAnchor = function(x) { 5287 var newHash = 'anchor' + x; 5288 if ($location.hash() !== newHash) { 5289 // set the $location.hash to `newHash` and 5290 // $anchorScroll will automatically scroll to it 5291 $location.hash('anchor' + x); 5292 } else { 5293 // call $anchorScroll() explicitly, 5294 // since $location.hash hasn't changed 5295 $anchorScroll(); 5296 } 5297 }; 5298 } 5299 ]); 5300 </file> 5301 <file name="style.css"> 5302 body { 5303 padding-top: 50px; 5304 } 5305 5306 .anchor { 5307 border: 2px dashed DarkOrchid; 5308 padding: 10px 10px 200px 10px; 5309 } 5310 5311 .fixed-header { 5312 background-color: rgba(0, 0, 0, 0.2); 5313 height: 50px; 5314 position: fixed; 5315 top: 0; left: 0; right: 0; 5316 } 5317 5318 .fixed-header > a { 5319 display: inline-block; 5320 margin: 5px 15px; 5321 } 5322 </file> 5323 </example> 5324 */ 5325 this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { 5326 var document = $window.document; 5327 5328 // Helper function to get first anchor from a NodeList 5329 // (using `Array#some()` instead of `angular#forEach()` since it's more performant 5330 // and working in all supported browsers.) 5331 function getFirstAnchor(list) { 5332 var result = null; 5333 Array.prototype.some.call(list, function(element) { 5334 if (nodeName_(element) === 'a') { 5335 result = element; 5336 return true; 5337 } 5338 }); 5339 return result; 5340 } 5341 5342 function getYOffset() { 5343 5344 var offset = scroll.yOffset; 5345 5346 if (isFunction(offset)) { 5347 offset = offset(); 5348 } else if (isElement(offset)) { 5349 var elem = offset[0]; 5350 var style = $window.getComputedStyle(elem); 5351 if (style.position !== 'fixed') { 5352 offset = 0; 5353 } else { 5354 offset = elem.getBoundingClientRect().bottom; 5355 } 5356 } else if (!isNumber(offset)) { 5357 offset = 0; 5358 } 5359 5360 return offset; 5361 } 5362 5363 function scrollTo(elem) { 5364 if (elem) { 5365 elem.scrollIntoView(); 5366 5367 var offset = getYOffset(); 5368 5369 if (offset) { 5370 // `offset` is the number of pixels we should scroll UP in order to align `elem` properly. 5371 // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the 5372 // top of the viewport. 5373 // 5374 // IF the number of pixels from the top of `elem` to the end of the page's content is less 5375 // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some 5376 // way down the page. 5377 // 5378 // This is often the case for elements near the bottom of the page. 5379 // 5380 // In such cases we do not need to scroll the whole `offset` up, just the difference between 5381 // the top of the element and the offset, which is enough to align the top of `elem` at the 5382 // desired position. 5383 var elemTop = elem.getBoundingClientRect().top; 5384 $window.scrollBy(0, elemTop - offset); 5385 } 5386 } else { 5387 $window.scrollTo(0, 0); 5388 } 5389 } 5390 5391 function scroll(hash) { 5392 // Allow numeric hashes 5393 hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash(); 5394 var elm; 5395 5396 // empty hash, scroll to the top of the page 5397 if (!hash) scrollTo(null); 5398 5399 // element with given id 5400 else if ((elm = document.getElementById(hash))) scrollTo(elm); 5401 5402 // first anchor with given name :-D 5403 else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm); 5404 5405 // no element and hash === 'top', scroll to the top of the page 5406 else if (hash === 'top') scrollTo(null); 5407 } 5408 5409 // does not scroll when user clicks on anchor link that is currently on 5410 // (no url change, no $location.hash() change), browser native does scroll 5411 if (autoScrollingEnabled) { 5412 $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, 5413 function autoScrollWatchAction(newVal, oldVal) { 5414 // skip the initial scroll if $location.hash is empty 5415 if (newVal === oldVal && newVal === '') return; 5416 5417 jqLiteDocumentLoaded(function() { 5418 $rootScope.$evalAsync(scroll); 5419 }); 5420 }); 5421 } 5422 5423 return scroll; 5424 }]; 5425} 5426 5427var $animateMinErr = minErr('$animate'); 5428var ELEMENT_NODE = 1; 5429var NG_ANIMATE_CLASSNAME = 'ng-animate'; 5430 5431function mergeClasses(a,b) { 5432 if (!a && !b) return ''; 5433 if (!a) return b; 5434 if (!b) return a; 5435 if (isArray(a)) a = a.join(' '); 5436 if (isArray(b)) b = b.join(' '); 5437 return a + ' ' + b; 5438} 5439 5440function extractElementNode(element) { 5441 for (var i = 0; i < element.length; i++) { 5442 var elm = element[i]; 5443 if (elm.nodeType === ELEMENT_NODE) { 5444 return elm; 5445 } 5446 } 5447} 5448 5449function splitClasses(classes) { 5450 if (isString(classes)) { 5451 classes = classes.split(' '); 5452 } 5453 5454 // Use createMap() to prevent class assumptions involving property names in 5455 // Object.prototype 5456 var obj = createMap(); 5457 forEach(classes, function(klass) { 5458 // sometimes the split leaves empty string values 5459 // incase extra spaces were applied to the options 5460 if (klass.length) { 5461 obj[klass] = true; 5462 } 5463 }); 5464 return obj; 5465} 5466 5467// if any other type of options value besides an Object value is 5468// passed into the $animate.method() animation then this helper code 5469// will be run which will ignore it. While this patch is not the 5470// greatest solution to this, a lot of existing plugins depend on 5471// $animate to either call the callback (< 1.2) or return a promise 5472// that can be changed. This helper function ensures that the options 5473// are wiped clean incase a callback function is provided. 5474function prepareAnimateOptions(options) { 5475 return isObject(options) 5476 ? options 5477 : {}; 5478} 5479 5480var $$CoreAnimateJsProvider = /** @this */ function() { 5481 this.$get = noop; 5482}; 5483 5484// this is prefixed with Core since it conflicts with 5485// the animateQueueProvider defined in ngAnimate/animateQueue.js 5486var $$CoreAnimateQueueProvider = /** @this */ function() { 5487 var postDigestQueue = new NgMap(); 5488 var postDigestElements = []; 5489 5490 this.$get = ['$$AnimateRunner', '$rootScope', 5491 function($$AnimateRunner, $rootScope) { 5492 return { 5493 enabled: noop, 5494 on: noop, 5495 off: noop, 5496 pin: noop, 5497 5498 push: function(element, event, options, domOperation) { 5499 if (domOperation) { 5500 domOperation(); 5501 } 5502 5503 options = options || {}; 5504 if (options.from) { 5505 element.css(options.from); 5506 } 5507 if (options.to) { 5508 element.css(options.to); 5509 } 5510 5511 if (options.addClass || options.removeClass) { 5512 addRemoveClassesPostDigest(element, options.addClass, options.removeClass); 5513 } 5514 5515 var runner = new $$AnimateRunner(); 5516 5517 // since there are no animations to run the runner needs to be 5518 // notified that the animation call is complete. 5519 runner.complete(); 5520 return runner; 5521 } 5522 }; 5523 5524 5525 function updateData(data, classes, value) { 5526 var changed = false; 5527 if (classes) { 5528 classes = isString(classes) ? classes.split(' ') : 5529 isArray(classes) ? classes : []; 5530 forEach(classes, function(className) { 5531 if (className) { 5532 changed = true; 5533 data[className] = value; 5534 } 5535 }); 5536 } 5537 return changed; 5538 } 5539 5540 function handleCSSClassChanges() { 5541 forEach(postDigestElements, function(element) { 5542 var data = postDigestQueue.get(element); 5543 if (data) { 5544 var existing = splitClasses(element.attr('class')); 5545 var toAdd = ''; 5546 var toRemove = ''; 5547 forEach(data, function(status, className) { 5548 var hasClass = !!existing[className]; 5549 if (status !== hasClass) { 5550 if (status) { 5551 toAdd += (toAdd.length ? ' ' : '') + className; 5552 } else { 5553 toRemove += (toRemove.length ? ' ' : '') + className; 5554 } 5555 } 5556 }); 5557 5558 forEach(element, function(elm) { 5559 if (toAdd) { 5560 jqLiteAddClass(elm, toAdd); 5561 } 5562 if (toRemove) { 5563 jqLiteRemoveClass(elm, toRemove); 5564 } 5565 }); 5566 postDigestQueue.delete(element); 5567 } 5568 }); 5569 postDigestElements.length = 0; 5570 } 5571 5572 5573 function addRemoveClassesPostDigest(element, add, remove) { 5574 var data = postDigestQueue.get(element) || {}; 5575 5576 var classesAdded = updateData(data, add, true); 5577 var classesRemoved = updateData(data, remove, false); 5578 5579 if (classesAdded || classesRemoved) { 5580 5581 postDigestQueue.set(element, data); 5582 postDigestElements.push(element); 5583 5584 if (postDigestElements.length === 1) { 5585 $rootScope.$$postDigest(handleCSSClassChanges); 5586 } 5587 } 5588 } 5589 }]; 5590}; 5591 5592/** 5593 * @ngdoc provider 5594 * @name $animateProvider 5595 * 5596 * @description 5597 * Default implementation of $animate that doesn't perform any animations, instead just 5598 * synchronously performs DOM updates and resolves the returned runner promise. 5599 * 5600 * In order to enable animations the `ngAnimate` module has to be loaded. 5601 * 5602 * To see the functional implementation check out `src/ngAnimate/animate.js`. 5603 */ 5604var $AnimateProvider = ['$provide', /** @this */ function($provide) { 5605 var provider = this; 5606 var classNameFilter = null; 5607 var customFilter = null; 5608 5609 this.$$registeredAnimations = Object.create(null); 5610 5611 /** 5612 * @ngdoc method 5613 * @name $animateProvider#register 5614 * 5615 * @description 5616 * Registers a new injectable animation factory function. The factory function produces the 5617 * animation object which contains callback functions for each event that is expected to be 5618 * animated. 5619 * 5620 * * `eventFn`: `function(element, ... , doneFunction, options)` 5621 * The element to animate, the `doneFunction` and the options fed into the animation. Depending 5622 * on the type of animation additional arguments will be injected into the animation function. The 5623 * list below explains the function signatures for the different animation methods: 5624 * 5625 * - setClass: function(element, addedClasses, removedClasses, doneFunction, options) 5626 * - addClass: function(element, addedClasses, doneFunction, options) 5627 * - removeClass: function(element, removedClasses, doneFunction, options) 5628 * - enter, leave, move: function(element, doneFunction, options) 5629 * - animate: function(element, fromStyles, toStyles, doneFunction, options) 5630 * 5631 * Make sure to trigger the `doneFunction` once the animation is fully complete. 5632 * 5633 * ```js 5634 * return { 5635 * //enter, leave, move signature 5636 * eventFn : function(element, done, options) { 5637 * //code to run the animation 5638 * //once complete, then run done() 5639 * return function endFunction(wasCancelled) { 5640 * //code to cancel the animation 5641 * } 5642 * } 5643 * } 5644 * ``` 5645 * 5646 * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to). 5647 * @param {Function} factory The factory function that will be executed to return the animation 5648 * object. 5649 */ 5650 this.register = function(name, factory) { 5651 if (name && name.charAt(0) !== '.') { 5652 throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name); 5653 } 5654 5655 var key = name + '-animation'; 5656 provider.$$registeredAnimations[name.substr(1)] = key; 5657 $provide.factory(key, factory); 5658 }; 5659 5660 /** 5661 * @ngdoc method 5662 * @name $animateProvider#customFilter 5663 * 5664 * @description 5665 * Sets and/or returns the custom filter function that is used to "filter" animations, i.e. 5666 * determine if an animation is allowed or not. When no filter is specified (the default), no 5667 * animation will be blocked. Setting the `customFilter` value will only allow animations for 5668 * which the filter function's return value is truthy. 5669 * 5670 * This allows to easily create arbitrarily complex rules for filtering animations, such as 5671 * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc. 5672 * Filtering animations can also boost performance for low-powered devices, as well as 5673 * applications containing a lot of structural operations. 5674 * 5675 * <div class="alert alert-success"> 5676 * **Best Practice:** 5677 * Keep the filtering function as lean as possible, because it will be called for each DOM 5678 * action (e.g. insertion, removal, class change) performed by "animation-aware" directives. 5679 * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in 5680 * directives that support animations. 5681 * Performing computationally expensive or time-consuming operations on each call of the 5682 * filtering function can make your animations sluggish. 5683 * </div> 5684 * 5685 * **Note:** If present, `customFilter` will be checked before 5686 * {@link $animateProvider#classNameFilter classNameFilter}. 5687 * 5688 * @param {Function=} filterFn - The filter function which will be used to filter all animations. 5689 * If a falsy value is returned, no animation will be performed. The function will be called 5690 * with the following arguments: 5691 * - **node** `{DOMElement}` - The DOM element to be animated. 5692 * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass` 5693 * etc). 5694 * - **options** `{Object}` - A collection of options/styles used for the animation. 5695 * @return {Function} The current filter function or `null` if there is none set. 5696 */ 5697 this.customFilter = function(filterFn) { 5698 if (arguments.length === 1) { 5699 customFilter = isFunction(filterFn) ? filterFn : null; 5700 } 5701 5702 return customFilter; 5703 }; 5704 5705 /** 5706 * @ngdoc method 5707 * @name $animateProvider#classNameFilter 5708 * 5709 * @description 5710 * Sets and/or returns the CSS class regular expression that is checked when performing 5711 * an animation. Upon bootstrap the classNameFilter value is not set at all and will 5712 * therefore enable $animate to attempt to perform an animation on any element that is triggered. 5713 * When setting the `classNameFilter` value, animations will only be performed on elements 5714 * that successfully match the filter expression. This in turn can boost performance 5715 * for low-powered devices as well as applications containing a lot of structural operations. 5716 * 5717 * **Note:** If present, `classNameFilter` will be checked after 5718 * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns 5719 * false, `classNameFilter` will not be checked. 5720 * 5721 * @param {RegExp=} expression The className expression which will be checked against all animations 5722 * @return {RegExp} The current CSS className expression value. If null then there is no expression value 5723 */ 5724 this.classNameFilter = function(expression) { 5725 if (arguments.length === 1) { 5726 classNameFilter = (expression instanceof RegExp) ? expression : null; 5727 if (classNameFilter) { 5728 var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]'); 5729 if (reservedRegex.test(classNameFilter.toString())) { 5730 classNameFilter = null; 5731 throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME); 5732 } 5733 } 5734 } 5735 return classNameFilter; 5736 }; 5737 5738 this.$get = ['$$animateQueue', function($$animateQueue) { 5739 function domInsert(element, parentElement, afterElement) { 5740 // if for some reason the previous element was removed 5741 // from the dom sometime before this code runs then let's 5742 // just stick to using the parent element as the anchor 5743 if (afterElement) { 5744 var afterNode = extractElementNode(afterElement); 5745 if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) { 5746 afterElement = null; 5747 } 5748 } 5749 if (afterElement) { 5750 afterElement.after(element); 5751 } else { 5752 parentElement.prepend(element); 5753 } 5754 } 5755 5756 /** 5757 * @ngdoc service 5758 * @name $animate 5759 * @description The $animate service exposes a series of DOM utility methods that provide support 5760 * for animation hooks. The default behavior is the application of DOM operations, however, 5761 * when an animation is detected (and animations are enabled), $animate will do the heavy lifting 5762 * to ensure that animation runs with the triggered DOM operation. 5763 * 5764 * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't 5765 * included and only when it is active then the animation hooks that `$animate` triggers will be 5766 * functional. Once active then all structural `ng-` directives will trigger animations as they perform 5767 * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`, 5768 * `ngShow`, `ngHide` and `ngMessages` also provide support for animations. 5769 * 5770 * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives. 5771 * 5772 * To learn more about enabling animation support, click here to visit the 5773 * {@link ngAnimate ngAnimate module page}. 5774 */ 5775 return { 5776 // we don't call it directly since non-existant arguments may 5777 // be interpreted as null within the sub enabled function 5778 5779 /** 5780 * 5781 * @ngdoc method 5782 * @name $animate#on 5783 * @kind function 5784 * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...) 5785 * has fired on the given element or among any of its children. Once the listener is fired, the provided callback 5786 * is fired with the following params: 5787 * 5788 * ```js 5789 * $animate.on('enter', container, 5790 * function callback(element, phase) { 5791 * // cool we detected an enter animation within the container 5792 * } 5793 * ); 5794 * ``` 5795 * 5796 * <div class="alert alert-warning"> 5797 * **Note**: Generally, the events that are fired correspond 1:1 to `$animate` method names, 5798 * e.g. {@link ng.$animate#addClass addClass()} will fire `addClass`, and {@link ng.ngClass} 5799 * will fire `addClass` if classes are added, and `removeClass` if classes are removed. 5800 * However, there are two exceptions: 5801 * 5802 * <ul> 5803 * <li>if both an {@link ng.$animate#addClass addClass()} and a 5804 * {@link ng.$animate#removeClass removeClass()} action are performed during the same 5805 * animation, the event fired will be `setClass`. This is true even for `ngClass`.</li> 5806 * <li>an {@link ng.$animate#animate animate()} call that adds and removes classes will fire 5807 * the `setClass` event, but if it either removes or adds classes, 5808 * it will fire `animate` instead.</li> 5809 * </ul> 5810 * 5811 * </div> 5812 * 5813 * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...) 5814 * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself 5815 * as well as among its children 5816 * @param {Function} callback the callback function that will be fired when the listener is triggered. 5817 * 5818 * The arguments present in the callback function are: 5819 * * `element` - The captured DOM element that the animation was fired on. 5820 * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends). 5821 * * `data` - an object with these properties: 5822 * * addClass - `{string|null}` - space-separated CSS classes to add to the element 5823 * * removeClass - `{string|null}` - space-separated CSS classes to remove from the element 5824 * * from - `{Object|null}` - CSS properties & values at the beginning of the animation 5825 * * to - `{Object|null}` - CSS properties & values at the end of the animation 5826 * 5827 * Note that the callback does not trigger a scope digest. Wrap your call into a 5828 * {@link $rootScope.Scope#$apply scope.$apply} to propagate changes to the scope. 5829 */ 5830 on: $$animateQueue.on, 5831 5832 /** 5833 * 5834 * @ngdoc method 5835 * @name $animate#off 5836 * @kind function 5837 * @description Deregisters an event listener based on the event which has been associated with the provided element. This method 5838 * can be used in three different ways depending on the arguments: 5839 * 5840 * ```js 5841 * // remove all the animation event listeners listening for `enter` 5842 * $animate.off('enter'); 5843 * 5844 * // remove listeners for all animation events from the container element 5845 * $animate.off(container); 5846 * 5847 * // remove all the animation event listeners listening for `enter` on the given element and its children 5848 * $animate.off('enter', container); 5849 * 5850 * // remove the event listener function provided by `callback` that is set 5851 * // to listen for `enter` on the given `container` as well as its children 5852 * $animate.off('enter', container, callback); 5853 * ``` 5854 * 5855 * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move, 5856 * addClass, removeClass, etc...), or the container element. If it is the element, all other 5857 * arguments are ignored. 5858 * @param {DOMElement=} container the container element the event listener was placed on 5859 * @param {Function=} callback the callback function that was registered as the listener 5860 */ 5861 off: $$animateQueue.off, 5862 5863 /** 5864 * @ngdoc method 5865 * @name $animate#pin 5866 * @kind function 5867 * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists 5868 * outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the 5869 * element despite being outside the realm of the application or within another application. Say for example if the application 5870 * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated 5871 * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind 5872 * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association. 5873 * 5874 * Note that this feature is only active when the `ngAnimate` module is used. 5875 * 5876 * @param {DOMElement} element the external element that will be pinned 5877 * @param {DOMElement} parentElement the host parent element that will be associated with the external element 5878 */ 5879 pin: $$animateQueue.pin, 5880 5881 /** 5882 * 5883 * @ngdoc method 5884 * @name $animate#enabled 5885 * @kind function 5886 * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This 5887 * function can be called in four ways: 5888 * 5889 * ```js 5890 * // returns true or false 5891 * $animate.enabled(); 5892 * 5893 * // changes the enabled state for all animations 5894 * $animate.enabled(false); 5895 * $animate.enabled(true); 5896 * 5897 * // returns true or false if animations are enabled for an element 5898 * $animate.enabled(element); 5899 * 5900 * // changes the enabled state for an element and its children 5901 * $animate.enabled(element, true); 5902 * $animate.enabled(element, false); 5903 * ``` 5904 * 5905 * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state 5906 * @param {boolean=} enabled whether or not the animations will be enabled for the element 5907 * 5908 * @return {boolean} whether or not animations are enabled 5909 */ 5910 enabled: $$animateQueue.enabled, 5911 5912 /** 5913 * @ngdoc method 5914 * @name $animate#cancel 5915 * @kind function 5916 * @description Cancels the provided animation and applies the end state of the animation. 5917 * Note that this does not cancel the underlying operation, e.g. the setting of classes or 5918 * adding the element to the DOM. 5919 * 5920 * @param {animationRunner} animationRunner An animation runner returned by an $animate function. 5921 * 5922 * @example 5923 <example module="animationExample" deps="angular-animate.js" animations="true" name="animate-cancel"> 5924 <file name="app.js"> 5925 angular.module('animationExample', ['ngAnimate']).component('cancelExample', { 5926 templateUrl: 'template.html', 5927 controller: function($element, $animate) { 5928 this.runner = null; 5929 5930 this.addClass = function() { 5931 this.runner = $animate.addClass($element.find('div'), 'red'); 5932 var ctrl = this; 5933 this.runner.finally(function() { 5934 ctrl.runner = null; 5935 }); 5936 }; 5937 5938 this.removeClass = function() { 5939 this.runner = $animate.removeClass($element.find('div'), 'red'); 5940 var ctrl = this; 5941 this.runner.finally(function() { 5942 ctrl.runner = null; 5943 }); 5944 }; 5945 5946 this.cancel = function() { 5947 $animate.cancel(this.runner); 5948 }; 5949 } 5950 }); 5951 </file> 5952 <file name="template.html"> 5953 <p> 5954 <button id="add" ng-click="$ctrl.addClass()">Add</button> 5955 <button ng-click="$ctrl.removeClass()">Remove</button> 5956 <br> 5957 <button id="cancel" ng-click="$ctrl.cancel()" ng-disabled="!$ctrl.runner">Cancel</button> 5958 <br> 5959 <div id="target">CSS-Animated Text</div> 5960 </p> 5961 </file> 5962 <file name="index.html"> 5963 <cancel-example></cancel-example> 5964 </file> 5965 <file name="style.css"> 5966 .red-add, .red-remove { 5967 transition: all 4s cubic-bezier(0.250, 0.460, 0.450, 0.940); 5968 } 5969 5970 .red, 5971 .red-add.red-add-active { 5972 color: #FF0000; 5973 font-size: 40px; 5974 } 5975 5976 .red-remove.red-remove-active { 5977 font-size: 10px; 5978 color: black; 5979 } 5980 5981 </file> 5982 </example> 5983 */ 5984 cancel: function(runner) { 5985 if (runner.cancel) { 5986 runner.cancel(); 5987 } 5988 }, 5989 5990 /** 5991 * 5992 * @ngdoc method 5993 * @name $animate#enter 5994 * @kind function 5995 * @description Inserts the element into the DOM either after the `after` element (if provided) or 5996 * as the first child within the `parent` element and then triggers an animation. 5997 * A promise is returned that will be resolved during the next digest once the animation 5998 * has completed. 5999 * 6000 * @param {DOMElement} element the element which will be inserted into the DOM 6001 * @param {DOMElement} parent the parent element which will append the element as 6002 * a child (so long as the after element is not present) 6003 * @param {DOMElement=} after the sibling element after which the element will be appended 6004 * @param {object=} options an optional collection of options/styles that will be applied to the element. 6005 * The object can have the following properties: 6006 * 6007 * - **addClass** - `{string}` - space-separated CSS classes to add to element 6008 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 6009 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 6010 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 6011 * 6012 * @return {Runner} the animation runner 6013 */ 6014 enter: function(element, parent, after, options) { 6015 parent = parent && jqLite(parent); 6016 after = after && jqLite(after); 6017 parent = parent || after.parent(); 6018 domInsert(element, parent, after); 6019 return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options)); 6020 }, 6021 6022 /** 6023 * 6024 * @ngdoc method 6025 * @name $animate#move 6026 * @kind function 6027 * @description Inserts (moves) the element into its new position in the DOM either after 6028 * the `after` element (if provided) or as the first child within the `parent` element 6029 * and then triggers an animation. A promise is returned that will be resolved 6030 * during the next digest once the animation has completed. 6031 * 6032 * @param {DOMElement} element the element which will be moved into the new DOM position 6033 * @param {DOMElement} parent the parent element which will append the element as 6034 * a child (so long as the after element is not present) 6035 * @param {DOMElement=} after the sibling element after which the element will be appended 6036 * @param {object=} options an optional collection of options/styles that will be applied to the element. 6037 * The object can have the following properties: 6038 * 6039 * - **addClass** - `{string}` - space-separated CSS classes to add to element 6040 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 6041 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 6042 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 6043 * 6044 * @return {Runner} the animation runner 6045 */ 6046 move: function(element, parent, after, options) { 6047 parent = parent && jqLite(parent); 6048 after = after && jqLite(after); 6049 parent = parent || after.parent(); 6050 domInsert(element, parent, after); 6051 return $$animateQueue.push(element, 'move', prepareAnimateOptions(options)); 6052 }, 6053 6054 /** 6055 * @ngdoc method 6056 * @name $animate#leave 6057 * @kind function 6058 * @description Triggers an animation and then removes the element from the DOM. 6059 * When the function is called a promise is returned that will be resolved during the next 6060 * digest once the animation has completed. 6061 * 6062 * @param {DOMElement} element the element which will be removed from the DOM 6063 * @param {object=} options an optional collection of options/styles that will be applied to the element. 6064 * The object can have the following properties: 6065 * 6066 * - **addClass** - `{string}` - space-separated CSS classes to add to element 6067 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 6068 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 6069 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 6070 * 6071 * @return {Runner} the animation runner 6072 */ 6073 leave: function(element, options) { 6074 return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() { 6075 element.remove(); 6076 }); 6077 }, 6078 6079 /** 6080 * @ngdoc method 6081 * @name $animate#addClass 6082 * @kind function 6083 * 6084 * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon 6085 * execution, the addClass operation will only be handled after the next digest and it will not trigger an 6086 * animation if element already contains the CSS class or if the class is removed at a later step. 6087 * Note that class-based animations are treated differently compared to structural animations 6088 * (like enter, move and leave) since the CSS classes may be added/removed at different points 6089 * depending if CSS or JavaScript animations are used. 6090 * 6091 * @param {DOMElement} element the element which the CSS classes will be applied to 6092 * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces) 6093 * @param {object=} options an optional collection of options/styles that will be applied to the element. 6094 * The object can have the following properties: 6095 * 6096 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 6097 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 6098 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 6099 * 6100 * @return {Runner} animationRunner the animation runner 6101 */ 6102 addClass: function(element, className, options) { 6103 options = prepareAnimateOptions(options); 6104 options.addClass = mergeClasses(options.addclass, className); 6105 return $$animateQueue.push(element, 'addClass', options); 6106 }, 6107 6108 /** 6109 * @ngdoc method 6110 * @name $animate#removeClass 6111 * @kind function 6112 * 6113 * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon 6114 * execution, the removeClass operation will only be handled after the next digest and it will not trigger an 6115 * animation if element does not contain the CSS class or if the class is added at a later step. 6116 * Note that class-based animations are treated differently compared to structural animations 6117 * (like enter, move and leave) since the CSS classes may be added/removed at different points 6118 * depending if CSS or JavaScript animations are used. 6119 * 6120 * @param {DOMElement} element the element which the CSS classes will be applied to 6121 * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces) 6122 * @param {object=} options an optional collection of options/styles that will be applied to the element. 6123 * The object can have the following properties: 6124 * 6125 * - **addClass** - `{string}` - space-separated CSS classes to add to element 6126 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 6127 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 6128 * 6129 * @return {Runner} the animation runner 6130 */ 6131 removeClass: function(element, className, options) { 6132 options = prepareAnimateOptions(options); 6133 options.removeClass = mergeClasses(options.removeClass, className); 6134 return $$animateQueue.push(element, 'removeClass', options); 6135 }, 6136 6137 /** 6138 * @ngdoc method 6139 * @name $animate#setClass 6140 * @kind function 6141 * 6142 * @description Performs both the addition and removal of a CSS classes on an element and (during the process) 6143 * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and 6144 * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has 6145 * passed. Note that class-based animations are treated differently compared to structural animations 6146 * (like enter, move and leave) since the CSS classes may be added/removed at different points 6147 * depending if CSS or JavaScript animations are used. 6148 * 6149 * @param {DOMElement} element the element which the CSS classes will be applied to 6150 * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces) 6151 * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces) 6152 * @param {object=} options an optional collection of options/styles that will be applied to the element. 6153 * The object can have the following properties: 6154 * 6155 * - **addClass** - `{string}` - space-separated CSS classes to add to element 6156 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 6157 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 6158 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 6159 * 6160 * @return {Runner} the animation runner 6161 */ 6162 setClass: function(element, add, remove, options) { 6163 options = prepareAnimateOptions(options); 6164 options.addClass = mergeClasses(options.addClass, add); 6165 options.removeClass = mergeClasses(options.removeClass, remove); 6166 return $$animateQueue.push(element, 'setClass', options); 6167 }, 6168 6169 /** 6170 * @ngdoc method 6171 * @name $animate#animate 6172 * @kind function 6173 * 6174 * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element. 6175 * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take 6176 * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and 6177 * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding 6178 * style in `to`, the style in `from` is applied immediately, and no animation is run. 6179 * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate` 6180 * method (or as part of the `options` parameter): 6181 * 6182 * ```js 6183 * ngModule.animation('.my-inline-animation', function() { 6184 * return { 6185 * animate : function(element, from, to, done, options) { 6186 * //animation 6187 * done(); 6188 * } 6189 * } 6190 * }); 6191 * ``` 6192 * 6193 * @param {DOMElement} element the element which the CSS styles will be applied to 6194 * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation. 6195 * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation. 6196 * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If 6197 * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element. 6198 * (Note that if no animation is detected then this value will not be applied to the element.) 6199 * @param {object=} options an optional collection of options/styles that will be applied to the element. 6200 * The object can have the following properties: 6201 * 6202 * - **addClass** - `{string}` - space-separated CSS classes to add to element 6203 * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` 6204 * - **removeClass** - `{string}` - space-separated CSS classes to remove from element 6205 * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` 6206 * 6207 * @return {Runner} the animation runner 6208 */ 6209 animate: function(element, from, to, className, options) { 6210 options = prepareAnimateOptions(options); 6211 options.from = options.from ? extend(options.from, from) : from; 6212 options.to = options.to ? extend(options.to, to) : to; 6213 6214 className = className || 'ng-inline-animate'; 6215 options.tempClasses = mergeClasses(options.tempClasses, className); 6216 return $$animateQueue.push(element, 'animate', options); 6217 } 6218 }; 6219 }]; 6220}]; 6221 6222var $$AnimateAsyncRunFactoryProvider = /** @this */ function() { 6223 this.$get = ['$$rAF', function($$rAF) { 6224 var waitQueue = []; 6225 6226 function waitForTick(fn) { 6227 waitQueue.push(fn); 6228 if (waitQueue.length > 1) return; 6229 $$rAF(function() { 6230 for (var i = 0; i < waitQueue.length; i++) { 6231 waitQueue[i](); 6232 } 6233 waitQueue = []; 6234 }); 6235 } 6236 6237 return function() { 6238 var passed = false; 6239 waitForTick(function() { 6240 passed = true; 6241 }); 6242 return function(callback) { 6243 if (passed) { 6244 callback(); 6245 } else { 6246 waitForTick(callback); 6247 } 6248 }; 6249 }; 6250 }]; 6251}; 6252 6253var $$AnimateRunnerFactoryProvider = /** @this */ function() { 6254 this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout', 6255 function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) { 6256 6257 var INITIAL_STATE = 0; 6258 var DONE_PENDING_STATE = 1; 6259 var DONE_COMPLETE_STATE = 2; 6260 6261 AnimateRunner.chain = function(chain, callback) { 6262 var index = 0; 6263 6264 next(); 6265 function next() { 6266 if (index === chain.length) { 6267 callback(true); 6268 return; 6269 } 6270 6271 chain[index](function(response) { 6272 if (response === false) { 6273 callback(false); 6274 return; 6275 } 6276 index++; 6277 next(); 6278 }); 6279 } 6280 }; 6281 6282 AnimateRunner.all = function(runners, callback) { 6283 var count = 0; 6284 var status = true; 6285 forEach(runners, function(runner) { 6286 runner.done(onProgress); 6287 }); 6288 6289 function onProgress(response) { 6290 status = status && response; 6291 if (++count === runners.length) { 6292 callback(status); 6293 } 6294 } 6295 }; 6296 6297 function AnimateRunner(host) { 6298 this.setHost(host); 6299 6300 var rafTick = $$animateAsyncRun(); 6301 var timeoutTick = function(fn) { 6302 $timeout(fn, 0, false); 6303 }; 6304 6305 this._doneCallbacks = []; 6306 this._tick = function(fn) { 6307 if ($$isDocumentHidden()) { 6308 timeoutTick(fn); 6309 } else { 6310 rafTick(fn); 6311 } 6312 }; 6313 this._state = 0; 6314 } 6315 6316 AnimateRunner.prototype = { 6317 setHost: function(host) { 6318 this.host = host || {}; 6319 }, 6320 6321 done: function(fn) { 6322 if (this._state === DONE_COMPLETE_STATE) { 6323 fn(); 6324 } else { 6325 this._doneCallbacks.push(fn); 6326 } 6327 }, 6328 6329 progress: noop, 6330 6331 getPromise: function() { 6332 if (!this.promise) { 6333 var self = this; 6334 this.promise = $q(function(resolve, reject) { 6335 self.done(function(status) { 6336 if (status === false) { 6337 reject(); 6338 } else { 6339 resolve(); 6340 } 6341 }); 6342 }); 6343 } 6344 return this.promise; 6345 }, 6346 6347 then: function(resolveHandler, rejectHandler) { 6348 return this.getPromise().then(resolveHandler, rejectHandler); 6349 }, 6350 6351 'catch': function(handler) { 6352 return this.getPromise()['catch'](handler); 6353 }, 6354 6355 'finally': function(handler) { 6356 return this.getPromise()['finally'](handler); 6357 }, 6358 6359 pause: function() { 6360 if (this.host.pause) { 6361 this.host.pause(); 6362 } 6363 }, 6364 6365 resume: function() { 6366 if (this.host.resume) { 6367 this.host.resume(); 6368 } 6369 }, 6370 6371 end: function() { 6372 if (this.host.end) { 6373 this.host.end(); 6374 } 6375 this._resolve(true); 6376 }, 6377 6378 cancel: function() { 6379 if (this.host.cancel) { 6380 this.host.cancel(); 6381 } 6382 this._resolve(false); 6383 }, 6384 6385 complete: function(response) { 6386 var self = this; 6387 if (self._state === INITIAL_STATE) { 6388 self._state = DONE_PENDING_STATE; 6389 self._tick(function() { 6390 self._resolve(response); 6391 }); 6392 } 6393 }, 6394 6395 _resolve: function(response) { 6396 if (this._state !== DONE_COMPLETE_STATE) { 6397 forEach(this._doneCallbacks, function(fn) { 6398 fn(response); 6399 }); 6400 this._doneCallbacks.length = 0; 6401 this._state = DONE_COMPLETE_STATE; 6402 } 6403 } 6404 }; 6405 6406 return AnimateRunner; 6407 }]; 6408}; 6409 6410/* exported $CoreAnimateCssProvider */ 6411 6412/** 6413 * @ngdoc service 6414 * @name $animateCss 6415 * @kind object 6416 * @this 6417 * 6418 * @description 6419 * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included, 6420 * then the `$animateCss` service will actually perform animations. 6421 * 6422 * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}. 6423 */ 6424var $CoreAnimateCssProvider = function() { 6425 this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) { 6426 6427 return function(element, initialOptions) { 6428 // all of the animation functions should create 6429 // a copy of the options data, however, if a 6430 // parent service has already created a copy then 6431 // we should stick to using that 6432 var options = initialOptions || {}; 6433 if (!options.$$prepared) { 6434 options = copy(options); 6435 } 6436 6437 // there is no point in applying the styles since 6438 // there is no animation that goes on at all in 6439 // this version of $animateCss. 6440 if (options.cleanupStyles) { 6441 options.from = options.to = null; 6442 } 6443 6444 if (options.from) { 6445 element.css(options.from); 6446 options.from = null; 6447 } 6448 6449 var closed, runner = new $$AnimateRunner(); 6450 return { 6451 start: run, 6452 end: run 6453 }; 6454 6455 function run() { 6456 $$rAF(function() { 6457 applyAnimationContents(); 6458 if (!closed) { 6459 runner.complete(); 6460 } 6461 closed = true; 6462 }); 6463 return runner; 6464 } 6465 6466 function applyAnimationContents() { 6467 if (options.addClass) { 6468 element.addClass(options.addClass); 6469 options.addClass = null; 6470 } 6471 if (options.removeClass) { 6472 element.removeClass(options.removeClass); 6473 options.removeClass = null; 6474 } 6475 if (options.to) { 6476 element.css(options.to); 6477 options.to = null; 6478 } 6479 } 6480 }; 6481 }]; 6482}; 6483 6484/* global getHash: true, stripHash: false */ 6485 6486function getHash(url) { 6487 var index = url.indexOf('#'); 6488 return index === -1 ? '' : url.substr(index); 6489} 6490 6491function trimEmptyHash(url) { 6492 return url.replace(/#$/, ''); 6493} 6494 6495/** 6496 * ! This is a private undocumented service ! 6497 * 6498 * @name $browser 6499 * @requires $log 6500 * @description 6501 * This object has two goals: 6502 * 6503 * - hide all the global state in the browser caused by the window object 6504 * - abstract away all the browser specific features and inconsistencies 6505 * 6506 * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` 6507 * service, which can be used for convenient testing of the application without the interaction with 6508 * the real browser apis. 6509 */ 6510/** 6511 * @param {object} window The global window object. 6512 * @param {object} document jQuery wrapped document. 6513 * @param {object} $log window.console or an object with the same interface. 6514 * @param {object} $sniffer $sniffer service 6515 */ 6516function Browser(window, document, $log, $sniffer, $$taskTrackerFactory) { 6517 var self = this, 6518 location = window.location, 6519 history = window.history, 6520 setTimeout = window.setTimeout, 6521 clearTimeout = window.clearTimeout, 6522 pendingDeferIds = {}, 6523 taskTracker = $$taskTrackerFactory($log); 6524 6525 self.isMock = false; 6526 6527 ////////////////////////////////////////////////////////////// 6528 // Task-tracking API 6529 ////////////////////////////////////////////////////////////// 6530 6531 // TODO(vojta): remove this temporary api 6532 self.$$completeOutstandingRequest = taskTracker.completeTask; 6533 self.$$incOutstandingRequestCount = taskTracker.incTaskCount; 6534 6535 // TODO(vojta): prefix this method with $$ ? 6536 self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks; 6537 6538 ////////////////////////////////////////////////////////////// 6539 // URL API 6540 ////////////////////////////////////////////////////////////// 6541 6542 var cachedState, lastHistoryState, 6543 lastBrowserUrl = location.href, 6544 baseElement = document.find('base'), 6545 pendingLocation = null, 6546 getCurrentState = !$sniffer.history ? noop : function getCurrentState() { 6547 try { 6548 return history.state; 6549 } catch (e) { 6550 // MSIE can reportedly throw when there is no state (UNCONFIRMED). 6551 } 6552 }; 6553 6554 cacheState(); 6555 6556 /** 6557 * @name $browser#url 6558 * 6559 * @description 6560 * GETTER: 6561 * Without any argument, this method just returns current value of `location.href` (with a 6562 * trailing `#` stripped of if the hash is empty). 6563 * 6564 * SETTER: 6565 * With at least one argument, this method sets url to new value. 6566 * If html5 history api supported, `pushState`/`replaceState` is used, otherwise 6567 * `location.href`/`location.replace` is used. 6568 * Returns its own instance to allow chaining. 6569 * 6570 * NOTE: this api is intended for use only by the `$location` service. Please use the 6571 * {@link ng.$location $location service} to change url. 6572 * 6573 * @param {string} url New url (when used as setter) 6574 * @param {boolean=} replace Should new url replace current history record? 6575 * @param {object=} state State object to use with `pushState`/`replaceState` 6576 */ 6577 self.url = function(url, replace, state) { 6578 // In modern browsers `history.state` is `null` by default; treating it separately 6579 // from `undefined` would cause `$browser.url('/foo')` to change `history.state` 6580 // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. 6581 if (isUndefined(state)) { 6582 state = null; 6583 } 6584 6585 // Android Browser BFCache causes location, history reference to become stale. 6586 if (location !== window.location) location = window.location; 6587 if (history !== window.history) history = window.history; 6588 6589 // setter 6590 if (url) { 6591 var sameState = lastHistoryState === state; 6592 6593 // Don't change anything if previous and current URLs and states match. This also prevents 6594 // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. 6595 // See https://github.com/angular/angular.js/commit/ffb2701 6596 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { 6597 return self; 6598 } 6599 var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); 6600 lastBrowserUrl = url; 6601 lastHistoryState = state; 6602 // Don't use history API if only the hash changed 6603 // due to a bug in IE10/IE11 which leads 6604 // to not firing a `hashchange` nor `popstate` event 6605 // in some cases (see #9143). 6606 if ($sniffer.history && (!sameBase || !sameState)) { 6607 history[replace ? 'replaceState' : 'pushState'](state, '', url); 6608 cacheState(); 6609 } else { 6610 if (!sameBase) { 6611 pendingLocation = url; 6612 } 6613 if (replace) { 6614 location.replace(url); 6615 } else if (!sameBase) { 6616 location.href = url; 6617 } else { 6618 location.hash = getHash(url); 6619 } 6620 if (location.href !== url) { 6621 pendingLocation = url; 6622 } 6623 } 6624 if (pendingLocation) { 6625 pendingLocation = url; 6626 } 6627 return self; 6628 // getter 6629 } else { 6630 // - pendingLocation is needed as browsers don't allow to read out 6631 // the new location.href if a reload happened or if there is a bug like in iOS 9 (see 6632 // https://openradar.appspot.com/22186109). 6633 return trimEmptyHash(pendingLocation || location.href); 6634 } 6635 }; 6636 6637 /** 6638 * @name $browser#state 6639 * 6640 * @description 6641 * This method is a getter. 6642 * 6643 * Return history.state or null if history.state is undefined. 6644 * 6645 * @returns {object} state 6646 */ 6647 self.state = function() { 6648 return cachedState; 6649 }; 6650 6651 var urlChangeListeners = [], 6652 urlChangeInit = false; 6653 6654 function cacheStateAndFireUrlChange() { 6655 pendingLocation = null; 6656 fireStateOrUrlChange(); 6657 } 6658 6659 // This variable should be used *only* inside the cacheState function. 6660 var lastCachedState = null; 6661 function cacheState() { 6662 // This should be the only place in $browser where `history.state` is read. 6663 cachedState = getCurrentState(); 6664 cachedState = isUndefined(cachedState) ? null : cachedState; 6665 6666 // Prevent callbacks fo fire twice if both hashchange & popstate were fired. 6667 if (equals(cachedState, lastCachedState)) { 6668 cachedState = lastCachedState; 6669 } 6670 6671 lastCachedState = cachedState; 6672 lastHistoryState = cachedState; 6673 } 6674 6675 function fireStateOrUrlChange() { 6676 var prevLastHistoryState = lastHistoryState; 6677 cacheState(); 6678 6679 if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) { 6680 return; 6681 } 6682 6683 lastBrowserUrl = self.url(); 6684 lastHistoryState = cachedState; 6685 forEach(urlChangeListeners, function(listener) { 6686 listener(self.url(), cachedState); 6687 }); 6688 } 6689 6690 /** 6691 * @name $browser#onUrlChange 6692 * 6693 * @description 6694 * Register callback function that will be called, when url changes. 6695 * 6696 * It's only called when the url is changed from outside of AngularJS: 6697 * - user types different url into address bar 6698 * - user clicks on history (forward/back) button 6699 * - user clicks on a link 6700 * 6701 * It's not called when url is changed by $browser.url() method 6702 * 6703 * The listener gets called with new url as parameter. 6704 * 6705 * NOTE: this api is intended for use only by the $location service. Please use the 6706 * {@link ng.$location $location service} to monitor url changes in AngularJS apps. 6707 * 6708 * @param {function(string)} listener Listener function to be called when url changes. 6709 * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. 6710 */ 6711 self.onUrlChange = function(callback) { 6712 // TODO(vojta): refactor to use node's syntax for events 6713 if (!urlChangeInit) { 6714 // We listen on both (hashchange/popstate) when available, as some browsers don't 6715 // fire popstate when user changes the address bar and don't fire hashchange when url 6716 // changed by push/replaceState 6717 6718 // html5 history api - popstate event 6719 if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); 6720 // hashchange event 6721 jqLite(window).on('hashchange', cacheStateAndFireUrlChange); 6722 6723 urlChangeInit = true; 6724 } 6725 6726 urlChangeListeners.push(callback); 6727 return callback; 6728 }; 6729 6730 /** 6731 * @private 6732 * Remove popstate and hashchange handler from window. 6733 * 6734 * NOTE: this api is intended for use only by $rootScope. 6735 */ 6736 self.$$applicationDestroyed = function() { 6737 jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange); 6738 }; 6739 6740 /** 6741 * Checks whether the url has changed outside of AngularJS. 6742 * Needs to be exported to be able to check for changes that have been done in sync, 6743 * as hashchange/popstate events fire in async. 6744 */ 6745 self.$$checkUrlChange = fireStateOrUrlChange; 6746 6747 ////////////////////////////////////////////////////////////// 6748 // Misc API 6749 ////////////////////////////////////////////////////////////// 6750 6751 /** 6752 * @name $browser#baseHref 6753 * 6754 * @description 6755 * Returns current <base href> 6756 * (always relative - without domain) 6757 * 6758 * @returns {string} The current base href 6759 */ 6760 self.baseHref = function() { 6761 var href = baseElement.attr('href'); 6762 return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : ''; 6763 }; 6764 6765 /** 6766 * @name $browser#defer 6767 * @param {function()} fn A function, who's execution should be deferred. 6768 * @param {number=} [delay=0] Number of milliseconds to defer the function execution. 6769 * @param {string=} [taskType=DEFAULT_TASK_TYPE] The type of task that is deferred. 6770 * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. 6771 * 6772 * @description 6773 * Executes a fn asynchronously via `setTimeout(fn, delay)`. 6774 * 6775 * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using 6776 * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed 6777 * via `$browser.defer.flush()`. 6778 * 6779 */ 6780 self.defer = function(fn, delay, taskType) { 6781 var timeoutId; 6782 6783 delay = delay || 0; 6784 taskType = taskType || taskTracker.DEFAULT_TASK_TYPE; 6785 6786 taskTracker.incTaskCount(taskType); 6787 timeoutId = setTimeout(function() { 6788 delete pendingDeferIds[timeoutId]; 6789 taskTracker.completeTask(fn, taskType); 6790 }, delay); 6791 pendingDeferIds[timeoutId] = taskType; 6792 6793 return timeoutId; 6794 }; 6795 6796 6797 /** 6798 * @name $browser#defer.cancel 6799 * 6800 * @description 6801 * Cancels a deferred task identified with `deferId`. 6802 * 6803 * @param {*} deferId Token returned by the `$browser.defer` function. 6804 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully 6805 * canceled. 6806 */ 6807 self.defer.cancel = function(deferId) { 6808 if (pendingDeferIds.hasOwnProperty(deferId)) { 6809 var taskType = pendingDeferIds[deferId]; 6810 delete pendingDeferIds[deferId]; 6811 clearTimeout(deferId); 6812 taskTracker.completeTask(noop, taskType); 6813 return true; 6814 } 6815 return false; 6816 }; 6817 6818} 6819 6820/** @this */ 6821function $BrowserProvider() { 6822 this.$get = ['$window', '$log', '$sniffer', '$document', '$$taskTrackerFactory', 6823 function($window, $log, $sniffer, $document, $$taskTrackerFactory) { 6824 return new Browser($window, $document, $log, $sniffer, $$taskTrackerFactory); 6825 }]; 6826} 6827 6828/** 6829 * @ngdoc service 6830 * @name $cacheFactory 6831 * @this 6832 * 6833 * @description 6834 * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to 6835 * them. 6836 * 6837 * ```js 6838 * 6839 * var cache = $cacheFactory('cacheId'); 6840 * expect($cacheFactory.get('cacheId')).toBe(cache); 6841 * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); 6842 * 6843 * cache.put("key", "value"); 6844 * cache.put("another key", "another value"); 6845 * 6846 * // We've specified no options on creation 6847 * expect(cache.info()).toEqual({id: 'cacheId', size: 2}); 6848 * 6849 * ``` 6850 * 6851 * 6852 * @param {string} cacheId Name or id of the newly created cache. 6853 * @param {object=} options Options object that specifies the cache behavior. Properties: 6854 * 6855 * - `{number=}` `capacity` — turns the cache into LRU cache. 6856 * 6857 * @returns {object} Newly created cache object with the following set of methods: 6858 * 6859 * - `{object}` `info()` — Returns id, size, and options of cache. 6860 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns 6861 * it. 6862 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. 6863 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. 6864 * - `{void}` `removeAll()` — Removes all cached values. 6865 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. 6866 * 6867 * @example 6868 <example module="cacheExampleApp" name="cache-factory"> 6869 <file name="index.html"> 6870 <div ng-controller="CacheController"> 6871 <input ng-model="newCacheKey" placeholder="Key"> 6872 <input ng-model="newCacheValue" placeholder="Value"> 6873 <button ng-click="put(newCacheKey, newCacheValue)">Cache</button> 6874 6875 <p ng-if="keys.length">Cached Values</p> 6876 <div ng-repeat="key in keys"> 6877 <span ng-bind="key"></span> 6878 <span>: </span> 6879 <b ng-bind="cache.get(key)"></b> 6880 </div> 6881 6882 <p>Cache Info</p> 6883 <div ng-repeat="(key, value) in cache.info()"> 6884 <span ng-bind="key"></span> 6885 <span>: </span> 6886 <b ng-bind="value"></b> 6887 </div> 6888 </div> 6889 </file> 6890 <file name="script.js"> 6891 angular.module('cacheExampleApp', []). 6892 controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) { 6893 $scope.keys = []; 6894 $scope.cache = $cacheFactory('cacheId'); 6895 $scope.put = function(key, value) { 6896 if (angular.isUndefined($scope.cache.get(key))) { 6897 $scope.keys.push(key); 6898 } 6899 $scope.cache.put(key, angular.isUndefined(value) ? null : value); 6900 }; 6901 }]); 6902 </file> 6903 <file name="style.css"> 6904 p { 6905 margin: 10px 0 3px; 6906 } 6907 </file> 6908 </example> 6909 */ 6910function $CacheFactoryProvider() { 6911 6912 this.$get = function() { 6913 var caches = {}; 6914 6915 function cacheFactory(cacheId, options) { 6916 if (cacheId in caches) { 6917 throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId); 6918 } 6919 6920 var size = 0, 6921 stats = extend({}, options, {id: cacheId}), 6922 data = createMap(), 6923 capacity = (options && options.capacity) || Number.MAX_VALUE, 6924 lruHash = createMap(), 6925 freshEnd = null, 6926 staleEnd = null; 6927 6928 /** 6929 * @ngdoc type 6930 * @name $cacheFactory.Cache 6931 * 6932 * @description 6933 * A cache object used to store and retrieve data, primarily used by 6934 * {@link $templateRequest $templateRequest} and the {@link ng.directive:script script} 6935 * directive to cache templates and other data. 6936 * 6937 * ```js 6938 * angular.module('superCache') 6939 * .factory('superCache', ['$cacheFactory', function($cacheFactory) { 6940 * return $cacheFactory('super-cache'); 6941 * }]); 6942 * ``` 6943 * 6944 * Example test: 6945 * 6946 * ```js 6947 * it('should behave like a cache', inject(function(superCache) { 6948 * superCache.put('key', 'value'); 6949 * superCache.put('another key', 'another value'); 6950 * 6951 * expect(superCache.info()).toEqual({ 6952 * id: 'super-cache', 6953 * size: 2 6954 * }); 6955 * 6956 * superCache.remove('another key'); 6957 * expect(superCache.get('another key')).toBeUndefined(); 6958 * 6959 * superCache.removeAll(); 6960 * expect(superCache.info()).toEqual({ 6961 * id: 'super-cache', 6962 * size: 0 6963 * }); 6964 * })); 6965 * ``` 6966 */ 6967 return (caches[cacheId] = { 6968 6969 /** 6970 * @ngdoc method 6971 * @name $cacheFactory.Cache#put 6972 * @kind function 6973 * 6974 * @description 6975 * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be 6976 * retrieved later, and incrementing the size of the cache if the key was not already 6977 * present in the cache. If behaving like an LRU cache, it will also remove stale 6978 * entries from the set. 6979 * 6980 * It will not insert undefined values into the cache. 6981 * 6982 * @param {string} key the key under which the cached data is stored. 6983 * @param {*} value the value to store alongside the key. If it is undefined, the key 6984 * will not be stored. 6985 * @returns {*} the value stored. 6986 */ 6987 put: function(key, value) { 6988 if (isUndefined(value)) return; 6989 if (capacity < Number.MAX_VALUE) { 6990 var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); 6991 6992 refresh(lruEntry); 6993 } 6994 6995 if (!(key in data)) size++; 6996 data[key] = value; 6997 6998 if (size > capacity) { 6999 this.remove(staleEnd.key); 7000 } 7001 7002 return value; 7003 }, 7004 7005 /** 7006 * @ngdoc method 7007 * @name $cacheFactory.Cache#get 7008 * @kind function 7009 * 7010 * @description 7011 * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. 7012 * 7013 * @param {string} key the key of the data to be retrieved 7014 * @returns {*} the value stored. 7015 */ 7016 get: function(key) { 7017 if (capacity < Number.MAX_VALUE) { 7018 var lruEntry = lruHash[key]; 7019 7020 if (!lruEntry) return; 7021 7022 refresh(lruEntry); 7023 } 7024 7025 return data[key]; 7026 }, 7027 7028 7029 /** 7030 * @ngdoc method 7031 * @name $cacheFactory.Cache#remove 7032 * @kind function 7033 * 7034 * @description 7035 * Removes an entry from the {@link $cacheFactory.Cache Cache} object. 7036 * 7037 * @param {string} key the key of the entry to be removed 7038 */ 7039 remove: function(key) { 7040 if (capacity < Number.MAX_VALUE) { 7041 var lruEntry = lruHash[key]; 7042 7043 if (!lruEntry) return; 7044 7045 if (lruEntry === freshEnd) freshEnd = lruEntry.p; 7046 if (lruEntry === staleEnd) staleEnd = lruEntry.n; 7047 link(lruEntry.n,lruEntry.p); 7048 7049 delete lruHash[key]; 7050 } 7051 7052 if (!(key in data)) return; 7053 7054 delete data[key]; 7055 size--; 7056 }, 7057 7058 7059 /** 7060 * @ngdoc method 7061 * @name $cacheFactory.Cache#removeAll 7062 * @kind function 7063 * 7064 * @description 7065 * Clears the cache object of any entries. 7066 */ 7067 removeAll: function() { 7068 data = createMap(); 7069 size = 0; 7070 lruHash = createMap(); 7071 freshEnd = staleEnd = null; 7072 }, 7073 7074 7075 /** 7076 * @ngdoc method 7077 * @name $cacheFactory.Cache#destroy 7078 * @kind function 7079 * 7080 * @description 7081 * Destroys the {@link $cacheFactory.Cache Cache} object entirely, 7082 * removing it from the {@link $cacheFactory $cacheFactory} set. 7083 */ 7084 destroy: function() { 7085 data = null; 7086 stats = null; 7087 lruHash = null; 7088 delete caches[cacheId]; 7089 }, 7090 7091 7092 /** 7093 * @ngdoc method 7094 * @name $cacheFactory.Cache#info 7095 * @kind function 7096 * 7097 * @description 7098 * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. 7099 * 7100 * @returns {object} an object with the following properties: 7101 * <ul> 7102 * <li>**id**: the id of the cache instance</li> 7103 * <li>**size**: the number of entries kept in the cache instance</li> 7104 * <li>**...**: any additional properties from the options object when creating the 7105 * cache.</li> 7106 * </ul> 7107 */ 7108 info: function() { 7109 return extend({}, stats, {size: size}); 7110 } 7111 }); 7112 7113 7114 /** 7115 * makes the `entry` the freshEnd of the LRU linked list 7116 */ 7117 function refresh(entry) { 7118 if (entry !== freshEnd) { 7119 if (!staleEnd) { 7120 staleEnd = entry; 7121 } else if (staleEnd === entry) { 7122 staleEnd = entry.n; 7123 } 7124 7125 link(entry.n, entry.p); 7126 link(entry, freshEnd); 7127 freshEnd = entry; 7128 freshEnd.n = null; 7129 } 7130 } 7131 7132 7133 /** 7134 * bidirectionally links two entries of the LRU linked list 7135 */ 7136 function link(nextEntry, prevEntry) { 7137 if (nextEntry !== prevEntry) { 7138 if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify 7139 if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify 7140 } 7141 } 7142 } 7143 7144 7145 /** 7146 * @ngdoc method 7147 * @name $cacheFactory#info 7148 * 7149 * @description 7150 * Get information about all the caches that have been created 7151 * 7152 * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` 7153 */ 7154 cacheFactory.info = function() { 7155 var info = {}; 7156 forEach(caches, function(cache, cacheId) { 7157 info[cacheId] = cache.info(); 7158 }); 7159 return info; 7160 }; 7161 7162 7163 /** 7164 * @ngdoc method 7165 * @name $cacheFactory#get 7166 * 7167 * @description 7168 * Get access to a cache object by the `cacheId` used when it was created. 7169 * 7170 * @param {string} cacheId Name or id of a cache to access. 7171 * @returns {object} Cache object identified by the cacheId or undefined if no such cache. 7172 */ 7173 cacheFactory.get = function(cacheId) { 7174 return caches[cacheId]; 7175 }; 7176 7177 7178 return cacheFactory; 7179 }; 7180} 7181 7182/** 7183 * @ngdoc service 7184 * @name $templateCache 7185 * @this 7186 * 7187 * @description 7188 * `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the 7189 * {@link ng.$cacheFactory $cacheFactory}. 7190 * 7191 * The first time a template is used, it is loaded in the template cache for quick retrieval. You 7192 * can load templates directly into the cache in a `script` tag, by using {@link $templateRequest}, 7193 * or by consuming the `$templateCache` service directly. 7194 * 7195 * Adding via the `script` tag: 7196 * 7197 * ```html 7198 * <script type="text/ng-template" id="templateId.html"> 7199 * <p>This is the content of the template</p> 7200 * </script> 7201 * ``` 7202 * 7203 * **Note:** the `script` tag containing the template does not need to be included in the `head` of 7204 * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g. 7205 * element with {@link ngApp} attribute), otherwise the template will be ignored. 7206 * 7207 * Adding via the `$templateCache` service: 7208 * 7209 * ```js 7210 * var myApp = angular.module('myApp', []); 7211 * myApp.run(function($templateCache) { 7212 * $templateCache.put('templateId.html', 'This is the content of the template'); 7213 * }); 7214 * ``` 7215 * 7216 * To retrieve the template later, simply use it in your component: 7217 * ```js 7218 * myApp.component('myComponent', { 7219 * templateUrl: 'templateId.html' 7220 * }); 7221 * ``` 7222 * 7223 * or get it via the `$templateCache` service: 7224 * ```js 7225 * $templateCache.get('templateId.html') 7226 * ``` 7227 * 7228 */ 7229function $TemplateCacheProvider() { 7230 this.$get = ['$cacheFactory', function($cacheFactory) { 7231 return $cacheFactory('templates'); 7232 }]; 7233} 7234 7235/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 7236 * Any commits to this file should be reviewed with security in mind. * 7237 * Changes to this file can potentially create security vulnerabilities. * 7238 * An approval from 2 Core members with history of modifying * 7239 * this file is required. * 7240 * * 7241 * Does the change somehow allow for arbitrary javascript to be executed? * 7242 * Or allows for someone to change the prototype of built-in objects? * 7243 * Or gives undesired access to variables like document or window? * 7244 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 7245 7246/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! 7247 * 7248 * DOM-related variables: 7249 * 7250 * - "node" - DOM Node 7251 * - "element" - DOM Element or Node 7252 * - "$node" or "$element" - jqLite-wrapped node or element 7253 * 7254 * 7255 * Compiler related stuff: 7256 * 7257 * - "linkFn" - linking fn of a single directive 7258 * - "nodeLinkFn" - function that aggregates all linking fns for a particular node 7259 * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node 7260 * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) 7261 */ 7262 7263 7264/** 7265 * @ngdoc service 7266 * @name $compile 7267 * @kind function 7268 * 7269 * @description 7270 * Compiles an HTML string or DOM into a template and produces a template function, which 7271 * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together. 7272 * 7273 * The compilation is a process of walking the DOM tree and matching DOM elements to 7274 * {@link ng.$compileProvider#directive directives}. 7275 * 7276 * <div class="alert alert-warning"> 7277 * **Note:** This document is an in-depth reference of all directive options. 7278 * For a gentle introduction to directives with examples of common use cases, 7279 * see the {@link guide/directive directive guide}. 7280 * </div> 7281 * 7282 * ## Comprehensive Directive API 7283 * 7284 * There are many different options for a directive. 7285 * 7286 * The difference resides in the return value of the factory function. 7287 * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)} 7288 * that defines the directive properties, or just the `postLink` function (all other properties will have 7289 * the default values). 7290 * 7291 * <div class="alert alert-success"> 7292 * **Best Practice:** It's recommended to use the "directive definition object" form. 7293 * </div> 7294 * 7295 * Here's an example directive declared with a Directive Definition Object: 7296 * 7297 * ```js 7298 * var myModule = angular.module(...); 7299 * 7300 * myModule.directive('directiveName', function factory(injectables) { 7301 * var directiveDefinitionObject = { 7302 * {@link $compile#-priority- priority}: 0, 7303 * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... }, 7304 * // or 7305 * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... }, 7306 * {@link $compile#-transclude- transclude}: false, 7307 * {@link $compile#-restrict- restrict}: 'A', 7308 * {@link $compile#-templatenamespace- templateNamespace}: 'html', 7309 * {@link $compile#-scope- scope}: false, 7310 * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, 7311 * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier', 7312 * {@link $compile#-bindtocontroller- bindToController}: false, 7313 * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], 7314 * {@link $compile#-multielement- multiElement}: false, 7315 * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) { 7316 * return { 7317 * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... }, 7318 * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... } 7319 * } 7320 * // or 7321 * // return function postLink( ... ) { ... } 7322 * }, 7323 * // or 7324 * // {@link $compile#-link- link}: { 7325 * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... }, 7326 * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... } 7327 * // } 7328 * // or 7329 * // {@link $compile#-link- link}: function postLink( ... ) { ... } 7330 * }; 7331 * return directiveDefinitionObject; 7332 * }); 7333 * ``` 7334 * 7335 * <div class="alert alert-warning"> 7336 * **Note:** Any unspecified options will use the default value. You can see the default values below. 7337 * </div> 7338 * 7339 * Therefore the above can be simplified as: 7340 * 7341 * ```js 7342 * var myModule = angular.module(...); 7343 * 7344 * myModule.directive('directiveName', function factory(injectables) { 7345 * var directiveDefinitionObject = { 7346 * link: function postLink(scope, iElement, iAttrs) { ... } 7347 * }; 7348 * return directiveDefinitionObject; 7349 * // or 7350 * // return function postLink(scope, iElement, iAttrs) { ... } 7351 * }); 7352 * ``` 7353 * 7354 * ### Life-cycle hooks 7355 * Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the 7356 * directive: 7357 * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and 7358 * had their bindings initialized (and before the pre & post linking functions for the directives on 7359 * this element). This is a good place to put initialization code for your controller. 7360 * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The 7361 * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an 7362 * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a 7363 * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will 7364 * also be called when your bindings are initialized. 7365 * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on 7366 * changes. Any actions that you wish to take in response to the changes that you detect must be 7367 * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook 7368 * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not 7369 * be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; 7370 * if detecting changes, you must store the previous value(s) for comparison to the current values. 7371 * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing 7372 * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in 7373 * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent 7374 * components will have their `$onDestroy()` hook called before child components. 7375 * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link 7376 * function this hook can be used to set up DOM event handlers and do direct DOM manipulation. 7377 * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since 7378 * they are waiting for their template to load asynchronously and their own compilation and linking has been 7379 * suspended until that occurs. 7380 * 7381 * #### Comparison with life-cycle hooks in the new Angular 7382 * The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are 7383 * some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular: 7384 * 7385 * * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`. 7386 * * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor. 7387 * In Angular you can only define hooks on the prototype of the Component class. 7388 * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to 7389 * `ngDoCheck` in Angular. 7390 * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be 7391 * propagated throughout the application. 7392 * Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an 7393 * error or do nothing depending upon the state of `enableProdMode()`. 7394 * 7395 * #### Life-cycle hook examples 7396 * 7397 * This example shows how you can check for mutations to a Date object even though the identity of the object 7398 * has not changed. 7399 * 7400 * <example name="doCheckDateExample" module="do-check-module"> 7401 * <file name="app.js"> 7402 * angular.module('do-check-module', []) 7403 * .component('app', { 7404 * template: 7405 * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' + 7406 * 'Date: {{ $ctrl.date }}' + 7407 * '<test date="$ctrl.date"></test>', 7408 * controller: function() { 7409 * this.date = new Date(); 7410 * this.month = this.date.getMonth(); 7411 * this.updateDate = function() { 7412 * this.date.setMonth(this.month); 7413 * }; 7414 * } 7415 * }) 7416 * .component('test', { 7417 * bindings: { date: '<' }, 7418 * template: 7419 * '<pre>{{ $ctrl.log | json }}</pre>', 7420 * controller: function() { 7421 * var previousValue; 7422 * this.log = []; 7423 * this.$doCheck = function() { 7424 * var currentValue = this.date && this.date.valueOf(); 7425 * if (previousValue !== currentValue) { 7426 * this.log.push('doCheck: date mutated: ' + this.date); 7427 * previousValue = currentValue; 7428 * } 7429 * }; 7430 * } 7431 * }); 7432 * </file> 7433 * <file name="index.html"> 7434 * <app></app> 7435 * </file> 7436 * </example> 7437 * 7438 * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the 7439 * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large 7440 * arrays or objects can have a negative impact on your application performance) 7441 * 7442 * <example name="doCheckArrayExample" module="do-check-module"> 7443 * <file name="index.html"> 7444 * <div ng-init="items = []"> 7445 * <button ng-click="items.push(items.length)">Add Item</button> 7446 * <button ng-click="items = []">Reset Items</button> 7447 * <pre>{{ items }}</pre> 7448 * <test items="items"></test> 7449 * </div> 7450 * </file> 7451 * <file name="app.js"> 7452 * angular.module('do-check-module', []) 7453 * .component('test', { 7454 * bindings: { items: '<' }, 7455 * template: 7456 * '<pre>{{ $ctrl.log | json }}</pre>', 7457 * controller: function() { 7458 * this.log = []; 7459 * 7460 * this.$doCheck = function() { 7461 * if (this.items_ref !== this.items) { 7462 * this.log.push('doCheck: items changed'); 7463 * this.items_ref = this.items; 7464 * } 7465 * if (!angular.equals(this.items_clone, this.items)) { 7466 * this.log.push('doCheck: items mutated'); 7467 * this.items_clone = angular.copy(this.items); 7468 * } 7469 * }; 7470 * } 7471 * }); 7472 * </file> 7473 * </example> 7474 * 7475 * 7476 * ### Directive Definition Object 7477 * 7478 * The directive definition object provides instructions to the {@link ng.$compile 7479 * compiler}. The attributes are: 7480 * 7481 * #### `multiElement` 7482 * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between 7483 * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them 7484 * together as the directive elements. It is recommended that this feature be used on directives 7485 * which are not strictly behavioral (such as {@link ngClick}), and which 7486 * do not manipulate or replace child nodes (such as {@link ngInclude}). 7487 * 7488 * #### `priority` 7489 * When there are multiple directives defined on a single DOM element, sometimes it 7490 * is necessary to specify the order in which the directives are applied. The `priority` is used 7491 * to sort the directives before their `compile` functions get called. Priority is defined as a 7492 * number. Directives with greater numerical `priority` are compiled first. Pre-link functions 7493 * are also run in priority order, but post-link functions are run in reverse order. The order 7494 * of directives with the same priority is undefined. The default priority is `0`. 7495 * 7496 * #### `terminal` 7497 * If set to true then the current `priority` will be the last set of directives 7498 * which will execute (any directives at the current priority will still execute 7499 * as the order of execution on same `priority` is undefined). Note that expressions 7500 * and other directives used in the directive's template will also be excluded from execution. 7501 * 7502 * #### `scope` 7503 * The scope property can be `false`, `true`, or an object: 7504 * 7505 * * **`false` (default):** No scope will be created for the directive. The directive will use its 7506 * parent's scope. 7507 * 7508 * * **`true`:** A new child scope that prototypically inherits from its parent will be created for 7509 * the directive's element. If multiple directives on the same element request a new scope, 7510 * only one new scope is created. 7511 * 7512 * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template. 7513 * The 'isolate' scope differs from normal scope in that it does not prototypically 7514 * inherit from its parent scope. This is useful when creating reusable components, which should not 7515 * accidentally read or modify data in the parent scope. Note that an isolate scope 7516 * directive without a `template` or `templateUrl` will not apply the isolate scope 7517 * to its children elements. 7518 * 7519 * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the 7520 * directive's element. These local properties are useful for aliasing values for templates. The keys in 7521 * the object hash map to the name of the property on the isolate scope; the values define how the property 7522 * is bound to the parent scope, via matching attributes on the directive's element: 7523 * 7524 * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is 7525 * always a string since DOM attributes are strings. If no `attr` name is specified then the 7526 * attribute name is assumed to be the same as the local name. Given `<my-component 7527 * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`, 7528 * the directive's scope property `localName` will reflect the interpolated value of `hello 7529 * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's 7530 * scope. The `name` is read from the parent scope (not the directive's scope). 7531 * 7532 * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression 7533 * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope. 7534 * If no `attr` name is specified then the attribute name is assumed to be the same as the local 7535 * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: { 7536 * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the 7537 * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in 7538 * `localModel` and vice versa. If the binding expression is non-assignable, or if the attribute 7539 * isn't optional and doesn't exist, an exception 7540 * ({@link error/$compile/nonassign `$compile:nonassign`}) will be thrown upon discovering changes 7541 * to the local value, since it will be impossible to sync them back to the parent scope. 7542 * 7543 * By default, the {@link ng.$rootScope.Scope#$watch `$watch`} 7544 * method is used for tracking changes, and the equality check is based on object identity. 7545 * However, if an object literal or an array literal is passed as the binding expression, the 7546 * equality check is done by value (using the {@link angular.equals} function). It's also possible 7547 * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection 7548 * `$watchCollection`}: use `=*` or `=*attr` 7549 * 7550 * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an 7551 * expression passed via the attribute `attr`. The expression is evaluated in the context of the 7552 * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the 7553 * local name. 7554 * 7555 * For example, given `<my-component my-attr="parentModel">` and directive definition of 7556 * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the 7557 * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected 7558 * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however 7559 * two caveats: 7560 * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply 7561 * sets the same value. That means if your bound value is an object, changes to its properties 7562 * in the isolated scope will be reflected in the parent scope (because both reference the same object). 7563 * 2. one-way binding watches changes to the **identity** of the parent value. That means the 7564 * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference 7565 * to the value has changed. In most cases, this should not be of concern, but can be important 7566 * to know if you one-way bind to an object, and then replace that object in the isolated scope. 7567 * If you now change a property of the object in your parent scope, the change will not be 7568 * propagated to the isolated scope, because the identity of the object on the parent scope 7569 * has not changed. Instead you must assign a new object. 7570 * 7571 * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings 7572 * back to the parent. However, it does not make this completely impossible. 7573 * 7574 * By default, the {@link ng.$rootScope.Scope#$watch `$watch`} 7575 * method is used for tracking changes, and the equality check is based on object identity. 7576 * It's also possible to watch the evaluated value shallowly with 7577 * {@link ng.$rootScope.Scope#$watchCollection `$watchCollection`}: use `<*` or `<*attr` 7578 * 7579 * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If 7580 * no `attr` name is specified then the attribute name is assumed to be the same as the local name. 7581 * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: { 7582 * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for 7583 * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope 7584 * via an expression to the parent scope. This can be done by passing a map of local variable names 7585 * and values into the expression wrapper fn. For example, if the expression is `increment(amount)` 7586 * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`. 7587 * 7588 * All 4 kinds of bindings (`@`, `=`, `<`, and `&`) can be made optional by adding `?` to the expression. 7589 * The marker must come after the mode and before the attribute name. 7590 * See the {@link error/$compile/iscp Invalid Isolate Scope Definition error} for definition examples. 7591 * This is useful to refine the interface directives provide. 7592 * One subtle difference between optional and non-optional happens **when the binding attribute is not 7593 * set**: 7594 * - the binding is optional: the property will not be defined 7595 * - the binding is not optional: the property is defined 7596 * 7597 * ```js 7598 *app.directive('testDir', function() { 7599 return { 7600 scope: { 7601 notoptional: '=', 7602 optional: '=?', 7603 }, 7604 bindToController: true, 7605 controller: function() { 7606 this.$onInit = function() { 7607 console.log(this.hasOwnProperty('notoptional')) // true 7608 console.log(this.hasOwnProperty('optional')) // false 7609 } 7610 } 7611 } 7612 }) 7613 *``` 7614 * 7615 * 7616 * ##### Combining directives with different scope defintions 7617 * 7618 * In general it's possible to apply more than one directive to one element, but there might be limitations 7619 * depending on the type of scope required by the directives. The following points will help explain these limitations. 7620 * For simplicity only two directives are taken into account, but it is also applicable for several directives: 7621 * 7622 * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope 7623 * * **child scope** + **no scope** => Both directives will share one single child scope 7624 * * **child scope** + **child scope** => Both directives will share one single child scope 7625 * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use 7626 * its parent's scope 7627 * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot 7628 * be applied to the same element. 7629 * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives 7630 * cannot be applied to the same element. 7631 * 7632 * 7633 * #### `bindToController` 7634 * This property is used to bind scope properties directly to the controller. It can be either 7635 * `true` or an object hash with the same format as the `scope` property. 7636 * 7637 * When an isolate scope is used for a directive (see above), `bindToController: true` will 7638 * allow a component to have its properties bound to the controller, rather than to scope. 7639 * 7640 * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller 7641 * properties. You can access these bindings once they have been initialized by providing a controller method called 7642 * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings 7643 * initialized. 7644 * 7645 * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property. 7646 * This will set up the scope bindings to the controller directly. Note that `scope` can still be used 7647 * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate 7648 * scope (useful for component directives). 7649 * 7650 * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`. 7651 * 7652 * 7653 * #### `controller` 7654 * Controller constructor function. The controller is instantiated before the 7655 * pre-linking phase and can be accessed by other directives (see 7656 * `require` attribute). This allows the directives to communicate with each other and augment 7657 * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: 7658 * 7659 * * `$scope` - Current scope associated with the element 7660 * * `$element` - Current element 7661 * * `$attrs` - Current attributes object for the element 7662 * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: 7663 * `function([scope], cloneLinkingFn, futureParentElement, slotName)`: 7664 * * `scope`: (optional) override the scope. 7665 * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content. 7666 * * `futureParentElement` (optional): 7667 * * defines the parent to which the `cloneLinkingFn` will add the cloned elements. 7668 * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`. 7669 * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) 7670 * and when the `cloneLinkingFn` is passed, 7671 * as those elements need to created and cloned in a special way when they are defined outside their 7672 * usual containers (e.g. like `<svg>`). 7673 * * See also the `directive.templateNamespace` property. 7674 * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`) 7675 * then the default transclusion is provided. 7676 * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns 7677 * `true` if the specified slot contains content (i.e. one or more DOM nodes). 7678 * 7679 * #### `require` 7680 * Require another directive and inject its controller as the fourth argument to the linking function. The 7681 * `require` property can be a string, an array or an object: 7682 * * a **string** containing the name of the directive to pass to the linking function 7683 * * an **array** containing the names of directives to pass to the linking function. The argument passed to the 7684 * linking function will be an array of controllers in the same order as the names in the `require` property 7685 * * an **object** whose property values are the names of the directives to pass to the linking function. The argument 7686 * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding 7687 * controllers. 7688 * 7689 * If the `require` property is an object and `bindToController` is truthy, then the required controllers are 7690 * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers 7691 * have been constructed but before `$onInit` is called. 7692 * If the name of the required controller is the same as the local name (the key), the name can be 7693 * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`. 7694 * See the {@link $compileProvider#component} helper for an example of how this can be used. 7695 * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is 7696 * raised (unless no link function is specified and the required controllers are not being bound to the directive 7697 * controller, in which case error checking is skipped). The name can be prefixed with: 7698 * 7699 * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. 7700 * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. 7701 * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. 7702 * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found. 7703 * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass 7704 * `null` to the `link` fn if not found. 7705 * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass 7706 * `null` to the `link` fn if not found. 7707 * 7708 * 7709 * #### `controllerAs` 7710 * Identifier name for a reference to the controller in the directive's scope. 7711 * This allows the controller to be referenced from the directive template. This is especially 7712 * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible 7713 * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the 7714 * `controllerAs` reference might overwrite a property that already exists on the parent scope. 7715 * 7716 * 7717 * #### `restrict` 7718 * String of subset of `EACM` which restricts the directive to a specific directive 7719 * declaration style. If omitted, the defaults (elements and attributes) are used. 7720 * 7721 * * `E` - Element name (default): `<my-directive></my-directive>` 7722 * * `A` - Attribute (default): `<div my-directive="exp"></div>` 7723 * * `C` - Class: `<div class="my-directive: exp;"></div>` 7724 * * `M` - Comment: `<!-- directive: my-directive exp -->` 7725 * 7726 * 7727 * #### `templateNamespace` 7728 * String representing the document type used by the markup in the template. 7729 * AngularJS needs this information as those elements need to be created and cloned 7730 * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`. 7731 * 7732 * * `html` - All root nodes in the template are HTML. Root nodes may also be 7733 * top-level elements such as `<svg>` or `<math>`. 7734 * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`). 7735 * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`). 7736 * 7737 * If no `templateNamespace` is specified, then the namespace is considered to be `html`. 7738 * 7739 * #### `template` 7740 * HTML markup that may: 7741 * * Replace the contents of the directive's element (default). 7742 * * Replace the directive's element itself (if `replace` is true - DEPRECATED). 7743 * * Wrap the contents of the directive's element (if `transclude` is true). 7744 * 7745 * Value may be: 7746 * 7747 * * A string. For example `<div red-on-hover>{{delete_str}}</div>`. 7748 * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` 7749 * function api below) and returns a string value. 7750 * 7751 * 7752 * #### `templateUrl` 7753 * This is similar to `template` but the template is loaded from the specified URL, asynchronously. 7754 * 7755 * Because template loading is asynchronous the compiler will suspend compilation of directives on that element 7756 * for later when the template has been resolved. In the meantime it will continue to compile and link 7757 * sibling and parent elements as though this element had not contained any directives. 7758 * 7759 * The compiler does not suspend the entire compilation to wait for templates to be loaded because this 7760 * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the 7761 * case when only one deeply nested directive has `templateUrl`. 7762 * 7763 * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
7763 7764 * 7765 * You can specify `templateUrl` as a string representing the URL or as a function which takes two 7766 * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns 7767 * a string value representing the url. In either case, the template URL is passed through {@link 7768 * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. 7769 * 7770 * 7771 * #### `replace` 7772 * <div class="alert alert-danger"> 7773 * **Note:** `replace` is deprecated in AngularJS and has been removed in the new Angular (v2+). 7774 * </div> 7775 * 7776 * Specifies what the template should replace. Defaults to `false`. 7777 * 7778 * * `true` - the template will replace the directive's element. 7779 * * `false` - the template will replace the contents of the directive's element. 7780 * 7781 * The replacement process migrates all of the attributes / classes from the old element to the new 7782 * one. See the {@link guide/directive#template-expanding-directive 7783 * Directives Guide} for an example. 7784 * 7785 * There are very few scenarios where element replacement is required for the application function, 7786 * the main one being reusable custom components that are used within SVG contexts 7787 * (because SVG doesn't work with custom elements in the DOM tree). 7788 * 7789 * #### `transclude` 7790 * Extract the contents of the element where the directive appears and make it available to the directive. 7791 * The contents are compiled and provided to the directive as a **transclusion function**. See the 7792 * {@link $compile#transclusion Transclusion} section below. 7793 * 7794 * 7795 * #### `compile` 7796 * 7797 * ```js 7798 * function compile(tElement, tAttrs, transclude) { ... } 7799 * ``` 7800 * 7801 * The compile function deals with transforming the template DOM. Since most directives do not do 7802 * template transformation, it is not used often. The compile function takes the following arguments: 7803 * 7804 * * `tElement` - template element - The element where the directive has been declared. It is 7805 * safe to do template transformation on the element and child elements only. 7806 * 7807 * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared 7808 * between all directive compile functions. 7809 * 7810 * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)` 7811 * 7812 * <div class="alert alert-warning"> 7813 * **Note:** The template instance and the link instance may be different objects if the template has 7814 * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that 7815 * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration 7816 * should be done in a linking function rather than in a compile function. 7817 * </div> 7818 7819 * <div class="alert alert-warning"> 7820 * **Note:** The compile function cannot handle directives that recursively use themselves in their 7821 * own templates or compile functions. Compiling these directives results in an infinite loop and 7822 * stack overflow errors. 7823 * 7824 * This can be avoided by manually using $compile
vendor: 5,458 bytes, lines 7824-7928
7824 in the postLink function to imperatively compile 7825 * a directive's template instead of relying on automatic template compilation via `template` or 7826 * `templateUrl` declaration or manual compilation inside the compile function. 7827 * </div> 7828 * 7829 * <div class="alert alert-danger"> 7830 * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it 7831 * e.g. does not know about the right outer scope. Please use the transclude function that is passed 7832 * to the link function instead. 7833 * </div> 7834 7835 * A compile function can have a return value which can be either a function or an object. 7836 * 7837 * * returning a (post-link) function - is equivalent to registering the linking function via the 7838 * `link` property of the config object when the compile function is empty. 7839 * 7840 * * returning an object with function(s) registered via `pre` and `post` properties - allows you to 7841 * control when a linking function should be called during the linking phase. See info about 7842 * pre-linking and post-linking functions below. 7843 * 7844 * 7845 * #### `link` 7846 * This property is used only if the `compile` property is not defined. 7847 * 7848 * ```js 7849 * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... } 7850 * ``` 7851 * 7852 * The link function is responsible for registering DOM listeners as well as updating the DOM. It is 7853 * executed after the template has been cloned. This is where most of the directive logic will be 7854 * put. 7855 * 7856 * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the 7857 * directive for registering {@link ng.$rootScope.Scope#$watch watches}. 7858 * 7859 * * `iElement` - instance element - The element where the directive is to be used. It is safe to 7860 * manipulate the children of the element only in `postLink` function since the children have 7861 * already been linked. 7862 * 7863 * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared 7864 * between all directive linking functions. 7865 * 7866 * * `controller` - the directive's required controller instance(s) - Instances are shared 7867 * among all directives, which allows the directives to use the controllers as a communication 7868 * channel. The exact value depends on the directive's `require` property: 7869 * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one 7870 * * `string`: the controller instance 7871 * * `array`: array of controller instances 7872 * 7873 * If a required controller cannot be found, and it is optional, the instance is `null`, 7874 * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown. 7875 * 7876 * Note that you can also require the directive's own controller - it will be made available like 7877 * any other controller. 7878 * 7879 * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. 7880 * This is the same as the `$transclude` parameter of directive controllers, 7881 * see {@link ng.$compile#-controller- the controller section for details}. 7882 * `function([scope], cloneLinkingFn, futureParentElement)`. 7883 * 7884 * #### Pre-linking function 7885 * 7886 * Executed before the child elements are linked. Not safe to do DOM transformation since the 7887 * compiler linking function will fail to locate the correct elements for linking. 7888 * 7889 * #### Post-linking function 7890 * 7891 * Executed after the child elements are linked. 7892 * 7893 * Note that child elements that contain `templateUrl` directives will not have been compiled 7894 * and linked since they are waiting for their template to load asynchronously and their own 7895 * compilation and linking has been suspended until that occurs. 7896 * 7897 * It is safe to do DOM transformation in the post-linking function on elements that are not waiting 7898 * for their async templates to be resolved. 7899 * 7900 * 7901 * ### Transclusion 7902 * 7903 * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and 7904 * copying them to another part of the DOM, while maintaining their connection to the original AngularJS 7905 * scope from where they were taken. 7906 * 7907 * Transclusion is used (often with {@link ngTransclude}) to insert the 7908 * original contents of a directive's element into a specified place in the template of the directive. 7909 * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded 7910 * content has access to the properties on the scope from which it was taken, even if the directive 7911 * has isolated scope. 7912 * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}. 7913 * 7914 * This makes it possible for the widget to have private state for its template, while the transcluded 7915 * content has access to its originating scope. 7916 * 7917 * <div class="alert alert-warning"> 7918 * **Note:** When testing an element transclude directive you must not place the directive at the root of the 7919 * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives 7920 * Testing Transclusion Directives}. 7921 * </div> 7922 * 7923 * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the 7924 * directive's element, the entire element or multiple parts of the element contents: 7925 * 7926 * * `true` - transclude the content (i.e. the child nodes) of the directive's element. 7927 * * `'element'` - transclude the whole of the directive's element including any directives on this 7928 * element that
7928defined at a lower priority than this directive. When used, the `template` 7929 * property is ignored. 7930 * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template. 7931 * 7932 * **Mult-slot transclusion** is declared by providing an object for the `transclude` property. 7933 * 7934 * This object is a map where the keys are the name of the slot to fill and the value is an element selector 7935 * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`) 7936 * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc). 7937 * 7938 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} 7939 * 7940 * If the element selector is prefixed with a `?` then that slot is optional. 7941 * 7942 * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to 7943 * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive. 7944 * 7945 * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements 7946 * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call 7947 * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and 7948 * injectable into the directive's controller. 7949 * 7950 * 7951 * #### Transclusion Functions 7952 * 7953 * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion 7954 * function** to the directive's `link` function and `controller`. This transclusion function is a special 7955 * **linking function** that will return the compiled contents linked to a new transclusion scope. 7956 * 7957 * <div class="alert alert-info"> 7958 * If you are just using {@link ngTransclude} then you don't need to worry about this function, since 7959 * ngTransclude will deal with it for us. 7960 * </div> 7961 * 7962 * If you want to manually control the insertion and removal of the transcluded content in your directive 7963 * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery 7964 * object that contains the compiled DOM, which is linked to the correct transclusion scope. 7965 * 7966 * When you call a transclusion function you can pass in a **clone attach function**. This function accepts 7967 * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded 7968 * content and the `scope` is the newly created transclusion scope, which the clone will be linked to. 7969 * 7970 * <div class="alert alert-info"> 7971 * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function 7972 * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope. 7973 * </div> 7974 * 7975 * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone 7976 * attach function**: 7977 * 7978 * ```js 7979 * var transcludedContent, transclusionScope; 7980 * 7981 * $transclude(function(clone, scope) { 7982 * element.append(clone); 7983 * transcludedContent = clone; 7984 * transclusionScope = scope; 7985 * }); 7986 * ``` 7987 * 7988 * Later, if you want to remove the transcluded content from your DOM then you should also destroy the 7989 * associated transclusion scope: 7990 * 7991 * ```js 7992 * transcludedContent.remove(); 7993 * transclusionScope.$destroy(); 7994 * ``` 7995 * 7996 * <div class="alert alert-info"> 7997 * **Best Practice**: if you intend to add and remove transcluded content manually in your directive 7998 * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it), 7999 * then you are also responsible for calling `$destroy` on the transclusion scope. 8000 * </div> 8001 * 8002 * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat} 8003 * automatically destroy their transcluded clones as necessary so you do not need to worry about this if 8004 * you are simply using {@link ngTransclude} to inject the transclusion into your directive. 8005 * 8006 * 8007 * #### Transclusion Scopes 8008 * 8009 * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion 8010 * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed 8011 * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it 8012 * was taken. 8013 * 8014 * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look 8015 * like this: 8016 * 8017 * ```html 8018 * <div ng-app> 8019 * <div isolate> 8020 * <div transclusion>
8021 * </div> 8022 * </div> 8023 * </div> 8024 * ``` 8025 * 8026 * The `$parent` scope hierarchy will look like this: 8027 * 8028 ``` 8029 - $rootScope 8030 - isolate 8031 - transclusion 8032 ``` 8033 * 8034 * but the scopes will inherit prototypically from different scopes to their `$parent`. 8035 * 8036 ``` 8037 - $rootScope 8038 - transclusion 8039 - isolate 8040 ``` 8041 * 8042 * 8043 * ### Attributes 8044 * 8045 * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the 8046 * `link()` or `compile()` functions. It has a variety of uses. 8047 * 8048 * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways: 8049 * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access 8050 * to the attributes. 8051 * 8052 * * *Directive inter-communication:* All directives share the same instance of the attributes 8053 * object which allows the directives to use the attributes object as inter directive 8054 * communication. 8055 * 8056 * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object 8057 * allowing other directives to read the interpolated value. 8058 * 8059 * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes 8060 * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also 8061 * the only way to easily get the actual value because during the linking phase the interpolation 8062 * hasn't been evaluated yet and so the value is at this time set to `undefined`. 8063 * 8064 * ```js 8065 * function linkingFn(scope, elm, attrs, ctrl) { 8066 * // get the attribute value 8067 * console.log(attrs.ngModel); 8068 * 8069 * // change the attribute 8070 * attrs.$set('ngModel', 'new value'); 8071 * 8072 * // observe changes to interpolated attribute 8073 * attrs.$observe('ngModel', function(value) { 8074 * console.log('ngModel has changed value to ' + value); 8075 * }); 8076 * } 8077 * ``` 8078 * 8079 * ## Example 8080 * 8081 * <div class="alert alert-warning"> 8082 * **Note**: Typically directives are registered with `module.directive`. The example below is 8083 * to illustrate how `$compile` works. 8084 * </div> 8085 * 8086 <example module="compileExample" name="compile"> 8087 <file name="index.html"> 8088 <script> 8089 angular.module('compileExample', [], function($compileProvider) { 8090 // configure new 'compile' directive by passing a directive 8091 // factory function. The factory function injects the '$compile' 8092 $compileProvider.directive('compile', function($compile) { 8093 // directive factory creates a link function 8094 return function(scope, element, attrs) { 8095 scope.$watch( 8096 function(scope) { 8097 // watch the 'compile' expression for changes 8098 return scope.$eval(attrs.compile); 8099 }, 8100 function(value) { 8101 // when the 'compile' expression changes 8102 // assign it into the current DOM 8103 element.html(value); 8104 8105 // compile the new DOM and link it to the current 8106 // scope. 8107 // NOTE: we only compile .childNodes so that 8108 // we don't get into infinite loop compiling ourselves 8109 $compile(element.contents())(scope); 8110 } 8111 ); 8112 }; 8113 }); 8114 }) 8115 .controller('GreeterController', ['$scope', function($scope) { 8116 $scope.name = 'AngularJS'; 8117 $scope.html = 'Hello {{name}}'; 8118 }]); 8119 </script> 8120 <div ng-controller="GreeterController"> 8121 <input ng-model="name"> <br/> 8122 <textarea ng-model="html"></textarea> <br/> 8123 <div compile="html"></div> 8124 </div> 8125 </file> 8126 <file name="protractor.js" type="protractor"> 8127 it('should auto compile', function() { 8128 var textarea = $('textarea'); 8129 var output = $('div[compile]'); 8130 // The initial state reads 'Hello AngularJS'. 8131 expect(output.getText()).toBe('Hello AngularJS'); 8132 textarea.clear(); 8133 textarea.sendKeys('{{name}}!'); 8134 expect(output.getText()).toBe('AngularJS!'); 8135 }); 8136 </file> 8137 </example> 8138 8139 * 8140 * 8141 * @param {string|DOMElement} element Element or HTML string to compile into a template function. 8142 * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED. 8143 * 8144 * <div class="alert alert-danger"> 8145 * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it 8146 * e.g. will not use the right outer scope. Please pass the transclude function as a 8147 * `parentBoundTranscludeFn` to the link function instead. 8148 * </div> 8149 * 8150 * @param {number} maxPriority only apply directives lower than given priority (Only effects the
8151 * root element(s), not their children) 8152 * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template 8153 * (a DOM element/tree) to a scope. Where: 8154 * 8155 * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. 8156 * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the 8157 * `template` and call the `cloneAttachFn` function allowing the caller to attach the 8158 * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is 8159 * called as: <br/> `cloneAttachFn(clonedElement, scope)` where: 8160 * 8161 * * `clonedElement` - is a clone of the original `element` passed into the compiler. 8162 * * `scope` - is the current scope with which the linking function is working with. 8163 * 8164 * * `options` - An optional object hash with linking options. If `options` is provided, then the following 8165 * keys may be used to control linking behavior: 8166 * 8167 * * `parentBoundTranscludeFn` - the transclude function made available to 8168 * directives; if given, it will be passed through to the link functions of 8169 * directives found in `element` during compilation. 8170 * * `transcludeControllers` - an object hash with keys that map controller names 8171 * to a hash with the key `instance`, which maps to the controller instance; 8172 * if given, it will make the controllers available to directives on the compileNode: 8173 * ``` 8174 * { 8175 * parent: { 8176 * instance: parentControllerInstance 8177 * } 8178 * } 8179 * ``` 8180 * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add 8181 * the cloned elements; only needed for transcludes that are allowed to contain non html 8182 * elements (e.g. SVG elements). See also the directive.controller property. 8183 * 8184 * Calling the linking function returns the element of the template. It is either the original 8185 * element passed in, or the clone of the element if the `cloneAttachFn` is provided. 8186 * 8187 * After linking the view is not updated until after a call to $digest which typically is done by 8188 * AngularJS automatically. 8189 * 8190 * If you need access to the bound view, there are two ways to do it: 8191 * 8192 * - If you are not asking the linking function to clone the template, create the DOM element(s) 8193 * before you send them to the compiler and keep this reference around. 8194 * ```js 8195 * var element = $compile('<p>{{total}}</p>')(scope); 8196 * ``` 8197 * 8198 * - if on the other hand, you need the element to be cloned, the view reference from the original 8199 * example would not point to the clone, but rather to the original template that was cloned. In 8200 * this case, you can access the clone via the cloneAttachFn: 8201 * ```js 8202 * var templateElement = angular.element('<p>{{total}}</p>'), 8203 * scope = ....; 8204 * 8205 * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { 8206 * //attach the clone to DOM document at the right place 8207 * }); 8208 * 8209 * //now we have reference to the cloned DOM via `clonedElement` 8210 * ``` 8211 * 8212 * 8213 * For information on how the compiler works, see the 8214 * {@link guide/compiler AngularJS HTML Compiler} section of the Developer Guide. 8215 * 8216 * @knownIssue 8217 * 8218 * ### Double Compilation 8219 * 8220 Double compilation occurs when an already compiled part of the DOM gets 8221 compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues, 8222 and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it 8223 section on double compilation} for an in-depth explanation and ways to avoid it. 8224 8225 * @knownIssue 8226 8227 ### Issues with `replace: true` 8228 * 8229 * <div class="alert alert-danger"> 8230 * **Note**: {@link $compile#-replace- `replace: true`} is deprecated and not recommended to use, 8231 * mainly due to the issues listed here. It has been completely removed in the new Angular. 8232 * </div> 8233 * 8234 * #### Attribute values are not merged 8235 * 8236 * When a `replace` directive encounters the same attribute on the original and the replace node, 8237 * it will simply deduplicate the attribute and join the values with a space or with a `;` in case of 8238 * the `style` attribute. 8239 * ```html 8240 * Original Node: <span class="original" style="color: red;"></span> 8241 * Replace Template: <span class="replaced" style="background: blue;"></span> 8242 * Result: <span class="original replaced" style="color: red; background: blue;"></span> 8243 * ``` 8244 * 8245 * That means attributes that contain AngularJS expressions will not be merged correctly, e.g. 8246 * {@link ngShow} or {@link ngClass} will cause a {@link $parse} error: 8247 * 8248 * ```html 8249 * Original Node: <span ng-class="{'something': something}" ng-show="!condition"></span> 8250 * Replace Template: <span ng-class="{'else': else}" ng-show="otherCondition"></span> 8251 * Result: <span ng-class="{'something': something} {'else': else}" ng-show="!condition otherCondition"></span> 8252 * ``` 8253 * 8254 * See issue [#5695](https://github.com/angular/angular.js/issues/5695). 8255 * 8256 * #### Directives are not deduplicated before compilation 8257 * 8258 * When the original node and the replace template declare the same directive(s), they will be 8259 * {@link guide/compiler#double-compilation-and-how-to-avoid-it compiled twice} because the compiler 8260 * does not deduplicate them. In many cases, this is not noticable, but e.g. {@link ngModel} will 8261 * attach `$formatters` and `$parsers` twice. 8262 * 8263 * See issue [#2573](https://github.com/angular/angular.js/issues/2573). 8264 * 8265 * #### `transclude: element` in the replace template root can have unex
8265pected effects 8266 * 8267 * When the replace template has a directive at the root node that uses 8268 * {@link $compile#-transclude- `transclude: element`}, e.g. 8269 * {@link ngIf} or {@link ngRepeat}, the DOM structure or scope inheritance can be incorrect. 8270 * See the following issues: 8271 * 8272 * - Incorrect scope on replaced element: 8273 * [#9837](https://github.com/angular/angular.js/issues/9837) 8274 * - Different DOM between `template` and `templateUrl`: 8275 * [#10612](https://github.com/angular/angular.js/issues/14326) 8276 * 8277 */ 8278 8279/** 8280 * @ngdoc directive 8281 * @name ngProp 8282 * @restrict A 8283 * @element ANY 8284 * 8285 * @usage 8286 * 8287 * ```html 8288 * <ANY ng-prop-propname="expression"> 8289 * </ANY> 8290 * ``` 8291 * 8292 * or with uppercase letters in property (e.g. "propName"): 8293 * 8294 * 8295 * ```html 8296 * <ANY ng-prop-prop_name="expression"> 8297 * </ANY> 8298 * ``` 8299 * 8300 * 8301 * @description 8302 * The `ngProp` directive binds an expression to a DOM element property. 8303 * `ngProp` allows writing to arbitrary properties by including 8304 * the property name in the attribute, e.g. `ng-prop-value="'my value'"` binds 'my value' to 8305 * the `value` property. 8306 * 8307 * Usually, it's not necessary to write to properties in AngularJS, as the built-in directives 8308 * handle the most common use cases (instead of the above example, you would use {@link ngValue}). 8309 * 8310 * However, [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements) 8311 * often use custom properties to hold data, and `ngProp` can be used to provide input to these 8312 * custom elements. 8313 * 8314 * ## Binding to camelCase properties 8315 * 8316 * Since HTML attributes are case-insensitive, camelCase properties like `innerHTML` must be escaped. 8317 * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so 8318 * `innerHTML` must be written as `ng-prop-inner_h_t_m_l="expression"` (Note that this is just an 8319 * example, and for binding HTML {@link ngBindHtml} should be used. 8320 * 8321 * ## Security 8322 * 8323 * Binding expressions to arbitrary properties poses a security risk, as properties like `innerHTML` 8324 * can insert potentially dangerous HTML into the application, e.g. script tags that execute 8325 * malicious code. 8326 * For this reason, `ngProp` applies Strict Contextual Escaping with the {@link ng.$sce $sce service}. 8327 * This means vulnerable properties require their content to be "trusted", based on the 8328 * context of the property. For example, the `innerHTML` is in the `HTML` context, and the 8329 * `iframe.src` property is in the `RESOURCE_URL` context, which requires that values written to 8330 * this property are trusted as a `RESOURCE_URL`. 8331 * 8332 * This can be set explicitly by calling $sce.trustAs(type, value) on the value that is 8333 * trusted before passing it to the `ng-prop-*` directive. There are exist shorthand methods for 8334 * each context type in the form of {@link ng.$sce#trustAsResourceUrl $sce.trustAsResourceUrl()} et al. 8335 * 8336 * In some cases you can also rely upon automatic sanitization of untrusted values - see below. 8337 * 8338 * Based on the context, other options may exist to mark a value as trusted / configure the behavior 8339 * of {@link ng.$sce}. For example, to restrict the `RESOURCE_URL` context to specific origins, use 8340 * the {@link $sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist()} 8341 * and {@link $sceDelegateProvider#resourceUrlBlacklist resourceUrlBlacklist()}. 8342 * 8343 * {@link ng.$sce#what-trusted-context-types-are-supported- Find out more about the different context types}. 8344 * 8345 * ### HTML Sanitization 8346 * 8347 * By default, `$sce` will throw an error if it detects untrusted HTML content, and will not bind the 8348 * content. 8349 * However, if you include the {@link ngSanitize ngSanitize module}, it will try to sanitize the 8350 * potentially dangerous HTML, e.g. strip non-whiteli
vendor: 12,775 bytes, lines 8350-8735
8350sted tags and attributes when binding to 8351 * `innerHTML`. 8352 * 8353 * @example 8354 * ### Binding to different contexts 8355 * 8356 * <example name="ngProp" module="exampleNgProp"> 8357 * <file name="app.js"> 8358 * angular.module('exampleNgProp', []) 8359 * .component('main', { 8360 * templateUrl: 'main.html', 8361 * controller: function($sce) { 8362 * this.safeContent = '<strong>Safe content</strong>'; 8363 * this.unsafeContent = '<button onclick="alert(\'Hello XSS!\')">Click for XSS</button>'; 8364 * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent); 8365 * } 8366 * }); 8367 * </file> 8368 * <file name="main.html"> 8369 * <div> 8370 * <div class="prop-unit"> 8371 * Binding to a property without security context: 8372 * <div class="prop-binding" ng-prop-inner_text="$ctrl.safeContent"></div> 8373 * <span class="prop-note">innerText</span> (safeContent) 8374 * </div> 8375 * 8376 * <div class="prop-unit"> 8377 * "Safe" content that requires a security context will throw because the contents could potentially be dangerous ... 8378 * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.safeContent"></div> 8379 * <span class="prop-note">innerHTML</span> (safeContent) 8380 * </div> 8381 * 8382 * <div class="prop-unit"> 8383 * ... so that actually dangerous content cannot be executed: 8384 * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.unsafeContent"></div> 8385 * <span class="prop-note">innerHTML</span> (unsafeContent) 8386 * </div> 8387 * 8388 * <div class="prop-unit"> 8389 * ... but unsafe Content that has been trusted explicitly works - only do this if you are 100% sure! 8390 * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.trustedUnsafeContent"></div> 8391 * <span class="prop-note">innerHTML</span> (trustedUnsafeContent) 8392 * </div> 8393 * </div> 8394 * </file> 8395 * <file name="index.html"> 8396 * <main></main> 8397 * </file> 8398 * <file name="styles.css"> 8399 * .prop-unit { 8400 * margin-bottom: 10px; 8401 * } 8402 * 8403 * .prop-binding { 8404 * min-height: 30px; 8405 * border: 1px solid blue; 8406 * } 8407 * 8408 * .prop-note { 8409 * font-family: Monospace; 8410 * } 8411 * </file> 8412 * </example> 8413 * 8414 * 8415 * @example 8416 * ### Binding to innerHTML with ngSanitize 8417 * 8418 * <example name="ngProp" module="exampleNgProp" deps="angular-sanitize.js"> 8419 * <file name="app.js"> 8420 * angular.module('exampleNgProp', ['ngSanitize']) 8421 * .component('main', { 8422 * templateUrl: 'main.html', 8423 * controller: function($sce) { 8424 * this.safeContent = '<strong>Safe content</strong>'; 8425 * this.unsafeContent = '<button onclick="alert(\'Hello XSS!\')">Click for XSS</button>'; 8426 * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent); 8427 * } 8428 * }); 8429 * </file> 8430 * <file name="main.html"> 8431 * <div> 8432 * <div class="prop-unit"> 8433 * "Safe" content will be sanitized ... 8434 * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.safeContent"></div> 8435 * <span class="prop-note">innerHTML</span> (safeContent) 8436 * </div> 8437 * 8438 * <div class="prop-unit"> 8439 * ... as will dangerous content: 8440 * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.unsafeContent"></div> 8441 * <span class="prop-note">innerHTML</span> (unsafeContent) 8442 * </div> 8443 * 8444 * <div class="prop-unit"> 8445 * ... and content that has been trusted explicitly works the same as without ngSanitize: 8446 * <div class="prop-binding" ng-prop-inner_h_t_m_l="$ctrl.trustedUnsafeContent"></div> 8447 * <span class="prop-note">innerHTML</span> (trustedUnsafeContent) 8448 * </div> 8449 * </div> 8450 * </file> 8451 * <file name="index.html"> 8452 * <main></main> 8453 * </file> 8454 * <file name="styles.css"> 8455 * .prop-unit { 8456 * margin-bottom: 10px; 8457 * } 8458 * 8459 * .prop-binding { 8460 * min-height: 30px; 8461 * border: 1px solid blue; 8462 * } 8463 * 8464 * .prop-note { 8465 * font-family: Monospace; 8466 * } 8467 * </file> 8468 * </example> 8469 * 8470 */ 8471 8472/** @ngdoc directive 8473 * @name ngOn 8474 * @restrict A 8475 * @element ANY 8476 * 8477 * @usage 8478 * 8479 * ```html 8480 * <ANY ng-on-eventname="expression"> 8481 * </ANY> 8482 * ``` 8483 * 8484 * or with uppercase letters in property (e.g. "eventName"): 8485 * 8486 * 8487 * ```html 8488 * <ANY ng-on-event_name="expression"> 8489 * </ANY> 8490 * ``` 8491 * 8492 * @description 8493 * The `ngOn` directive adds an event listener to a DOM element via 8494 * {@link angular.element angular.element().on()}, and evaluates an expression when the event is 8495 * fired. 8496 * `ngOn` allows adding listeners for arbitrary events by including 8497 * the event name in the attribute, e.g. `ng-on-drop="onDrop()"` executes the 'onDrop()' expression 8498 * when the `drop` event is fired. 8499 * 8500 * AngularJS provides specific directives for many events, such as {@link ngClick}, so in most 8501 * cases it is not necessary to use `ngOn`. However, AngularJS does not support all events 8502 * (e.g. the `drop` event in the example above), and new events might be introduced in later DOM 8503 * standards. 8504 * 8505 * Another use-case for `ngOn` is listening to 8506 * [custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events) 8507 * fired by 8508 * [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements). 8509 * 8510 * ## Binding to camelCase properties 8511 * 8512 * Since HTML attributes are case-insensitive, camelCase properties like `myEvent` must be escaped. 8513 * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so 8514 * `myEvent` must be written as `ng-on-my_event="expression"`. 8515 * 8516 * @example 8517 * ### Bind to built-in DOM events 8518 * 8519 * <example name="ngOn" module="exampleNgOn"> 8520 * <file name="app.js"> 8521 * angular.module('exampleNgOn', []) 8522 * .component('main', { 8523 * templateUrl: 'main.html', 8524 * controller: function() { 8525 * this.clickCount = 0; 8526 * this.mouseoverCount = 0; 8527 * 8528 * this.loadingState = 0; 8529 * } 8530 * }); 8531 * </file> 8532 * <file name="main.html"> 8533 * <div> 8534 * This is equivalent to `ngClick` and `ngMouseover`:<br> 8535 * <button 8536 * ng-on-click="$ctrl.clickCount = $ctrl.clickCount + 1" 8537 * ng-on-mouseover="$ctrl.mouseoverCount = $ctrl.mouseoverCount + 1">Click or mouseover</button><br> 8538 * clickCount: {{$ctrl.clickCount}}<br> 8539 * mouseover: {{$ctrl.mouseoverCount}} 8540 * 8541 * <hr> 8542 * 8543 * For the `error` and `load` event on images no built-in AngularJS directives exist:<br> 8544 * <img src="thisimagedoesnotexist.png" ng-on-error="$ctrl.loadingState = -1" ng-on-load="$ctrl.loadingState = 1"><br> 8545 * <div ng-switch="$ctrl.loadingState"> 8546 * <span ng-switch-when="0">Image is loading</span> 8547 * <span ng-switch-when="-1">Image load error</span> 8548 * <span ng-switch-when="1">Image loaded successfully</span> 8549 * </div> 8550 * </div> 8551 * </file> 8552 * <file name="index.html"> 8553 * <main></main> 8554 * </file> 8555 * </example> 8556 * 8557 * 8558 * @example 8559 * ### Bind to custom DOM events 8560 * 8561 * <example name="ngOnCustom" module="exampleNgOn"> 8562 * <file name="app.js"> 8563 * angular.module('exampleNgOn', []) 8564 * .component('main', { 8565 * templateUrl: 'main.html', 8566 * controller: function() { 8567 * this.eventLog = ''; 8568 * 8569 * this.listener = function($event) { 8570 * this.eventLog = 'Event with type "' + $event.type + '" fired at ' + $event.detail; 8571 * }; 8572 * } 8573 * }) 8574 * .component('childComponent', { 8575 * templateUrl: 'child.html', 8576 * controller: function($element) { 8577 * this.fireEvent = function() { 8578 * var event = new CustomEvent('customtype', { detail: new Date()}); 8579 * 8580 * $element[0].dispatchEvent(event); 8581 * }; 8582 * } 8583 * }); 8584 * </file> 8585 * <file name="main.html"> 8586 * <child-component ng-on-customtype="$ctrl.listener($event)"></child-component><br> 8587 * <span>Event log: {{$ctrl.eventLog}}</span> 8588 * </file> 8589 * <file name="child.html"> 8590 <button ng-click="$ctrl.fireEvent()">Fire custom event</button> 8591 * </file> 8592 * <file name="index.html"> 8593 * <main></main> 8594 * </file> 8595 * </example> 8596 */ 8597 8598var $compileMinErr = minErr('$compile'); 8599 8600function UNINITIALIZED_VALUE() {} 8601var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE(); 8602 8603/** 8604 * @ngdoc provider 8605 * @name $compileProvider 8606 * 8607 * @description 8608 */ 8609$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; 8610/** @this */ 8611function $CompileProvider($provide, $$sanitizeUriProvider) { 8612 var hasDirectives = {}, 8613 Suffix = 'Directive', 8614 COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/, 8615 CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/, 8616 ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'), 8617 REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; 8618 8619 // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes 8620 // The assumption is that future DOM event attribute names will begin with 8621 // 'on' and be composed of only English letters. 8622 var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; 8623 var bindingCache = createMap(); 8624 8625 function parseIsolateBindings(scope, directiveName, isController) { 8626 var LOCAL_REGEXP = /^([@&]|[=<](\*?))(\??)\s*([\w$]*)$/; 8627 8628 var bindings = createMap(); 8629 8630 forEach(scope, function(definition, scopeName) { 8631 definition = definition.trim(); 8632 8633 if (definition in bindingCache) { 8634 bindings[scopeName] = bindingCache[definition]; 8635 return; 8636 } 8637 var match = definition.match(LOCAL_REGEXP); 8638 8639 if (!match) { 8640 throw $compileMinErr('iscp', 8641 'Invalid {3} for directive \'{0}\'.' + 8642 ' Definition: {... {1}: \'{2}\' ...}', 8643 directiveName, scopeName, definition, 8644 (isController ? 'controller bindings definition' : 8645 'isolate scope definition')); 8646 } 8647 8648 bindings[scopeName] = { 8649 mode: match[1][0], 8650 collection: match[2] === '*', 8651 optional: match[3] === '?', 8652 attrName: match[4] || scopeName 8653 }; 8654 if (match[4]) { 8655 bindingCache[definition] = bindings[scopeName]; 8656 } 8657 }); 8658 8659 return bindings; 8660 } 8661 8662 function parseDirectiveBindings(directive, directiveName) { 8663 var bindings = { 8664 isolateScope: null, 8665 bindToController: null 8666 }; 8667 if (isObject(directive.scope)) { 8668 if (directive.bindToController === true) { 8669 bindings.bindToController = parseIsolateBindings(directive.scope, 8670 directiveName, true); 8671 bindings.isolateScope = {}; 8672 } else { 8673 bindings.isolateScope = parseIsolateBindings(directive.scope, 8674 directiveName, false); 8675 } 8676 } 8677 if (isObject(directive.bindToController)) { 8678 bindings.bindToController = 8679 parseIsolateBindings(directive.bindToController, directiveName, true); 8680 } 8681 if (bindings.bindToController && !directive.controller) { 8682 // There is no controller 8683 throw $compileMinErr('noctrl', 8684 'Cannot bind to controller without directive \'{0}\'s controller.', 8685 directiveName); 8686 } 8687 return bindings; 8688 } 8689 8690 function assertValidDirectiveName(name) { 8691 var letter = name.charAt(0); 8692 if (!letter || letter !== lowercase(letter)) { 8693 throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name); 8694 } 8695 if (name !== name.trim()) { 8696 throw $compileMinErr('baddir', 8697 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces', 8698 name); 8699 } 8700 } 8701 8702 function getDirectiveRequire(directive) { 8703 var require = directive.require || (directive.controller && directive.name); 8704 8705 if (!isArray(require) && isObject(require)) { 8706 forEach(require, function(value, key) { 8707 var match = value.match(REQUIRE_PREFIX_REGEXP); 8708 var name = value.substring(match[0].length); 8709 if (!name) require[key] = match[0] + key; 8710 }); 8711 } 8712 8713 return require; 8714 } 8715 8716 function getDirectiveRestrict(restrict, name) { 8717 if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) { 8718 throw $compileMinErr('badrestrict', 8719 'Restrict property \'{0}\' of directive \'{1}\' is invalid', 8720 restrict, 8721 name); 8722 } 8723 8724 return restrict || 'EA'; 8725 } 8726 8727 /** 8728 * @ngdoc method 8729 * @name $compileProvider#directive 8730 * @kind function 8731 * 8732 * @description 8733 * Register a new directive with the compiler. 8734 * 8735 * @param {string|Object} name Name of the directive in camel-case (i.e.
8735<code>ngBind</code> which 8736 * will match as <code>ng-bind</code>), or an object map of directives where the keys are the 8737 * names and the values
vendor: 8,746 bytes, lines 8737-8932
8737 are the factories. 8738 * @param {Function|Array} directiveFactory An injectable directive factory function. See the 8739 * {@link guide/directive directive guide} and the {@link $compile compile API} for more info. 8740 * @returns {ng.$compileProvider} Self for chaining. 8741 */ 8742 this.directive = function registerDirective(name, directiveFactory) { 8743 assertArg(name, 'name'); 8744 assertNotHasOwnProperty(name, 'directive'); 8745 if (isString(name)) { 8746 assertValidDirectiveName(name); 8747 assertArg(directiveFactory, 'directiveFactory'); 8748 if (!hasDirectives.hasOwnProperty(name)) { 8749 hasDirectives[name] = []; 8750 $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', 8751 function($injector, $exceptionHandler) { 8752 var directives = []; 8753 forEach(hasDirectives[name], function(directiveFactory, index) { 8754 try { 8755 var directive = $injector.invoke(directiveFactory); 8756 if (isFunction(directive)) { 8757 directive = { compile: valueFn(directive) }; 8758 } else if (!directive.compile && directive.link) { 8759 directive.compile = valueFn(directive.link); 8760 } 8761 directive.priority = directive.priority || 0; 8762 directive.index = index; 8763 directive.name = directive.name || name; 8764 directive.require = getDirectiveRequire(directive); 8765 directive.restrict = getDirectiveRestrict(directive.restrict, name); 8766 directive.$$moduleName = directiveFactory.$$moduleName; 8767 directives.push(directive); 8768 } catch (e) { 8769 $exceptionHandler(e); 8770 } 8771 }); 8772 return directives; 8773 }]); 8774 } 8775 hasDirectives[name].push(directiveFactory); 8776 } else { 8777 forEach(name, reverseParams(registerDirective)); 8778 } 8779 return this; 8780 }; 8781 8782 /** 8783 * @ngdoc method 8784 * @name $compileProvider#component 8785 * @module ng 8786 * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`), 8787 * or an object map of components where the keys are the names and the values are the component definition objects. 8788 * @param {Object} options Component definition object (a simplified 8789 * {@link ng.$compile#directive-definition-object directive definition object}), 8790 * with the following properties (all optional): 8791 * 8792 * - `controller` – `{(string|function()=}` – controller constructor function that should be 8793 * associated with newly created scope or the name of a {@link ng.$compile#-controller- 8794 * registered controller} if passed as a string. An empty `noop` function by default. 8795 * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope. 8796 * If present, the controller will be published to scope under the `controllerAs` name. 8797 * If not present, this will default to be `$ctrl`. 8798 * - `template` – `{string=|function()=}` – html template as a string or a function that 8799 * returns an html template as a string which should be used as the contents of this component. 8800 * Empty string by default. 8801 * 8802 * If `template` is a function, then it is {@link auto.$injector#invoke injected} with 8803 * the following locals: 8804 * 8805 * - `$element` - Current element 8806 * - `$attrs` - Current attributes object for the element 8807 * 8808 * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html 8809 * template that should be used as the contents of this component. 8810 * 8811 * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with 8812 * the following locals: 8813 * 8814 * - `$element` - Current element 8815 * - `$attrs` - Current attributes object for the element 8816 * 8817 * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties. 8818 * Component properties are always bound to the component controller and not to the scope. 8819 * See {@link ng.$compile#-bindtocontroller- `bindToController`}. 8820 * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled. 8821 * Disabled by default. 8822 * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to 8823 * this component's controller. The object keys specify the property names under which the required 8824 * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}. 8825 * - `$...` – additional properties to attach to the directive factory function and the controller 8826 * constructor function. (This is used by the component router to annotate) 8827 * 8828 * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls. 8829 * @description 8830 * Register a **component definition** with the compiler. This is a shorthand for registering a special 8831 * type of directive, which represents a self-contained UI component in your application. Such components 8832 * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`). 8833 * 8834 * Component definitions are very simple and do not require as much configuration as defining general 8835 * directives. Component definitions usually consist only of a template and a controller backing it. 8836 * 8837 * In order to make the definition easier, components enforce best practices like use of `controllerAs`, 8838 * `bindToController`. They always have **isolate scope** and are restricted to elements. 8839 * 8840 * Here are a few examples of how you would usually define components: 8841 * 8842 * ```js 8843 * var myMod = angular.module(...); 8844 * myMod.component('myComp', { 8845 * template: '<div>My name is {{$ctrl.name}}</div>', 8846 * controller: function() { 8847 * this.name = 'shahar'; 8848 * } 8849 * }); 8850 * 8851 * myMod.component('myComp', { 8852 * template: '<div>My name is {{$ctrl.name}}</div>', 8853 * bindings: {name: '@'} 8854 * }); 8855 * 8856 * myMod.component('myComp', { 8857 * templateUrl: 'views/my-comp.html', 8858 * controller: 'MyCtrl', 8859 * controllerAs: 'ctrl', 8860 * bindings: {name: '@'} 8861 * }); 8862 * 8863 * ``` 8864 * For more examples, and an in-depth guide, see the {@link guide/component component guide}. 8865 * 8866 * <br /> 8867 * See also {@link ng.$compileProvider#directive $compileProvider.directive()}. 8868 */ 8869 this.component = function registerComponent(name, options) { 8870 if (!isString(name)) { 8871 forEach(name, reverseParams(bind(this, registerComponent))); 8872 return this; 8873 } 8874 8875 var controller = options.controller || function() {}; 8876 8877 function factory($injector) { 8878 function makeInjectable(fn) { 8879 if (isFunction(fn) || isArray(fn)) { 8880 return /** @this */ function(tElement, tAttrs) { 8881 return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs}); 8882 }; 8883 } else { 8884 return fn; 8885 } 8886 } 8887 8888 var template = (!options.template && !options.templateUrl ? '' : options.template); 8889 var ddo = { 8890 controller: controller, 8891 controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl', 8892 template: makeInjectable(template), 8893 templateUrl: makeInjectable(options.templateUrl), 8894 transclude: options.transclude, 8895 scope: {}, 8896 bindToController: options.bindings || {}, 8897 restrict: 'E', 8898 require: options.require 8899 }; 8900 8901 // Copy annotations (starting with $) over to the DDO 8902 forEach(options, function(val, key) { 8903 if (key.charAt(0) === '$') ddo[key] = val; 8904 }); 8905 8906 return ddo; 8907 } 8908 8909 // TODO(pete) remove the following `forEach` before we release 1.6.0 8910 // The [email protected] looks for the annotations on the controller constructor 8911 // Nothing in AngularJS looks for annotations on the factory function but we can't remove 8912 // it from 1.5.x yet. 8913 8914 // Copy any annotation properties (starting with $) over to the factory and controller constructor functions 8915 // These could be used by libraries such as the new component router 8916 forEach(options, function(val, key) { 8917 if (key.charAt(0) === '$') { 8918 factory[key] = val; 8919 // Don't try to copy over annotations to named controller 8920 if (isFunction(controller)) controller[key] = val; 8921 } 8922 }); 8923 8924 factory.$inject = ['$injector']; 8925 8926 return this.directive(name, factory); 8927 }; 8928 8929 8930 /** 8931 * @ngdoc method 8932 * @name $compileProvider#aHrefSanitization
8932Whitelist 8933 * @kind function 8934 * 8935 * @description 8936 * Retrieves or overrides the default regular expression that is used for whitelisting of safe 8937 * urls during a[href] sanitization. 8938 * 8939 * The sanitization is a security measure aimed at preventing XSS attacks via html links. 8940 * 8941 * Any url about to be assigned to a[href] via data-binding is first normalized and turned into 8942 * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` 8943 * regular expression. If a match is found, the original url is written into the dom. Otherwise, 8944 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. 8945 * 8946 * @param {RegExp=} regexp New regexp to whitelist urls with. 8947 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for 8948 * chaining otherwise. 8949 */ 8950 this.aHrefSanitizationWhitelist = function(regexp) { 8951 if (isDefined(regexp)) { 8952 $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); 8953 return this; 8954 } else { 8955 return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); 8956 } 8957 }; 8958 8959 8960 /** 8961 * @ngdoc method 8962 * @name $compileProvider#imgSrcSanitizationWhitelist 8963 * @kind function 8964 * 8965 * @description 8966 * Retrieves or overrides the default regular expression that is used for whitelisting of safe 8967 * urls during img[src] sanitization. 8968 * 8969 * The sanitization is a security measure aimed at prevent XSS attacks via html links. 8970 * 8971 * Any url about to be assigned to img[src] via data-binding is first normalized and turned into 8972 * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` 8973 * regular expression. If a match is found, the original url is written into the dom. Otherwise, 8974 * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. 8975 * 8976 * @param {RegExp=} regexp New regexp to whitelist urls with. 8977 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for 8978 * chaining otherwise. 8979 */ 8980 this.imgSrcSanitizationWhitelist = function(regexp) { 8981 if (isDefined(regexp)) { 8982 $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); 8983 return this; 8984 } else { 8985 return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); 8986 } 8987 }
vendor: 17,217 bytes, lines 8987-9466
8987; 8988 8989 /** 8990 * @ngdoc method 8991 * @name $compileProvider#debugInfoEnabled 8992 * 8993 * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the 8994 * current debugInfoEnabled state 8995 * @returns {*} current value if used as getter or itself (chaining) if used as setter 8996 * 8997 * @kind function 8998 * 8999 * @description 9000 * Call this method to enable/disable various debug runtime information in the compiler such as adding 9001 * binding information and a reference to the current scope on to DOM elements. 9002 * If enabled, the compiler will add the following to DOM elements that have been bound to the scope 9003 * * `ng-binding` CSS class 9004 * * `ng-scope` and `ng-isolated-scope` CSS classes 9005 * * `$binding` data property containing an array of the binding expressions 9006 * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return 9007 * the element's scope. 9008 * * Placeholder comments will contain information about what directive and binding caused the placeholder. 9009 * E.g. `<!-- ngIf: shouldShow() -->`. 9010 * 9011 * You may want to disable this in production for a significant performance boost. See 9012 * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. 9013 * 9014 * The default value is true. 9015 */ 9016 var debugInfoEnabled = true; 9017 this.debugInfoEnabled = function(enabled) { 9018 if (isDefined(enabled)) { 9019 debugInfoEnabled = enabled; 9020 return this; 9021 } 9022 return debugInfoEnabled; 9023 }; 9024 9025 /** 9026 * @ngdoc method 9027 * @name $compileProvider#strictComponentBindingsEnabled 9028 * 9029 * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided, 9030 * otherwise return the current strictComponentBindingsEnabled state. 9031 * @returns {*} current value if used as getter or itself (chaining) if used as setter 9032 * 9033 * @kind function 9034 * 9035 * @description 9036 * Call this method to enable / disable the strict component bindings check. If enabled, the 9037 * compiler will enforce that all scope / controller bindings of a 9038 * {@link $compileProvider#directive directive} / {@link $compileProvider#component component} 9039 * that are not set as optional with `?`, must be provided when the directive is instantiated. 9040 * If not provided, the compiler will throw the 9041 * {@link error/$compile/missingattr $compile:missingattr error}. 9042 * 9043 * The default value is false. 9044 */ 9045 var strictComponentBindingsEnabled = false; 9046 this.strictComponentBindingsEnabled = function(enabled) { 9047 if (isDefined(enabled)) { 9048 strictComponentBindingsEnabled = enabled; 9049 return this; 9050 } 9051 return strictComponentBindingsEnabled; 9052 }; 9053 9054 var TTL = 10; 9055 /** 9056 * @ngdoc method 9057 * @name $compileProvider#onChangesTtl 9058 * @description 9059 * 9060 * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and 9061 * assuming that the model is unstable. 9062 * 9063 * The current default is 10 iterations. 9064 * 9065 * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result 9066 * in several iterations of calls to these hooks. However if an application needs more than the default 10 9067 * iterations to stabilize then you should investigate what is causing the model to continuously change during 9068 * the `$onChanges` hook execution. 9069 * 9070 * Increasing the TTL could have performance implications, so you should not change it without proper justification. 9071 * 9072 * @param {number} limit The number of `$onChanges` hook iterations. 9073 * @returns {number|object} the current limit (or `this` if called as a setter for chaining) 9074 */ 9075 this.onChangesTtl = function(value) { 9076 if (arguments.length) { 9077 TTL = value; 9078 return this; 9079 } 9080 return TTL; 9081 }; 9082 9083 var commentDirectivesEnabledConfig = true; 9084 /** 9085 * @ngdoc method 9086 * @name $compileProvider#commentDirectivesEnabled 9087 * @description 9088 * 9089 * It indicates to the compiler 9090 * whether or not directives on comments should be compiled. 9091 * Defaults to `true`. 9092 * 9093 * Calling this function with false disables the compilation of directives 9094 * on comments for the whole application. 9095 * This results in a compilation performance gain, 9096 * as the compiler doesn't have to check comments when looking for directives. 9097 * This should however only be used if you are sure that no comment directives are used in 9098 * the application (including any 3rd party directives). 9099 * 9100 * @param {boolean} enabled `false` if the compiler may ignore directives on comments 9101 * @returns {boolean|object} the current value (or `this` if called as a setter for chaining) 9102 */ 9103 this.commentDirectivesEnabled = function(value) { 9104 if (arguments.length) { 9105 commentDirectivesEnabledConfig = value; 9106 return this; 9107 } 9108 return commentDirectivesEnabledConfig; 9109 }; 9110 9111 9112 var cssClassDirectivesEnabledConfig = true; 9113 /** 9114 * @ngdoc method 9115 * @name $compileProvider#cssClassDirectivesEnabled 9116 * @description 9117 * 9118 * It indicates to the compiler 9119 * whether or not directives on element classes should be compiled. 9120 * Defaults to `true`. 9121 * 9122 * Calling this function with false disables the compilation of directives 9123 * on element classes for the whole application. 9124 * This results in a compilation performance gain, 9125 * as the compiler doesn't have to check element classes when looking for directives. 9126 * This should however only be used if you are sure that no class directives are used in 9127 * the application (including any 3rd party directives). 9128 * 9129 * @param {boolean} enabled `false` if the compiler may ignore directives on element classes 9130 * @returns {boolean|object} the current value (or `this` if called as a setter for chaining) 9131 */ 9132 this.cssClassDirectivesEnabled = function(value) { 9133 if (arguments.length) { 9134 cssClassDirectivesEnabledConfig = value; 9135 return this; 9136 } 9137 return cssClassDirectivesEnabledConfig; 9138 }; 9139 9140 9141 /** 9142 * The security context of DOM Properties. 9143 * @private 9144 */ 9145 var PROP_CONTEXTS = createMap(); 9146 9147 /** 9148 * @ngdoc method 9149 * @name $compileProvider#addPropertySecurityContext 9150 * @description 9151 * 9152 * Defines the security context for DOM properties bound by ng-prop-*. 9153 * 9154 * @param {string} elementName The element name or '*' to match any element. 9155 * @param {string} propertyName The DOM property name. 9156 * @param {string} ctx The {@link $sce} security context in which this value is safe for use, e.g. `$sce.URL` 9157 * @returns {object} `this` for chaining 9158 */ 9159 this.addPropertySecurityContext = function(elementName, propertyName, ctx) { 9160 var key = (elementName.toLowerCase() + '|' + propertyName.toLowerCase()); 9161 9162 if (key in PROP_CONTEXTS && PROP_CONTEXTS[key] !== ctx) { 9163 throw $compileMinErr('ctxoverride', 'Property context \'{0}.{1}\' already set to \'{2}\', cannot override to \'{3}\'.', elementName, propertyName, PROP_CONTEXTS[key], ctx); 9164 } 9165 9166 PROP_CONTEXTS[key] = ctx; 9167 return this; 9168 }; 9169 9170 /* Default property contexts. 9171 * 9172 * Copy of https://github.com/angular/angular/blob/6.0.6/packages/compiler/src/schema/dom_security_schema.ts#L31-L58 9173 * Changing: 9174 * - SecurityContext.* => SCE_CONTEXTS/$sce.* 9175 * - STYLE => CSS 9176 * - various URL => MEDIA_URL 9177 * - *|formAction, form|action URL => RESOURCE_URL (like the attribute) 9178 */ 9179 (function registerNativePropertyContexts() { 9180 function registerContext(ctx, values) { 9181 forEach(values, function(v) { PROP_CONTEXTS[v.toLowerCase()] = ctx; }); 9182 } 9183 9184 registerContext(SCE_CONTEXTS.HTML, [ 9185 'iframe|srcdoc', 9186 '*|innerHTML', 9187 '*|outerHTML' 9188 ]); 9189 registerContext(SCE_CONTEXTS.CSS, ['*|style']); 9190 registerContext(SCE_CONTEXTS.URL, [ 9191 'area|href', 'area|ping', 9192 'a|href', 'a|ping', 9193 'blockquote|cite', 9194 'body|background', 9195 'del|cite', 9196 'input|src', 9197 'ins|cite', 9198 'q|cite' 9199 ]); 9200 registerContext(SCE_CONTEXTS.MEDIA_URL, [ 9201 'audio|src', 9202 'img|src', 'img|srcset', 9203 'source|src', 'source|srcset', 9204 'track|src', 9205 'video|src', 'video|poster' 9206 ]); 9207 registerContext(SCE_CONTEXTS.RESOURCE_URL, [ 9208 '*|formAction', 9209 'applet|code', 'applet|codebase', 9210 'base|href', 9211 'embed|src', 9212 'frame|src', 9213 'form|action', 9214 'head|profile', 9215 'html|manifest', 9216 'iframe|src', 9217 'link|href', 9218 'media|src', 9219 'object|codebase', 'object|data', 9220 'script|src' 9221 ]); 9222 })(); 9223 9224 9225 this.$get = [ 9226 '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse', 9227 '$controller', '$rootScope', '$sce', '$animate', 9228 function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, 9229 $controller, $rootScope, $sce, $animate) { 9230 9231 var SIMPLE_ATTR_NAME = /^\w/; 9232 var specialAttrHolder = window.document.createElement('div'); 9233 9234 9235 var commentDirectivesEnabled = commentDirectivesEnabledConfig; 9236 var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig; 9237 9238 9239 var onChangesTtl = TTL; 9240 // The onChanges hooks should all be run together in a single digest 9241 // When changes occur, the call to trigger their hooks will be added to this queue 9242 var onChangesQueue; 9243 9244 // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest 9245 function flushOnChangesQueue() { 9246 try { 9247 if (!(--onChangesTtl)) { 9248 // We have hit the TTL limit so reset everything 9249 onChangesQueue = undefined; 9250 throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL); 9251 } 9252 // We must run this hook in an apply since the $$postDigest runs outside apply 9253 $rootScope.$apply(function() { 9254 for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) { 9255 try { 9256 onChangesQueue[i](); 9257 } catch (e) { 9258 $exceptionHandler(e); 9259 } 9260 } 9261 // Reset the queue to trigger a new schedule next time there is a change 9262 onChangesQueue = undefined; 9263 }); 9264 } finally { 9265 onChangesTtl++; 9266 } 9267 } 9268 9269 9270 function sanitizeSrcset(value, invokeType) { 9271 if (!value) { 9272 return value; 9273 } 9274 if (!isString(value)) { 9275 throw $compileMinErr('srcset', 'Can\'t pass trusted values to `{0}`: "{1}"', invokeType, value.toString()); 9276 } 9277 9278 // Such values are a bit too complex to handle automatically inside $sce. 9279 // Instead, we sanitize each of the URIs individually, which works, even dynamically. 9280 9281 // It's not possible to work around this using `$sce.trustAsMediaUrl`. 9282 // If you want to programmatically set explicitly trusted unsafe URLs, you should use 9283 // `$sce.trustAsHtml` on the whole `img` tag and inject it into the DOM using the 9284 // `ng-bind-html` directive. 9285 9286 var result = ''; 9287 9288 // first check if there are spaces because it's not the same pattern 9289 var trimmedSrcset = trim(value); 9290 // ( 999x ,| 999w ,| ,|, ) 9291 var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/; 9292 var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/; 9293 9294 // split srcset into tuple of uri and descriptor except for the last item 9295 var rawUris = trimmedSrcset.split(pattern); 9296 9297 // for each tuples 9298 var nbrUrisWith2parts = Math.floor(rawUris.length / 2); 9299 for (var i = 0; i < nbrUrisWith2parts; i++) { 9300 var innerIdx = i * 2; 9301 // sanitize the uri 9302 result += $sce.getTrustedMediaUrl(trim(rawUris[innerIdx])); 9303 // add the descriptor 9304 result += ' ' + trim(rawUris[innerIdx + 1]); 9305 } 9306 9307 // split the last item into uri and descriptor 9308 var lastTuple = trim(rawUris[i * 2]).split(/\s/); 9309 9310 // sanitize the last uri 9311 result += $sce.getTrustedMediaUrl(trim(lastTuple[0])); 9312 9313 // and add the last descriptor if any 9314 if (lastTuple.length === 2) { 9315 result += (' ' + trim(lastTuple[1])); 9316 } 9317 return result; 9318 } 9319 9320 9321 function Attributes(element, attributesToCopy) { 9322 if (attributesToCopy) { 9323 var keys = Object.keys(attributesToCopy); 9324 var i, l, key; 9325 9326 for (i = 0, l = keys.length; i < l; i++) { 9327 key = keys[i]; 9328 this[key] = attributesToCopy[key]; 9329 } 9330 } else { 9331 this.$attr = {}; 9332 } 9333 9334 this.$$element = element; 9335 } 9336 9337 Attributes.prototype = { 9338 /** 9339 * @ngdoc method 9340 * @name $compile.directive.Attributes#$normalize 9341 * @kind function 9342 * 9343 * @description 9344 * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or 9345 * `data-`) to its normalized, camelCase form. 9346 * 9347 * Also there is special case for Moz prefix starting with upper case letter. 9348 * 9349 * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} 9350 * 9351 * @param {string} name Name to normalize 9352 */ 9353 $normalize: directiveNormalize, 9354 9355 9356 /** 9357 * @ngdoc method 9358 * @name $compile.directive.Attributes#$addClass 9359 * @kind function 9360 * 9361 * @description 9362 * Adds the CSS class value specified by the classVal parameter to the element. If animations 9363 * are enabled then an animation will be triggered for the class addition. 9364 * 9365 * @param {string} classVal The className value that will be added to the element 9366 */ 9367 $addClass: function(classVal) { 9368 if (classVal && classVal.length > 0) { 9369 $animate.addClass(this.$$element, classVal); 9370 } 9371 }, 9372 9373 /** 9374 * @ngdoc method 9375 * @name $compile.directive.Attributes#$removeClass 9376 * @kind function 9377 * 9378 * @description 9379 * Removes the CSS class value specified by the classVal parameter from the element. If 9380 * animations are enabled then an animation will be triggered for the class removal. 9381 * 9382 * @param {string} classVal The className value that will be removed from the element 9383 */ 9384 $removeClass: function(classVal) { 9385 if (classVal && classVal.length > 0) { 9386 $animate.removeClass(this.$$element, classVal); 9387 } 9388 }, 9389 9390 /** 9391 * @ngdoc method 9392 * @name $compile.directive.Attributes#$updateClass 9393 * @kind function 9394 * 9395 * @description 9396 * Adds and removes the appropriate CSS class values to the element based on the difference 9397 * between the new and old CSS class values (specified as newClasses and oldClasses). 9398 * 9399 * @param {string} newClasses The current CSS className value 9400 * @param {string} oldClasses The former CSS className value 9401 */ 9402 $updateClass: function(newClasses, oldClasses) { 9403 var toAdd = tokenDifference(newClasses, oldClasses); 9404 if (toAdd && toAdd.length) { 9405 $animate.addClass(this.$$element, toAdd); 9406 } 9407 9408 var toRemove = tokenDifference(oldClasses, newClasses); 9409 if (toRemove && toRemove.length) { 9410 $animate.removeClass(this.$$element, toRemove); 9411 } 9412 }, 9413 9414 /** 9415 * Set a normalized attribute on the element in a way such that all directives 9416 * can share the attribute. This function properly handles boolean attributes. 9417 * @param {string} key Normalized key. (ie ngAttribute) 9418 * @param {string|boolean} value The value to set. If `null` attribute will be deleted. 9419 * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. 9420 * Defaults to true. 9421 * @param {string=} attrName Optional none normalized name. Defaults to key. 9422 */ 9423 $set: function(key, value, writeAttr, attrName) { 9424 // TODO: decide whether or not to throw an error if "class" 9425 // is set through this function since it may cause $updateClass to 9426 // become unstable. 9427 9428 var node = this.$$element[0], 9429 booleanKey = getBooleanAttrName(node, key), 9430 aliasedKey = getAliasedAttrName(key), 9431 observer = key, 9432 nodeName; 9433 9434 if (booleanKey) { 9435 this.$$element.prop(key, value); 9436 attrName = booleanKey; 9437 } else if (aliasedKey) { 9438 this[aliasedKey] = value; 9439 observer = aliasedKey; 9440 } 9441 9442 this[key] = value; 9443 9444 // translate normalized key to actual key 9445 if (attrName) { 9446 this.$attr[key] = attrName; 9447 } else { 9448 attrName = this.$attr[key]; 9449 if (!attrName) { 9450 this.$attr[key] = attrName = snake_case(key, '-'); 9451 } 9452 } 9453 9454 nodeName = nodeName_(this.$$element); 9455 9456 // Sanitize img[srcset] values. 9457 if (nodeName === 'img' && key === 'srcset') { 9458 this[key] = value = sanitizeSrcset(value, '$set(\'srcset\', value)'); 9459 } 9460 9461 if (writeAttr !== false) { 9462 if (value === null || isUndefined(value)) { 9463 this.$$element.removeAttr(attrName); 9464 } else { 9465 if (SIMPLE_ATTR_NAME.test(attrName)) { 9466
9466this.$$element.attr(attrName, value);
vendor: 66,959 bytes, lines 9466-11063
9466 9467 } else { 9468 setSpecialAttr(this.$$element[0], attrName, value); 9469 } 9470 } 9471 } 9472 9473 // fire observers 9474 var $$observers = this.$$observers; 9475 if ($$observers) { 9476 forEach($$observers[observer], function(fn) { 9477 try { 9478 fn(value); 9479 } catch (e) { 9480 $exceptionHandler(e); 9481 } 9482 }); 9483 } 9484 }, 9485 9486 9487 /** 9488 * @ngdoc method 9489 * @name $compile.directive.Attributes#$observe 9490 * @kind function 9491 * 9492 * @description 9493 * Observes an interpolated attribute. 9494 * 9495 * The observer function will be invoked once during the next `$digest` following 9496 * compilation. The observer is then invoked whenever the interpolated value 9497 * changes. 9498 * 9499 * @param {string} key Normalized key. (ie ngAttribute) . 9500 * @param {function(interpolatedValue)} fn Function that will be called whenever 9501 the interpolated value of the attribute changes. 9502 * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation 9503 * guide} for more info. 9504 * @returns {function()} Returns a deregistration function for this observer. 9505 */ 9506 $observe: function(key, fn) { 9507 var attrs = this, 9508 $$observers = (attrs.$$observers || (attrs.$$observers = createMap())), 9509 listeners = ($$observers[key] || ($$observers[key] = [])); 9510 9511 listeners.push(fn); 9512 $rootScope.$evalAsync(function() { 9513 if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) { 9514 // no one registered attribute interpolation function, so lets call it manually 9515 fn(attrs[key]); 9516 } 9517 }); 9518 9519 return function() { 9520 arrayRemove(listeners, fn); 9521 }; 9522 } 9523 }; 9524 9525 function setSpecialAttr(element, attrName, value) { 9526 // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute` 9527 // so we have to jump through some hoops to get such an attribute 9528 // https://github.com/angular/angular.js/pull/13318 9529 specialAttrHolder.innerHTML = '<span ' + attrName + '>'; 9530 var attributes = specialAttrHolder.firstChild.attributes; 9531 var attribute = attributes[0]; 9532 // We have to remove the attribute from its container element before we can add it to the destination element 9533 attributes.removeNamedItem(attribute.name); 9534 attribute.value = value; 9535 element.attributes.setNamedItem(attribute); 9536 } 9537 9538 function safeAddClass($element, className) { 9539 try { 9540 $element.addClass(className); 9541 } catch (e) { 9542 // ignore, since it means that we are trying to set class on 9543 // SVG element, where class name is read-only. 9544 } 9545 } 9546 9547 9548 var startSymbol = $interpolate.startSymbol(), 9549 endSymbol = $interpolate.endSymbol(), 9550 denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}') 9551 ? identity 9552 : function denormalizeTemplate(template) { 9553 return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); 9554 }, 9555 NG_PREFIX_BINDING = /^ng(Attr|Prop|On)([A-Z].*)$/; 9556 var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/; 9557 9558 compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) { 9559 var bindings = $element.data('$binding') || []; 9560 9561 if (isArray(binding)) { 9562 bindings = bindings.concat(binding); 9563 } else { 9564 bindings.push(binding); 9565 } 9566 9567 $element.data('$binding', bindings); 9568 } : noop; 9569 9570 compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) { 9571 safeAddClass($element, 'ng-binding'); 9572 } : noop; 9573 9574 compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) { 9575 var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope'; 9576 $element.data(dataName, scope); 9577 } : noop; 9578 9579 compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) { 9580 safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope'); 9581 } : noop; 9582 9583 compile.$$createComment = function(directiveName, comment) { 9584 var content = ''; 9585 if (debugInfoEnabled) { 9586 content = ' ' + (directiveName || '') + ': '; 9587 if (comment) content += comment + ' '; 9588 } 9589 return window.document.createComment(content); 9590 }; 9591 9592 return compile; 9593 9594 //================================ 9595 9596 function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, 9597 previousCompileContext) { 9598 if (!($compileNodes instanceof jqLite)) { 9599 // jquery always rewraps, whereas we need to preserve the original selector so that we can 9600 // modify it. 9601 $compileNodes = jqLite($compileNodes); 9602 } 9603 var compositeLinkFn = 9604 compileNodes($compileNodes, transcludeFn, $compileNodes, 9605 maxPriority, ignoreDirective, previousCompileContext); 9606 compile.$$addScopeClass($compileNodes); 9607 var namespace = null; 9608 return function publicLinkFn(scope, cloneConnectFn, options) { 9609 if (!$compileNodes) { 9610 throw $compileMinErr('multilink', 'This element has already been linked.'); 9611 } 9612 assertArg(scope, 'scope'); 9613 9614 if (previousCompileContext && previousCompileContext.needsNewScope) { 9615 // A parent directive did a replace and a directive on this element asked 9616 // for transclusion, which caused us to lose a layer of element on which 9617 // we could hold the new transclusion scope, so we will create it manually 9618 // here. 9619 scope = scope.$parent.$new(); 9620 } 9621 9622 options = options || {}; 9623 var parentBoundTranscludeFn = options.parentBoundTranscludeFn, 9624 transcludeControllers = options.transcludeControllers, 9625 futureParentElement = options.futureParentElement; 9626 9627 // When `parentBoundTranscludeFn` is passed, it is a 9628 // `controllersBoundTransclude` function (it was previously passed 9629 // as `transclude` to directive.link) so we must unwrap it to get 9630 // its `boundTranscludeFn` 9631 if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) { 9632 parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude; 9633 } 9634 9635 if (!namespace) { 9636 namespace = detectNamespaceForChildElements(futureParentElement); 9637 } 9638 var $linkNode; 9639 if (namespace !== 'html') { 9640 // When using a directive with replace:true and templateUrl the $compileNodes 9641 // (or a child element inside of them) 9642 // might change, so we need to recreate the namespace adapted compileNodes 9643 // for call to the link function. 9644 // Note: This will already clone the nodes... 9645 $linkNode = jqLite( 9646 wrapTemplate(namespace, jqLite('<div></div>').append($compileNodes).html()) 9647 ); 9648 } else if (cloneConnectFn) { 9649 // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart 9650 // and sometimes changes the structure of the DOM. 9651 $linkNode = JQLitePrototype.clone.call($compileNodes); 9652 } else { 9653 $linkNode = $compileNodes; 9654 } 9655 9656 if (transcludeControllers) { 9657 for (var controllerName in transcludeControllers) { 9658 $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance); 9659 } 9660 } 9661 9662 compile.$$addScopeInfo($linkNode, scope); 9663 9664 if (cloneConnectFn) cloneConnectFn($linkNode, scope); 9665 if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); 9666 9667 if (!cloneConnectFn) { 9668 $compileNodes = compositeLinkFn = null; 9669 } 9670 return $linkNode; 9671 }; 9672 } 9673 9674 function detectNamespaceForChildElements(parentElement) { 9675 // TODO: Make this detect MathML as well... 9676 var node = parentElement && parentElement[0]; 9677 if (!node) { 9678 return 'html'; 9679 } else { 9680 return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html'; 9681 } 9682 } 9683 9684 /** 9685 * Compile function matches each node in nodeList against the directives. Once all directives 9686 * for a particular node are collected their compile functions are executed. The compile 9687 * functions return values - the linking functions - are combined into a composite linking 9688 * function, which is the a linking function for the node. 9689 * 9690 * @param {NodeList} nodeList an array of nodes or NodeList to compile 9691 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the 9692 * scope argument is auto-generated to the new child of the transcluded parent scope. 9693 * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then 9694 * the rootElement must be set the jqLite collection of the compile root. This is 9695 * needed so that the jqLite collection items can be replaced with widgets. 9696 * @param {number=} maxPriority Max directive priority. 9697 * @returns {Function} A composite linking function of all of the matched directives or null. 9698 */ 9699 function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, 9700 previousCompileContext) { 9701 var linkFns = [], 9702 // `nodeList` can be either an element's `.childNodes` (live NodeList) 9703 // or a jqLite/jQuery collection or an array 9704 notLiveList = isArray(nodeList) || (nodeList instanceof jqLite), 9705 attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound; 9706 9707 9708 for (var i = 0; i < nodeList.length; i++) { 9709 attrs = new Attributes(); 9710 9711 // Support: IE 11 only 9712 // Workaround for #11781 and #14924 9713 if (msie === 11) { 9714 mergeConsecutiveTextNodes(nodeList, i, notLiveList); 9715 } 9716 9717 // We must always refer to `nodeList[i]` hereafter, 9718 // since the nodes can be replaced underneath us. 9719 directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, 9720 ignoreDirective); 9721 9722 nodeLinkFn = (directives.length) 9723 ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement, 9724 null, [], [], previousCompileContext) 9725 : null; 9726 9727 if (nodeLinkFn && nodeLinkFn.scope) { 9728 compile.$$addScopeClass(attrs.$$element); 9729 } 9730 9731 childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || 9732 !(childNodes = nodeList[i].childNodes) || 9733 !childNodes.length) 9734 ? null 9735 : compileNodes(childNodes, 9736 nodeLinkFn ? ( 9737 (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) 9738 && nodeLinkFn.transclude) : transcludeFn); 9739 9740 if (nodeLinkFn || childLinkFn) { 9741 linkFns.push(i, nodeLinkFn, childLinkFn); 9742 linkFnFound = true; 9743 nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn; 9744 } 9745 9746 //use the previous context only for the first element in the virtual group 9747 previousCompileContext = null; 9748 } 9749 9750 // return a linking function if we have found anything, null otherwise 9751 return linkFnFound ? compositeLinkFn : null; 9752 9753 function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { 9754 var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn; 9755 var stableNodeList; 9756 9757 9758 if (nodeLinkFnFound) { 9759 // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our 9760 // offsets don't get screwed up 9761 var nodeListLength = nodeList.length; 9762 stableNodeList = new Array(nodeListLength); 9763 9764 // create a sparse array by only copying the elements which have a linkFn 9765 for (i = 0; i < linkFns.length; i += 3) { 9766 idx = linkFns[i]; 9767 stableNodeList[idx] = nodeList[idx]; 9768 } 9769 } else { 9770 stableNodeList = nodeList; 9771 } 9772 9773 for (i = 0, ii = linkFns.length; i < ii;) { 9774 node = stableNodeList[linkFns[i++]]; 9775 nodeLinkFn = linkFns[i++]; 9776 childLinkFn = linkFns[i++]; 9777 9778 if (nodeLinkFn) { 9779 if (nodeLinkFn.scope) { 9780 childScope = scope.$new(); 9781 compile.$$addScopeInfo(jqLite(node), childScope); 9782 } else { 9783 childScope = scope; 9784 } 9785 9786 if (nodeLinkFn.transcludeOnThisElement) { 9787 childBoundTranscludeFn = createBoundTranscludeFn( 9788 scope, nodeLinkFn.transclude, parentBoundTranscludeFn); 9789 9790 } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { 9791 childBoundTranscludeFn = parentBoundTranscludeFn; 9792 9793 } else if (!parentBoundTranscludeFn && transcludeFn) { 9794 childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); 9795 9796 } else { 9797 childBoundTranscludeFn = null; 9798 } 9799 9800 nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); 9801 9802 } else if (childLinkFn) { 9803 childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); 9804 } 9805 } 9806 } 9807 } 9808 9809 function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) { 9810 var node = nodeList[idx]; 9811 var parent = node.parentNode; 9812 var sibling; 9813 9814 if (node.nodeType !== NODE_TYPE_TEXT) { 9815 return; 9816 } 9817 9818 while (true) { 9819 sibling = parent ? node.nextSibling : nodeList[idx + 1]; 9820 if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) { 9821 break; 9822 } 9823 9824 node.nodeValue = node.nodeValue + sibling.nodeValue; 9825 9826 if (sibling.parentNode) { 9827 sibling.parentNode.removeChild(sibling); 9828 } 9829 if (notLiveList && sibling === nodeList[idx + 1]) { 9830 nodeList.splice(idx + 1, 1); 9831 } 9832 } 9833 } 9834 9835 function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) { 9836 function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { 9837 9838 if (!transcludedScope) { 9839 transcludedScope = scope.$new(false, containingScope); 9840 transcludedScope.$$transcluded = true; 9841 } 9842 9843 return transcludeFn(transcludedScope, cloneFn, { 9844 parentBoundTranscludeFn: previousBoundTranscludeFn, 9845 transcludeControllers: controllers, 9846 futureParentElement: futureParentElement 9847 }); 9848 } 9849 9850 // We need to attach the transclusion slots onto the `boundTranscludeFn` 9851 // so that they are available inside the `controllersBoundTransclude` function 9852 var boundSlots = boundTranscludeFn.$$slots = createMap(); 9853 for (var slotName in transcludeFn.$$slots) { 9854 if (transcludeFn.$$slots[slotName]) { 9855 boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn); 9856 } else { 9857 boundSlots[slotName] = null; 9858 } 9859 } 9860 9861 return boundTranscludeFn; 9862 } 9863 9864 /** 9865 * Looks for directives on the given node and adds them to the directive collection which is 9866 * sorted. 9867 * 9868 * @param node Node to search. 9869 * @param directives An array to which the directives are added to. This array is sorted before 9870 * the function returns. 9871 * @param attrs The shared attrs object which is used to populate the normalized attributes. 9872 * @param {number=} maxPriority Max directive priority. 9873 */ 9874 function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) { 9875 var nodeType = node.nodeType, 9876 attrsMap = attrs.$attr, 9877 match, 9878 nodeName, 9879 className; 9880 9881 switch (nodeType) { 9882 case NODE_TYPE_ELEMENT: /* Element */ 9883 9884 nodeName = nodeName_(node); 9885 9886 // use the node name: <directive> 9887 addDirective(directives, 9888 directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective); 9889 9890 // iterate over the attributes 9891 for (var attr, name, nName, value, ngPrefixMatch, nAttrs = node.attributes, 9892 j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { 9893 var attrStartName = false; 9894 var attrEndName = false; 9895 9896 var isNgAttr = false, isNgProp = false, isNgEvent = false; 9897 var multiElementMatch; 9898 9899 attr = nAttrs[j]; 9900 name = attr.name; 9901 value = attr.value; 9902 9903 nName = directiveNormalize(name.toLowerCase()); 9904 9905 // Support ng-attr-*, ng-prop-* and ng-on-* 9906 if ((ngPrefixMatch = nName.match(NG_PREFIX_BINDING))) { 9907 isNgAttr = ngPrefixMatch[1] === 'Attr'; 9908 isNgProp = ngPrefixMatch[1] === 'Prop'; 9909 isNgEvent = ngPrefixMatch[1] === 'On'; 9910 9911 // Normalize the non-prefixed name 9912 name = name.replace(PREFIX_REGEXP, '') 9913 .toLowerCase() 9914 .substr(4 + ngPrefixMatch[1].length).replace(/_(.)/g, function(match, letter) { 9915 return letter.toUpperCase(); 9916 }); 9917 9918 // Support *-start / *-end multi element directives 9919 } else if ((multiElementMatch = nName.match(MULTI_ELEMENT_DIR_RE)) && directiveIsMultiElement(multiElementMatch[1])) { 9920 attrStartName = name; 9921 attrEndName = name.substr(0, name.length - 5) + 'end'; 9922 name = name.substr(0, name.length - 6); 9923 } 9924 9925 if (isNgProp || isNgEvent) { 9926 attrs[nName] = value; 9927 attrsMap[nName] = attr.name; 9928 9929 if (isNgProp) { 9930 addPropertyDirective(node, directives, nName, name); 9931 } else { 9932 addEventDirective(directives, nName, name); 9933 } 9934 } else { 9935 // Update nName for cases where a prefix was removed 9936 // NOTE: the .toLowerCase() is unnecessary and causes https://github.com/angular/angular.js/issues/16624 for ng-attr-* 9937 nName = directiveNormalize(name.toLowerCase()); 9938 attrsMap[nName] = name; 9939 9940 if (isNgAttr || !attrs.hasOwnProperty(nName)) { 9941 attrs[nName] = value; 9942 if (getBooleanAttrName(node, nName)) { 9943 attrs[nName] = true; // presence means true 9944 } 9945 } 9946 9947 addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); 9948 addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, 9949 attrEndName); 9950 } 9951 } 9952 9953 if (nodeName === 'input' && node.getAttribute('type') === 'hidden') { 9954 // Hidden input elements can have strange behaviour when navigating back to the page 9955 // This tells the browser not to try to cache and reinstate previous values 9956 node.setAttribute('autocomplete', 'off'); 9957 } 9958 9959 // use class as directive 9960 if (!cssClassDirectivesEnabled) break; 9961 className = node.className; 9962 if (isObject(className)) { 9963 // Maybe SVGAnimatedString 9964 className = className.animVal; 9965 } 9966 if (isString(className) && className !== '') { 9967 while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) { 9968 nName = directiveNormalize(match[2]); 9969 if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { 9970 attrs[nName] = trim(match[3]); 9971 } 9972 className = className.substr(match.index + match[0].length); 9973 } 9974 } 9975 break; 9976 case NODE_TYPE_TEXT: /* Text Node */ 9977 addTextInterpolateDirective(directives, node.nodeValue); 9978 break; 9979 case NODE_TYPE_COMMENT: /* Comment */ 9980 if (!commentDirectivesEnabled) break; 9981 collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective); 9982 break; 9983 } 9984 9985 directives.sort(byPriority); 9986 return directives; 9987 } 9988 9989 function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) { 9990 // function created because of performance, try/catch disables 9991 // the optimization of the whole function #14848 9992 try { 9993 var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); 9994 if (match) { 9995 var nName = directiveNormalize(match[1]); 9996 if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { 9997 attrs[nName] = trim(match[2]); 9998 } 9999 } 10000 } catch (e) { 10001 // turns out that under some circumstances IE9 throws errors when one attempts to read 10002 // comment's node value. 10003 // Just ignore it and continue. (Can't seem to reproduce in test case.) 10004 } 10005 } 10006 10007 /** 10008 * Given a node with a directive-start it collects all of the siblings until it finds 10009 * directive-end. 10010 * @param node 10011 * @param attrStart 10012 * @param attrEnd 10013 * @returns {*} 10014 */ 10015 function groupScan(node, attrStart, attrEnd) { 10016 var nodes = []; 10017 var depth = 0; 10018 if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { 10019 do { 10020 if (!node) { 10021 throw $compileMinErr('uterdir', 10022 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.', 10023 attrStart, attrEnd); 10024 } 10025 if (node.nodeType === NODE_TYPE_ELEMENT) { 10026 if (node.hasAttribute(attrStart)) depth++; 10027 if (node.hasAttribute(attrEnd)) depth--; 10028 } 10029 nodes.push(node); 10030 node = node.nextSibling; 10031 } while (depth > 0); 10032 } else { 10033 nodes.push(node); 10034 } 10035 10036 return jqLite(nodes); 10037 } 10038 10039 /** 10040 * Wrapper for linking function which converts normal linking function into a grouped 10041 * linking function. 10042 * @param linkFn 10043 * @param attrStart 10044 * @param attrEnd 10045 * @returns {Function} 10046 */ 10047 function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { 10048 return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) { 10049 element = groupScan(element[0], attrStart, attrEnd); 10050 return linkFn(scope, element, attrs, controllers, transcludeFn); 10051 }; 10052 } 10053 10054 /** 10055 * A function generator that is used to support both eager and lazy compilation 10056 * linking function. 10057 * @param eager 10058 * @param $compileNodes 10059 * @param transcludeFn 10060 * @param maxPriority 10061 * @param ignoreDirective 10062 * @param previousCompileContext 10063 * @returns {Function} 10064 */ 10065 function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) { 10066 var compiled; 10067 10068 if (eager) { 10069 return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext); 10070 } 10071 return /** @this */ function lazyCompilation() { 10072 if (!compiled) { 10073 compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext); 10074 10075 // Null out all of these references in order to make them eligible for garbage collection 10076 // since this is a potentially long lived closure 10077 $compileNodes = transcludeFn = previousCompileContext = null; 10078 } 10079 return compiled.apply(this, arguments); 10080 }; 10081 } 10082 10083 /** 10084 * Once the directives have been collected, their compile functions are executed. This method 10085 * is responsible for inlining directive templates as well as terminating the application 10086 * of the directives if the terminal directive has been reached. 10087 * 10088 * @param {Array} directives Array of collected directives to execute their compile function. 10089 * this needs to be pre-sorted by priority order. 10090 * @param {Node} compileNode The raw DOM node to apply the compile functions to 10091 * @param {Object} templateAttrs The shared attribute function 10092 * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the 10093 * scope argument is auto-generated to the new 10094 * child of the transcluded parent scope. 10095 * @param {JQLite} jqCollection If we are working on the root of the compile tree then this 10096 * argument has the root jqLite array so that we can replace nodes 10097 * on it. 10098 * @param {Object=} originalReplaceDirective An optional directive that will be ignored when 10099 * compiling the transclusion. 10100 * @param {Array.<Function>} preLinkFns 10101 * @param {Array.<Function>} postLinkFns 10102 * @param {Object} previousCompileContext Context used for previous compilation of the current 10103 * node 10104 * @returns {Function} linkFn 10105 */ 10106 function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, 10107 jqCollection, originalReplaceDirective, preLinkFns, postLinkFns, 10108 previousCompileContext) { 10109 previousCompileContext = previousCompileContext || {}; 10110 10111 var terminalPriority = -Number.MAX_VALUE, 10112 newScopeDirective = previousCompileContext.newScopeDirective, 10113 controllerDirectives = previousCompileContext.controllerDirectives, 10114 newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, 10115 templateDirective = previousCompileContext.templateDirective, 10116 nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, 10117 hasTranscludeDirective = false, 10118 hasTemplate = false, 10119 hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, 10120 $compileNode = templateAttrs.$$element = jqLite(compileNode), 10121 directive, 10122 directiveName, 10123 $template, 10124 replaceDirective = originalReplaceDirective, 10125 childTranscludeFn = transcludeFn, 10126 linkFn, 10127 didScanForMultipleTransclusion = false, 10128 mightHaveMultipleTransclusionError = false, 10129 directiveValue; 10130 10131 // executes all directives on the current element 10132 for (var i = 0, ii = directives.length; i < ii; i++) { 10133 directive = directives[i]; 10134 var attrStart = directive.$$start; 10135 var attrEnd = directive.$$end; 10136 10137 // collect multiblock sections 10138 if (attrStart) { 10139 $compileNode = groupScan(compileNode, attrStart, attrEnd); 10140 } 10141 $template = undefined; 10142 10143 if (terminalPriority > directive.priority) { 10144 break; // prevent further processing of directives 10145 } 10146 10147 directiveValue = directive.scope; 10148 10149 if (directiveValue) { 10150 10151 // skip the check for directives with async templates, we'll check the derived sync 10152 // directive when the template arrives 10153 if (!directive.templateUrl) { 10154 if (isObject(directiveValue)) { 10155 // This directive is trying to add an isolated scope. 10156 // Check that there is no scope of any kind already 10157 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, 10158 directive, $compileNode); 10159 newIsolateScopeDirective = directive; 10160 } else { 10161 // This directive is trying to add a child scope. 10162 // Check that there is no isolated scope already 10163 assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, 10164 $compileNode); 10165 } 10166 } 10167 10168 newScopeDirective = newScopeDirective || directive; 10169 } 10170 10171 directiveName = directive.name; 10172 10173 // If we encounter a condition that can result in transclusion on the directive, 10174 // then scan ahead in the remaining directives for others that may cause a multiple 10175 // transclusion error to be thrown during the compilation process. If a matching directive 10176 // is found, then we know that when we encounter a transcluded directive, we need to eagerly 10177 // compile the `transclude` function rather than doing it lazily in order to throw 10178 // exceptions at the correct time 10179 if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template)) 10180 || (directive.transclude && !directive.$$tlb))) { 10181 var candidateDirective; 10182 10183 for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) { 10184 if ((candidateDirective.transclude && !candidateDirective.$$tlb) 10185 || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) { 10186 mightHaveMultipleTransclusionError = true; 10187 break; 10188 } 10189 } 10190 10191 didScanForMultipleTransclusion = true; 10192 } 10193 10194 if (!directive.templateUrl && directive.controller) { 10195 controllerDirectives = controllerDirectives || createMap(); 10196 assertNoDuplicate('\'' + directiveName + '\' controller', 10197 controllerDirectives[directiveName], directive, $compileNode); 10198 controllerDirectives[directiveName] = directive; 10199 } 10200 10201 directiveValue = directive.transclude; 10202 10203 if (directiveValue) { 10204 hasTranscludeDirective = true; 10205 10206 // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. 10207 // This option should only be used by directives that know how to safely handle element transclusion, 10208 // where the transcluded nodes are added or replaced after linking. 10209 if (!directive.$$tlb) { 10210 assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode); 10211 nonTlbTranscludeDirective = directive; 10212 } 10213 10214 if (directiveValue === 'element') { 10215 hasElementTranscludeDirective = true; 10216 terminalPriority = directive.priority; 10217 $template = $compileNode; 10218 $compileNode = templateAttrs.$$element = 10219 jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName])); 10220 compileNode = $compileNode[0]; 10221 replaceWith(jqCollection, sliceArgs($template), compileNode); 10222 10223 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority, 10224 replaceDirective && replaceDirective.name, { 10225 // Don't pass in: 10226 // - controllerDirectives - otherwise we'll create duplicates controllers 10227 // - newIsolateScopeDirective or templateDirective - combining templates with 10228 // element transclusion doesn't make sense. 10229 // 10230 // We need only nonTlbTranscludeDirective so that we prevent putting transclusion 10231 // on the same element more than once. 10232 nonTlbTranscludeDirective: nonTlbTranscludeDirective 10233 }); 10234 } else { 10235 10236 var slots = createMap(); 10237 10238 if (!isObject(directiveValue)) { 10239 $template = jqLite(jqLiteClone(compileNode)).contents(); 10240 } else { 10241 10242 // We have transclusion slots, 10243 // collect them up, compile them and store their transclusion functions 10244 $template = window.document.createDocumentFragment(); 10245 10246 var slotMap = createMap(); 10247 var filledSlots = createMap(); 10248 10249 // Parse the element selectors 10250 forEach(directiveValue, function(elementSelector, slotName) { 10251 // If an element selector starts with a ? then it is optional 10252 var optional = (elementSelector.charAt(0) === '?'); 10253 elementSelector = optional ? elementSelector.substring(1) : elementSelector; 10254 10255 slotMap[elementSelector] = slotName; 10256 10257 // We explicitly assign `null` since this implies that a slot was defined but not filled. 10258 // Later when calling boundTransclusion functions with a slot name we only error if the 10259 // slot is `undefined` 10260 slots[slotName] = null; 10261 10262 // filledSlots contains `true` for all slots that are either optional or have been 10263 // filled. This is used to check that we have not missed any required slots 10264 filledSlots[slotName] = optional; 10265 }); 10266 10267 // Add the matching elements into their slot 10268 forEach($compileNode.contents(), function(node) { 10269 var slotName = slotMap[directiveNormalize(nodeName_(node))]; 10270 if (slotName) { 10271 filledSlots[slotName] = true; 10272 slots[slotName] = slots[slotName] || window.document.createDocumentFragment(); 10273 slots[slotName].appendChild(node); 10274 } else { 10275 $template.appendChild(node); 10276 } 10277 }); 10278 10279 // Check for required slots that were not filled 10280 forEach(filledSlots, function(filled, slotName) { 10281 if (!filled) { 10282 throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName); 10283 } 10284 }); 10285 10286 for (var slotName in slots) { 10287 if (slots[slotName]) { 10288 // Only define a transclusion function if the slot was filled 10289 var slotCompileNodes = jqLite(slots[slotName].childNodes); 10290 slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slotCompileNodes, transcludeFn); 10291 } 10292 } 10293 10294 $template = jqLite($template.childNodes); 10295 } 10296 10297 $compileNode.empty(); // clear contents 10298 childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined, 10299 undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope}); 10300 childTranscludeFn.$$slots = slots; 10301 } 10302 } 10303 10304 if (directive.template) { 10305 hasTemplate = true; 10306 assertNoDuplicate('template', templateDirective, directive, $compileNode); 10307 templateDirective = directive; 10308 10309 directiveValue = (isFunction(directive.template)) 10310 ? directive.template($compileNode, templateAttrs) 10311 : directive.template; 10312 10313 directiveValue = denormalizeTemplate(directiveValue); 10314 10315 if (directive.replace) { 10316 replaceDirective = directive; 10317 if (jqLiteIsTextNode(directiveValue)) { 10318 $template = []; 10319 } else { 10320 $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue))); 10321 } 10322 compileNode = $template[0]; 10323 10324 if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { 10325 throw $compileMinErr('tplrt', 10326 'Template for directive \'{0}\' must have exactly one root element. {1}', 10327 directiveName, ''); 10328 } 10329 10330 replaceWith(jqCollection, $compileNode, compileNode); 10331 10332 var newTemplateAttrs = {$attr: {}}; 10333 10334 // combine directives from the original node and from the template: 10335 // - take the array of directives for this element 10336 // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed) 10337 // - collect directives from the template and sort them by priority 10338 // - combine directives as: processed + template + unprocessed 10339 var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); 10340 var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); 10341 10342 if (newIsolateScopeDirective || newScopeDirective) { 10343 // The original directive caused the current element to be replaced but this element 10344 // also needs to have a new scope, so we need to tell the template directives 10345 // that they would need to get their scope from further up, if they require transclusion 10346 markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective); 10347 } 10348 directives = directives.concat(templateDirectives).concat(unprocessedDirectives); 10349 mergeTemplateAttributes(templateAttrs, newTemplateAttrs); 10350 10351 ii = directives.length; 10352 } else { 10353 $compileNode.html(directiveValue); 10354 } 10355 } 10356 10357 if (directive.templateUrl) { 10358 hasTemplate = true; 10359 assertNoDuplicate('template', templateDirective, directive, $compileNode); 10360 templateDirective = directive; 10361 10362 if (directive.replace) { 10363 replaceDirective = directive; 10364 } 10365 10366 // eslint-disable-next-line no-func-assign 10367 nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, 10368 templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { 10369 controllerDirectives: controllerDirectives, 10370 newScopeDirective: (newScopeDirective !== directive) && newScopeDirective, 10371 newIsolateScopeDirective: newIsolateScopeDirective, 10372 templateDirective: templateDirective, 10373 nonTlbTranscludeDirective: nonTlbTranscludeDirective 10374 }); 10375 ii = directives.length; 10376 } else if (directive.compile) { 10377 try { 10378 linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); 10379 var context = directive.$$originalDirective || directive; 10380 if (isFunction(linkFn)) { 10381 addLinkFns(null, bind(context, linkFn), attrStart, attrEnd); 10382 } else if (linkFn) { 10383 addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd); 10384 } 10385 } catch (e) { 10386 $exceptionHandler(e, startingTag($compileNode)); 10387 } 10388 } 10389 10390 if (directive.terminal) { 10391 nodeLinkFn.terminal = true; 10392 terminalPriority = Math.max(terminalPriority, directive.priority); 10393 } 10394 10395 } 10396 10397 nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; 10398 nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; 10399 nodeLinkFn.templateOnThisElement = hasTemplate; 10400 nodeLinkFn.transclude = childTranscludeFn; 10401 10402 previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; 10403 10404 // might be normal or delayed nodeLinkFn depending on if templateUrl is present 10405 return nodeLinkFn; 10406 10407 //////////////////// 10408 10409 function addLinkFns(pre, post, attrStart, attrEnd) { 10410 if (pre) { 10411 if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); 10412 pre.require = directive.require; 10413 pre.directiveName = directiveName; 10414 if (newIsolateScopeDirective === directive || directive.$$isolateScope) { 10415 pre = cloneAndAnnotateFn(pre, {isolateScope: true}); 10416 } 10417 preLinkFns.push(pre); 10418 } 10419 if (post) { 10420 if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); 10421 post.require = directive.require; 10422 post.directiveName = directiveName; 10423 if (newIsolateScopeDirective === directive || directive.$$isolateScope) { 10424 post = cloneAndAnnotateFn(post, {isolateScope: true}); 10425 } 10426 postLinkFns.push(post); 10427 } 10428 } 10429 10430 function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { 10431 var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element, 10432 attrs, scopeBindingInfo; 10433 10434 if (compileNode === linkNode) { 10435 attrs = templateAttrs; 10436 $element = templateAttrs.$$element; 10437 } else { 10438 $element = jqLite(linkNode); 10439 attrs = new Attributes($element, templateAttrs); 10440 } 10441 10442 controllerScope = scope; 10443 if (newIsolateScopeDirective) { 10444 isolateScope = scope.$new(true); 10445 } else if (newScopeDirective) { 10446 controllerScope = scope.$parent; 10447 } 10448 10449 if (boundTranscludeFn) { 10450 // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn` 10451 // is later passed as `parentBoundTranscludeFn` to `publicLinkFn` 10452 transcludeFn = controllersBoundTransclude; 10453 transcludeFn.$$boundTransclude = boundTranscludeFn; 10454 // expose the slots on the `$transclude` function 10455 transcludeFn.isSlotFilled = function(slotName) { 10456 return !!boundTranscludeFn.$$slots[slotName]; 10457 }; 10458 } 10459 10460 if (controllerDirectives) { 10461 elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective); 10462 } 10463 10464 if (newIsolateScopeDirective) { 10465 // Initialize isolate scope bindings for new isolate scope directive. 10466 compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective || 10467 templateDirective === newIsolateScopeDirective.$$originalDirective))); 10468 compile.$$addScopeClass($element, true); 10469 isolateScope.$$isolateBindings = 10470 newIsolateScopeDirective.$$isolateBindings; 10471 scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope, 10472 isolateScope.$$isolateBindings, 10473 newIsolateScopeDirective); 10474 if (scopeBindingInfo.removeWatches) { 10475 isolateScope.$on('$destroy', scopeBindingInfo.removeWatches); 10476 } 10477 } 10478 10479 // Initialize bindToController bindings 10480 for (var name in elementControllers) { 10481 var controllerDirective = controllerDirectives[name]; 10482 var controller = elementControllers[name]; 10483 var bindings = controllerDirective.$$bindings.bindToController; 10484 10485 controller.instance = controller(); 10486 $element.data('$' + controllerDirective.name + 'Controller', controller.instance); 10487 controller.bindingInfo = 10488 initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); 10489 } 10490 10491 // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy 10492 forEach(controllerDirectives, function(controllerDirective, name) { 10493 var require = controllerDirective.require; 10494 if (controllerDirective.bindToController && !isArray(require) && isObject(require)) { 10495 extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers)); 10496 } 10497 }); 10498 10499 // Handle the init and destroy lifecycle hooks on all controllers that have them 10500 forEach(elementControllers, function(controller) { 10501 var controllerInstance = controller.instance; 10502 if (isFunction(controllerInstance.$onChanges)) { 10503 try { 10504 controllerInstance.$onChanges(controller.bindingInfo.initialChanges); 10505 } catch (e) { 10506 $exceptionHandler(e); 10507 } 10508 } 10509 if (isFunction(controllerInstance.$onInit)) { 10510 try { 10511 controllerInstance.$onInit(); 10512 } catch (e) { 10513 $exceptionHandler(e); 10514 } 10515 } 10516 if (isFunction(controllerInstance.$doCheck)) { 10517 controllerScope.$watch(function() { controllerInstance.$doCheck(); }); 10518 controllerInstance.$doCheck(); 10519 } 10520 if (isFunction(controllerInstance.$onDestroy)) { 10521 controllerScope.$on('$destroy', function callOnDestroyHook() { 10522 controllerInstance.$onDestroy(); 10523 }); 10524 } 10525 }); 10526 10527 // PRELINKING 10528 for (i = 0, ii = preLinkFns.length; i < ii; i++) { 10529 linkFn = preLinkFns[i]; 10530 invokeLinkFn(linkFn, 10531 linkFn.isolateScope ? isolateScope : scope, 10532 $element, 10533 attrs, 10534 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), 10535 transcludeFn 10536 ); 10537 } 10538 10539 // RECURSION 10540 // We only pass the isolate scope, if the isolate directive has a template, 10541 // otherwise the child elements do not belong to the isolate directive. 10542 var scopeToChild = scope; 10543 if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { 10544 scopeToChild = isolateScope; 10545 } 10546 if (childLinkFn) { 10547 childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); 10548 } 10549 10550 // POSTLINKING 10551 for (i = postLinkFns.length - 1; i >= 0; i--) { 10552 linkFn = postLinkFns[i]; 10553 invokeLinkFn(linkFn, 10554 linkFn.isolateScope ? isolateScope : scope, 10555 $element, 10556 attrs, 10557 linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), 10558 transcludeFn 10559 ); 10560 } 10561 10562 // Trigger $postLink lifecycle hooks 10563 forEach(elementControllers, function(controller) { 10564 var controllerInstance = controller.instance; 10565 if (isFunction(controllerInstance.$postLink)) { 10566 controllerInstance.$postLink(); 10567 } 10568 }); 10569 10570 // This is the function that is injected as `$transclude`. 10571 // Note: all arguments are optional! 10572 function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) { 10573 var transcludeControllers; 10574 // No scope passed in: 10575 if (!isScope(scope)) { 10576 slotName = futureParentElement; 10577 futureParentElement = cloneAttachFn; 10578 cloneAttachFn = scope; 10579 scope = undefined; 10580 } 10581 10582 if (hasElementTranscludeDirective) { 10583 transcludeControllers = elementControllers; 10584 } 10585 if (!futureParentElement) { 10586 futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; 10587 } 10588 if (slotName) { 10589 // slotTranscludeFn can be one of three things: 10590 // * a transclude function - a filled slot 10591 // * `null` - an optional slot that was not filled 10592 // * `undefined` - a slot that was not declared (i.e. invalid) 10593 var slotTranscludeFn = boundTranscludeFn.$$slots[slotName]; 10594 if (slotTranscludeFn) { 10595 return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); 10596 } else if (isUndefined(slotTranscludeFn)) { 10597 throw $compileMinErr('noslot', 10598 'No parent directive that requires a transclusion with slot name "{0}". ' + 10599 'Element: {1}', 10600 slotName, startingTag($element)); 10601 } 10602 } else { 10603 return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); 10604 } 10605 } 10606 } 10607 } 10608 10609 function getControllers(directiveName, require, $element, elementControllers) { 10610 var value; 10611 10612 if (isString(require)) { 10613 var match = require.match(REQUIRE_PREFIX_REGEXP); 10614 var name = require.substring(match[0].length); 10615 var inheritType = match[1] || match[3]; 10616 var optional = match[2] === '?'; 10617 10618 //If only parents then start at the parent element 10619 if (inheritType === '^^') { 10620 $element = $element.parent(); 10621 //Otherwise attempt getting the controller from elementControllers in case 10622 //the element is transcluded (and has no data) and to avoid .data if possible 10623 } else { 10624 value = elementControllers && elementControllers[name]; 10625 value = value && value.instance; 10626 } 10627 10628 if (!value) { 10629 var dataName = '$' + name + 'Controller'; 10630 10631 if (inheritType === '^^' && $element[0] && $element[0].nodeType === NODE_TYPE_DOCUMENT) { 10632 // inheritedData() uses the documentElement when it finds the document, so we would 10633 // require from the element itself. 10634 value = null; 10635 } else { 10636 value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName); 10637 } 10638 } 10639 10640 if (!value && !optional) { 10641 throw $compileMinErr('ctreq', 10642 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!', 10643 name, directiveName); 10644 } 10645 } else if (isArray(require)) { 10646 value = []; 10647 for (var i = 0, ii = require.length; i < ii; i++) { 10648 value[i] = getControllers(directiveName, require[i], $element, elementControllers); 10649 } 10650 } else if (isObject(require)) { 10651 value = {}; 10652 forEach(require, function(controller, property) { 10653 value[property] = getControllers(directiveName, controller, $element, elementControllers); 10654 }); 10655 } 10656 10657 return value || null; 10658 } 10659 10660 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) { 10661 var elementControllers = createMap(); 10662 for (var controllerKey in controllerDirectives) { 10663 var directive = controllerDirectives[controllerKey]; 10664 var locals = { 10665 $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, 10666 $element: $element, 10667 $attrs: attrs, 10668 $transclude: transcludeFn 10669 }; 10670 10671 var controller = directive.controller; 10672 if (controller === '@') { 10673 controller = attrs[directive.name]; 10674 } 10675 10676 var controllerInstance = $controller(controller, locals, true, directive.controllerAs); 10677 10678 // For directives with element transclusion the element is a comment. 10679 // In this case .data will not attach any data. 10680 // Instead, we save the controllers for the element in a local hash and attach to .data 10681 // later, once we have the actual element. 10682 elementControllers[directive.name] = controllerInstance; 10683 $element.data('$' + directive.name + 'Controller', controllerInstance.instance); 10684 } 10685 return elementControllers; 10686 } 10687 10688 // Depending upon the context in which a directive finds itself it might need to have a new isolated 10689 // or child scope created. For instance: 10690 // * if the directive has been pulled into a template because another directive with a higher priority 10691 // asked for element transclusion 10692 // * if the directive itself asks for transclusion but it is at the root of a template and the original 10693 // element was replaced. See https://github.com/angular/angular.js/issues/12936 10694 function markDirectiveScope(directives, isolateScope, newScope) { 10695 for (var j = 0, jj = directives.length; j < jj; j++) { 10696 directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope}); 10697 } 10698 } 10699 10700 /** 10701 * looks up the directive and decorates it with exception handling and proper parameters. We 10702 * call this the boundDirective. 10703 * 10704 * @param {string} name name of the directive to look up. 10705 * @param {string} location The directive must be found in specific format. 10706 * String containing any of theses characters: 10707 * 10708 * * `E`: element name 10709 * * `A': attribute 10710 * * `C`: class 10711 * * `M`: comment 10712 * @returns {boolean} true if directive was added. 10713 */ 10714 function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName, 10715 endAttrName) { 10716 if (name === ignoreDirective) return null; 10717 var match = null; 10718 if (hasDirectives.hasOwnProperty(name)) { 10719 for (var directive, directives = $injector.get(name + Suffix), 10720 i = 0, ii = directives.length; i < ii; i++) { 10721 directive = directives[i]; 10722 if ((isUndefined(maxPriority) || maxPriority > directive.priority) && 10723 directive.restrict.indexOf(location) !== -1) { 10724 if (startAttrName) { 10725 directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); 10726 } 10727 if (!directive.$$bindings) { 10728 var bindings = directive.$$bindings = 10729 parseDirectiveBindings(directive, directive.name); 10730 if (isObject(bindings.isolateScope)) { 10731 directive.$$isolateBindings = bindings.isolateScope; 10732 } 10733 } 10734 tDirectives.push(directive); 10735 match = directive; 10736 } 10737 } 10738 } 10739 return match; 10740 } 10741 10742 10743 /** 10744 * looks up the directive and returns true if it is a multi-element directive, 10745 * and therefore requires DOM nodes between -start and -end markers to be grouped 10746 * together. 10747 * 10748 * @param {string} name name of the directive to look up. 10749 * @returns true if directive was registered as multi-element. 10750 */ 10751 function directiveIsMultiElement(name) { 10752 if (hasDirectives.hasOwnProperty(name)) { 10753 for (var directive, directives = $injector.get(name + Suffix), 10754 i = 0, ii = directives.length; i < ii; i++) { 10755 directive = directives[i]; 10756 if (directive.multiElement) { 10757 return true; 10758 } 10759 } 10760 } 10761 return false; 10762 } 10763 10764 /** 10765 * When the element is replaced with HTML template then the new attributes 10766 * on the template need to be merged with the existing attributes in the DOM. 10767 * The desired effect is to have both of the attributes present. 10768 * 10769 * @param {object} dst destination attributes (original DOM) 10770 * @param {object} src source attributes (from the directive template) 10771 */ 10772 function mergeTemplateAttributes(dst, src) { 10773 var srcAttr = src.$attr, 10774 dstAttr = dst.$attr; 10775 10776 // reapply the old attributes to the new element 10777 forEach(dst, function(value, key) { 10778 if (key.charAt(0) !== '$') { 10779 if (src[key] && src[key] !== value) { 10780 if (value.length) { 10781 value += (key === 'style' ? ';' : ' ') + src[key]; 10782 } else { 10783 value = src[key]; 10784 } 10785 } 10786 dst.$set(key, value, true, srcAttr[key]); 10787 } 10788 }); 10789 10790 // copy the new attributes on the old attrs object 10791 forEach(src, function(value, key) { 10792 // Check if we already set this attribute in the loop above. 10793 // `dst` will never contain hasOwnProperty as DOM parser won't let it. 10794 // You will get an "InvalidCharacterError: DOM Exception 5" error if you 10795 // have an attribute like "has-own-property" or "data-has-own-property", etc. 10796 if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') { 10797 dst[key] = value; 10798 10799 if (key !== 'class' && key !== 'style') { 10800 dstAttr[key] = srcAttr[key]; 10801 } 10802 } 10803 }); 10804 } 10805 10806 10807 function compileTemplateUrl(directives, $compileNode, tAttrs, 10808 $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) { 10809 var linkQueue = [], 10810 afterTemplateNodeLinkFn, 10811 afterTemplateChildLinkFn, 10812 beforeTemplateCompileNode = $compileNode[0], 10813 origAsyncDirective = directives.shift(), 10814 derivedSyncDirective = inherit(origAsyncDirective, { 10815 templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective 10816 }), 10817 templateUrl = (isFunction(origAsyncDirective.templateUrl)) 10818 ? origAsyncDirective.templateUrl($compileNode, tAttrs) 10819 : origAsyncDirective.templateUrl, 10820 templateNamespace = origAsyncDirective.templateNamespace; 10821 10822 $compileNode.empty(); 10823 10824 $templateRequest(templateUrl) 10825 .then(function(content) { 10826 var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; 10827 10828 content = denormalizeTemplate(content); 10829 10830 if (origAsyncDirective.replace) { 10831 if (jqLiteIsTextNode(content)) { 10832 $template = []; 10833 } else { 10834 $template = removeComments(wrapTemplate(templateNamespace, trim(content))); 10835 } 10836 compileNode = $template[0]; 10837 10838 if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { 10839 throw $compileMinErr('tplrt', 10840 'Template for directive \'{0}\' must have exactly one root element. {1}', 10841 origAsyncDirective.name, templateUrl); 10842 } 10843 10844 tempTemplateAttrs = {$attr: {}}; 10845 replaceWith($rootElement, $compileNode, compileNode); 10846 var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); 10847 10848 if (isObject(origAsyncDirective.scope)) { 10849 // the original directive that caused the template to be loaded async required 10850 // an isolate scope 10851 markDirectiveScope(templateDirectives, true); 10852 } 10853 directives = templateDirectives.concat(directives); 10854 mergeTemplateAttributes(tAttrs, tempTemplateAttrs); 10855 } else { 10856 compileNode = beforeTemplateCompileNode; 10857 $compileNode.html(content); 10858 } 10859 10860 directives.unshift(derivedSyncDirective); 10861 10862 afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, 10863 childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, 10864 previousCompileContext); 10865 forEach($rootElement, function(node, i) { 10866 if (node === compileNode) { 10867 $rootElement[i] = $compileNode[0]; 10868 } 10869 }); 10870 afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); 10871 10872 while (linkQueue.length) { 10873 var scope = linkQueue.shift(), 10874 beforeTemplateLinkNode = linkQueue.shift(), 10875 linkRootElement = linkQueue.shift(), 10876 boundTranscludeFn = linkQueue.shift(), 10877 linkNode = $compileNode[0]; 10878 10879 if (scope.$$destroyed) continue; 10880 10881 if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { 10882 var oldClasses = beforeTemplateLinkNode.className; 10883 10884 if (!(previousCompileContext.hasElementTranscludeDirective && 10885 origAsyncDirective.replace)) { 10886 // it was cloned therefore we have to clone as well. 10887 linkNode = jqLiteClone(compileNode); 10888 } 10889 replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); 10890 10891 // Copy in CSS classes from original node 10892 safeAddClass(jqLite(linkNode), oldClasses); 10893 } 10894 if (afterTemplateNodeLinkFn.transcludeOnThisElement) { 10895 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); 10896 } else { 10897 childBoundTranscludeFn = boundTranscludeFn; 10898 } 10899 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, 10900 childBoundTranscludeFn); 10901 } 10902 linkQueue = null; 10903 }).catch(function(error) { 10904 if (isError(error)) { 10905 $exceptionHandler(error); 10906 } 10907 }); 10908 10909 return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { 10910 var childBoundTranscludeFn = boundTranscludeFn; 10911 if (scope.$$destroyed) return; 10912 if (linkQueue) { 10913 linkQueue.push(scope, 10914 node, 10915 rootElement, 10916 childBoundTranscludeFn); 10917 } else { 10918 if (afterTemplateNodeLinkFn.transcludeOnThisElement) { 10919 childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); 10920 } 10921 afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); 10922 } 10923 }; 10924 } 10925 10926 10927 /** 10928 * Sorting function for bound directives. 10929 */ 10930 function byPriority(a, b) { 10931 var diff = b.priority - a.priority; 10932 if (diff !== 0) return diff; 10933 if (a.name !== b.name) return (a.name < b.name) ? -1 : 1; 10934 return a.index - b.index; 10935 } 10936 10937 function assertNoDuplicate(what, previousDirective, directive, element) { 10938 10939 function wrapModuleNameIfDefined(moduleName) { 10940 return moduleName ? 10941 (' (module: ' + moduleName + ')') : 10942 ''; 10943 } 10944 10945 if (previousDirective) { 10946 throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}', 10947 previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName), 10948 directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element)); 10949 } 10950 } 10951 10952 10953 function addTextInterpolateDirective(directives, text) { 10954 var interpolateFn = $interpolate(text, true); 10955 if (interpolateFn) { 10956 directives.push({ 10957 priority: 0, 10958 compile: function textInterpolateCompileFn(templateNode) { 10959 var templateNodeParent = templateNode.parent(), 10960 hasCompileParent = !!templateNodeParent.length; 10961 10962 // When transcluding a template that has bindings in the root 10963 // we don't have a parent and thus need to add the class during linking fn. 10964 if (hasCompileParent) compile.$$addBindingClass(templateNodeParent); 10965 10966 return function textInterpolateLinkFn(scope, node) { 10967 var parent = node.parent(); 10968 if (!hasCompileParent) compile.$$addBindingClass(parent); 10969 compile.$$addBindingInfo(parent, interpolateFn.expressions); 10970 scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { 10971 node[0].nodeValue = value; 10972 }); 10973 }; 10974 } 10975 }); 10976 } 10977 } 10978 10979 10980 function wrapTemplate(type, template) { 10981 type = lowercase(type || 'html'); 10982 switch (type) { 10983 case 'svg': 10984 case 'math': 10985 var wrapper = window.document.createElement('div'); 10986 wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>'; 10987 return wrapper.childNodes[0].childNodes; 10988 default: 10989 return template; 10990 } 10991 } 10992 10993 10994 function getTrustedAttrContext(nodeName, attrNormalizedName) { 10995 if (attrNormalizedName === 'srcdoc') { 10996 return $sce.HTML; 10997 } 10998 // All nodes with src attributes require a RESOURCE_URL value, except for 10999 // img and various html5 media nodes, which require the MEDIA_URL context. 11000 if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') { 11001 if (['img', 'video', 'audio', 'source', 'track'].indexOf(nodeName) === -1) { 11002 return $sce.RESOURCE_URL; 11003 } 11004 return $sce.MEDIA_URL; 11005 } else if (attrNormalizedName === 'xlinkHref') { 11006 // Some xlink:href are okay, most aren't 11007 if (nodeName === 'image') return $sce.MEDIA_URL; 11008 if (nodeName === 'a') return $sce.URL; 11009 return $sce.RESOURCE_URL; 11010 } else if ( 11011 // Formaction 11012 (nodeName === 'form' && attrNormalizedName === 'action') || 11013 // If relative URLs can go where they are not expected to, then 11014 // all sorts of trust issues can arise. 11015 (nodeName === 'base' && attrNormalizedName === 'href') || 11016 // links can be stylesheets or imports, which can run script in the current origin 11017 (nodeName === 'link' && attrNormalizedName === 'href') 11018 ) { 11019 return $sce.RESOURCE_URL; 11020 } else if (nodeName === 'a' && (attrNormalizedName === 'href' || 11021 attrNormalizedName === 'ngHref')) { 11022 return $sce.URL; 11023 } 11024 } 11025 11026 function getTrustedPropContext(nodeName, propNormalizedName) { 11027 var prop = propNormalizedName.toLowerCase(); 11028 return PROP_CONTEXTS[nodeName + '|' + prop] || PROP_CONTEXTS['*|' + prop]; 11029 } 11030 11031 function sanitizeSrcsetPropertyValue(value) { 11032 return sanitizeSrcset($sce.valueOf(value), 'ng-prop-srcset'); 11033 } 11034 function addPropertyDirective(node, directives, attrName, propName) { 11035 if (EVENT_HANDLER_ATTR_REGEXP.test(propName)) { 11036 throw $compileMinErr('nodomevents', 'Property bindings for HTML DOM event properties are disallowed'); 11037 } 11038 11039 var nodeName = nodeName_(node); 11040 var trustedContext = getTrustedPropContext(nodeName, propName); 11041 11042 var sanitizer = identity; 11043 // Sanitize img[srcset] + source[srcset] values. 11044 if (propName === 'srcset' && (nodeName === 'img' || nodeName === 'source')) { 11045 sanitizer = sanitizeSrcsetPropertyValue; 11046 } else if (trustedContext) { 11047 sanitizer = $sce.getTrusted.bind($sce, trustedContext); 11048 } 11049 11050 directives.push({ 11051 priority: 100, 11052 compile: function ngPropCompileFn(_, attr) { 11053 var ngPropGetter = $parse(attr[attrName]); 11054 var ngPropWatch = $parse(attr[attrName], function sceValueOf(val) { 11055 // Unwrap the value to compare the actual inner safe value, not the wrapper object. 11056 return $sce.valueOf(val); 11057 }); 11058 11059 return { 11060 pre: function ngPropPreLinkFn(scope, $element) { 11061 function applyPropValue() { 11062 var propValue = ngPropGetter(scope); 11063 $element
11063.prop(propName, sanitizer(propValue)
vendor: 40,700 bytes, lines 11063-12230
11063); 11064 } 11065 11066 applyPropValue(); 11067 scope.$watch(ngPropWatch, applyPropValue); 11068 } 11069 }; 11070 } 11071 }); 11072 } 11073 11074 function addEventDirective(directives, attrName, eventName) { 11075 directives.push( 11076 createEventDirective($parse, $rootScope, $exceptionHandler, attrName, eventName, /*forceAsync=*/false) 11077 ); 11078 } 11079 11080 function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) { 11081 var nodeName = nodeName_(node); 11082 var trustedContext = getTrustedAttrContext(nodeName, name); 11083 var mustHaveExpression = !isNgAttr; 11084 var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr; 11085 11086 var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing); 11087 11088 // no interpolation found -> ignore 11089 if (!interpolateFn) return; 11090 11091 if (name === 'multiple' && nodeName === 'select') { 11092 throw $compileMinErr('selmulti', 11093 'Binding to the \'multiple\' attribute is not supported. Element: {0}', 11094 startingTag(node)); 11095 } 11096 11097 if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { 11098 throw $compileMinErr('nodomevents', 'Interpolations for HTML DOM event attributes are disallowed'); 11099 } 11100 11101 directives.push({ 11102 priority: 100, 11103 compile: function() { 11104 return { 11105 pre: function attrInterpolatePreLinkFn(scope, element, attr) { 11106 var $$observers = (attr.$$observers || (attr.$$observers = createMap())); 11107 11108 // If the attribute has changed since last $interpolate()ed 11109 var newValue = attr[name]; 11110 if (newValue !== value) { 11111 // we need to interpolate again since the attribute value has been updated 11112 // (e.g. by another directive's compile function) 11113 // ensure unset/empty values make interpolateFn falsy 11114 interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing); 11115 value = newValue; 11116 } 11117 11118 // if attribute was updated so that there is no interpolation going on we don't want to 11119 // register any observers 11120 if (!interpolateFn) return; 11121 11122 // initialize attr object so that it's ready in case we need the value for isolate 11123 // scope initialization, otherwise the value would not be available from isolate 11124 // directive's linking fn during linking phase 11125 attr[name] = interpolateFn(scope); 11126 11127 ($$observers[name] || ($$observers[name] = [])).$$inter = true; 11128 (attr.$$observers && attr.$$observers[name].$$scope || scope). 11129 $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { 11130 //special case for class attribute addition + removal 11131 //so that class changes can tap into the animation 11132 //hooks provided by the $animate service. Be sure to 11133 //skip animations when the first digest occurs (when 11134 //both the new and the old values are the same) since 11135 //the CSS classes are the non-interpolated values 11136 if (name === 'class' && newValue !== oldValue) { 11137 attr.$updateClass(newValue, oldValue); 11138 } else { 11139 attr.$set(name, newValue); 11140 } 11141 }); 11142 } 11143 }; 11144 } 11145 }); 11146 } 11147 11148 11149 /** 11150 * This is a special jqLite.replaceWith, which can replace items which 11151 * have no parents, provided that the containing jqLite collection is provided. 11152 * 11153 * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes 11154 * in the root of the tree. 11155 * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep 11156 * the shell, but replace its DOM node reference. 11157 * @param {Node} newNode The new DOM node. 11158 */ 11159 function replaceWith($rootElement, elementsToRemove, newNode) { 11160 var firstElementToRemove = elementsToRemove[0], 11161 removeCount = elementsToRemove.length, 11162 parent = firstElementToRemove.parentNode, 11163 i, ii; 11164 11165 if ($rootElement) { 11166 for (i = 0, ii = $rootElement.length; i < ii; i++) { 11167 if ($rootElement[i] === firstElementToRemove) { 11168 $rootElement[i++] = newNode; 11169 for (var j = i, j2 = j + removeCount - 1, 11170 jj = $rootElement.length; 11171 j < jj; j++, j2++) { 11172 if (j2 < jj) { 11173 $rootElement[j] = $rootElement[j2]; 11174 } else { 11175 delete $rootElement[j]; 11176 } 11177 } 11178 $rootElement.length -= removeCount - 1; 11179 11180 // If the replaced element is also the jQuery .context then replace it 11181 // .context is a deprecated jQuery api, so we should set it only when jQuery set it 11182 // http://api.jquery.com/context/ 11183 if ($rootElement.context === firstElementToRemove) { 11184 $rootElement.context = newNode; 11185 } 11186 break; 11187 } 11188 } 11189 } 11190 11191 if (parent) { 11192 parent.replaceChild(newNode, firstElementToRemove); 11193 } 11194 11195 // Append all the `elementsToRemove` to a fragment. This will... 11196 // - remove them from the DOM 11197 // - allow them to still be traversed with .nextSibling 11198 // - allow a single fragment.qSA to fetch all elements being removed 11199 var fragment = window.document.createDocumentFragment(); 11200 for (i = 0; i < removeCount; i++) { 11201 fragment.appendChild(elementsToRemove[i]); 11202 } 11203 11204 if (jqLite.hasData(firstElementToRemove)) { 11205 // Copy over user data (that includes AngularJS's $scope etc.). Don't copy private 11206 // data here because there's no public interface in jQuery to do that and copying over 11207 // event listeners (which is the main use of private data) wouldn't work anyway. 11208 jqLite.data(newNode, jqLite.data(firstElementToRemove)); 11209 11210 // Remove $destroy event listeners from `firstElementToRemove` 11211 jqLite(firstElementToRemove).off('$destroy'); 11212 } 11213 11214 // Cleanup any data/listeners on the elements and children. 11215 // This includes invoking the $destroy event on any elements with listeners. 11216 jqLite.cleanData(fragment.querySelectorAll('*')); 11217 11218 // Update the jqLite collection to only contain the `newNode` 11219 for (i = 1; i < removeCount; i++) { 11220 delete elementsToRemove[i]; 11221 } 11222 elementsToRemove[0] = newNode; 11223 elementsToRemove.length = 1; 11224 } 11225 11226 11227 function cloneAndAnnotateFn(fn, annotation) { 11228 return extend(function() { return fn.apply(null, arguments); }, fn, annotation); 11229 } 11230 11231 11232 function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) { 11233 try { 11234 linkFn(scope, $element, attrs, controllers, transcludeFn); 11235 } catch (e) { 11236 $exceptionHandler(e, startingTag($element)); 11237 } 11238 } 11239 11240 function strictBindingsCheck(attrName, directiveName) { 11241 if (strictComponentBindingsEnabled) { 11242 throw $compileMinErr('missingattr', 11243 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!', 11244 attrName, directiveName); 11245 } 11246 } 11247 11248 // Set up $watches for isolate scope and controller bindings. 11249 function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) { 11250 var removeWatchCollection = []; 11251 var initialChanges = {}; 11252 var changes; 11253 11254 forEach(bindings, function initializeBinding(definition, scopeName) { 11255 var attrName = definition.attrName, 11256 optional = definition.optional, 11257 mode = definition.mode, // @, =, <, or & 11258 lastValue, 11259 parentGet, parentSet, compare, removeWatch; 11260 11261 switch (mode) { 11262 11263 case '@': 11264 if (!optional && !hasOwnProperty.call(attrs, attrName)) { 11265 strictBindingsCheck(attrName, directive.name); 11266 destination[scopeName] = attrs[attrName] = undefined; 11267 11268 } 11269 removeWatch = attrs.$observe(attrName, function(value) { 11270 if (isString(value) || isBoolean(value)) { 11271 var oldValue = destination[scopeName]; 11272 recordChanges(scopeName, value, oldValue); 11273 destination[scopeName] = value; 11274 } 11275 }); 11276 attrs.$$observers[attrName].$$scope = scope; 11277 lastValue = attrs[attrName]; 11278 if (isString(lastValue)) { 11279 // If the attribute has been provided then we trigger an interpolation to ensure 11280 // the value is there for use in the link fn 11281 destination[scopeName] = $interpolate(lastValue)(scope); 11282 } else if (isBoolean(lastValue)) { 11283 // If the attributes is one of the BOOLEAN_ATTR then AngularJS will have converted 11284 // the value to boolean rather than a string, so we special case this situation 11285 destination[scopeName] = lastValue; 11286 } 11287 initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]); 11288 removeWatchCollection.push(removeWatch); 11289 break; 11290 11291 case '=': 11292 if (!hasOwnProperty.call(attrs, attrName)) { 11293 if (optional) break; 11294 strictBindingsCheck(attrName, directive.name); 11295 attrs[attrName] = undefined; 11296 } 11297 if (optional && !attrs[attrName]) break; 11298 11299 parentGet = $parse(attrs[attrName]); 11300 if (parentGet.literal) { 11301 compare = equals; 11302 } else { 11303 compare = simpleCompare; 11304 } 11305 parentSet = parentGet.assign || function() { 11306 // reset the change, or we will throw this exception on every $digest 11307 lastValue = destination[scopeName] = parentGet(scope); 11308 throw $compileMinErr('nonassign', 11309 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!', 11310 attrs[attrName], attrName, directive.name); 11311 }; 11312 lastValue = destination[scopeName] = parentGet(scope); 11313 var parentValueWatch = function parentValueWatch(parentValue) { 11314 if (!compare(parentValue, destination[scopeName])) { 11315 // we are out of sync and need to copy 11316 if (!compare(parentValue, lastValue)) { 11317 // parent changed and it has precedence 11318 destination[scopeName] = parentValue; 11319 } else { 11320 // if the parent can be assigned then do so 11321 parentSet(scope, parentValue = destination[scopeName]); 11322 } 11323 } 11324 lastValue = parentValue; 11325 return lastValue; 11326 }; 11327 parentValueWatch.$stateful = true; 11328 if (definition.collection) { 11329 removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch); 11330 } else { 11331 removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); 11332 } 11333 removeWatchCollection.push(removeWatch); 11334 break; 11335 11336 case '<': 11337 if (!hasOwnProperty.call(attrs, attrName)) { 11338 if (optional) break; 11339 strictBindingsCheck(attrName, directive.name); 11340 attrs[attrName] = undefined; 11341 } 11342 if (optional && !attrs[attrName]) break; 11343 11344 parentGet = $parse(attrs[attrName]); 11345 var isLiteral = parentGet.literal; 11346 11347 var initialValue = destination[scopeName] = parentGet(scope); 11348 initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]); 11349 11350 removeWatch = scope[definition.collection ? '$watchCollection' : '$watch'](parentGet, function parentValueWatchAction(newValue, oldValue) { 11351 if (oldValue === newValue) { 11352 if (oldValue === initialValue || (isLiteral && equals(oldValue, initialValue))) { 11353 return; 11354 } 11355 oldValue = initialValue; 11356 } 11357 recordChanges(scopeName, newValue, oldValue); 11358 destination[scopeName] = newValue; 11359 }); 11360 11361 removeWatchCollection.push(removeWatch); 11362 break; 11363 11364 case '&': 11365 if (!optional && !hasOwnProperty.call(attrs, attrName)) { 11366 strictBindingsCheck(attrName, directive.name); 11367 } 11368 // Don't assign Object.prototype method to scope 11369 parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop; 11370 11371 // Don't assign noop to destination if expression is not valid 11372 if (parentGet === noop && optional) break; 11373 11374 destination[scopeName] = function(locals) { 11375 return parentGet(scope, locals); 11376 }; 11377 break; 11378 } 11379 }); 11380 11381 function recordChanges(key, currentValue, previousValue) { 11382 if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) { 11383 // If we have not already scheduled the top level onChangesQueue handler then do so now 11384 if (!onChangesQueue) { 11385 scope.$$postDigest(flushOnChangesQueue); 11386 onChangesQueue = []; 11387 } 11388 // If we have not already queued a trigger of onChanges for this controller then do so now 11389 if (!changes) { 11390 changes = {}; 11391 onChangesQueue.push(triggerOnChangesHook); 11392 } 11393 // If the has been a change on this property already then we need to reuse the previous value 11394 if (changes[key]) { 11395 previousValue = changes[key].previousValue; 11396 } 11397 // Store this change 11398 changes[key] = new SimpleChange(previousValue, currentValue); 11399 } 11400 } 11401 11402 function triggerOnChangesHook() { 11403 destination.$onChanges(changes); 11404 // Now clear the changes so that we schedule onChanges when more changes arrive 11405 changes = undefined; 11406 } 11407 11408 return { 11409 initialChanges: initialChanges, 11410 removeWatches: removeWatchCollection.length && function removeWatches() { 11411 for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) { 11412 removeWatchCollection[i](); 11413 } 11414 } 11415 }; 11416 } 11417 }]; 11418} 11419 11420function SimpleChange(previous, current) { 11421 this.previousValue = previous; 11422 this.currentValue = current; 11423} 11424SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; }; 11425 11426 11427var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i; 11428var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g; 11429 11430/** 11431 * Converts all accepted directives format into proper directive name. 11432 * @param name Name to normalize 11433 */ 11434function directiveNormalize(name) { 11435 return name 11436 .replace(PREFIX_REGEXP, '') 11437 .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) { 11438 return offset ? letter.toUpperCase() : letter; 11439 }); 11440} 11441 11442/** 11443 * @ngdoc type 11444 * @name $compile.directive.Attributes 11445 * 11446 * @description 11447 * A shared object between directive compile / linking functions which contains normalized DOM 11448 * element attributes. The values reflect current binding state `{{ }}`. The normalization is 11449 * needed since all of these are treated as equivalent in AngularJS: 11450 * 11451 * ``` 11452 * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> 11453 * ``` 11454 */ 11455 11456/** 11457 * @ngdoc property 11458 * @name $compile.directive.Attributes#$attr 11459 * 11460 * @description 11461 * A map of DOM element attribute names to the normalized name. This is 11462 * needed to do reverse lookup from normalized name back to actual name. 11463 */ 11464 11465 11466/** 11467 * @ngdoc method 11468 * @name $compile.directive.Attributes#$set 11469 * @kind function 11470 * 11471 * @description 11472 * Set DOM element attribute value. 11473 * 11474 * 11475 * @param {string} name Normalized element attribute name of the property to modify. The name is 11476 * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} 11477 * property to the original name. 11478 * @param {string} value Value to set the attribute to. The value can be an interpolated string. 11479 */ 11480 11481 11482 11483/** 11484 * Closure compiler type information 11485 */ 11486 11487function nodesetLinkingFn( 11488 /* angular.Scope */ scope, 11489 /* NodeList */ nodeList, 11490 /* Element */ rootElement, 11491 /* function(Function) */ boundTranscludeFn 11492) {} 11493 11494function directiveLinkingFn( 11495 /* nodesetLinkingFn */ nodesetLinkingFn, 11496 /* angular.Scope */ scope, 11497 /* Node */ node, 11498 /* Element */ rootElement, 11499 /* function(Function) */ boundTranscludeFn 11500) {} 11501 11502function tokenDifference(str1, str2) { 11503 var values = '', 11504 tokens1 = str1.split(/\s+/), 11505 tokens2 = str2.split(/\s+/); 11506 11507 outer: 11508 for (var i = 0; i < tokens1.length; i++) { 11509 var token = tokens1[i]; 11510 for (var j = 0; j < tokens2.length; j++) { 11511 if (token === tokens2[j]) continue outer; 11512 } 11513 values += (values.length > 0 ? ' ' : '') + token; 11514 } 11515 return values; 11516} 11517 11518function removeComments(jqNodes) { 11519 jqNodes = jqLite(jqNodes); 11520 var i = jqNodes.length; 11521 11522 if (i <= 1) { 11523 return jqNodes; 11524 } 11525 11526 while (i--) { 11527 var node = jqNodes[i]; 11528 if (node.nodeType === NODE_TYPE_COMMENT || 11529 (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) { 11530 splice.call(jqNodes, i, 1); 11531 } 11532 } 11533 return jqNodes; 11534} 11535 11536var $controllerMinErr = minErr('$controller'); 11537 11538 11539var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/; 11540function identifierForController(controller, ident) { 11541 if (ident && isString(ident)) return ident; 11542 if (isString(controller)) { 11543 var match = CNTRL_REG.exec(controller); 11544 if (match) return match[3]; 11545 } 11546} 11547 11548 11549/** 11550 * @ngdoc provider 11551 * @name $controllerProvider 11552 * @this 11553 * 11554 * @description 11555 * The {@link ng.$controller $controller service} is used by AngularJS to create new 11556 * controllers. 11557 * 11558 * This provider allows controller registration via the 11559 * {@link ng.$controllerProvider#register register} method. 11560 */ 11561function $ControllerProvider() { 11562 var controllers = {}; 11563 11564 /** 11565 * @ngdoc method 11566 * @name $controllerProvider#has 11567 * @param {string} name Controller name to check. 11568 */ 11569 this.has = function(name) { 11570 return controllers.hasOwnProperty(name); 11571 }; 11572 11573 /** 11574 * @ngdoc method 11575 * @name $controllerProvider#register 11576 * @param {string|Object} name Controller name, or an object map of controllers where the keys are 11577 * the names and the values are the constructors. 11578 * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI 11579 * annotations in the array notation). 11580 */ 11581 this.register = function(name, constructor) { 11582 assertNotHasOwnProperty(name, 'controller'); 11583 if (isObject(name)) { 11584 extend(controllers, name); 11585 } else { 11586 controllers[name] = constructor; 11587 } 11588 }; 11589 11590 this.$get = ['$injector', function($injector) { 11591 11592 /** 11593 * @ngdoc service 11594 * @name $controller 11595 * @requires $injector 11596 * 11597 * @param {Function|string} constructor If called with a function then it's considered to be the 11598 * controller constructor function. Otherwise it's considered to be a string which is used 11599 * to retrieve the controller constructor using the following steps: 11600 * 11601 * * check if a controller with given name is registered via `$controllerProvider` 11602 * * check if evaluating the string on the current scope returns a constructor 11603 * 11604 * The string can use the `controller as property` syntax, where the controller instance is published 11605 * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this 11606 * to work correctly. 11607 * 11608 * @param {Object} locals Injection locals for Controller. 11609 * @return {Object} Instance of given controller. 11610 * 11611 * @description 11612 * `$controller` service is responsible for instantiating controllers. 11613 * 11614 * It's just a simple call to {@link auto.$injector $injector}, but extracted into 11615 * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). 11616 */ 11617 return function $controller(expression, locals, later, ident) { 11618 // PRIVATE API: 11619 // param `later` --- indicates that the controller's constructor is invoked at a later time. 11620 // If true, $controller will allocate the object with the correct 11621 // prototype chain, but will not invoke the controller until a returned 11622 // callback is invoked. 11623 // param `ident` --- An optional label which overrides the label parsed from the controller 11624 // expression, if any. 11625 var instance, match, constructor, identifier; 11626 later = later === true; 11627 if (ident && isString(ident)) { 11628 identifier = ident; 11629 } 11630 11631 if (isString(expression)) { 11632 match = expression.match(CNTRL_REG); 11633 if (!match) { 11634 throw $controllerMinErr('ctrlfmt', 11635 'Badly formed controller string \'{0}\'. ' + 11636 'Must match `__name__ as __id__` or `__name__`.', expression); 11637 } 11638 constructor = match[1]; 11639 identifier = identifier || match[3]; 11640 expression = controllers.hasOwnProperty(constructor) 11641 ? controllers[constructor] 11642 : getter(locals.$scope, constructor, true); 11643 11644 if (!expression) { 11645 throw $controllerMinErr('ctrlreg', 11646 'The controller with the name \'{0}\' is not registered.', constructor); 11647 } 11648 11649 assertArgFn(expression, constructor, true); 11650 } 11651 11652 if (later) { 11653 // Instantiate controller later: 11654 // This machinery is used to create an instance of the object before calling the 11655 // controller's constructor itself. 11656 // 11657 // This allows properties to be added to the controller before the constructor is 11658 // invoked. Primarily, this is used for isolate scope bindings in $compile. 11659 // 11660 // This feature is not intended for use by applications, and is thus not documented 11661 // publicly. 11662 // Object creation: http://jsperf.com/create-constructor/2 11663 var controllerPrototype = (isArray(expression) ? 11664 expression[expression.length - 1] : expression).prototype; 11665 instance = Object.create(controllerPrototype || null); 11666 11667 if (identifier) { 11668 addIdentifier(locals, identifier, instance, constructor || expression.name); 11669 } 11670 11671 return extend(function $controllerInit() { 11672 var result = $injector.invoke(expression, instance, locals, constructor); 11673 if (result !== instance && (isObject(result) || isFunction(result))) { 11674 instance = result; 11675 if (identifier) { 11676 // If result changed, re-assign controllerAs value to scope. 11677 addIdentifier(locals, identifier, instance, constructor || expression.name); 11678 } 11679 } 11680 return instance; 11681 }, { 11682 instance: instance, 11683 identifier: identifier 11684 }); 11685 } 11686 11687 instance = $injector.instantiate(expression, locals, constructor); 11688 11689 if (identifier) { 11690 addIdentifier(locals, identifier, instance, constructor || expression.name); 11691 } 11692 11693 return instance; 11694 }; 11695 11696 function addIdentifier(locals, identifier, instance, name) { 11697 if (!(locals && isObject(locals.$scope))) { 11698 throw minErr('$controller')('noscp', 11699 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.', 11700 name, identifier); 11701 } 11702 11703 locals.$scope[identifier] = instance; 11704 } 11705 }]; 11706} 11707 11708/** 11709 * @ngdoc service 11710 * @name $document 11711 * @requires $window 11712 * @this 11713 * 11714 * @description 11715 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. 11716 * 11717 * @example 11718 <example module="documentExample" name="document"> 11719 <file name="index.html"> 11720 <div ng-controller="ExampleController"> 11721 <p>$document title: <b ng-bind="title"></b></p> 11722 <p>window.document title: <b ng-bind="windowTitle"></b></p> 11723 </div> 11724 </file> 11725 <file name="script.js"> 11726 angular.module('documentExample', []) 11727 .controller('ExampleController', ['$scope', '$document', function($scope, $document) { 11728 $scope.title = $document[0].title; 11729 $scope.windowTitle = angular.element(window.document)[0].title; 11730 }]); 11731 </file> 11732 </example> 11733 */ 11734function $DocumentProvider() { 11735 this.$get = ['$window', function(window) { 11736 return jqLite(window.document); 11737 }]; 11738} 11739 11740 11741/** 11742 * @private 11743 * @this 11744 * Listens for document visibility change and makes the current status accessible. 11745 */ 11746function $$IsDocumentHiddenProvider() { 11747 this.$get = ['$document', '$rootScope', function($document, $rootScope) { 11748 var doc = $document[0]; 11749 var hidden = doc && doc.hidden; 11750 11751 $document.on('visibilitychange', changeListener); 11752 11753 $rootScope.$on('$destroy', function() { 11754 $document.off('visibilitychange', changeListener); 11755 }); 11756 11757 function changeListener() { 11758 hidden = doc.hidden; 11759 } 11760 11761 return function() { 11762 return hidden; 11763 }; 11764 }]; 11765} 11766 11767/** 11768 * @ngdoc service 11769 * @name $exceptionHandler 11770 * @requires ng.$log 11771 * @this 11772 * 11773 * @description 11774 * Any uncaught exception in AngularJS expressions is delegated to this service. 11775 * The default implementation simply delegates to `$log.error` which logs it into 11776 * the browser console. 11777 * 11778 * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by 11779 * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. 11780 * 11781 * ## Example: 11782 * 11783 * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught 11784 * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead 11785 * of `$log.error()`. 11786 * 11787 * ```js 11788 * angular. 11789 * module('exceptionOverwrite', []). 11790 * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) { 11791 * return function myExceptionHandler(exception, cause) { 11792 * logErrorsToBackend(exception, cause); 11793 * $log.warn(exception, cause); 11794 * }; 11795 * }]); 11796 * ``` 11797 * 11798 * <hr /> 11799 * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind` 11800 * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler} 11801 * (unless executed during a digest). 11802 * 11803 * If you wish, you can manually delegate exceptions, e.g. 11804 * `try { ... } catch(e) { $exceptionHandler(e); }` 11805 * 11806 * @param {Error} exception Exception associated with the error. 11807 * @param {string=} cause Optional information about the context in which 11808 * the error was thrown. 11809 * 11810 */ 11811function $ExceptionHandlerProvider() { 11812 this.$get = ['$log', function($log) { 11813 return function(exception, cause) { 11814 $log.error.apply($log, arguments); 11815 }; 11816 }]; 11817} 11818 11819var $$ForceReflowProvider = /** @this */ function() { 11820 this.$get = ['$document', function($document) { 11821 return function(domNode) { 11822 //the line below will force the browser to perform a repaint so 11823 //that all the animated elements within the animation frame will 11824 //be properly updated and drawn on screen. This is required to 11825 //ensure that the preparation animation is properly flushed so that 11826 //the active state picks up from there. DO NOT REMOVE THIS LINE. 11827 //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH 11828 //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND 11829 //WILL TAKE YEARS AWAY FROM YOUR LIFE. 11830 if (domNode) { 11831 if (!domNode.nodeType && domNode instanceof jqLite) { 11832 domNode = domNode[0]; 11833 } 11834 } else { 11835 domNode = $document[0].body; 11836 } 11837 return domNode.offsetWidth + 1; 11838 }; 11839 }]; 11840}; 11841 11842var APPLICATION_JSON = 'application/json'; 11843var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; 11844var JSON_START = /^\[|^\{(?!\{)/; 11845var JSON_ENDS = { 11846 '[': /]$/, 11847 '{': /}$/ 11848}; 11849var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/; 11850var $httpMinErr = minErr('$http'); 11851 11852function serializeValue(v) { 11853 if (isObject(v)) { 11854 return isDate(v) ? v.toISOString() : toJson(v); 11855 } 11856 return v; 11857} 11858 11859 11860/** @this */ 11861function $HttpParamSerializerProvider() { 11862 /** 11863 * @ngdoc service 11864 * @name $httpParamSerializer 11865 * @description 11866 * 11867 * Default {@link $http `$http`} params serializer that converts objects to strings 11868 * according to the following rules: 11869 * 11870 * * `{'foo': 'bar'}` results in `foo=bar` 11871 * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object) 11872 * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element) 11873 * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object) 11874 * 11875 * Note that serializer will sort the request parameters alphabetically. 11876 */ 11877 11878 this.$get = function() { 11879 return function ngParamSerializer(params) { 11880 if (!params) return ''; 11881 var parts = []; 11882 forEachSorted(params, function(value, key) { 11883 if (value === null || isUndefined(value) || isFunction(value)) return; 11884 if (isArray(value)) { 11885 forEach(value, function(v) { 11886 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v))); 11887 }); 11888 } else { 11889 parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value))); 11890 } 11891 }); 11892 11893 return parts.join('&'); 11894 }; 11895 }; 11896} 11897 11898/** @this */ 11899function $HttpParamSerializerJQLikeProvider() { 11900 /** 11901 * @ngdoc service 11902 * @name $httpParamSerializerJQLike 11903 * 11904 * @description 11905 * 11906 * Alternative {@link $http `$http`} params serializer that follows 11907 * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic. 11908 * The serializer will also sort the params alphabetically. 11909 * 11910 * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property: 11911 * 11912 * ```js 11913 * $http({ 11914 * url: myUrl, 11915 * method: 'GET', 11916 * params: myParams, 11917 * paramSerializer: '$httpParamSerializerJQLike' 11918 * }); 11919 * ``` 11920 * 11921 * It is also possible to set it as the default `paramSerializer` in the 11922 * {@link $httpProvider#defaults `$httpProvider`}. 11923 * 11924 * Additionally, you can inject the serializer and use it explicitly, for example to serialize 11925 * form data for submission: 11926 * 11927 * ```js 11928 * .controller(function($http, $httpParamSerializerJQLike) { 11929 * //... 11930 * 11931 * $http({ 11932 * url: myUrl, 11933 * method: 'POST', 11934 * data: $httpParamSerializerJQLike(myData), 11935 * headers: { 11936 * 'Content-Type': 'application/x-www-form-urlencoded' 11937 * } 11938 * }); 11939 * 11940 * }); 11941 * ``` 11942 * 11943 */ 11944 this.$get = function() { 11945 return function jQueryLikeParamSerializer(params) { 11946 if (!params) return ''; 11947 var parts = []; 11948 serialize(params, '', true); 11949 return parts.join('&'); 11950 11951 function serialize(toSerialize, prefix, topLevel) { 11952 if (isArray(toSerialize)) { 11953 forEach(toSerialize, function(value, index) { 11954 serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']'); 11955 }); 11956 } else if (isObject(toSerialize) && !isDate(toSerialize)) { 11957 forEachSorted(toSerialize, function(value, key) { 11958 serialize(value, prefix + 11959 (topLevel ? '' : '[') + 11960 key + 11961 (topLevel ? '' : ']')); 11962 }); 11963 } else { 11964 if (isFunction(toSerialize)) { 11965 toSerialize = toSerialize(); 11966 } 11967 parts.push(encodeUriQuery(prefix) + '=' + 11968 (toSerialize == null ? '' : encodeUriQuery(serializeValue(toSerialize)))); 11969 } 11970 } 11971 }; 11972 }; 11973} 11974 11975function defaultHttpResponseTransform(data, headers) { 11976 if (isString(data)) { 11977 // Strip json vulnerability protection prefix and trim whitespace 11978 var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim(); 11979 11980 if (tempData) { 11981 var contentType = headers('Content-Type'); 11982 var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0); 11983 11984 if (hasJsonContentType || isJsonLike(tempData)) { 11985 try { 11986 data = fromJson(tempData); 11987 } catch (e) { 11988 if (!hasJsonContentType) { 11989 return data; 11990 } 11991 throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' + 11992 'Parse error: "{1}"', data, e); 11993 } 11994 } 11995 } 11996 } 11997 11998 return data; 11999} 12000 12001function isJsonLike(str) { 12002 var jsonStart = str.match(JSON_START); 12003 return jsonStart && JSON_ENDS[jsonStart[0]].test(str); 12004} 12005 12006/** 12007 * Parse headers into key value object 12008 * 12009 * @param {string} headers Raw headers as a string 12010 * @returns {Object} Parsed headers as key value object 12011 */ 12012function parseHeaders(headers) { 12013 var parsed = createMap(), i; 12014 12015 function fillInParsed(key, val) { 12016 if (key) { 12017 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; 12018 } 12019 } 12020 12021 if (isString(headers)) { 12022 forEach(headers.split('\n'), function(line) { 12023 i = line.indexOf(':'); 12024 fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1))); 12025 }); 12026 } else if (isObject(headers)) { 12027 forEach(headers, function(headerVal, headerKey) { 12028 fillInParsed(lowercase(headerKey), trim(headerVal)); 12029 }); 12030 } 12031 12032 return parsed; 12033} 12034 12035 12036/** 12037 * Returns a function that provides access to parsed headers. 12038 * 12039 * Headers are lazy parsed when first requested. 12040 * @see parseHeaders 12041 * 12042 * @param {(string|Object)} headers Headers to provide access to. 12043 * @returns {function(string=)} Returns a getter function which if called with: 12044 * 12045 * - if called with an argument returns a single header value or null 12046 * - if called with no arguments returns an object containing all headers. 12047 */ 12048function headersGetter(headers) { 12049 var headersObj; 12050 12051 return function(name) { 12052 if (!headersObj) headersObj = parseHeaders(headers); 12053 12054 if (name) { 12055 var value = headersObj[lowercase(name)]; 12056 if (value === undefined) { 12057 value = null; 12058 } 12059 return value; 12060 } 12061 12062 return headersObj; 12063 }; 12064} 12065 12066 12067/** 12068 * Chain all given functions 12069 * 12070 * This function is used for both request and response transforming 12071 * 12072 * @param {*} data Data to transform. 12073 * @param {function(string=)} headers HTTP headers getter fn. 12074 * @param {number} status HTTP status code of the response. 12075 * @param {(Function|Array.<Function>)} fns Function or an array of functions. 12076 * @returns {*} Transformed data. 12077 */ 12078function transformData(data, headers, status, fns) { 12079 if (isFunction(fns)) { 12080 return fns(data, headers, status); 12081 } 12082 12083 forEach(fns, function(fn) { 12084 data = fn(data, headers, status); 12085 }); 12086 12087 return data; 12088} 12089 12090 12091function isSuccess(status) { 12092 return 200 <= status && status < 300; 12093} 12094 12095 12096/** 12097 * @ngdoc provider 12098 * @name $httpProvider 12099 * @this 12100 * 12101 * @description 12102 * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. 12103 */ 12104function $HttpProvider() { 12105 /** 12106 * @ngdoc property 12107 * @name $httpProvider#defaults 12108 * @description 12109 * 12110 * Object containing default values for all {@link ng.$http $http} requests. 12111 * 12112 * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with 12113 * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses 12114 * by default. See {@link $http#caching $http Caching} for more information. 12115 * 12116 * - **`defaults.headers`** - {Object} - Default headers for all $http requests. 12117 * Refer to {@link ng.$http#setting-http-headers $http} for documentation on 12118 * setting default headers. 12119 * - **`defaults.headers.common`** 12120 * - **`defaults.headers.post`** 12121 * - **`defaults.headers.put`** 12122 * - **`defaults.headers.patch`** 12123 * 12124 * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the 12125 * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the 12126 * {@link $jsonpCallbacks} service. Defaults to `'callback'`. 12127 * 12128 * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function 12129 * used to the prepare string representation of request parameters (specified as an object). 12130 * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}. 12131 * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}. 12132 * 12133 * - **`defaults.transformRequest`** - 12134 * `{Array<function(data, headersGetter)>|function(data, headersGetter)}` - 12135 * An array of functions (or a single function) which are applied to the request data. 12136 * By default, this is an array with one request transformation function: 12137 * 12138 * - If the `data` property of the request configuration object contains an object, serialize it 12139 * into JSON format. 12140 * 12141 * - **`defaults.transformResponse`** - 12142 * `{Array<function(data, headersGetter, status)>|function(data, headersGetter, status)}` - 12143 * An array of functions (or a single function) which are applied to the response data. By default, 12144 * this is an array which applies one response transformation function that does two things: 12145 * 12146 * - If XSRF prefix is detected, strip it 12147 * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}). 12148 * - If the `Content-Type` is `application/json` or the response looks like JSON, 12149 * deserialize it using a JSON parser. 12150 * 12151 * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. 12152 * Defaults value is `'XSRF-TOKEN'`. 12153 * 12154 * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the 12155 * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. 12156 * 12157 */ 12158 var defaults = this.defaults = { 12159 // transform incoming response data 12160 transformResponse: [defaultHttpResponseTransform], 12161 12162 // transform outgoing request data 12163 transformRequest: [function(d) { 12164 return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d; 12165 }], 12166 12167 // default headers 12168 headers: { 12169 common: { 12170 'Accept': 'application/json, text/plain, */*' 12171 }, 12172 post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), 12173 put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), 12174 patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) 12175 }, 12176 12177 xsrfCookieName: 'XSRF-TOKEN', 12178 xsrfHeaderName: 'X-XSRF-TOKEN', 12179 12180 paramSerializer: '$httpParamSerializer', 12181 12182 jsonpCallbackParam: 'callback' 12183 }; 12184 12185 var useApplyAsync = false; 12186 /** 12187 * @ngdoc method 12188 * @name $httpProvider#useApplyAsync 12189 * @description 12190 * 12191 * Configure $http service to combine processing of multiple http responses received at around 12192 * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in 12193 * significant performance improvement for bigger applications that make many HTTP requests 12194 * concurrently (common during application bootstrap). 12195 * 12196 * Defaults to false. If no value is specified, returns the current configured value. 12197 * 12198 * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred 12199 * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window 12200 * to load and share the same digest cycle. 12201 * 12202 * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. 12203 * otherwise, returns the current configured value. 12204 */ 12205 this.useApplyAsync = function(value) { 12206 if (isDefined(value)) { 12207 useApplyAsync = !!value; 12208 return this; 12209 } 12210 return useApplyAsync; 12211 }; 12212 12213 /** 12214 * @ngdoc property 12215 * @name $httpProvider#interceptors 12216 * @description 12217 * 12218 * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} 12219 * pre-processing of request or postprocessing of responses. 12220 * 12221 * These service factories are ordered by request, i.e. they are applied in the same order as the 12222 * array, on request, but reverse order, on response. 12223 * 12224 * {@link ng.$http#interceptors Interceptors detailed info} 12225 */ 12226 var interceptorFactories = this.interceptors = []; 12227 12228 /** 12229 * @ngdoc property 12230 * @name $httpProvider#xsrf
12230WhitelistedOrigins 12231 * @description 12232 * 12233 * Array containing URLs whose origins are trusted to receive the XSRF token. See the 12234 * {@link ng.$http#security-considerations Security Considerations} sections for more details on 12235 * XSRF. 12236 * 12237 * **Note:** An "origin" consists of the [URI scheme](https://en.wikipedia.org/wiki/URI_scheme), 12238 * the [hostname](https://en.wikipedia.org/wiki/Hostname) and the 12239 * [port number](https://en.wikipedia.org/wiki/Port_(computer_networking). For `http:` and 12240 * `https:`, the port number can be omitted if using th default ports (80 and 443 respectively). 12241 * Examples: `http://example.com`, `https://api.example.com:9876` 12242 * 12243 * <div class="alert alert-warning"> 12244 * It is not possible to whitelist specific URLs/paths. The `path`, `query` and `fragment` parts 12245 * of a URL will be ignored. For example, `https://foo.com/path/bar?query=baz#fragment` will be 12246 * treated as `https://foo.com`, meaning that **all** requests to URLs starting with 12247 * `https://foo.com/` will include the XSRF token. 12248 * </div> 12249 * 12250 * @example 12251 * 12252 * ```js 12253 * // App served from `https://example.com/`. 12254 * angular. 12255 * module('xsrfWhitelistedOriginsExample', []). 12256 * config(['$httpProvider', function($httpProvider) { 12257 * $httpProvider.xsrfWhitelistedOrigins.push('https://api.example.com'); 12258 * }]). 12259 * run(['$http', function($http) { 12260 * // The XSRF token will be sent. 12261 * $http.get('https://api.example.com/preferences').then(...); 12262 * 12263 * // The XSRF token will NOT be sent. 12264 * $http.get('https://stats.example.com/activity').then(...); 12265 * }]); 12266 * ``` 12267 */ 12268 var xsrfWhitelistedOrigins = this.xsrfWhitelistedOrigins = []; 12269 12270 this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce', 12271 function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) { 12272 12273 var defaultCache = $cacheFactory('$http'); 12274 12275 /** 12276 * Make sure that default param serializer is exposed as a function 12277 */ 12278 defaults.paramSerializer = isString(defaults.paramSerializer) ? 12279 $injector.get(defaults.paramSerializer) : defaults.paramSerializer; 12280 12281 /** 12282 * Interceptors stored in reverse order. Inner interceptors before outer interceptors. 12283 * The reversal is needed so that we can build up the interception chain around the 12284 * server request. 12285 */ 12286 var reversedInterceptors = []; 12287 12288 forEach(interceptorFactories, function(interceptorFactory) { 12289 reversedInterceptors.unshift(isString(interceptorFactory) 12290 ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); 12291 }); 12292 12293 /** 12294 * A function to check request URLs against a list of allowed origins. 12295 */ 12296 var urlIsAllowedOrigin = urlIsAllowedOriginFactory(xsrfWhiteli
vendor: 17,452 bytes, lines 12296-12670
12296stedOrigins); 12297 12298 /** 12299 * @ngdoc service 12300 * @kind function 12301 * @name $http 12302 * @requires ng.$httpBackend 12303 * @requires $cacheFactory 12304 * @requires $rootScope 12305 * @requires $q 12306 * @requires $injector 12307 * 12308 * @description 12309 * The `$http` service is a core AngularJS service that facilitates communication with the remote 12310 * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) 12311 * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). 12312 * 12313 * For unit testing applications that use `$http` service, see 12314 * {@link ngMock.$httpBackend $httpBackend mock}. 12315 * 12316 * For a higher level of abstraction, please check out the {@link ngResource.$resource 12317 * $resource} service. 12318 * 12319 * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by 12320 * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage 12321 * it is important to familiarize yourself with these APIs and the guarantees they provide. 12322 * 12323 * 12324 * ## General usage 12325 * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} — 12326 * that is used to generate an HTTP request and returns a {@link ng.$q promise} that is 12327 * resolved (request success) or rejected (request failure) with a 12328 * {@link ng.$http#$http-returns response} object. 12329 * 12330 * ```js 12331 * // Simple GET request example: 12332 * $http({ 12333 * method: 'GET', 12334 * url: '/someUrl' 12335 * }).then(function successCallback(response) { 12336 * // this callback will be called asynchronously 12337 * // when the response is available 12338 * }, function errorCallback(response) { 12339 * // called asynchronously if an error occurs 12340 * // or server returns response with an error status. 12341 * }); 12342 * ``` 12343 * 12344 * 12345 * ## Shortcut methods 12346 * 12347 * Shortcut methods are also available. All shortcut methods require passing in the URL, and 12348 * request data must be passed in for POST/PUT requests. An optional config can be passed as the 12349 * last argument. 12350 * 12351 * ```js 12352 * $http.get('/someUrl', config).then(successCallback, errorCallback); 12353 * $http.post('/someUrl', data, config).then(successCallback, errorCallback); 12354 * ``` 12355 * 12356 * Complete list of shortcut methods: 12357 * 12358 * - {@link ng.$http#get $http.get} 12359 * - {@link ng.$http#head $http.head} 12360 * - {@link ng.$http#post $http.post} 12361 * - {@link ng.$http#put $http.put} 12362 * - {@link ng.$http#delete $http.delete} 12363 * - {@link ng.$http#jsonp $http.jsonp} 12364 * - {@link ng.$http#patch $http.patch} 12365 * 12366 * 12367 * ## Writing Unit Tests that use $http 12368 * When unit testing (using {@link ngMock ngMock}), it is necessary to call 12369 * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending 12370 * request using trained responses. 12371 * 12372 * ``` 12373 * $httpBackend.expectGET(...); 12374 * $http.get(...); 12375 * $httpBackend.flush(); 12376 * ``` 12377 * 12378 * ## Setting HTTP Headers 12379 * 12380 * The $http service will automatically add certain HTTP headers to all requests. These defaults 12381 * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration 12382 * object, which currently contains this default configuration: 12383 * 12384 * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): 12385 * - <code>Accept: application/json, text/plain, \*/\*</code> 12386 * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) 12387 * - `Content-Type: application/json` 12388 * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) 12389 * - `Content-Type: application/json` 12390 * 12391 * To add or overwrite these defaults, simply add or remove a property from these configuration 12392 * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object 12393 * with the lowercased HTTP method name as the key, e.g. 12394 * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`. 12395 * 12396 * The defaults can also be set at runtime via the `$http.defaults` object in the same 12397 * fashion. For example: 12398 * 12399 * ``` 12400 * module.run(function($http) { 12401 * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'; 12402 * }); 12403 * ``` 12404 * 12405 * In addition, you can supply a `headers` property in the config object passed when 12406 * calling `$http(config)`, which overrides the defaults without changing them globally. 12407 * 12408 * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, 12409 * Use the `headers` property, setting the desired header to `undefined`. For example: 12410 * 12411 * ```js 12412 * var req = { 12413 * method: 'POST', 12414 * url: 'http://example.com', 12415 * headers: { 12416 * 'Content-Type': undefined 12417 * }, 12418 * data: { test: 'test' } 12419 * } 12420 * 12421 * $http(req).then(function(){...}, function(){...}); 12422 * ``` 12423 * 12424 * ## Transforming Requests and Responses 12425 * 12426 * Both requests and responses can be transformed using transformation functions: `transformRequest` 12427 * and `transformResponse`. These properties can be a single function that returns 12428 * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions, 12429 * which allows you to `push` or `unshift` a new transformation function into the transformation chain. 12430 * 12431 * <div class="alert alert-warning"> 12432 * **Note:** AngularJS does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline. 12433 * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference). 12434 * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest 12435 * function will be reflected on the scope and in any templates where the object is data-bound. 12436 * To prevent this, transform functions should have no side-effects. 12437 * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return. 12438 * </div> 12439 * 12440 * ### Default Transformations 12441 * 12442 * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and 12443 * `defaults.transformResponse` properties. If a request does not provide its own transformations 12444 * then these will be applied. 12445 * 12446 * You can augment or replace the default transformations by modifying these properties by adding to or 12447 * replacing the array. 12448 * 12449 * AngularJS provides the following default transformations: 12450 * 12451 * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is 12452 * an array with one function that does the following: 12453 * 12454 * - If the `data` property of the request configuration object contains an object, serialize it 12455 * into JSON format. 12456 * 12457 * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is 12458 * an array with one function that does the following: 12459 * 12460 * - If XSRF prefix is detected, strip it (see Security Considerations section below). 12461 * - If the `Content-Type` is `application/json` or the response looks like JSON, 12462 * deserialize it using a JSON parser. 12463 * 12464 * 12465 * ### Overriding the Default Transformations Per Request 12466 * 12467 * If you wish to override the request/response transformations only for a single request then provide 12468 * `transformRequest` and/or `transformResponse` properties on the configuration object passed 12469 * into `$http`. 12470 * 12471 * Note that if you provide these properties on the config object the default transformations will be 12472 * overwritten. If you wish to augment the default transformations then you must include them in your 12473 * local transformation array. 12474 * 12475 * The following code demonstrates adding a new response transformation to be run after the default response 12476 * transformations have been run. 12477 * 12478 * ```js 12479 * function appendTransform(defaults, transform) { 12480 * 12481 * // We can't guarantee that the default transformation is an array 12482 * defaults = angular.isArray(defaults) ? defaults : [defaults]; 12483 * 12484 * // Append the new transformation to the defaults 12485 * return defaults.concat(transform); 12486 * } 12487 * 12488 * $http({ 12489 * url: '...', 12490 * method: 'GET', 12491 * transformResponse: appendTransform($http.defaults.transformResponse, function(value) { 12492 * return doTransform(value); 12493 * }) 12494 * }); 12495 * ``` 12496 * 12497 * 12498 * ## Caching 12499 * 12500 * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must 12501 * set the config.cache value or the default cache value to TRUE or to a cache object (created 12502 * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes 12503 * precedence over the default cache value. 12504 * 12505 * In order to: 12506 * * cache all responses - set the default cache value to TRUE or to a cache object 12507 * * cache a specific response - set config.cache value to TRUE or to a cache object 12508 * 12509 * If caching is enabled, but neither the default cache nor config.cache are set to a cache object, 12510 * then the default `$cacheFactory("$http")` object is used. 12511 * 12512 * The default cache value can be set by updating the 12513 * {@link ng.$http#defaults `$http.defaults.cache`} property or the 12514 * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property. 12515 * 12516 * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using 12517 * the relevant cache object. The next time the same request is made, the response is returned 12518 * from the cache without sending a request to the server. 12519 * 12520 * Take note that: 12521 * 12522 * * Only GET and JSONP requests are cached. 12523 * * The cache key is the request URL including search parameters; headers are not considered. 12524 * * Cached responses are returned asynchronously, in the same way as responses from the server. 12525 * * If multiple identical requests are made using the same cache, which is not yet populated, 12526 * one request will be made to the server and remaining requests will return the same response. 12527 * * A cache-control header on the response does not affect if or how responses are cached. 12528 * 12529 * 12530 * ## Interceptors 12531 * 12532 * Before you start creating interceptors, be sure to understand the 12533 * {@link ng.$q $q and deferred/promise APIs}. 12534 * 12535 * For purposes of global error handling, authentication, or any kind of synchronous or 12536 * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be 12537 * able to intercept requests before they are handed to the server and 12538 * responses before they are handed over to the application code that 12539 * initiated these requests. The interceptors leverage the {@link ng.$q 12540 * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. 12541 * 12542 * The interceptors are service factories that are registered with the `$httpProvider` by 12543 * adding them to the `$httpProvider.interceptors` array. The factory is called and 12544 * injected with dependencies (if specified) and returns the interceptor. 12545 * 12546 * There are two kinds of interceptors (and two kinds of rejection interceptors): 12547 * 12548 * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to 12549 * modify the `config` object or create a new one. The function needs to return the `config` 12550 * object directly, or a promise containing the `config` or a new `config` object. 12551 * * `requestError`: interceptor gets called when a previous interceptor threw an error or 12552 * resolved with a rejection. 12553 * * `response`: interceptors get called with http `response` object. The function is free to 12554 * modify the `response` object or create a new one. The function needs to return the `response` 12555 * object directly, or as a promise containing the `response` or a new `response` object. 12556 * * `responseError`: interceptor gets called when a previous interceptor threw an error or 12557 * resolved with a rejection. 12558 * 12559 * 12560 * ```js 12561 * // register the interceptor as a service 12562 * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { 12563 * return { 12564 * // optional method 12565 * 'request': function(config) { 12566 * // do something on success 12567 * return config; 12568 * }, 12569 * 12570 * // optional method 12571 * 'requestError': function(rejection) { 12572 * // do something on error 12573 * if (canRecover(rejection)) { 12574 * return responseOrNewPromise 12575 * } 12576 * return $q.reject(rejection); 12577 * }, 12578 * 12579 * 12580 * 12581 * // optional method 12582 * 'response': function(response) { 12583 * // do something on success 12584 * return response; 12585 * }, 12586 * 12587 * // optional method 12588 * 'responseError': function(rejection) { 12589 * // do something on error 12590 * if (canRecover(rejection)) { 12591 * return responseOrNewPromise 12592 * } 12593 * return $q.reject(rejection); 12594 * } 12595 * }; 12596 * }); 12597 * 12598 * $httpProvider.interceptors.push('myHttpInterceptor'); 12599 * 12600 * 12601 * // alternatively, register the interceptor via an anonymous factory 12602 * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { 12603 * return { 12604 * 'request': function(config) { 12605 * // same as above 12606 * }, 12607 * 12608 * 'response': function(response) { 12609 * // same as above 12610 * } 12611 * }; 12612 * }); 12613 * ``` 12614 * 12615 * ## Security Considerations 12616 * 12617 * When designing web applications, consider security threats from: 12618 * 12619 * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) 12620 * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 12621 * 12622 * Both server and the client must cooperate in order to eliminate these threats. AngularJS comes 12623 * pre-configured with strategies that address these issues, but for this to work backend server 12624 * cooperation is required. 12625 * 12626 * ### JSON Vulnerability Protection 12627 * 12628 * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) 12629 * allows third party website to turn your JSON resource URL into 12630 * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To 12631 * counter this your server can prefix all JSON requests with following string `")]}',\n"`. 12632 * AngularJS will automatically strip the prefix before processing it as JSON. 12633 * 12634 * For example if your server needs to return: 12635 * ```js 12636 * ['one','two'] 12637 * ``` 12638 * 12639 * which is vulnerable to attack, your server can return: 12640 * ```js 12641 * )]}', 12642 * ['one','two'] 12643 * ``` 12644 * 12645 * AngularJS will strip the prefix, before processing the JSON. 12646 * 12647 * 12648 * ### Cross Site Request Forgery (XSRF) Protection 12649 * 12650 * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by 12651 * which the attacker can trick an authenticated user into unknowingly executing actions on your 12652 * website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the 12653 * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP 12654 * header (by default `X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read 12655 * the cookie, your server can be assured that the XHR came from JavaScript running on your 12656 * domain. 12657 * 12658 * To take advantage of this, your server needs to set a token in a JavaScript readable session 12659 * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the 12660 * server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be 12661 * sure that only JavaScript running on your domain could have sent the request. The token must 12662 * be unique for each user and must be verifiable by the server (to prevent the JavaScript from 12663 * making up its own tokens). We recommend that the token is a digest of your site's 12664 * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) 12665 * for added security. 12666 * 12667 * The header will — by default — **not** be set for cross-domain requests. This 12668 * prevents unauthorized servers (e.g. malicious or compromised 3rd-party APIs) from gaining 12669 * access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you 12670 * want to, you can
12670whitelist additional origins to also receive the XSRF token, by adding them 12671 * to {@link ng.$httpProvider#xsrfWhitelistedOrigins xsrfWhitelistedOrigins}. This might be 12672 * useful, for example, if your application, served from `example.com`, needs to access your API 12673 * at `api.example.com`. 12674 * See {@link ng.$httpProvider#xsrfWhitelistedOrigins $httpProvider.xsrfWhitelistedOrigins} for 12675 * more details. 12676 * 12677 * <div class="alert alert-danger"> 12678 * **Warning**<br /> 12679 * Only whitelist origins that you have control over and make sure you understand the 12680 * implications of doing so. 12681 * </div> 12682 * 12683 * The name of the cookie and the header can be specified using the `xsrfCookieName` and 12684 * `xsrfHeaderName` properties of either `$httpProvider.defaults` at config-time, 12685 * `$http.defaults` at run-time, or the per-request config object. 12686 * 12687 * In order to prevent collisions in environments where multiple AngularJS apps share the 12688 * same domain or subdomain, we recommend that each application uses a unique cookie name. 12689 * 12690 * 12691 * @param {object} config Object describing the request to be made and how it should be 12692 * processed. The object has following properties: 12693 * 12694 * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) 12695 * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested; 12696 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 12697 * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized 12698 * with the `paramSerializer` and appended as GET parameters. 12699 * - **data** – `{string|Object}` – Data to be sent as the request message data. 12700 * - **headers** – `{Object}` – Map of strings or functions which return strings representing 12701 * HTTP headers to send to the server. If the return value of a function is null, the 12702 * header will not be sent. Functions accept a config object as an argument. 12703 * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object. 12704 * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`. 12705 * The handler will be called in the context of a `$apply` block. 12706 * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload 12707 * object. To bind events to the XMLHttpRequest object, use `eventHandlers`. 12708 * The handler will be called in the context of a `$apply` block. 12709 * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. 12710 * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. 12711 * - **transformRequest** – 12712 * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – 12713 * transform function or an array of such functions. The transform function takes the http 12714 * request body and headers and returns its transformed (typically serialized) version. 12715 * See {@link ng.$http#overriding-the-default-transformations-per-request 12716 * Overriding the Default Transformations} 12717 * - **transformResponse** – 12718 * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` – 12719 * transform function or an array of such functions. The transform function takes the http 12720 * response body, headers and status and returns its transformed (typically deserialized) version. 12721 * See {@link ng.$http#overriding-the-default-transformations-per-request 12722 * Overriding the Default Transformations} 12723 * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to 12724 * prepare the string representation of request parameters (specified as an object). 12725 * If specified as string, it is interpreted as function registered with the 12726 * {@link $injector $injector}, which means you can create your own serializer 12727 * by registering it as a {@link auto.$provide#service service}. 12728 * The default serializer is the {@link $httpParamSerializer $httpParamSerializer}; 12729 * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike} 12730 * - **cache** – `{boolean|Object}` – A boolean value or object created with 12731 * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response. 12732 * See {@link $http#caching $http Caching} for more information. 12733 * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} 12734 * that should abort the request when resolved. 12735 * 12736 * A numerical timeout or a promise returned from {@link ng.$timeout $timeout}, will set 12737 * the `xhrStatus` in the {@link $http#$http-returns response} to "timeout", and any other 12738 * resolved promise will set it to "abort", following standard XMLHttpRequest behavior. 12739 * 12740 * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the 12741 * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) 12742 * for more information. 12743 * - **responseType** - `{string}` - see 12744 * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype). 12745 * 12746 * @returns {HttpPromise} A {@link ng.$q `Promise}` that will be resolved (request success) 12747 * or rejected (request failure) with a response object. 12748 * 12749 * The response object has these properties: 12750 * 12751 * - **data** – `{string|Object}` – The response body transformed with 12752 * the transform functions. 12753 * - **status** – `{number}` – HTTP status code of the response. 12754 * - **headers** – `{function([headerName])}` – Header getter function. 12755 * - **config** – `{Object}` – The configuration object that was used 12756 * to generate the request. 12757 * - **statusText** – `{string}` – HTTP status text of the response. 12758 * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest 12759 * (`complete`, `error`, `timeout` or `abort`). 12760 * 12761 * 12762 * A response status code between 200 and 299 is considered a success status 12763 * and will result in the success callback being called. Any response status 12764 * code outside of that range is considered an error status and will result 12765 * in the error callback being called. 12766 * Also, status codes less than -1 are normalized to zero. -1 usually means 12767 * the request was aborted, e.g. using a `config.timeout`. More information 12768 * about the status might be available in the `xhrStatus` property. 12769 * 12770 * Note that if the response is a redirect, XMLHttpRequest will transparently 12771 * follow it, meaning that the outcome (success or error) will be determined 12772 * by the final response status code. 12773 * 12774 * 12775 * @property {Array.<Object>} pendingRequests Array of config objects for currently pending 12776 * requests. This is primarily meant to be used for debugging purposes. 12777 * 12778 * 12779 * @example 12780<example module="httpExample" name="http-service"> 12781<file name="index.html"> 12782 <div ng-controller="FetchController"> 12783 <select ng-model="method" aria-label="Request method"> 12784 <option>GET</option> 12785 <option>JSONP</option> 12786 </select> 12787 <input type="text" ng-model="url" size="80" aria-label="URL" /> 12788 <button id="fetchbtn" ng-click="fetch()">fetch</button><br> 12789 <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> 12790 <button id="samplejsonpbtn" 12791 ng-click="updateModel('JSONP', 12792 'https://angularjs.org/greet.php?name=Super%20Hero')"> 12793 Sample JSONP 12794 </button> 12795 <button id="invalidjsonpbtn" 12796 ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')"> 12797 Invalid JSONP 12798 </button> 12799 <pre>http status code: {{status}}</pre> 12800 <pre>http response data: {{data}}</pre> 12801 </div> 12802</file> 12803<file name="script.js"> 12804 angular.module('httpExample', []) 12805 .config(['$sceDelegateProvider', function($sceDelegateProvider) { 12806 // We must whitelist the JSONP endpoint that we are using to show that we trust it 12807 $sceDelegateProvider.resourceUrlWhitel
vendor: 9,267 bytes, lines 12807-13064
12807ist([ 12808 'self', 12809 'https://angularjs.org/**' 12810 ]); 12811 }]) 12812 .controller('FetchController', ['$scope', '$http', '$templateCache', 12813 function($scope, $http, $templateCache) { 12814 $scope.method = 'GET'; 12815 $scope.url = 'http-hello.html'; 12816 12817 $scope.fetch = function() { 12818 $scope.code = null; 12819 $scope.response = null; 12820 12821 $http({method: $scope.method, url: $scope.url, cache: $templateCache}). 12822 then(function(response) { 12823 $scope.status = response.status; 12824 $scope.data = response.data; 12825 }, function(response) { 12826 $scope.data = response.data || 'Request failed'; 12827 $scope.status = response.status; 12828 }); 12829 }; 12830 12831 $scope.updateModel = function(method, url) { 12832 $scope.method = method; 12833 $scope.url = url; 12834 }; 12835 }]); 12836</file> 12837<file name="http-hello.html"> 12838 Hello, $http! 12839</file> 12840<file name="protractor.js" type="protractor"> 12841 var status = element(by.binding('status')); 12842 var data = element(by.binding('data')); 12843 var fetchBtn = element(by.id('fetchbtn')); 12844 var sampleGetBtn = element(by.id('samplegetbtn')); 12845 var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); 12846 12847 it('should make an xhr GET request', function() { 12848 sampleGetBtn.click(); 12849 fetchBtn.click(); 12850 expect(status.getText()).toMatch('200'); 12851 expect(data.getText()).toMatch(/Hello, \$http!/); 12852 }); 12853 12854// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 12855// it('should make a JSONP request to angularjs.org', function() { 12856// var sampleJsonpBtn = element(by.id('samplejsonpbtn')); 12857// sampleJsonpBtn.click(); 12858// fetchBtn.click(); 12859// expect(status.getText()).toMatch('200'); 12860// expect(data.getText()).toMatch(/Super Hero!/); 12861// }); 12862 12863 it('should make JSONP request to invalid URL and invoke the error handler', 12864 function() { 12865 invalidJsonpBtn.click(); 12866 fetchBtn.click(); 12867 expect(status.getText()).toMatch('0'); 12868 expect(data.getText()).toMatch('Request failed'); 12869 }); 12870</file> 12871</example> 12872 */ 12873 function $http(requestConfig) { 12874 12875 if (!isObject(requestConfig)) { 12876 throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig); 12877 } 12878 12879 if (!isString($sce.valueOf(requestConfig.url))) { 12880 throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url); 12881 } 12882 12883 var config = extend({ 12884 method: 'get', 12885 transformRequest: defaults.transformRequest, 12886 transformResponse: defaults.transformResponse, 12887 paramSerializer: defaults.paramSerializer, 12888 jsonpCallbackParam: defaults.jsonpCallbackParam 12889 }, requestConfig); 12890 12891 config.headers = mergeHeaders(requestConfig); 12892 config.method = uppercase(config.method); 12893 config.paramSerializer = isString(config.paramSerializer) ? 12894 $injector.get(config.paramSerializer) : config.paramSerializer; 12895 12896 $browser.$$incOutstandingRequestCount('$http'); 12897 12898 var requestInterceptors = []; 12899 var responseInterceptors = []; 12900 var promise = $q.resolve(config); 12901 12902 // apply interceptors 12903 forEach(reversedInterceptors, function(interceptor) { 12904 if (interceptor.request || interceptor.requestError) { 12905 requestInterceptors.unshift(interceptor.request, interceptor.requestError); 12906 } 12907 if (interceptor.response || interceptor.responseError) { 12908 responseInterceptors.push(interceptor.response, interceptor.responseError); 12909 } 12910 }); 12911 12912 promise = chainInterceptors(promise, requestInterceptors); 12913 promise = promise.then(serverRequest); 12914 promise = chainInterceptors(promise, responseInterceptors); 12915 promise = promise.finally(completeOutstandingRequest); 12916 12917 return promise; 12918 12919 12920 function chainInterceptors(promise, interceptors) { 12921 for (var i = 0, ii = interceptors.length; i < ii;) { 12922 var thenFn = interceptors[i++]; 12923 var rejectFn = interceptors[i++]; 12924 12925 promise = promise.then(thenFn, rejectFn); 12926 } 12927 12928 interceptors.length = 0; 12929 12930 return promise; 12931 } 12932 12933 function completeOutstandingRequest() { 12934 $browser.$$completeOutstandingRequest(noop, '$http'); 12935 } 12936 12937 function executeHeaderFns(headers, config) { 12938 var headerContent, processedHeaders = {}; 12939 12940 forEach(headers, function(headerFn, header) { 12941 if (isFunction(headerFn)) { 12942 headerContent = headerFn(config); 12943 if (headerContent != null) { 12944 processedHeaders[header] = headerContent; 12945 } 12946 } else { 12947 processedHeaders[header] = headerFn; 12948 } 12949 }); 12950 12951 return processedHeaders; 12952 } 12953 12954 function mergeHeaders(config) { 12955 var defHeaders = defaults.headers, 12956 reqHeaders = extend({}, config.headers), 12957 defHeaderName, lowercaseDefHeaderName, reqHeaderName; 12958 12959 defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); 12960 12961 // using for-in instead of forEach to avoid unnecessary iteration after header has been found 12962 defaultHeadersIteration: 12963 for (defHeaderName in defHeaders) { 12964 lowercaseDefHeaderName = lowercase(defHeaderName); 12965 12966 for (reqHeaderName in reqHeaders) { 12967 if (lowercase(reqHeaderName) === lowercaseDefHeaderName) { 12968 continue defaultHeadersIteration; 12969 } 12970 } 12971 12972 reqHeaders[defHeaderName] = defHeaders[defHeaderName]; 12973 } 12974 12975 // execute if header value is a function for merged headers 12976 return executeHeaderFns(reqHeaders, shallowCopy(config)); 12977 } 12978 12979 function serverRequest(config) { 12980 var headers = config.headers; 12981 var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); 12982 12983 // strip content-type if data is undefined 12984 if (isUndefined(reqData)) { 12985 forEach(headers, function(value, header) { 12986 if (lowercase(header) === 'content-type') { 12987 delete headers[header]; 12988 } 12989 }); 12990 } 12991 12992 if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { 12993 config.withCredentials = defaults.withCredentials; 12994 } 12995 12996 // send request 12997 return sendReq(config, reqData).then(transformResponse, transformResponse); 12998 } 12999 13000 function transformResponse(response) { 13001 // make a copy since the response must be cacheable 13002 var resp = extend({}, response); 13003 resp.data = transformData(response.data, response.headers, response.status, 13004 config.transformResponse); 13005 return (isSuccess(response.status)) 13006 ? resp 13007 : $q.reject(resp); 13008 } 13009 } 13010 13011 $http.pendingRequests = []; 13012 13013 /** 13014 * @ngdoc method 13015 * @name $http#get 13016 * 13017 * @description 13018 * Shortcut method to perform `GET` request. 13019 * 13020 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; 13021 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 13022 * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. 13023 * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. 13024 * See {@link ng.$http#$http-returns `$http()` return value}. 13025 */ 13026 13027 /** 13028 * @ngdoc method 13029 * @name $http#delete 13030 * 13031 * @description 13032 * Shortcut method to perform `DELETE` request. 13033 * 13034 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; 13035 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 13036 * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. 13037 * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. 13038 * See {@link ng.$http#$http-returns `$http()` return value}. 13039 */ 13040 13041 /** 13042 * @ngdoc method 13043 * @name $http#head 13044 * 13045 * @description 13046 * Shortcut method to perform `HEAD` request. 13047 * 13048 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; 13049 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 13050 * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. 13051 * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. 13052 * See {@link ng.$http#$http-returns `$http()` return value}. 13053 */ 13054 13055 /** 13056 * @ngdoc method 13057 * @name $http#jsonp 13058 * 13059 * @description 13060 * Shortcut method to perform `JSONP` request. 13061 * 13062 * Note that, since JSONP requests are sensitive because the response is given full access to the browser, 13063 * the url must be declared, via {@link $sce} as a trusted resource URL. 13064 * You can trust a URL by adding it to the
13064whitelist via 13065 * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitel
vendor: 29,939 bytes, lines 13065-13852
13065ist`} or 13066 * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}. 13067 * 13068 * You should avoid generating the URL for the JSONP request from user provided data. 13069 * Provide additional query parameters via `params` property of the `config` parameter, rather than 13070 * modifying the URL itself. 13071 * 13072 * JSONP requests must specify a callback to be used in the response from the server. This callback 13073 * is passed as a query parameter in the request. You must specify the name of this parameter by 13074 * setting the `jsonpCallbackParam` property on the request config object. 13075 * 13076 * ``` 13077 * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'}) 13078 * ``` 13079 * 13080 * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`. 13081 * Initially this is set to `'callback'`. 13082 * 13083 * <div class="alert alert-danger"> 13084 * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback 13085 * parameter value should go. 13086 * </div> 13087 * 13088 * If you would like to customise where and how the callbacks are stored then try overriding 13089 * or decorating the {@link $jsonpCallbacks} service. 13090 * 13091 * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; 13092 * or an object created by a call to `$sce.trustAsResourceUrl(url)`. 13093 * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. 13094 * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. 13095 * See {@link ng.$http#$http-returns `$http()` return value}. 13096 */ 13097 createShortMethods('get', 'delete', 'head', 'jsonp'); 13098 13099 /** 13100 * @ngdoc method 13101 * @name $http#post 13102 * 13103 * @description 13104 * Shortcut method to perform `POST` request. 13105 * 13106 * @param {string} url Relative or absolute URL specifying the destination of the request 13107 * @param {*} data Request content 13108 * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. 13109 * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. 13110 * See {@link ng.$http#$http-returns `$http()` return value}. 13111 */ 13112 13113 /** 13114 * @ngdoc method 13115 * @name $http#put 13116 * 13117 * @description 13118 * Shortcut method to perform `PUT` request. 13119 * 13120 * @param {string} url Relative or absolute URL specifying the destination of the request 13121 * @param {*} data Request content 13122 * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. 13123 * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. 13124 * See {@link ng.$http#$http-returns `$http()` return value}. 13125 */ 13126 13127 /** 13128 * @ngdoc method 13129 * @name $http#patch 13130 * 13131 * @description 13132 * Shortcut method to perform `PATCH` request. 13133 * 13134 * @param {string} url Relative or absolute URL specifying the destination of the request 13135 * @param {*} data Request content 13136 * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. 13137 * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. 13138 * See {@link ng.$http#$http-returns `$http()` return value}. 13139 */ 13140 createShortMethodsWithData('post', 'put', 'patch'); 13141 13142 /** 13143 * @ngdoc property 13144 * @name $http#defaults 13145 * 13146 * @description 13147 * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of 13148 * default headers, withCredentials as well as request and response transformations. 13149 * 13150 * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. 13151 */ 13152 $http.defaults = defaults; 13153 13154 13155 return $http; 13156 13157 13158 function createShortMethods(names) { 13159 forEach(arguments, function(name) { 13160 $http[name] = function(url, config) { 13161 return $http(extend({}, config || {}, { 13162 method: name, 13163 url: url 13164 })); 13165 }; 13166 }); 13167 } 13168 13169 13170 function createShortMethodsWithData(name) { 13171 forEach(arguments, function(name) { 13172 $http[name] = function(url, data, config) { 13173 return $http(extend({}, config || {}, { 13174 method: name, 13175 url: url, 13176 data: data 13177 })); 13178 }; 13179 }); 13180 } 13181 13182 13183 /** 13184 * Makes the request. 13185 * 13186 * !!! ACCESSES CLOSURE VARS: 13187 * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests 13188 */ 13189 function sendReq(config, reqData) { 13190 var deferred = $q.defer(), 13191 promise = deferred.promise, 13192 cache, 13193 cachedResp, 13194 reqHeaders = config.headers, 13195 isJsonp = lowercase(config.method) === 'jsonp', 13196 url = config.url; 13197 13198 if (isJsonp) { 13199 // JSONP is a pretty sensitive operation where we're allowing a script to have full access to 13200 // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL. 13201 url = $sce.getTrustedResourceUrl(url); 13202 } else if (!isString(url)) { 13203 // If it is not a string then the URL must be a $sce trusted object 13204 url = $sce.valueOf(url); 13205 } 13206 13207 url = buildUrl(url, config.paramSerializer(config.params)); 13208 13209 if (isJsonp) { 13210 // Check the url and add the JSONP callback placeholder 13211 url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam); 13212 } 13213 13214 $http.pendingRequests.push(config); 13215 promise.then(removePendingReq, removePendingReq); 13216 13217 if ((config.cache || defaults.cache) && config.cache !== false && 13218 (config.method === 'GET' || config.method === 'JSONP')) { 13219 cache = isObject(config.cache) ? config.cache 13220 : isObject(/** @type {?} */ (defaults).cache) 13221 ? /** @type {?} */ (defaults).cache 13222 : defaultCache; 13223 } 13224 13225 if (cache) { 13226 cachedResp = cache.get(url); 13227 if (isDefined(cachedResp)) { 13228 if (isPromiseLike(cachedResp)) { 13229 // cached request has already been sent, but there is no response yet 13230 cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult); 13231 } else { 13232 // serving from cache 13233 if (isArray(cachedResp)) { 13234 resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]); 13235 } else { 13236 resolvePromise(cachedResp, 200, {}, 'OK', 'complete'); 13237 } 13238 } 13239 } else { 13240 // put the promise for the non-transformed response into cache as a placeholder 13241 cache.put(url, promise); 13242 } 13243 } 13244 13245 13246 // if we won't have the response in cache, set the xsrf headers and 13247 // send the request to the backend 13248 if (isUndefined(cachedResp)) { 13249 var xsrfValue = urlIsAllowedOrigin(config.url) 13250 ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName] 13251 : undefined; 13252 if (xsrfValue) { 13253 reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; 13254 } 13255 13256 $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, 13257 config.withCredentials, config.responseType, 13258 createApplyHandlers(config.eventHandlers), 13259 createApplyHandlers(config.uploadEventHandlers)); 13260 } 13261 13262 return promise; 13263 13264 function createApplyHandlers(eventHandlers) { 13265 if (eventHandlers) { 13266 var applyHandlers = {}; 13267 forEach(eventHandlers, function(eventHandler, key) { 13268 applyHandlers[key] = function(event) { 13269 if (useApplyAsync) { 13270 $rootScope.$applyAsync(callEventHandler); 13271 } else if ($rootScope.$$phase) { 13272 callEventHandler(); 13273 } else { 13274 $rootScope.$apply(callEventHandler); 13275 } 13276 13277 function callEventHandler() { 13278 eventHandler(event); 13279 } 13280 }; 13281 }); 13282 return applyHandlers; 13283 } 13284 } 13285 13286 13287 /** 13288 * Callback registered to $httpBackend(): 13289 * - caches the response if desired 13290 * - resolves the raw $http promise 13291 * - calls $apply 13292 */ 13293 function done(status, response, headersString, statusText, xhrStatus) { 13294 if (cache) { 13295 if (isSuccess(status)) { 13296 cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]); 13297 } else { 13298 // remove promise from the cache 13299 cache.remove(url); 13300 } 13301 } 13302 13303 function resolveHttpPromise() { 13304 resolvePromise(response, status, headersString, statusText, xhrStatus); 13305 } 13306 13307 if (useApplyAsync) { 13308 $rootScope.$applyAsync(resolveHttpPromise); 13309 } else { 13310 resolveHttpPromise(); 13311 if (!$rootScope.$$phase) $rootScope.$apply(); 13312 } 13313 } 13314 13315 13316 /** 13317 * Resolves the raw $http promise. 13318 */ 13319 function resolvePromise(response, status, headers, statusText, xhrStatus) { 13320 //status: HTTP response status code, 0, -1 (aborted by timeout / promise) 13321 status = status >= -1 ? status : 0; 13322 13323 (isSuccess(status) ? deferred.resolve : deferred.reject)({ 13324 data: response, 13325 status: status, 13326 headers: headersGetter(headers), 13327 config: config, 13328 statusText: statusText, 13329 xhrStatus: xhrStatus 13330 }); 13331 } 13332 13333 function resolvePromiseWithResult(result) { 13334 resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus); 13335 } 13336 13337 function removePendingReq() { 13338 var idx = $http.pendingRequests.indexOf(config); 13339 if (idx !== -1) $http.pendingRequests.splice(idx, 1); 13340 } 13341 } 13342 13343 13344 function buildUrl(url, serializedParams) { 13345 if (serializedParams.length > 0) { 13346 url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams; 13347 } 13348 return url; 13349 } 13350 13351 function sanitizeJsonpCallbackParam(url, cbKey) { 13352 var parts = url.split('?'); 13353 if (parts.length > 2) { 13354 // Throw if the url contains more than one `?` query indicator 13355 throw $httpMinErr('badjsonp', 'Illegal use more than one "?", in url, "{1}"', url); 13356 } 13357 var params = parseKeyValue(parts[1]); 13358 forEach(params, function(value, key) { 13359 if (value === 'JSON_CALLBACK') { 13360 // Throw if the url already contains a reference to JSON_CALLBACK 13361 throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url); 13362 } 13363 if (key === cbKey) { 13364 // Throw if the callback param was already provided 13365 throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', cbKey, url); 13366 } 13367 }); 13368 13369 // Add in the JSON_CALLBACK callback param value 13370 url += ((url.indexOf('?') === -1) ? '?' : '&') + cbKey + '=JSON_CALLBACK'; 13371 13372 return url; 13373 } 13374 }]; 13375} 13376 13377/** 13378 * @ngdoc service 13379 * @name $xhrFactory 13380 * @this 13381 * 13382 * @description 13383 * Factory function used to create XMLHttpRequest objects. 13384 * 13385 * Replace or decorate this service to create your own custom XMLHttpRequest objects. 13386 * 13387 * ``` 13388 * angular.module('myApp', []) 13389 * .factory('$xhrFactory', function() { 13390 * return function createXhr(method, url) { 13391 * return new window.XMLHttpRequest({mozSystem: true}); 13392 * }; 13393 * }); 13394 * ``` 13395 * 13396 * @param {string} method HTTP method of the request (GET, POST, PUT, ..) 13397 * @param {string} url URL of the request. 13398 */ 13399function $xhrFactoryProvider() { 13400 this.$get = function() { 13401 return function createXhr() { 13402 return new window.XMLHttpRequest(); 13403 }; 13404 }; 13405} 13406 13407/** 13408 * @ngdoc service 13409 * @name $httpBackend 13410 * @requires $jsonpCallbacks 13411 * @requires $document 13412 * @requires $xhrFactory 13413 * @this 13414 * 13415 * @description 13416 * HTTP backend used by the {@link ng.$http service} that delegates to 13417 * XMLHttpRequest object or JSONP and deals with browser incompatibilities. 13418 * 13419 * You should never need to use this service directly, instead use the higher-level abstractions: 13420 * {@link ng.$http $http} or {@link ngResource.$resource $resource}. 13421 * 13422 * During testing this implementation is swapped with {@link ngMock.$httpBackend mock 13423 * $httpBackend} which can be trained with responses. 13424 */ 13425function $HttpBackendProvider() { 13426 this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) { 13427 return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]); 13428 }]; 13429} 13430 13431function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { 13432 // TODO(vojta): fix the signature 13433 return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) { 13434 url = url || $browser.url(); 13435 13436 if (lowercase(method) === 'jsonp') { 13437 var callbackPath = callbacks.createCallback(url); 13438 var jsonpDone = jsonpReq(url, callbackPath, function(status, text) { 13439 // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING) 13440 var response = (status === 200) && callbacks.getResponse(callbackPath); 13441 completeRequest(callback, status, response, '', text, 'complete'); 13442 callbacks.removeCallback(callbackPath); 13443 }); 13444 } else { 13445 13446 var xhr = createXhr(method, url); 13447 var abortedByTimeout = false; 13448 13449 xhr.open(method, url, true); 13450 forEach(headers, function(value, key) { 13451 if (isDefined(value)) { 13452 xhr.setRequestHeader(key, value); 13453 } 13454 }); 13455 13456 xhr.onload = function requestLoaded() { 13457 var statusText = xhr.statusText || ''; 13458 13459 // responseText is the old-school way of retrieving response (supported by IE9) 13460 // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) 13461 var response = ('response' in xhr) ? xhr.response : xhr.responseText; 13462 13463 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) 13464 var status = xhr.status === 1223 ? 204 : xhr.status; 13465 13466 // fix status code when it is 0 (0 status is undocumented). 13467 // Occurs when accessing file resources or on Android 4.1 stock browser 13468 // while retrieving files from application cache. 13469 if (status === 0) { 13470 status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0; 13471 } 13472 13473 completeRequest(callback, 13474 status, 13475 response, 13476 xhr.getAllResponseHeaders(), 13477 statusText, 13478 'complete'); 13479 }; 13480 13481 var requestError = function() { 13482 // The response is always empty 13483 // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error 13484 completeRequest(callback, -1, null, null, '', 'error'); 13485 }; 13486 13487 var requestAborted = function() { 13488 completeRequest(callback, -1, null, null, '', abortedByTimeout ? 'timeout' : 'abort'); 13489 }; 13490 13491 var requestTimeout = function() { 13492 // The response is always empty 13493 // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error 13494 completeRequest(callback, -1, null, null, '', 'timeout'); 13495 }; 13496 13497 xhr.onerror = requestError; 13498 xhr.ontimeout = requestTimeout; 13499 xhr.onabort = requestAborted; 13500 13501 forEach(eventHandlers, function(value, key) { 13502 xhr.addEventListener(key, value); 13503 }); 13504 13505 forEach(uploadEventHandlers, function(value, key) { 13506 xhr.upload.addEventListener(key, value); 13507 }); 13508 13509 if (withCredentials) { 13510 xhr.withCredentials = true; 13511 } 13512 13513 if (responseType) { 13514 try { 13515 xhr.responseType = responseType; 13516 } catch (e) { 13517 // WebKit added support for the json responseType value on 09/03/2013 13518 // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are 13519 // known to throw when setting the value "json" as the response type. Other older 13520 // browsers implementing the responseType 13521 // 13522 // The json response type can be ignored if not supported, because JSON payloads are 13523 // parsed on the client-side regardless. 13524 if (responseType !== 'json') { 13525 throw e; 13526 } 13527 } 13528 } 13529 13530 xhr.send(isUndefined(post) ? null : post); 13531 } 13532 13533 // Since we are using xhr.abort() when a request times out, we have to set a flag that 13534 // indicates to requestAborted if the request timed out or was aborted. 13535 // 13536 // http.timeout = numerical timeout timeout 13537 // http.timeout = $timeout timeout 13538 // http.timeout = promise abort 13539 // xhr.abort() abort (The xhr object is normally inaccessible, but 13540 // can be exposed with the xhrFactory) 13541 if (timeout > 0) { 13542 var timeoutId = $browserDefer(function() { 13543 timeoutRequest('timeout'); 13544 }, timeout); 13545 } else if (isPromiseLike(timeout)) { 13546 timeout.then(function() { 13547 timeoutRequest(isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort'); 13548 }); 13549 } 13550 13551 function timeoutRequest(reason) { 13552 abortedByTimeout = reason === 'timeout'; 13553 if (jsonpDone) { 13554 jsonpDone(); 13555 } 13556 if (xhr) { 13557 xhr.abort(); 13558 } 13559 } 13560 13561 function completeRequest(callback, status, response, headersString, statusText, xhrStatus) { 13562 // cancel timeout and subsequent timeout promise resolution 13563 if (isDefined(timeoutId)) { 13564 $browserDefer.cancel(timeoutId); 13565 } 13566 jsonpDone = xhr = null; 13567 13568 callback(status, response, headersString, statusText, xhrStatus); 13569 } 13570 }; 13571 13572 function jsonpReq(url, callbackPath, done) { 13573 url = url.replace('JSON_CALLBACK', callbackPath); 13574 // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.: 13575 // - fetches local scripts via XHR and evals them 13576 // - adds and immediately removes script elements from the document 13577 var script = rawDocument.createElement('script'), callback = null; 13578 script.type = 'text/javascript'; 13579 script.src = url; 13580 script.async = true; 13581 13582 callback = function(event) { 13583 script.removeEventListener('load', callback); 13584 script.removeEventListener('error', callback); 13585 rawDocument.body.removeChild(script); 13586 script = null; 13587 var status = -1; 13588 var text = 'unknown'; 13589 13590 if (event) { 13591 if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) { 13592 event = { type: 'error' }; 13593 } 13594 text = event.type; 13595 status = event.type === 'error' ? 404 : 200; 13596 } 13597 13598 if (done) { 13599 done(status, text); 13600 } 13601 }; 13602 13603 script.addEventListener('load', callback); 13604 script.addEventListener('error', callback); 13605 rawDocument.body.appendChild(script); 13606 return callback; 13607 } 13608} 13609 13610var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate'); 13611$interpolateMinErr.throwNoconcat = function(text) { 13612 throw $interpolateMinErr('noconcat', 13613 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' + 13614 'interpolations that concatenate multiple expressions when a trusted value is ' + 13615 'required. See http://docs.angularjs.org/api/ng.$sce', text); 13616}; 13617 13618$interpolateMinErr.interr = function(text, err) { 13619 return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString()); 13620}; 13621 13622/** 13623 * @ngdoc provider 13624 * @name $interpolateProvider 13625 * @this 13626 * 13627 * @description 13628 * 13629 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. 13630 * 13631 * <div class="alert alert-danger"> 13632 * This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS 13633 * template within a Python Jinja template (or any other template language). Mixing templating 13634 * languages is **very dangerous**. The embedding template language will not safely escape AngularJS 13635 * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS) 13636 * security bugs! 13637 * </div> 13638 * 13639 * @example 13640<example name="custom-interpolation-markup" module="customInterpolationApp"> 13641<file name="index.html"> 13642<script> 13643 var customInterpolationApp = angular.module('customInterpolationApp', []); 13644 13645 customInterpolationApp.config(function($interpolateProvider) { 13646 $interpolateProvider.startSymbol('//'); 13647 $interpolateProvider.endSymbol('//'); 13648 }); 13649 13650 13651 customInterpolationApp.controller('DemoController', function() { 13652 this.label = "This binding is brought you by // interpolation symbols."; 13653 }); 13654</script> 13655<div ng-controller="DemoController as demo"> 13656 //demo.label// 13657</div> 13658</file> 13659<file name="protractor.js" type="protractor"> 13660 it('should interpolate binding with custom symbols', function() { 13661 expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.'); 13662 }); 13663</file> 13664</example> 13665 */ 13666function $InterpolateProvider() { 13667 var startSymbol = '{{'; 13668 var endSymbol = '}}'; 13669 13670 /** 13671 * @ngdoc method 13672 * @name $interpolateProvider#startSymbol 13673 * @description 13674 * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. 13675 * 13676 * @param {string=} value new value to set the starting symbol to. 13677 * @returns {string|self} Returns the symbol when used as getter and self if used as setter. 13678 */ 13679 this.startSymbol = function(value) { 13680 if (value) { 13681 startSymbol = value; 13682 return this; 13683 } 13684 return startSymbol; 13685 }; 13686 13687 /** 13688 * @ngdoc method 13689 * @name $interpolateProvider#endSymbol 13690 * @description 13691 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. 13692 * 13693 * @param {string=} value new value to set the ending symbol to. 13694 * @returns {string|self} Returns the symbol when used as getter and self if used as setter. 13695 */ 13696 this.endSymbol = function(value) { 13697 if (value) { 13698 endSymbol = value; 13699 return this; 13700 } 13701 return endSymbol; 13702 }; 13703 13704 13705 this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { 13706 var startSymbolLength = startSymbol.length, 13707 endSymbolLength = endSymbol.length, 13708 escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), 13709 escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); 13710 13711 function escape(ch) { 13712 return '\\\\\\' + ch; 13713 } 13714 13715 function unescapeText(text) { 13716 return text.replace(escapedStartRegexp, startSymbol). 13717 replace(escapedEndRegexp, endSymbol); 13718 } 13719 13720 // TODO: this is the same as the constantWatchDelegate in parse.js 13721 function constantWatchDelegate(scope, listener, objectEquality, constantInterp) { 13722 var unwatch = scope.$watch(function constantInterpolateWatch(scope) { 13723 unwatch(); 13724 return constantInterp(scope); 13725 }, listener, objectEquality); 13726 return unwatch; 13727 } 13728 13729 /** 13730 * @ngdoc service 13731 * @name $interpolate 13732 * @kind function 13733 * 13734 * @requires $parse 13735 * @requires $sce 13736 * 13737 * @description 13738 * 13739 * Compiles a string with markup into an interpolation function. This service is used by the 13740 * HTML {@link ng.$compile $compile} service for data binding. See 13741 * {@link ng.$interpolateProvider $interpolateProvider} for configuring the 13742 * interpolation markup. 13743 * 13744 * 13745 * ```js 13746 * var $interpolate = ...; // injected 13747 * var exp = $interpolate('Hello {{name | uppercase}}!'); 13748 * expect(exp({name:'AngularJS'})).toEqual('Hello ANGULARJS!'); 13749 * ``` 13750 * 13751 * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is 13752 * `true`, the interpolation function will return `undefined` unless all embedded expressions 13753 * evaluate to a value other than `undefined`. 13754 * 13755 * ```js 13756 * var $interpolate = ...; // injected 13757 * var context = {greeting: 'Hello', name: undefined }; 13758 * 13759 * // default "forgiving" mode 13760 * var exp = $interpolate('{{greeting}} {{name}}!'); 13761 * expect(exp(context)).toEqual('Hello !'); 13762 * 13763 * // "allOrNothing" mode 13764 * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); 13765 * expect(exp(context)).toBeUndefined(); 13766 * context.name = 'AngularJS'; 13767 * expect(exp(context)).toEqual('Hello AngularJS!'); 13768 * ``` 13769 * 13770 * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. 13771 * 13772 * #### Escaped Interpolation 13773 * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers 13774 * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). 13775 * It will be rendered as a regular start/end marker, and will not be interpreted as an expression 13776 * or binding. 13777 * 13778 * This enables web-servers to prevent script injection attacks and defacing attacks, to some 13779 * degree, while also enabling code examples to work without relying on the 13780 * {@link ng.directive:ngNonBindable ngNonBindable} directive. 13781 * 13782 * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, 13783 * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all 13784 * interpolation start/end markers with their escaped counterparts.** 13785 * 13786 * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered 13787 * output when the $interpolate service processes the text. So, for HTML elements interpolated 13788 * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter 13789 * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, 13790 * this is typically useful only when user-data is used in rendering a template from the server, or 13791 * when otherwise untrusted data is used by a directive. 13792 * 13793 * <example name="interpolation"> 13794 * <file name="index.html"> 13795 * <div ng-init="username='A user'"> 13796 * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\} 13797 * </p> 13798 * <p><strong>{{username}}</strong> attempts to inject code which will deface the 13799 * application, but fails to accomplish their task, because the server has correctly 13800 * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) 13801 * characters.</p> 13802 * <p>Instead, the result of the attempted script injection is visible, and can be removed 13803 * from the database by an administrator.</p> 13804 * </div> 13805 * </file> 13806 * </example> 13807 * 13808 * @knownIssue 13809 * It is currently not possible for an interpolated expression to contain the interpolation end 13810 * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e. 13811 * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string. 13812 * 13813 * @knownIssue 13814 * All directives and components must use the standard `{{` `}}` interpolation symbols 13815 * in their templates. If you change the application interpolation symbols the {@link $compile} 13816 * service will attempt to denormalize the standard symbols to the custom symbols. 13817 * The denormalization process is not clever enough to know not to replace instances of the standard 13818 * symbols where they would not normally be treated as interpolation symbols. For example in the following 13819 * code snippet the closing braces of the literal object will get incorrectly denormalized: 13820 * 13821 * ``` 13822 * <div data-context='{"context":{"id":3,"type":"page"}}"> 13823 * ``` 13824 * 13825 * The workaround is to ensure that such instances are separated by whitespace: 13826 * ``` 13827 * <div data-context='{"context":{"id":3,"type":"page"} }"> 13828 * ``` 13829 * 13830 * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information. 13831 * 13832 * @param {string} text The text with markup to interpolate. 13833 * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have 13834 * embedded expression in order to return an interpolation function. Strings with no 13835 * embedded expression will return null for the interpolation function. 13836 * @param {string=} trustedContext when provided, the returned function passes the interpolated 13837 * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, 13838 * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that 13839 * provides Strict Contextual Escaping for details. 13840 * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined 13841 * unless all embedded expressions evaluate to a value other than `undefined`. 13842 * @returns {function(context)} an interpolation function which is used to compute the 13843 * interpolated string. The function has these parameters: 13844 * 13845 * - `context`: evaluation context for all expressions embedded in the interpolated text 13846 */ 13847 function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { 13848 var contextAllowsConcatenation = trustedContext === $sce.URL || trustedContext === $sce.MEDIA_URL; 13849 13850 // Provide a quick exit and simplified result function for text with no interpolation 13851 if (!text.length || text.indexOf(startSymbol) === -1) { 13852 if (mustHaveExpression
13852 && !contextAllowsConcatenat
vendor: 117,999 bytes, lines 13852-17441
13852ion) return; 13853 13854 var unescapedText = unescapeText(text); 13855 if (contextAllowsConcatenation) { 13856 unescapedText = $sce.getTrusted(trustedContext, unescapedText); 13857 } 13858 var constantInterp = valueFn(unescapedText); 13859 constantInterp.exp = text; 13860 constantInterp.expressions = []; 13861 constantInterp.$$watchDelegate = constantWatchDelegate; 13862 13863 return constantInterp; 13864 } 13865 13866 allOrNothing = !!allOrNothing; 13867 var startIndex, 13868 endIndex, 13869 index = 0, 13870 expressions = [], 13871 parseFns, 13872 textLength = text.length, 13873 exp, 13874 concat = [], 13875 expressionPositions = [], 13876 singleExpression; 13877 13878 13879 while (index < textLength) { 13880 if (((startIndex = text.indexOf(startSymbol, index)) !== -1) && 13881 ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) { 13882 if (index !== startIndex) { 13883 concat.push(unescapeText(text.substring(index, startIndex))); 13884 } 13885 exp = text.substring(startIndex + startSymbolLength, endIndex); 13886 expressions.push(exp); 13887 index = endIndex + endSymbolLength; 13888 expressionPositions.push(concat.length); 13889 concat.push(''); // Placeholder that will get replaced with the evaluated expression. 13890 } else { 13891 // we did not find an interpolation, so we have to add the remainder to the separators array 13892 if (index !== textLength) { 13893 concat.push(unescapeText(text.substring(index))); 13894 } 13895 break; 13896 } 13897 } 13898 13899 singleExpression = concat.length === 1 && expressionPositions.length === 1; 13900 // Intercept expression if we need to stringify concatenated inputs, which may be SCE trusted 13901 // objects rather than simple strings 13902 // (we don't modify the expression if the input consists of only a single trusted input) 13903 var interceptor = contextAllowsConcatenation && singleExpression ? undefined : parseStringifyInterceptor; 13904 parseFns = expressions.map(function(exp) { return $parse(exp, interceptor); }); 13905 13906 // Concatenating expressions makes it hard to reason about whether some combination of 13907 // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a 13908 // single expression be used for some $sce-managed secure contexts (RESOURCE_URLs mostly), 13909 // we ensure that the value that's used is assigned or constructed by some JS code somewhere 13910 // that is more testable or make it obvious that you bound the value to some user controlled 13911 // value. This helps reduce the load when auditing for XSS issues. 13912 13913 // Note that URL and MEDIA_URL $sce contexts do not need this, since `$sce` can sanitize the values 13914 // passed to it. In that case, `$sce.getTrusted` will be called on either the single expression 13915 // or on the overall concatenated string (losing trusted types used in the mix, by design). 13916 // Both these methods will sanitize plain strings. Also, HTML could be included, but since it's 13917 // only used in srcdoc attributes, this would not be very useful. 13918 13919 if (!mustHaveExpression || expressions.length) { 13920 var compute = function(values) { 13921 for (var i = 0, ii = expressions.length; i < ii; i++) { 13922 if (allOrNothing && isUndefined(values[i])) return; 13923 concat[expressionPositions[i]] = values[i]; 13924 } 13925 13926 if (contextAllowsConcatenation) { 13927 // If `singleExpression` then `concat[0]` might be a "trusted" value or `null`, rather than a string 13928 return $sce.getTrusted(trustedContext, singleExpression ? concat[0] : concat.join('')); 13929 } else if (trustedContext && concat.length > 1) { 13930 // This context does not allow more than one part, e.g. expr + string or exp + exp. 13931 $interpolateMinErr.throwNoconcat(text); 13932 } 13933 // In an unprivileged context or only one part: just concatenate and return. 13934 return concat.join(''); 13935 }; 13936 13937 return extend(function interpolationFn(context) { 13938 var i = 0; 13939 var ii = expressions.length; 13940 var values = new Array(ii); 13941 13942 try { 13943 for (; i < ii; i++) { 13944 values[i] = parseFns[i](context); 13945 } 13946 13947 return compute(values); 13948 } catch (err) { 13949 $exceptionHandler($interpolateMinErr.interr(text, err)); 13950 } 13951 13952 }, { 13953 // all of these properties are undocumented for now 13954 exp: text, //just for compatibility with regular watchers created via $watch 13955 expressions: expressions, 13956 $$watchDelegate: function(scope, listener) { 13957 var lastValue; 13958 return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) { 13959 var currValue = compute(values); 13960 listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); 13961 lastValue = currValue; 13962 }); 13963 } 13964 }); 13965 } 13966 13967 function parseStringifyInterceptor(value) { 13968 try { 13969 // In concatenable contexts, getTrusted comes at the end, to avoid sanitizing individual 13970 // parts of a full URL. We don't care about losing the trustedness here. 13971 // In non-concatenable contexts, where there is only one expression, this interceptor is 13972 // not applied to the expression. 13973 value = (trustedContext && !contextAllowsConcatenation) ? 13974 $sce.getTrusted(trustedContext, value) : 13975 $sce.valueOf(value); 13976 return allOrNothing && !isDefined(value) ? value : stringify(value); 13977 } catch (err) { 13978 $exceptionHandler($interpolateMinErr.interr(text, err)); 13979 } 13980 } 13981 } 13982 13983 13984 /** 13985 * @ngdoc method 13986 * @name $interpolate#startSymbol 13987 * @description 13988 * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. 13989 * 13990 * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change 13991 * the symbol. 13992 * 13993 * @returns {string} start symbol. 13994 */ 13995 $interpolate.startSymbol = function() { 13996 return startSymbol; 13997 }; 13998 13999 14000 /** 14001 * @ngdoc method 14002 * @name $interpolate#endSymbol 14003 * @description 14004 * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. 14005 * 14006 * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change 14007 * the symbol. 14008 * 14009 * @returns {string} end symbol. 14010 */ 14011 $interpolate.endSymbol = function() { 14012 return endSymbol; 14013 }; 14014 14015 return $interpolate; 14016 }]; 14017} 14018 14019var $intervalMinErr = minErr('$interval'); 14020 14021/** @this */ 14022function $IntervalProvider() { 14023 this.$get = ['$$intervalFactory', '$window', 14024 function($$intervalFactory, $window) { 14025 var intervals = {}; 14026 var setIntervalFn = function(tick, delay, deferred) { 14027 var id = $window.setInterval(tick, delay); 14028 intervals[id] = deferred; 14029 return id; 14030 }; 14031 var clearIntervalFn = function(id) { 14032 $window.clearInterval(id); 14033 delete intervals[id]; 14034 }; 14035 14036 /** 14037 * @ngdoc service 14038 * @name $interval 14039 * 14040 * @description 14041 * AngularJS's wrapper for `window.setInterval`. The `fn` function is executed every `delay` 14042 * milliseconds. 14043 * 14044 * The return value of registering an interval function is a promise. This promise will be 14045 * notified upon each tick of the interval, and will be resolved after `count` iterations, or 14046 * run indefinitely if `count` is not defined. The value of the notification will be the 14047 * number of iterations that have run. 14048 * To cancel an interval, call `$interval.cancel(promise)`. 14049 * 14050 * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to 14051 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that 14052 * time. 14053 * 14054 * <div class="alert alert-warning"> 14055 * **Note**: Intervals created by this service must be explicitly destroyed when you are finished 14056 * with them. In particular they are not automatically destroyed when a controller's scope or a 14057 * directive's element are destroyed. 14058 * You should take this into consideration and make sure to always cancel the interval at the 14059 * appropriate moment. See the example below for more details on how and when to do this. 14060 * </div> 14061 * 14062 * @param {function()} fn A function that should be called repeatedly. If no additional arguments 14063 * are passed (see below), the function is called with the current iteration count. 14064 * @param {number} delay Number of milliseconds between each function call. 14065 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat 14066 * indefinitely. 14067 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise 14068 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. 14069 * @param {...*=} Pass additional parameters to the executed function. 14070 * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete. 14071 * 14072 * @example 14073 * <example module="intervalExample" name="interval-service"> 14074 * <file name="index.html"> 14075 * <script> 14076 * angular.module('intervalExample', []) 14077 * .controller('ExampleController', ['$scope', '$interval', 14078 * function($scope, $interval) { 14079 * $scope.format = 'M/d/yy h:mm:ss a'; 14080 * $scope.blood_1 = 100; 14081 * $scope.blood_2 = 120; 14082 * 14083 * var stop; 14084 * $scope.fight = function() { 14085 * // Don't start a new fight if we are already fighting 14086 * if ( angular.isDefined(stop) ) return; 14087 * 14088 * stop = $interval(function() { 14089 * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) { 14090 * $scope.blood_1 = $scope.blood_1 - 3; 14091 * $scope.blood_2 = $scope.blood_2 - 4; 14092 * } else { 14093 * $scope.stopFight(); 14094 * } 14095 * }, 100); 14096 * }; 14097 * 14098 * $scope.stopFight = function() { 14099 * if (angular.isDefined(stop)) { 14100 * $interval.cancel(stop); 14101 * stop = undefined; 14102 * } 14103 * }; 14104 * 14105 * $scope.resetFight = function() { 14106 * $scope.blood_1 = 100; 14107 * $scope.blood_2 = 120; 14108 * }; 14109 * 14110 * $scope.$on('$destroy', function() { 14111 * // Make sure that the interval is destroyed too 14112 * $scope.stopFight(); 14113 * }); 14114 * }]) 14115 * // Register the 'myCurrentTime' directive factory method. 14116 * // We inject $interval and dateFilter service since the factory method is DI. 14117 * .directive('myCurrentTime', ['$interval', 'dateFilter', 14118 * function($interval, dateFilter) { 14119 * // return the directive link function. (compile function not needed) 14120 * return function(scope, element, attrs) { 14121 * var format, // date format 14122 * stopTime; // so that we can cancel the time updates 14123 * 14124 * // used to update the UI 14125 * function updateTime() { 14126 * element.text(dateFilter(new Date(), format)); 14127 * } 14128 * 14129 * // watch the expression, and update the UI on change. 14130 * scope.$watch(attrs.myCurrentTime, function(value) { 14131 * format = value; 14132 * updateTime(); 14133 * }); 14134 * 14135 * stopTime = $interval(updateTime, 1000); 14136 * 14137 * // listen on DOM destroy (removal) event, and cancel the next UI update 14138 * // to prevent updating time after the DOM element was removed. 14139 * element.on('$destroy', function() { 14140 * $interval.cancel(stopTime); 14141 * }); 14142 * } 14143 * }]); 14144 * </script> 14145 * 14146 * <div> 14147 * <div ng-controller="ExampleController"> 14148 * <label>Date format: <input ng-model="format"></label> <hr/> 14149 * Current time is: <span my-current-time="format"></span> 14150 * <hr/> 14151 * Blood 1 : <font color='red'>{{blood_1}}</font> 14152 * Blood 2 : <font color='red'>{{blood_2}}</font> 14153 * <button type="button" data-ng-click="fight()">Fight</button> 14154 * <button type="button" data-ng-click="stopFight()">StopFight</button> 14155 * <button type="button" data-ng-click="resetFight()">resetFight</button> 14156 * </div> 14157 * </div> 14158 * 14159 * </file> 14160 * </example> 14161 */ 14162 var interval = $$intervalFactory(setIntervalFn, clearIntervalFn); 14163 14164 /** 14165 * @ngdoc method 14166 * @name $interval#cancel 14167 * 14168 * @description 14169 * Cancels a task associated with the `promise`. 14170 * 14171 * @param {Promise=} promise returned by the `$interval` function. 14172 * @returns {boolean} Returns `true` if the task was successfully canceled. 14173 */ 14174 interval.cancel = function(promise) { 14175 if (!promise) return false; 14176 14177 if (!promise.hasOwnProperty('$$intervalId')) { 14178 throw $intervalMinErr('badprom', 14179 '`$interval.cancel()` called with a promise that was not generated by `$interval()`.'); 14180 } 14181 14182 if (!intervals.hasOwnProperty(promise.$$intervalId)) return false; 14183 14184 var id = promise.$$intervalId; 14185 var deferred = intervals[id]; 14186 14187 // Interval cancels should not report an unhandled promise. 14188 markQExceptionHandled(deferred.promise); 14189 deferred.reject('canceled'); 14190 clearIntervalFn(id); 14191 14192 return true; 14193 }; 14194 14195 return interval; 14196 }]; 14197} 14198 14199/** @this */ 14200function $$IntervalFactoryProvider() { 14201 this.$get = ['$browser', '$q', '$$q', '$rootScope', 14202 function($browser, $q, $$q, $rootScope) { 14203 return function intervalFactory(setIntervalFn, clearIntervalFn) { 14204 return function intervalFn(fn, delay, count, invokeApply) { 14205 var hasParams = arguments.length > 4, 14206 args = hasParams ? sliceArgs(arguments, 4) : [], 14207 iteration = 0, 14208 skipApply = isDefined(invokeApply) && !invokeApply, 14209 deferred = (skipApply ? $$q : $q).defer(), 14210 promise = deferred.promise; 14211 14212 count = isDefined(count) ? count : 0; 14213 14214 function callback() { 14215 if (!hasParams) { 14216 fn(iteration); 14217 } else { 14218 fn.apply(null, args); 14219 } 14220 } 14221 14222 function tick() { 14223 if (skipApply) { 14224 $browser.defer(callback); 14225 } else { 14226 $rootScope.$evalAsync(callback); 14227 } 14228 deferred.notify(iteration++); 14229 14230 if (count > 0 && iteration >= count) { 14231 deferred.resolve(iteration); 14232 clearIntervalFn(promise.$$intervalId); 14233 } 14234 14235 if (!skipApply) $rootScope.$apply(); 14236 } 14237 14238 promise.$$intervalId = setIntervalFn(tick, delay, deferred, skipApply); 14239 14240 return promise; 14241 }; 14242 }; 14243 }]; 14244} 14245 14246/** 14247 * @ngdoc service 14248 * @name $jsonpCallbacks 14249 * @requires $window 14250 * @description 14251 * This service handles the lifecycle of callbacks to handle JSONP requests. 14252 * Override this service if you wish to customise where the callbacks are stored and 14253 * how they vary compared to the requested url. 14254 */ 14255var $jsonpCallbacksProvider = /** @this */ function() { 14256 this.$get = function() { 14257 var callbacks = angular.callbacks; 14258 var callbackMap = {}; 14259 14260 function createCallback(callbackId) { 14261 var callback = function(data) { 14262 callback.data = data; 14263 callback.called = true; 14264 }; 14265 callback.id = callbackId; 14266 return callback; 14267 } 14268 14269 return { 14270 /** 14271 * @ngdoc method 14272 * @name $jsonpCallbacks#createCallback 14273 * @param {string} url the url of the JSONP request 14274 * @returns {string} the callback path to send to the server as part of the JSONP request 14275 * @description 14276 * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback 14277 * to pass to the server, which will be used to call the callback with its payload in the JSONP response. 14278 */ 14279 createCallback: function(url) { 14280 var callbackId = '_' + (callbacks.$$counter++).toString(36); 14281 var callbackPath = 'angular.callbacks.' + callbackId; 14282 var callback = createCallback(callbackId); 14283 callbackMap[callbackPath] = callbacks[callbackId] = callback; 14284 return callbackPath; 14285 }, 14286 /** 14287 * @ngdoc method 14288 * @name $jsonpCallbacks#wasCalled 14289 * @param {string} callbackPath the path to the callback that was sent in the JSONP request 14290 * @returns {boolean} whether the callback has been called, as a result of the JSONP response 14291 * @description 14292 * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the 14293 * callback that was passed in the request. 14294 */ 14295 wasCalled: function(callbackPath) { 14296 return callbackMap[callbackPath].called; 14297 }, 14298 /** 14299 * @ngdoc method 14300 * @name $jsonpCallbacks#getResponse 14301 * @param {string} callbackPath the path to the callback that was sent in the JSONP request 14302 * @returns {*} the data received from the response via the registered callback 14303 * @description 14304 * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback 14305 * in the JSONP response. 14306 */ 14307 getResponse: function(callbackPath) { 14308 return callbackMap[callbackPath].data; 14309 }, 14310 /** 14311 * @ngdoc method 14312 * @name $jsonpCallbacks#removeCallback 14313 * @param {string} callbackPath the path to the callback that was sent in the JSONP request 14314 * @description 14315 * {@link $httpBackend} calls this method to remove the callback after the JSONP request has 14316 * completed or timed-out. 14317 */ 14318 removeCallback: function(callbackPath) { 14319 var callback = callbackMap[callbackPath]; 14320 delete callbacks[callback.id]; 14321 delete callbackMap[callbackPath]; 14322 } 14323 }; 14324 }; 14325}; 14326 14327/** 14328 * @ngdoc service 14329 * @name $locale 14330 * 14331 * @description 14332 * $locale service provides localization rules for various AngularJS components. As of right now the 14333 * only public api is: 14334 * 14335 * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) 14336 */ 14337 14338/* global stripHash: true */ 14339 14340var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/, 14341 DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; 14342var $locationMinErr = minErr('$location'); 14343 14344 14345/** 14346 * Encode path using encodeUriSegment, ignoring forward slashes 14347 * 14348 * @param {string} path Path to encode 14349 * @returns {string} 14350 */ 14351function encodePath(path) { 14352 var segments = path.split('/'), 14353 i = segments.length; 14354 14355 while (i--) { 14356 // decode forward slashes to prevent them from being double encoded 14357 segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/')); 14358 } 14359 14360 return segments.join('/'); 14361} 14362 14363function decodePath(path, html5Mode) { 14364 var segments = path.split('/'), 14365 i = segments.length; 14366 14367 while (i--) { 14368 segments[i] = decodeURIComponent(segments[i]); 14369 if (html5Mode) { 14370 // encode forward slashes to prevent them from being mistaken for path separators 14371 segments[i] = segments[i].replace(/\//g, '%2F'); 14372 } 14373 } 14374 14375 return segments.join('/'); 14376} 14377 14378function normalizePath(pathValue, searchValue, hashValue) { 14379 var search = toKeyValue(searchValue), 14380 hash = hashValue ? '#' + encodeUriSegment(hashValue) : '', 14381 path = encodePath(pathValue); 14382 14383 return path + (search ? '?' + search : '') + hash; 14384} 14385 14386function parseAbsoluteUrl(absoluteUrl, locationObj) { 14387 var parsedUrl = urlResolve(absoluteUrl); 14388 14389 locationObj.$$protocol = parsedUrl.protocol; 14390 locationObj.$$host = parsedUrl.hostname; 14391 locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; 14392} 14393 14394var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/; 14395function parseAppUrl(url, locationObj, html5Mode) { 14396 14397 if (DOUBLE_SLASH_REGEX.test(url)) { 14398 throw $locationMinErr('badpath', 'Invalid url "{0}".', url); 14399 } 14400 14401 var prefixed = (url.charAt(0) !== '/'); 14402 if (prefixed) { 14403 url = '/' + url; 14404 } 14405 var match = urlResolve(url); 14406 var path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname; 14407 locationObj.$$path = decodePath(path, html5Mode); 14408 locationObj.$$search = parseKeyValue(match.search); 14409 locationObj.$$hash = decodeURIComponent(match.hash); 14410 14411 // make sure path starts with '/'; 14412 if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') { 14413 locationObj.$$path = '/' + locationObj.$$path; 14414 } 14415} 14416 14417function startsWith(str, search) { 14418 return str.slice(0, search.length) === search; 14419} 14420 14421/** 14422 * 14423 * @param {string} base 14424 * @param {string} url 14425 * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with 14426 * the expected string. 14427 */ 14428function stripBaseUrl(base, url) { 14429 if (startsWith(url, base)) { 14430 return url.substr(base.length); 14431 } 14432} 14433 14434function stripHash(url) { 14435 var index = url.indexOf('#'); 14436 return index === -1 ? url : url.substr(0, index); 14437} 14438 14439function stripFile(url) { 14440 return url.substr(0, stripHash(url).lastIndexOf('/') + 1); 14441} 14442 14443/* return the server only (scheme://host:port) */ 14444function serverBase(url) { 14445 return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); 14446} 14447 14448 14449/** 14450 * LocationHtml5Url represents a URL 14451 * This object is exposed as $location service when HTML5 mode is enabled and supported 14452 * 14453 * @constructor 14454 * @param {string} appBase application base URL 14455 * @param {string} appBaseNoFile application base URL stripped of any filename 14456 * @param {string} basePrefix URL path prefix 14457 */ 14458function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) { 14459 this.$$html5 = true; 14460 basePrefix = basePrefix || ''; 14461 parseAbsoluteUrl(appBase, this); 14462 14463 14464 /** 14465 * Parse given HTML5 (regular) URL string into properties 14466 * @param {string} url HTML5 URL 14467 * @private 14468 */ 14469 this.$$parse = function(url) { 14470 var pathUrl = stripBaseUrl(appBaseNoFile, url); 14471 if (!isString(pathUrl)) { 14472 throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, 14473 appBaseNoFile); 14474 } 14475 14476 parseAppUrl(pathUrl, this, true); 14477 14478 if (!this.$$path) { 14479 this.$$path = '/'; 14480 } 14481 14482 this.$$compose(); 14483 }; 14484 14485 this.$$normalizeUrl = function(url) { 14486 return appBaseNoFile + url.substr(1); // first char is always '/' 14487 }; 14488 14489 this.$$parseLinkUrl = function(url, relHref) { 14490 if (relHref && relHref[0] === '#') { 14491 // special case for links to hash fragments: 14492 // keep the old url and only replace the hash fragment 14493 this.hash(relHref.slice(1)); 14494 return true; 14495 } 14496 var appUrl, prevAppUrl; 14497 var rewrittenUrl; 14498 14499 14500 if (isDefined(appUrl = stripBaseUrl(appBase, url))) { 14501 prevAppUrl = appUrl; 14502 if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) { 14503 rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl); 14504 } else { 14505 rewrittenUrl = appBase + prevAppUrl; 14506 } 14507 } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) { 14508 rewrittenUrl = appBaseNoFile + appUrl; 14509 } else if (appBaseNoFile === url + '/') { 14510 rewrittenUrl = appBaseNoFile; 14511 } 14512 if (rewrittenUrl) { 14513 this.$$parse(rewrittenUrl); 14514 } 14515 return !!rewrittenUrl; 14516 }; 14517} 14518 14519 14520/** 14521 * LocationHashbangUrl represents URL 14522 * This object is exposed as $location service when developer doesn't opt into html5 mode. 14523 * It also serves as the base class for html5 mode fallback on legacy browsers. 14524 * 14525 * @constructor 14526 * @param {string} appBase application base URL 14527 * @param {string} appBaseNoFile application base URL stripped of any filename 14528 * @param {string} hashPrefix hashbang prefix 14529 */ 14530function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) { 14531 14532 parseAbsoluteUrl(appBase, this); 14533 14534 14535 /** 14536 * Parse given hashbang URL into properties 14537 * @param {string} url Hashbang URL 14538 * @private 14539 */ 14540 this.$$parse = function(url) { 14541 var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url); 14542 var withoutHashUrl; 14543 14544 if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') { 14545 14546 // The rest of the URL starts with a hash so we have 14547 // got either a hashbang path or a plain hash fragment 14548 withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl); 14549 if (isUndefined(withoutHashUrl)) { 14550 // There was no hashbang prefix so we just have a hash fragment 14551 withoutHashUrl = withoutBaseUrl; 14552 } 14553 14554 } else { 14555 // There was no hashbang path nor hash fragment: 14556 // If we are in HTML5 mode we use what is left as the path; 14557 // Otherwise we ignore what is left 14558 if (this.$$html5) { 14559 withoutHashUrl = withoutBaseUrl; 14560 } else { 14561 withoutHashUrl = ''; 14562 if (isUndefined(withoutBaseUrl)) { 14563 appBase = url; 14564 /** @type {?} */ (this).replace(); 14565 } 14566 } 14567 } 14568 14569 parseAppUrl(withoutHashUrl, this, false); 14570 14571 this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); 14572 14573 this.$$compose(); 14574 14575 /* 14576 * In Windows, on an anchor node on documents loaded from 14577 * the filesystem, the browser will return a pathname 14578 * prefixed with the drive name ('/C:/path') when a 14579 * pathname without a drive is set: 14580 * * a.setAttribute('href', '/foo') 14581 * * a.pathname === '/C:/foo' //true 14582 * 14583 * Inside of AngularJS, we're always using pathnames that 14584 * do not include drive names for routing. 14585 */ 14586 function removeWindowsDriveName(path, url, base) { 14587 /* 14588 Matches paths for file protocol on windows, 14589 such as /C:/foo/bar, and captures only /foo/bar. 14590 */ 14591 var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; 14592 14593 var firstPathSegmentMatch; 14594 14595 //Get the relative path from the input URL. 14596 if (startsWith(url, base)) { 14597 url = url.replace(base, ''); 14598 } 14599 14600 // The input URL intentionally contains a first path segment that ends with a colon. 14601 if (windowsFilePathExp.exec(url)) { 14602 return path; 14603 } 14604 14605 firstPathSegmentMatch = windowsFilePathExp.exec(path); 14606 return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path; 14607 } 14608 }; 14609 14610 this.$$normalizeUrl = function(url) { 14611 return appBase + (url ? hashPrefix + url : ''); 14612 }; 14613 14614 this.$$parseLinkUrl = function(url, relHref) { 14615 if (stripHash(appBase) === stripHash(url)) { 14616 this.$$parse(url); 14617 return true; 14618 } 14619 return false; 14620 }; 14621} 14622 14623 14624/** 14625 * LocationHashbangUrl represents URL 14626 * This object is exposed as $location service when html5 history api is enabled but the browser 14627 * does not support it. 14628 * 14629 * @constructor 14630 * @param {string} appBase application base URL 14631 * @param {string} appBaseNoFile application base URL stripped of any filename 14632 * @param {string} hashPrefix hashbang prefix 14633 */ 14634function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) { 14635 this.$$html5 = true; 14636 LocationHashbangUrl.apply(this, arguments); 14637 14638 this.$$parseLinkUrl = function(url, relHref) { 14639 if (relHref && relHref[0] === '#') { 14640 // special case for links to hash fragments: 14641 // keep the old url and only replace the hash fragment 14642 this.hash(relHref.slice(1)); 14643 return true; 14644 } 14645 14646 var rewrittenUrl; 14647 var appUrl; 14648 14649 if (appBase === stripHash(url)) { 14650 rewrittenUrl = url; 14651 } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) { 14652 rewrittenUrl = appBase + hashPrefix + appUrl; 14653 } else if (appBaseNoFile === url + '/') { 14654 rewrittenUrl = appBaseNoFile; 14655 } 14656 if (rewrittenUrl) { 14657 this.$$parse(rewrittenUrl); 14658 } 14659 return !!rewrittenUrl; 14660 }; 14661 14662 this.$$normalizeUrl = function(url) { 14663 // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#' 14664 return appBase + hashPrefix + url; 14665 }; 14666} 14667 14668 14669var locationPrototype = { 14670 14671 /** 14672 * Ensure absolute URL is initialized. 14673 * @private 14674 */ 14675 $$absUrl:'', 14676 14677 /** 14678 * Are we in html5 mode? 14679 * @private 14680 */ 14681 $$html5: false, 14682 14683 /** 14684 * Has any change been replacing? 14685 * @private 14686 */ 14687 $$replace: false, 14688 14689 /** 14690 * Compose url and update `url` and `absUrl` property 14691 * @private 14692 */ 14693 $$compose: function() { 14694 this.$$url = normalizePath(this.$$path, this.$$search, this.$$hash); 14695 this.$$absUrl = this.$$normalizeUrl(this.$$url); 14696 this.$$urlUpdatedByLocation = true; 14697 }, 14698 14699 /** 14700 * @ngdoc method 14701 * @name $location#absUrl 14702 * 14703 * @description 14704 * This method is getter only. 14705 * 14706 * Return full URL representation with all segments encoded according to rules specified in 14707 * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). 14708 * 14709 * 14710 * ```js 14711 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14712 * var absUrl = $location.absUrl(); 14713 * // => "http://example.com/#/some/path?foo=bar&baz=xoxo" 14714 * ``` 14715 * 14716 * @return {string} full URL 14717 */ 14718 absUrl: locationGetter('$$absUrl'), 14719 14720 /** 14721 * @ngdoc method 14722 * @name $location#url 14723 * 14724 * @description 14725 * This method is getter / setter. 14726 * 14727 * Return URL (e.g. `/path?a=b#hash`) when called without any parameter. 14728 * 14729 * Change path, search and hash, when called with parameter and return `$location`. 14730 * 14731 * 14732 * ```js 14733 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14734 * var url = $location.url(); 14735 * // => "/some/path?foo=bar&baz=xoxo" 14736 * ``` 14737 * 14738 * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`) 14739 * @return {string} url 14740 */ 14741 url: function(url) { 14742 if (isUndefined(url)) { 14743 return this.$$url; 14744 } 14745 14746 var match = PATH_MATCH.exec(url); 14747 if (match[1] || url === '') this.path(decodeURIComponent(match[1])); 14748 if (match[2] || match[1] || url === '') this.search(match[3] || ''); 14749 this.hash(match[5] || ''); 14750 14751 return this; 14752 }, 14753 14754 /** 14755 * @ngdoc method 14756 * @name $location#protocol 14757 * 14758 * @description 14759 * This method is getter only. 14760 * 14761 * Return protocol of current URL. 14762 * 14763 * 14764 * ```js 14765 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14766 * var protocol = $location.protocol(); 14767 * // => "http" 14768 * ``` 14769 * 14770 * @return {string} protocol of current URL 14771 */ 14772 protocol: locationGetter('$$protocol'), 14773 14774 /** 14775 * @ngdoc method 14776 * @name $location#host 14777 * 14778 * @description 14779 * This method is getter only. 14780 * 14781 * Return host of current URL. 14782 * 14783 * Note: compared to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only. 14784 * 14785 * 14786 * ```js 14787 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14788 * var host = $location.host(); 14789 * // => "example.com" 14790 * 14791 * // given URL http://user:[email protected]:8080/#/some/path?foo=bar&baz=xoxo 14792 * host = $location.host(); 14793 * // => "example.com" 14794 * host = location.host; 14795 * // => "example.com:8080" 14796 * ``` 14797 * 14798 * @return {string} host of current URL. 14799 */ 14800 host: locationGetter('$$host'), 14801 14802 /** 14803 * @ngdoc method 14804 * @name $location#port 14805 * 14806 * @description 14807 * This method is getter only. 14808 * 14809 * Return port of current URL. 14810 * 14811 * 14812 * ```js 14813 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14814 * var port = $location.port(); 14815 * // => 80 14816 * ``` 14817 * 14818 * @return {Number} port 14819 */ 14820 port: locationGetter('$$port'), 14821 14822 /** 14823 * @ngdoc method 14824 * @name $location#path 14825 * 14826 * @description 14827 * This method is getter / setter. 14828 * 14829 * Return path of current URL when called without any parameter. 14830 * 14831 * Change path when called with parameter and return `$location`. 14832 * 14833 * Note: Path should always begin with forward slash (/), this method will add the forward slash 14834 * if it is missing. 14835 * 14836 * 14837 * ```js 14838 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14839 * var path = $location.path(); 14840 * // => "/some/path" 14841 * ``` 14842 * 14843 * @param {(string|number)=} path New path 14844 * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter 14845 */ 14846 path: locationGetterSetter('$$path', function(path) { 14847 path = path !== null ? path.toString() : ''; 14848 return path.charAt(0) === '/' ? path : '/' + path; 14849 }), 14850 14851 /** 14852 * @ngdoc method 14853 * @name $location#search 14854 * 14855 * @description 14856 * This method is getter / setter. 14857 * 14858 * Return search part (as object) of current URL when called without any parameter. 14859 * 14860 * Change search part when called with parameter and return `$location`. 14861 * 14862 * 14863 * ```js 14864 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo 14865 * var searchObject = $location.search(); 14866 * // => {foo: 'bar', baz: 'xoxo'} 14867 * 14868 * // set foo to 'yipee' 14869 * $location.search('foo', 'yipee'); 14870 * // $location.search() => {foo: 'yipee', baz: 'xoxo'} 14871 * ``` 14872 * 14873 * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or 14874 * hash object. 14875 * 14876 * When called with a single argument the method acts as a setter, setting the `search` component 14877 * of `$location` to the specified value. 14878 * 14879 * If the argument is a hash object containing an array of values, these values will be encoded 14880 * as duplicate search parameters in the URL. 14881 * 14882 * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue` 14883 * will override only a single search property. 14884 * 14885 * If `paramValue` is an array, it will override the property of the `search` component of 14886 * `$location` specified via the first argument. 14887 * 14888 * If `paramValue` is `null`, the property specified via the first argument will be deleted. 14889 * 14890 * If `paramValue` is `true`, the property specified via the first argument will be added with no 14891 * value nor trailing equal sign. 14892 * 14893 * @return {Object} If called with no arguments returns the parsed `search` object. If called with 14894 * one or more arguments returns `$location` object itself. 14895 */ 14896 search: function(search, paramValue) { 14897 switch (arguments.length) { 14898 case 0: 14899 return this.$$search; 14900 case 1: 14901 if (isString(search) || isNumber(search)) { 14902 search = search.toString(); 14903 this.$$search = parseKeyValue(search); 14904 } else if (isObject(search)) { 14905 search = copy(search, {}); 14906 // remove object undefined or null properties 14907 forEach(search, function(value, key) { 14908 if (value == null) delete search[key]; 14909 }); 14910 14911 this.$$search = search; 14912 } else { 14913 throw $locationMinErr('isrcharg', 14914 'The first argument of the `$location#search()` call must be a string or an object.'); 14915 } 14916 break; 14917 default: 14918 if (isUndefined(paramValue) || paramValue === null) { 14919 delete this.$$search[search]; 14920 } else { 14921 this.$$search[search] = paramValue; 14922 } 14923 } 14924 14925 this.$$compose(); 14926 return this; 14927 }, 14928 14929 /** 14930 * @ngdoc method 14931 * @name $location#hash 14932 * 14933 * @description 14934 * This method is getter / setter. 14935 * 14936 * Returns the hash fragment when called without any parameters. 14937 * 14938 * Changes the hash fragment when called with a parameter and returns `$location`. 14939 * 14940 * 14941 * ```js 14942 * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue 14943 * var hash = $location.hash(); 14944 * // => "hashValue" 14945 * ``` 14946 * 14947 * @param {(string|number)=} hash New hash fragment 14948 * @return {string} hash 14949 */ 14950 hash: locationGetterSetter('$$hash', function(hash) { 14951 return hash !== null ? hash.toString() : ''; 14952 }), 14953 14954 /** 14955 * @ngdoc method 14956 * @name $location#replace 14957 * 14958 * @description 14959 * If called, all changes to $location during the current `$digest` will replace the current history 14960 * record, instead of adding a new one. 14961 */ 14962 replace: function() { 14963 this.$$replace = true; 14964 return this; 14965 } 14966}; 14967 14968forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) { 14969 Location.prototype = Object.create(locationPrototype); 14970 14971 /** 14972 * @ngdoc method 14973 * @name $location#state 14974 * 14975 * @description 14976 * This method is getter / setter. 14977 * 14978 * Return the history state object when called without any parameter. 14979 * 14980 * Change the history state object when called with one parameter and return `$location`. 14981 * The state object is later passed to `pushState` or `replaceState`. 14982 * 14983 * NOTE: This method is supported only in HTML5 mode and only in browsers supporting 14984 * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support 14985 * older browsers (like IE9 or Android < 4.0), don't use this method. 14986 * 14987 * @param {object=} state State object for pushState or replaceState 14988 * @return {object} state 14989 */ 14990 Location.prototype.state = function(state) { 14991 if (!arguments.length) { 14992 return this.$$state; 14993 } 14994 14995 if (Location !== LocationHtml5Url || !this.$$html5) { 14996 throw $locationMinErr('nostate', 'History API state support is available only ' + 14997 'in HTML5 mode and only in browsers supporting HTML5 History API'); 14998 } 14999 // The user might modify `stateObject` after invoking `$location.state(stateObject)` 15000 // but we're changing the $$state reference to $browser.state() during the $digest 15001 // so the modification window is narrow. 15002 this.$$state = isUndefined(state) ? null : state; 15003 this.$$urlUpdatedByLocation = true; 15004 15005 return this; 15006 }; 15007}); 15008 15009 15010function locationGetter(property) { 15011 return /** @this */ function() { 15012 return this[property]; 15013 }; 15014} 15015 15016 15017function locationGetterSetter(property, preprocess) { 15018 return /** @this */ function(value) { 15019 if (isUndefined(value)) { 15020 return this[property]; 15021 } 15022 15023 this[property] = preprocess(value); 15024 this.$$compose(); 15025 15026 return this; 15027 }; 15028} 15029 15030 15031/** 15032 * @ngdoc service 15033 * @name $location 15034 * 15035 * @requires $rootElement 15036 * 15037 * @description 15038 * The $location service parses the URL in the browser address bar (based on the 15039 * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL 15040 * available to your application. Changes to the URL in the address bar are reflected into 15041 * $location service and changes to $location are reflected into the browser address bar. 15042 * 15043 * **The $location service:** 15044 * 15045 * - Exposes the current URL in the browser address bar, so you can 15046 * - Watch and observe the URL. 15047 * - Change the URL. 15048 * - Synchronizes the URL with the browser when the user 15049 * - Changes the address bar. 15050 * - Clicks the back or forward button (or clicks a History link). 15051 * - Clicks on a link. 15052 * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). 15053 * 15054 * For more information see {@link guide/$location Developer Guide: Using $location} 15055 */ 15056 15057/** 15058 * @ngdoc provider 15059 * @name $locationProvider 15060 * @this 15061 * 15062 * @description 15063 * Use the `$locationProvider` to configure how the application deep linking paths are stored. 15064 */ 15065function $LocationProvider() { 15066 var hashPrefix = '!', 15067 html5Mode = { 15068 enabled: false, 15069 requireBase: true, 15070 rewriteLinks: true 15071 }; 15072 15073 /** 15074 * @ngdoc method 15075 * @name $locationProvider#hashPrefix 15076 * @description 15077 * The default value for the prefix is `'!'`. 15078 * @param {string=} prefix Prefix for hash part (containing path and search) 15079 * @returns {*} current value if used as getter or itself (chaining) if used as setter 15080 */ 15081 this.hashPrefix = function(prefix) { 15082 if (isDefined(prefix)) { 15083 hashPrefix = prefix; 15084 return this; 15085 } else { 15086 return hashPrefix; 15087 } 15088 }; 15089 15090 /** 15091 * @ngdoc method 15092 * @name $locationProvider#html5Mode 15093 * @description 15094 * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value. 15095 * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported 15096 * properties: 15097 * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to 15098 * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not 15099 * support `pushState`. 15100 * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies 15101 * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are 15102 * true, and a base tag is not present, an error will be thrown when `$location` is injected. 15103 * See the {@link guide/$location $location guide for more information} 15104 * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled, 15105 * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will 15106 * only happen on links with an attribute that matches the given string. For example, if set 15107 * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links. 15108 * Note that [attribute name normalization](guide/directive#normalization) does not apply 15109 * here, so `'internalLink'` will **not** match `'internal-link'`. 15110 * 15111 * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter 15112 */ 15113 this.html5Mode = function(mode) { 15114 if (isBoolean(mode)) { 15115 html5Mode.enabled = mode; 15116 return this; 15117 } else if (isObject(mode)) { 15118 15119 if (isBoolean(mode.enabled)) { 15120 html5Mode.enabled = mode.enabled; 15121 } 15122 15123 if (isBoolean(mode.requireBase)) { 15124 html5Mode.requireBase = mode.requireBase; 15125 } 15126 15127 if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) { 15128 html5Mode.rewriteLinks = mode.rewriteLinks; 15129 } 15130 15131 return this; 15132 } else { 15133 return html5Mode; 15134 } 15135 }; 15136 15137 /** 15138 * @ngdoc event 15139 * @name $location#$locationChangeStart 15140 * @eventType broadcast on root scope 15141 * @description 15142 * Broadcasted before a URL will change. 15143 * 15144 * This change can be prevented by calling 15145 * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more 15146 * details about event object. Upon successful change 15147 * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired. 15148 * 15149 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when 15150 * the browser supports the HTML5 History API. 15151 * 15152 * @param {Object} angularEvent Synthetic event object. 15153 * @param {string} newUrl New URL 15154 * @param {string=} oldUrl URL that was before it was changed. 15155 * @param {string=} newState New history state object 15156 * @param {string=} oldState History state object that was before it was changed. 15157 */ 15158 15159 /** 15160 * @ngdoc event 15161 * @name $location#$locationChangeSuccess 15162 * @eventType broadcast on root scope 15163 * @description 15164 * Broadcasted after a URL was changed. 15165 * 15166 * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when 15167 * the browser supports the HTML5 History API. 15168 * 15169 * @param {Object} angularEvent Synthetic event object. 15170 * @param {string} newUrl New URL 15171 * @param {string=} oldUrl URL that was before it was changed. 15172 * @param {string=} newState New history state object 15173 * @param {string=} oldState History state object that was before it was changed. 15174 */ 15175 15176 this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window', 15177 function($rootScope, $browser, $sniffer, $rootElement, $window) { 15178 var $location, 15179 LocationMode, 15180 baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' 15181 initialUrl = $browser.url(), 15182 appBase; 15183 15184 if (html5Mode.enabled) { 15185 if (!baseHref && html5Mode.requireBase) { 15186 throw $locationMinErr('nobase', 15187 '$location in HTML5 mode requires a <base> tag to be present!'); 15188 } 15189 appBase = serverBase(initialUrl) + (baseHref || '/'); 15190 LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; 15191 } else { 15192 appBase = stripHash(initialUrl); 15193 LocationMode = LocationHashbangUrl; 15194 } 15195 var appBaseNoFile = stripFile(appBase); 15196 15197 $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix); 15198 $location.$$parseLinkUrl(initialUrl, initialUrl); 15199 15200 $location.$$state = $browser.state(); 15201 15202 var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; 15203 15204 // Determine if two URLs are equal despite potentially having different encoding/normalizing 15205 // such as $location.absUrl() vs $browser.url() 15206 // See https://github.com/angular/angular.js/issues/16592 15207 function urlsEqual(a, b) { 15208 return a === b || urlResolve(a).href === urlResolve(b).href; 15209 } 15210 15211 function setBrowserUrlWithFallback(url, replace, state) { 15212 var oldUrl = $location.url(); 15213 var oldState = $location.$$state; 15214 try { 15215 $browser.url(url, replace, state); 15216 15217 // Make sure $location.state() returns referentially identical (not just deeply equal) 15218 // state object; this makes possible quick checking if the state changed in the digest 15219 // loop. Checking deep equality would be too expensive. 15220 $location.$$state = $browser.state(); 15221 } catch (e) { 15222 // Restore old values if pushState fails 15223 $location.url(oldUrl); 15224 $location.$$state = oldState; 15225 15226 throw e; 15227 } 15228 } 15229 15230 $rootElement.on('click', function(event) { 15231 var rewriteLinks = html5Mode.rewriteLinks; 15232 // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) 15233 // currently we open nice url link and redirect then 15234 15235 if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return; 15236 15237 var elm = jqLite(event.target); 15238 15239 // traverse the DOM up to find first A tag 15240 while (nodeName_(elm[0]) !== 'a') { 15241 // ignore rewriting if no A tag (reached root element, or no parent - removed from document) 15242 if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; 15243 } 15244 15245 if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return; 15246 15247 var absHref = elm.prop('href'); 15248 // get the actual href attribute - see 15249 // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx 15250 var relHref = elm.attr('href') || elm.attr('xlink:href'); 15251 15252 if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { 15253 // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during 15254 // an animation. 15255 absHref = urlResolve(absHref.animVal).href; 15256 } 15257 15258 // Ignore when url is started with javascript: or mailto: 15259 if (IGNORE_URI_REGEXP.test(absHref)) return; 15260 15261 if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { 15262 if ($location.$$parseLinkUrl(absHref, relHref)) { 15263 // We do a preventDefault for all urls that are part of the AngularJS application, 15264 // in html5mode and also without, so that we are able to abort navigation without 15265 // getting double entries in the location history. 15266 event.preventDefault(); 15267 // update location manually 15268 if ($location.absUrl() !== $browser.url()) { 15269 $rootScope.$apply(); 15270 } 15271 } 15272 } 15273 }); 15274 15275 15276 // rewrite hashbang url <> html5 url 15277 if ($location.absUrl() !== initialUrl) { 15278 $browser.url($location.absUrl(), true); 15279 } 15280 15281 var initializing = true; 15282 15283 // update $location when $browser url changes 15284 $browser.onUrlChange(function(newUrl, newState) { 15285 15286 if (!startsWith(newUrl, appBaseNoFile)) { 15287 // If we are navigating outside of the app then force a reload 15288 $window.location.href = newUrl; 15289 return; 15290 } 15291 15292 $rootScope.$evalAsync(function() { 15293 var oldUrl = $location.absUrl(); 15294 var oldState = $location.$$state; 15295 var defaultPrevented; 15296 $location.$$parse(newUrl); 15297 $location.$$state = newState; 15298 15299 defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, 15300 newState, oldState).defaultPrevented; 15301 15302 // if the location was changed by a `$locationChangeStart` handler then stop 15303 // processing this location change 15304 if ($location.absUrl() !== newUrl) return; 15305 15306 if (defaultPrevented) { 15307 $location.$$parse(oldUrl); 15308 $location.$$state = oldState; 15309 setBrowserUrlWithFallback(oldUrl, false, oldState); 15310 } else { 15311 initializing = false; 15312 afterLocationChange(oldUrl, oldState); 15313 } 15314 }); 15315 if (!$rootScope.$$phase) $rootScope.$digest(); 15316 }); 15317 15318 // update browser 15319 $rootScope.$watch(function $locationWatch() { 15320 if (initializing || $location.$$urlUpdatedByLocation) { 15321 $location.$$urlUpdatedByLocation = false; 15322 15323 var oldUrl = $browser.url(); 15324 var newUrl = $location.absUrl(); 15325 var oldState = $browser.state(); 15326 var currentReplace = $location.$$replace; 15327 var urlOrStateChanged = !urlsEqual(oldUrl, newUrl) || 15328 ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); 15329 15330 if (initializing || urlOrStateChanged) { 15331 initializing = false; 15332 15333 $rootScope.$evalAsync(function() { 15334 var newUrl = $location.absUrl(); 15335 var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, 15336 $location.$$state, oldState).defaultPrevented; 15337 15338 // if the location was changed by a `$locationChangeStart` handler then stop 15339 // processing this location change 15340 if ($location.absUrl() !== newUrl) return; 15341 15342 if (defaultPrevented) { 15343 $location.$$parse(oldUrl); 15344 $location.$$state = oldState; 15345 } else { 15346 if (urlOrStateChanged) { 15347 setBrowserUrlWithFallback(newUrl, currentReplace, 15348 oldState === $location.$$state ? null : $location.$$state); 15349 } 15350 afterLocationChange(oldUrl, oldState); 15351 } 15352 }); 15353 } 15354 } 15355 15356 $location.$$replace = false; 15357 15358 // we don't need to return anything because $evalAsync will make the digest loop dirty when 15359 // there is a change 15360 }); 15361 15362 return $location; 15363 15364 function afterLocationChange(oldUrl, oldState) { 15365 $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl, 15366 $location.$$state, oldState); 15367 } 15368}]; 15369} 15370 15371/** 15372 * @ngdoc service 15373 * @name $log 15374 * @requires $window 15375 * 15376 * @description 15377 * Simple service for logging. Default implementation safely writes the message 15378 * into the browser's console (if present). 15379 * 15380 * The main purpose of this service is to simplify debugging and troubleshooting. 15381 * 15382 * To reveal the location of the calls to `$log` in the JavaScript console, 15383 * you can "blackbox" the AngularJS source in your browser: 15384 * 15385 * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source). 15386 * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing). 15387 * 15388 * Note: Not all browsers support blackboxing. 15389 * 15390 * The default is to log `debug` messages. You can use 15391 * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. 15392 * 15393 * @example 15394 <example module="logExample" name="log-service"> 15395 <file name="script.js"> 15396 angular.module('logExample', []) 15397 .controller('LogController', ['$scope', '$log', function($scope, $log) { 15398 $scope.$log = $log; 15399 $scope.message = 'Hello World!'; 15400 }]); 15401 </file> 15402 <file name="index.html"> 15403 <div ng-controller="LogController"> 15404 <p>Reload this page with open console, enter text and hit the log button...</p> 15405 <label>Message: 15406 <input type="text" ng-model="message" /></label> 15407 <button ng-click="$log.log(message)">log</button> 15408 <button ng-click="$log.warn(message)">warn</button> 15409 <button ng-click="$log.info(message)">info</button> 15410 <button ng-click="$log.error(message)">error</button> 15411 <button ng-click="$log.debug(message)">debug</button> 15412 </div> 15413 </file> 15414 </example> 15415 */ 15416 15417/** 15418 * @ngdoc provider 15419 * @name $logProvider 15420 * @this 15421 * 15422 * @description 15423 * Use the `$logProvider` to configure how the application logs messages 15424 */ 15425function $LogProvider() { 15426 var debug = true, 15427 self = this; 15428 15429 /** 15430 * @ngdoc method 15431 * @name $logProvider#debugEnabled 15432 * @description 15433 * @param {boolean=} flag enable or disable debug level messages 15434 * @returns {*} current value if used as getter or itself (chaining) if used as setter 15435 */ 15436 this.debugEnabled = function(flag) { 15437 if (isDefined(flag)) { 15438 debug = flag; 15439 return this; 15440 } else { 15441 return debug; 15442 } 15443 }; 15444 15445 this.$get = ['$window', function($window) { 15446 // Support: IE 9-11, Edge 12-14+ 15447 // IE/Edge display errors in such a way that it requires the user to click in 4 places 15448 // to see the stack trace. There is no way to feature-detect it so there's a chance 15449 // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't 15450 // break apps. Other browsers display errors in a sensible way and some of them map stack 15451 // traces along source maps if available so it makes sense to let browsers display it 15452 // as they want. 15453 var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent); 15454 15455 return { 15456 /** 15457 * @ngdoc method 15458 * @name $log#log 15459 * 15460 * @description 15461 * Write a log message 15462 */ 15463 log: consoleLog('log'), 15464 15465 /** 15466 * @ngdoc method 15467 * @name $log#info 15468 * 15469 * @description 15470 * Write an information message 15471 */ 15472 info: consoleLog('info'), 15473 15474 /** 15475 * @ngdoc method 15476 * @name $log#warn 15477 * 15478 * @description 15479 * Write a warning message 15480 */ 15481 warn: consoleLog('warn'), 15482 15483 /** 15484 * @ngdoc method 15485 * @name $log#error 15486 * 15487 * @description 15488 * Write an error message 15489 */ 15490 error: consoleLog('error'), 15491 15492 /** 15493 * @ngdoc method 15494 * @name $log#debug 15495 * 15496 * @description 15497 * Write a debug message 15498 */ 15499 debug: (function() { 15500 var fn = consoleLog('debug'); 15501 15502 return function() { 15503 if (debug) { 15504 fn.apply(self, arguments); 15505 } 15506 }; 15507 })() 15508 }; 15509 15510 function formatError(arg) { 15511 if (isError(arg)) { 15512 if (arg.stack && formatStackTrace) { 15513 arg = (arg.message && arg.stack.indexOf(arg.message) === -1) 15514 ? 'Error: ' + arg.message + '\n' + arg.stack 15515 : arg.stack; 15516 } else if (arg.sourceURL) { 15517 arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; 15518 } 15519 } 15520 return arg; 15521 } 15522 15523 function consoleLog(type) { 15524 var console = $window.console || {}, 15525 logFn = console[type] || console.log || noop; 15526 15527 return function() { 15528 var args = []; 15529 forEach(arguments, function(arg) { 15530 args.push(formatError(arg)); 15531 }); 15532 // Support: IE 9 only 15533 // console methods don't inherit from Function.prototype in IE 9 so we can't 15534 // call `logFn.apply(console, args)` directly. 15535 return Function.prototype.apply.call(logFn, console, args); 15536 }; 15537 } 15538 }]; 15539} 15540 15541/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 15542 * Any commits to this file should be reviewed with security in mind. * 15543 * Changes to this file can potentially create security vulnerabilities. * 15544 * An approval from 2 Core members with history of modifying * 15545 * this file is required. * 15546 * * 15547 * Does the change somehow allow for arbitrary javascript to be executed? * 15548 * Or allows for someone to change the prototype of built-in objects? * 15549 * Or gives undesired access to variables likes document or window? * 15550 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 15551 15552var $parseMinErr = minErr('$parse'); 15553 15554var objectValueOf = {}.constructor.prototype.valueOf; 15555 15556// Sandboxing AngularJS Expressions 15557// ------------------------------ 15558// AngularJS expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by 15559// various means such as obtaining a reference to native JS functions like the Function constructor. 15560// 15561// As an example, consider the following AngularJS expression: 15562// 15563// {}.toString.constructor('alert("evil JS code")') 15564// 15565// It is important to realize that if you create an expression from a string that contains user provided 15566// content then it is possible that your application contains a security vulnerability to an XSS style attack. 15567// 15568// See https://docs.angularjs.org/guide/security 15569 15570 15571function getStringValue(name) { 15572 // Property names must be strings. This means that non-string objects cannot be used 15573 // as keys in an object. Any non-string object, including a number, is typecasted 15574 // into a string via the toString method. 15575 // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names 15576 // 15577 // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it 15578 // to a string. It's not always possible. If `name` is an object and its `toString` method is 15579 // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown: 15580 // 15581 // TypeError: Cannot convert object to primitive value 15582 // 15583 // For performance reasons, we don't catch this error here and allow it to propagate up the call 15584 // stack. Note that you'll get the same error in JavaScript if you try to access a property using 15585 // such a 'broken' object as a key. 15586 return name + ''; 15587} 15588 15589 15590var OPERATORS = createMap(); 15591forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; }); 15592var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'}; 15593 15594 15595///////////////////////////////////////// 15596 15597 15598/** 15599 * @constructor 15600 */ 15601var Lexer = function Lexer(options) { 15602 this.options = options; 15603}; 15604 15605Lexer.prototype = { 15606 constructor: Lexer, 15607 15608 lex: function(text) { 15609 this.text = text; 15610 this.index = 0; 15611 this.tokens = []; 15612 15613 while (this.index < this.text.length) { 15614 var ch = this.text.charAt(this.index); 15615 if (ch === '"' || ch === '\'') { 15616 this.readString(ch); 15617 } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) { 15618 this.readNumber(); 15619 } else if (this.isIdentifierStart(this.peekMultichar())) { 15620 this.readIdent(); 15621 } else if (this.is(ch, '(){}[].,;:?')) { 15622 this.tokens.push({index: this.index, text: ch}); 15623 this.index++; 15624 } else if (this.isWhitespace(ch)) { 15625 this.index++; 15626 } else { 15627 var ch2 = ch + this.peek(); 15628 var ch3 = ch2 + this.peek(2); 15629 var op1 = OPERATORS[ch]; 15630 var op2 = OPERATORS[ch2]; 15631 var op3 = OPERATORS[ch3]; 15632 if (op1 || op2 || op3) { 15633 var token = op3 ? ch3 : (op2 ? ch2 : ch); 15634 this.tokens.push({index: this.index, text: token, operator: true}); 15635 this.index += token.length; 15636 } else { 15637 this.throwError('Unexpected next character ', this.index, this.index + 1); 15638 } 15639 } 15640 } 15641 return this.tokens; 15642 }, 15643 15644 is: function(ch, chars) { 15645 return chars.indexOf(ch) !== -1; 15646 }, 15647 15648 peek: function(i) { 15649 var num = i || 1; 15650 return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false; 15651 }, 15652 15653 isNumber: function(ch) { 15654 return ('0' <= ch && ch <= '9') && typeof ch === 'string'; 15655 }, 15656 15657 isWhitespace: function(ch) { 15658 // IE treats non-breaking space as \u00A0 15659 return (ch === ' ' || ch === '\r' || ch === '\t' || 15660 ch === '\n' || ch === '\v' || ch === '\u00A0'); 15661 }, 15662 15663 isIdentifierStart: function(ch) { 15664 return this.options.isIdentifierStart ? 15665 this.options.isIdentifierStart(ch, this.codePointAt(ch)) : 15666 this.isValidIdentifierStart(ch); 15667 }, 15668 15669 isValidIdentifierStart: function(ch) { 15670 return ('a' <= ch && ch <= 'z' || 15671 'A' <= ch && ch <= 'Z' || 15672 '_' === ch || ch === '$'); 15673 }, 15674 15675 isIdentifierContinue: function(ch) { 15676 return this.options.isIdentifierContinue ? 15677 this.options.isIdentifierContinue(ch, this.codePointAt(ch)) : 15678 this.isValidIdentifierContinue(ch); 15679 }, 15680 15681 isValidIdentifierContinue: function(ch, cp) { 15682 return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch); 15683 }, 15684 15685 codePointAt: function(ch) { 15686 if (ch.length === 1) return ch.charCodeAt(0); 15687 // eslint-disable-next-line no-bitwise 15688 return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00; 15689 }, 15690 15691 peekMultichar: function() { 15692 var ch = this.text.charAt(this.index); 15693 var peek = this.peek(); 15694 if (!peek) { 15695 return ch; 15696 } 15697 var cp1 = ch.charCodeAt(0); 15698 var cp2 = peek.charCodeAt(0); 15699 if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) { 15700 return ch + peek; 15701 } 15702 return ch; 15703 }, 15704 15705 isExpOperator: function(ch) { 15706 return (ch === '-' || ch === '+' || this.isNumber(ch)); 15707 }, 15708 15709 throwError: function(error, start, end) { 15710 end = end || this.index; 15711 var colStr = (isDefined(start) 15712 ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' 15713 : ' ' + end); 15714 throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', 15715 error, colStr, this.text); 15716 }, 15717 15718 readNumber: function() { 15719 var number = ''; 15720 var start = this.index; 15721 while (this.index < this.text.length) { 15722 var ch = lowercase(this.text.charAt(this.index)); 15723 if (ch === '.' || this.isNumber(ch)) { 15724 number += ch; 15725 } else { 15726 var peekCh = this.peek(); 15727 if (ch === 'e' && this.isExpOperator(peekCh)) { 15728 number += ch; 15729 } else if (this.isExpOperator(ch) && 15730 peekCh && this.isNumber(peekCh) && 15731 number.charAt(number.length - 1) === 'e') { 15732 number += ch; 15733 } else if (this.isExpOperator(ch) && 15734 (!peekCh || !this.isNumber(peekCh)) && 15735 number.charAt(number.length - 1) === 'e') { 15736 this.throwError('Invalid exponent'); 15737 } else { 15738 break; 15739 } 15740 } 15741 this.index++; 15742 } 15743 this.tokens.push({ 15744 index: start, 15745 text: number, 15746 constant: true, 15747 value: Number(number) 15748 }); 15749 }, 15750 15751 readIdent: function() { 15752 var start = this.index; 15753 this.index += this.peekMultichar().length; 15754 while (this.index < this.text.length) { 15755 var ch = this.peekMultichar(); 15756 if (!this.isIdentifierContinue(ch)) { 15757 break; 15758 } 15759 this.index += ch.length; 15760 } 15761 this.tokens.push({ 15762 index: start, 15763 text: this.text.slice(start, this.index), 15764 identifier: true 15765 }); 15766 }, 15767 15768 readString: function(quote) { 15769 var start = this.index; 15770 this.index++; 15771 var string = ''; 15772 var rawString = quote; 15773 var escape = false; 15774 while (this.index < this.text.length) { 15775 var ch = this.text.charAt(this.index); 15776 rawString += ch; 15777 if (escape) { 15778 if (ch === 'u') { 15779 var hex = this.text.substring(this.index + 1, this.index + 5); 15780 if (!hex.match(/[\da-f]{4}/i)) { 15781 this.throwError('Invalid unicode escape [\\u' + hex + ']'); 15782 } 15783 this.index += 4; 15784 string += String.fromCharCode(parseInt(hex, 16)); 15785 } else { 15786 var rep = ESCAPE[ch]; 15787 string = string + (rep || ch); 15788 } 15789 escape = false; 15790 } else if (ch === '\\') { 15791 escape = true; 15792 } else if (ch === quote) { 15793 this.index++; 15794 this.tokens.push({ 15795 index: start, 15796 text: rawString, 15797 constant: true, 15798 value: string 15799 }); 15800 return; 15801 } else { 15802 string += ch; 15803 } 15804 this.index++; 15805 } 15806 this.throwError('Unterminated quote', start); 15807 } 15808}; 15809 15810var AST = function AST(lexer, options) { 15811 this.lexer = lexer; 15812 this.options = options; 15813}; 15814 15815AST.Program = 'Program'; 15816AST.ExpressionStatement = 'ExpressionStatement'; 15817AST.AssignmentExpression = 'AssignmentExpression'; 15818AST.ConditionalExpression = 'ConditionalExpression'; 15819AST.LogicalExpression = 'LogicalExpression'; 15820AST.BinaryExpression = 'BinaryExpression'; 15821AST.UnaryExpression = 'UnaryExpression'; 15822AST.CallExpression = 'CallExpression'; 15823AST.MemberExpression = 'MemberExpression'; 15824AST.Identifier = 'Identifier'; 15825AST.Literal = 'Literal'; 15826AST.ArrayExpression = 'ArrayExpression'; 15827AST.Property = 'Property'; 15828AST.ObjectExpression = 'ObjectExpression'; 15829AST.ThisExpression = 'ThisExpression'; 15830AST.LocalsExpression = 'LocalsExpression'; 15831 15832// Internal use only 15833AST.NGValueParameter = 'NGValueParameter'; 15834 15835AST.prototype = { 15836 ast: function(text) { 15837 this.text = text; 15838 this.tokens = this.lexer.lex(text); 15839 15840 var value = this.program(); 15841 15842 if (this.tokens.length !== 0) { 15843 this.throwError('is an unexpected token', this.tokens[0]); 15844 } 15845 15846 return value; 15847 }, 15848 15849 program: function() { 15850 var body = []; 15851 while (true) { 15852 if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) 15853 body.push(this.expressionStatement()); 15854 if (!this.expect(';')) { 15855 return { type: AST.Program, body: body}; 15856 } 15857 } 15858 }, 15859 15860 expressionStatement: function() { 15861 return { type: AST.ExpressionStatement, expression: this.filterChain() }; 15862 }, 15863 15864 filterChain: function() { 15865 var left = this.expression(); 15866 while (this.expect('|')) { 15867 left = this.filter(left); 15868 } 15869 return left; 15870 }, 15871 15872 expression: function() { 15873 return this.assignment(); 15874 }, 15875 15876 assignment: function() { 15877 var result = this.ternary(); 15878 if (this.expect('=')) { 15879 if (!isAssignable(result)) { 15880 throw $parseMinErr('lval', 'Trying to assign a value to a non l-value'); 15881 } 15882 15883 result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='}; 15884 } 15885 return result; 15886 }, 15887 15888 ternary: function() { 15889 var test = this.logicalOR(); 15890 var alternate; 15891 var consequent; 15892 if (this.expect('?')) { 15893 alternate = this.expression(); 15894 if (this.consume(':')) { 15895 consequent = this.expression(); 15896 return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent}; 15897 } 15898 } 15899 return test; 15900 }, 15901 15902 logicalOR: function() { 15903 var left = this.logicalAND(); 15904 while (this.expect('||')) { 15905 left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() }; 15906 } 15907 return left; 15908 }, 15909 15910 logicalAND: function() { 15911 var left = this.equality(); 15912 while (this.expect('&&')) { 15913 left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()}; 15914 } 15915 return left; 15916 }, 15917 15918 equality: function() { 15919 var left = this.relational(); 15920 var token; 15921 while ((token = this.expect('==','!=','===','!=='))) { 15922 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() }; 15923 } 15924 return left; 15925 }, 15926 15927 relational: function() { 15928 var left = this.additive(); 15929 var token; 15930 while ((token = this.expect('<', '>', '<=', '>='))) { 15931 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() }; 15932 } 15933 return left; 15934 }, 15935 15936 additive: function() { 15937 var left = this.multiplicative(); 15938 var token; 15939 while ((token = this.expect('+','-'))) { 15940 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() }; 15941 } 15942 return left; 15943 }, 15944 15945 multiplicative: function() { 15946 var left = this.unary(); 15947 var token; 15948 while ((token = this.expect('*','/','%'))) { 15949 left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() }; 15950 } 15951 return left; 15952 }, 15953 15954 unary: function() { 15955 var token; 15956 if ((token = this.expect('+', '-', '!'))) { 15957 return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() }; 15958 } else { 15959 return this.primary(); 15960 } 15961 }, 15962 15963 primary: function() { 15964 var primary; 15965 if (this.expect('(')) { 15966 primary = this.filterChain(); 15967 this.consume(')'); 15968 } else if (this.expect('[')) { 15969 primary = this.arrayDeclaration(); 15970 } else if (this.expect('{')) { 15971 primary = this.object(); 15972 } else if (this.selfReferential.hasOwnProperty(this.peek().text)) { 15973 primary = copy(this.selfReferential[this.consume().text]); 15974 } else if (this.options.literals.hasOwnProperty(this.peek().text)) { 15975 primary = { type: AST.Literal, value: this.options.literals[this.consume().text]}; 15976 } else if (this.peek().identifier) { 15977 primary = this.identifier(); 15978 } else if (this.peek().constant) { 15979 primary = this.constant(); 15980 } else { 15981 this.throwError('not a primary expression', this.peek()); 15982 } 15983 15984 var next; 15985 while ((next = this.expect('(', '[', '.'))) { 15986 if (next.text === '(') { 15987 primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() }; 15988 this.consume(')'); 15989 } else if (next.text === '[') { 15990 primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true }; 15991 this.consume(']'); 15992 } else if (next.text === '.') { 15993 primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false }; 15994 } else { 15995 this.throwError('IMPOSSIBLE'); 15996 } 15997 } 15998 return primary; 15999 }, 16000 16001 filter: function(baseExpression) { 16002 var args = [baseExpression]; 16003 var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true}; 16004 16005 while (this.expect(':')) { 16006 args.push(this.expression()); 16007 } 16008 16009 return result; 16010 }, 16011 16012 parseArguments: function() { 16013 var args = []; 16014 if (this.peekToken().text !== ')') { 16015 do { 16016 args.push(this.filterChain()); 16017 } while (this.expect(',')); 16018 } 16019 return args; 16020 }, 16021 16022 identifier: function() { 16023 var token = this.consume(); 16024 if (!token.identifier) { 16025 this.throwError('is not a valid identifier', token); 16026 } 16027 return { type: AST.Identifier, name: token.text }; 16028 }, 16029 16030 constant: function() { 16031 // TODO check that it is a constant 16032 return { type: AST.Literal, value: this.consume().value }; 16033 }, 16034 16035 arrayDeclaration: function() { 16036 var elements = []; 16037 if (this.peekToken().text !== ']') { 16038 do { 16039 if (this.peek(']')) { 16040 // Support trailing commas per ES5.1. 16041 break; 16042 } 16043 elements.push(this.expression()); 16044 } while (this.expect(',')); 16045 } 16046 this.consume(']'); 16047 16048 return { type: AST.ArrayExpression, elements: elements }; 16049 }, 16050 16051 object: function() { 16052 var properties = [], property; 16053 if (this.peekToken().text !== '}') { 16054 do { 16055 if (this.peek('}')) { 16056 // Support trailing commas per ES5.1. 16057 break; 16058 } 16059 property = {type: AST.Property, kind: 'init'}; 16060 if (this.peek().constant) { 16061 property.key = this.constant(); 16062 property.computed = false; 16063 this.consume(':'); 16064 property.value = this.expression(); 16065 } else if (this.peek().identifier) { 16066 property.key = this.identifier(); 16067 property.computed = false; 16068 if (this.peek(':')) { 16069 this.consume(':'); 16070 property.value = this.expression(); 16071 } else { 16072 property.value = property.key; 16073 } 16074 } else if (this.peek('[')) { 16075 this.consume('['); 16076 property.key = this.expression(); 16077 this.consume(']'); 16078 property.computed = true; 16079 this.consume(':'); 16080 property.value = this.expression(); 16081 } else { 16082 this.throwError('invalid key', this.peek()); 16083 } 16084 properties.push(property); 16085 } while (this.expect(',')); 16086 } 16087 this.consume('}'); 16088 16089 return {type: AST.ObjectExpression, properties: properties }; 16090 }, 16091 16092 throwError: function(msg, token) { 16093 throw $parseMinErr('syntax', 16094 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', 16095 token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); 16096 }, 16097 16098 consume: function(e1) { 16099 if (this.tokens.length === 0) { 16100 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); 16101 } 16102 16103 var token = this.expect(e1); 16104 if (!token) { 16105 this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); 16106 } 16107 return token; 16108 }, 16109 16110 peekToken: function() { 16111 if (this.tokens.length === 0) { 16112 throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); 16113 } 16114 return this.tokens[0]; 16115 }, 16116 16117 peek: function(e1, e2, e3, e4) { 16118 return this.peekAhead(0, e1, e2, e3, e4); 16119 }, 16120 16121 peekAhead: function(i, e1, e2, e3, e4) { 16122 if (this.tokens.length > i) { 16123 var token = this.tokens[i]; 16124 var t = token.text; 16125 if (t === e1 || t === e2 || t === e3 || t === e4 || 16126 (!e1 && !e2 && !e3 && !e4)) { 16127 return token; 16128 } 16129 } 16130 return false; 16131 }, 16132 16133 expect: function(e1, e2, e3, e4) { 16134 var token = this.peek(e1, e2, e3, e4); 16135 if (token) { 16136 this.tokens.shift(); 16137 return token; 16138 } 16139 return false; 16140 }, 16141 16142 selfReferential: { 16143 'this': {type: AST.ThisExpression }, 16144 '$locals': {type: AST.LocalsExpression } 16145 } 16146}; 16147 16148function ifDefined(v, d) { 16149 return typeof v !== 'undefined' ? v : d; 16150} 16151 16152function plusFn(l, r) { 16153 if (typeof l === 'undefined') return r; 16154 if (typeof r === 'undefined') return l; 16155 return l + r; 16156} 16157 16158function isStateless($filter, filterName) { 16159 var fn = $filter(filterName); 16160 return !fn.$stateful; 16161} 16162 16163var PURITY_ABSOLUTE = 1; 16164var PURITY_RELATIVE = 2; 16165 16166// Detect nodes which could depend on non-shallow state of objects 16167function isPure(node, parentIsPure) { 16168 switch (node.type) { 16169 // Computed members might invoke a stateful toString() 16170 case AST.MemberExpression: 16171 if (node.computed) { 16172 return false; 16173 } 16174 break; 16175 16176 // Unary always convert to primative 16177 case AST.UnaryExpression: 16178 return PURITY_ABSOLUTE; 16179 16180 // The binary + operator can invoke a stateful toString(). 16181 case AST.BinaryExpression: 16182 return node.operator !== '+' ? PURITY_ABSOLUTE : false; 16183 16184 // Functions / filters probably read state from within objects 16185 case AST.CallExpression: 16186 return false; 16187 } 16188 16189 return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure; 16190} 16191 16192function findConstantAndWatchExpressions(ast, $filter, parentIsPure) { 16193 var allConstants; 16194 var argsToWatch; 16195 var isStatelessFilter; 16196 16197 var astIsPure = ast.isPure = isPure(ast, parentIsPure); 16198 16199 switch (ast.type) { 16200 case AST.Program: 16201 allConstants = true; 16202 forEach(ast.body, function(expr) { 16203 findConstantAndWatchExpressions(expr.expression, $filter, astIsPure); 16204 allConstants = allConstants && expr.expression.constant; 16205 }); 16206 ast.constant = allConstants; 16207 break; 16208 case AST.Literal: 16209 ast.constant = true; 16210 ast.toWatch = []; 16211 break; 16212 case AST.UnaryExpression: 16213 findConstantAndWatchExpressions(ast.argument, $filter, astIsPure); 16214 ast.constant = ast.argument.constant; 16215 ast.toWatch = ast.argument.toWatch; 16216 break; 16217 case AST.BinaryExpression: 16218 findConstantAndWatchExpressions(ast.left, $filter, astIsPure); 16219 findConstantAndWatchExpressions(ast.right, $filter, astIsPure); 16220 ast.constant = ast.left.constant && ast.right.constant; 16221 ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch); 16222 break; 16223 case AST.LogicalExpression: 16224 findConstantAndWatchExpressions(ast.left, $filter, astIsPure); 16225 findConstantAndWatchExpressions(ast.right, $filter, astIsPure); 16226 ast.constant = ast.left.constant && ast.right.constant; 16227 ast.toWatch = ast.constant ? [] : [ast]; 16228 break; 16229 case AST.ConditionalExpression: 16230 findConstantAndWatchExpressions(ast.test, $filter, astIsPure); 16231 findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure); 16232 findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure); 16233 ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant; 16234 ast.toWatch = ast.constant ? [] : [ast]; 16235 break; 16236 case AST.Identifier: 16237 ast.constant = false; 16238 ast.toWatch = [ast]; 16239 break; 16240 case AST.MemberExpression: 16241 findConstantAndWatchExpressions(ast.object, $filter, astIsPure); 16242 if (ast.computed) { 16243 findConstantAndWatchExpressions(ast.property, $filter, astIsPure); 16244 } 16245 ast.constant = ast.object.constant && (!ast.computed || ast.property.constant); 16246 ast.toWatch = ast.constant ? [] : [ast]; 16247 break; 16248 case AST.CallExpression: 16249 isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false; 16250 allConstants = isStatelessFilter; 16251 argsToWatch = []; 16252 forEach(ast.arguments, function(expr) { 16253 findConstantAndWatchExpressions(expr, $filter, astIsPure); 16254 allConstants = allConstants && expr.constant; 16255 argsToWatch.push.apply(argsToWatch, expr.toWatch); 16256 }); 16257 ast.constant = allConstants; 16258 ast.toWatch = isStatelessFilter ? argsToWatch : [ast]; 16259 break; 16260 case AST.AssignmentExpression: 16261 findConstantAndWatchExpressions(ast.left, $filter, astIsPure); 16262 findConstantAndWatchExpressions(ast.right, $filter, astIsPure); 16263 ast.constant = ast.left.constant && ast.right.constant; 16264 ast.toWatch = [ast]; 16265 break; 16266 case AST.ArrayExpression: 16267 allConstants = true; 16268 argsToWatch = []; 16269 forEach(ast.elements, function(expr) { 16270 findConstantAndWatchExpressions(expr, $filter, astIsPure); 16271 allConstants = allConstants && expr.constant; 16272 argsToWatch.push.apply(argsToWatch, expr.toWatch); 16273 }); 16274 ast.constant = allConstants; 16275 ast.toWatch = argsToWatch; 16276 break; 16277 case AST.ObjectExpression: 16278 allConstants = true; 16279 argsToWatch = []; 16280 forEach(ast.properties, function(property) { 16281 findConstantAndWatchExpressions(property.value, $filter, astIsPure); 16282 allConstants = allConstants && property.value.constant; 16283 argsToWatch.push.apply(argsToWatch, property.value.toWatch); 16284 if (property.computed) { 16285 //`{[key]: value}` implicitly does `key.toString()` which may be non-pure 16286 findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false); 16287 allConstants = allConstants && property.key.constant; 16288 argsToWatch.push.apply(argsToWatch, property.key.toWatch); 16289 } 16290 }); 16291 ast.constant = allConstants; 16292 ast.toWatch = argsToWatch; 16293 break; 16294 case AST.ThisExpression: 16295 ast.constant = false; 16296 ast.toWatch = []; 16297 break; 16298 case AST.LocalsExpression: 16299 ast.constant = false; 16300 ast.toWatch = []; 16301 break; 16302 } 16303} 16304 16305function getInputs(body) { 16306 if (body.length !== 1) return; 16307 var lastExpression = body[0].expression; 16308 var candidate = lastExpression.toWatch; 16309 if (candidate.length !== 1) return candidate; 16310 return candidate[0] !== lastExpression ? candidate : undefined; 16311} 16312 16313function isAssignable(ast) { 16314 return ast.type === AST.Identifier || ast.type === AST.MemberExpression; 16315} 16316 16317function assignableAST(ast) { 16318 if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) { 16319 return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='}; 16320 } 16321} 16322 16323function isLiteral(ast) { 16324 return ast.body.length === 0 || 16325 ast.body.length === 1 && ( 16326 ast.body[0].expression.type === AST.Literal || 16327 ast.body[0].expression.type === AST.ArrayExpression || 16328 ast.body[0].expression.type === AST.ObjectExpression); 16329} 16330 16331function isConstant(ast) { 16332 return ast.constant; 16333} 16334 16335function ASTCompiler($filter) { 16336 this.$filter = $filter; 16337} 16338 16339ASTCompiler.prototype = { 16340 compile: function(ast) { 16341 var self = this; 16342 this.state = { 16343 nextId: 0, 16344 filters: {}, 16345 fn: {vars: [], body: [], own: {}}, 16346 assign: {vars: [], body: [], own: {}}, 16347 inputs: [] 16348 }; 16349 findConstantAndWatchExpressions(ast, self.$filter); 16350 var extra = ''; 16351 var assignable; 16352 this.stage = 'assign'; 16353 if ((assignable = assignableAST(ast))) { 16354 this.state.computing = 'assign'; 16355 var result = this.nextId(); 16356 this.recurse(assignable, result); 16357 this.return_(result); 16358 extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l'); 16359 } 16360 var toWatch = getInputs(ast.body); 16361 self.stage = 'inputs'; 16362 forEach(toWatch, function(watch, key) { 16363 var fnKey = 'fn' + key; 16364 self.state[fnKey] = {vars: [], body: [], own: {}}; 16365 self.state.computing = fnKey; 16366 var intoId = self.nextId(); 16367 self.recurse(watch, intoId); 16368 self.return_(intoId); 16369 self.state.inputs.push({name: fnKey, isPure: watch.isPure}); 16370 watch.watchId = key; 16371 }); 16372 this.state.computing = 'fn'; 16373 this.stage = 'main'; 16374 this.recurse(ast); 16375 var fnString = 16376 // The build and minification steps remove the string "use strict" from the code, but this is done using a regex. 16377 // This is a workaround for this until we do a better job at only removing the prefix only when we should. 16378 '"' + this.USE + ' ' + this.STRICT + '";\n' + 16379 this.filterPrefix() + 16380 'var fn=' + this.generateFunction('fn', 's,l,a,i') + 16381 extra + 16382 this.watchFns() + 16383 'return fn;'; 16384 16385 // eslint-disable-next-line no-new-func 16386 var fn = (new Function('$filter', 16387 'getStringValue', 16388 'ifDefined', 16389 'plus', 16390 fnString))( 16391 this.$filter, 16392 getStringValue, 16393 ifDefined, 16394 plusFn); 16395 this.state = this.stage = undefined; 16396 return fn; 16397 }, 16398 16399 USE: 'use', 16400 16401 STRICT: 'strict', 16402 16403 watchFns: function() { 16404 var result = []; 16405 var inputs = this.state.inputs; 16406 var self = this; 16407 forEach(inputs, function(input) { 16408 result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's')); 16409 if (input.isPure) { 16410 result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';'); 16411 } 16412 }); 16413 if (inputs.length) { 16414 result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];'); 16415 } 16416 return result.join(''); 16417 }, 16418 16419 generateFunction: function(name, params) { 16420 return 'function(' + params + '){' + 16421 this.varsPrefix(name) + 16422 this.body(name) + 16423 '};'; 16424 }, 16425 16426 filterPrefix: function() { 16427 var parts = []; 16428 var self = this; 16429 forEach(this.state.filters, function(id, filter) { 16430 parts.push(id + '=$filter(' + self.escape(filter) + ')'); 16431 }); 16432 if (parts.length) return 'var ' + parts.join(',') + ';'; 16433 return ''; 16434 }, 16435 16436 varsPrefix: function(section) { 16437 return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : ''; 16438 }, 16439 16440 body: function(section) { 16441 return this.state[section].body.join(''); 16442 }, 16443 16444 recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { 16445 var left, right, self = this, args, expression, computed; 16446 recursionFn = recursionFn || noop; 16447 if (!skipWatchIdCheck && isDefined(ast.watchId)) { 16448 intoId = intoId || this.nextId(); 16449 this.if_('i', 16450 this.lazyAssign(intoId, this.computedMember('i', ast.watchId)), 16451 this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true) 16452 ); 16453 return; 16454 } 16455 switch (ast.type) { 16456 case AST.Program: 16457 forEach(ast.body, function(expression, pos) { 16458 self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; }); 16459 if (pos !== ast.body.length - 1) { 16460 self.current().body.push(right, ';'); 16461 } else { 16462 self.return_(right); 16463 } 16464 }); 16465 break; 16466 case AST.Literal: 16467 expression = this.escape(ast.value); 16468 this.assign(intoId, expression); 16469 recursionFn(intoId || expression); 16470 break; 16471 case AST.UnaryExpression: 16472 this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; }); 16473 expression = ast.operator + '(' + this.ifDefined(right, 0) + ')'; 16474 this.assign(intoId, expression); 16475 recursionFn(expression); 16476 break; 16477 case AST.BinaryExpression: 16478 this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; }); 16479 this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; }); 16480 if (ast.operator === '+') { 16481 expression = this.plus(left, right); 16482 } else if (ast.operator === '-') { 16483 expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0); 16484 } else { 16485 expression = '(' + left + ')' + ast.operator + '(' + right + ')'; 16486 } 16487 this.assign(intoId, expression); 16488 recursionFn(expression); 16489 break; 16490 case AST.LogicalExpression: 16491 intoId = intoId || this.nextId(); 16492 self.recurse(ast.left, intoId); 16493 self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId)); 16494 recursionFn(intoId); 16495 break; 16496 case AST.ConditionalExpression: 16497 intoId = intoId || this.nextId(); 16498 self.recurse(ast.test, intoId); 16499 self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId)); 16500 recursionFn(intoId); 16501 break; 16502 case AST.Identifier: 16503 intoId = intoId || this.nextId(); 16504 if (nameId) { 16505 nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s'); 16506 nameId.computed = false; 16507 nameId.name = ast.name; 16508 } 16509 self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)), 16510 function() { 16511 self.if_(self.stage === 'inputs' || 's', function() { 16512 if (create && create !== 1) { 16513 self.if_( 16514 self.isNull(self.nonComputedMember('s', ast.name)), 16515 self.lazyAssign(self.nonComputedMember('s', ast.name), '{}')); 16516 } 16517 self.assign(intoId, self.nonComputedMember('s', ast.name)); 16518 }); 16519 }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name)) 16520 ); 16521 recursionFn(intoId); 16522 break; 16523 case AST.MemberExpression: 16524 left = nameId && (nameId.context = this.nextId()) || this.nextId(); 16525 intoId = intoId || this.nextId(); 16526 self.recurse(ast.object, left, undefined, function() { 16527 self.if_(self.notNull(left), function() { 16528 if (ast.computed) { 16529 right = self.nextId(); 16530 self.recurse(ast.property, right); 16531 self.getStringValue(right); 16532 if (create && create !== 1) { 16533 self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}')); 16534 } 16535 expression = self.computedMember(left, right); 16536 self.assign(intoId, expression); 16537 if (nameId) { 16538 nameId.computed = true; 16539 nameId.name = right; 16540 } 16541 } else { 16542 if (create && create !== 1) { 16543 self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}')); 16544 } 16545 expression = self.nonComputedMember(left, ast.property.name); 16546 self.assign(intoId, expression); 16547 if (nameId) { 16548 nameId.computed = false; 16549 nameId.name = ast.property.name; 16550 } 16551 } 16552 }, function() { 16553 self.assign(intoId, 'undefined'); 16554 }); 16555 recursionFn(intoId); 16556 }, !!create); 16557 break; 16558 case AST.CallExpression: 16559 intoId = intoId || this.nextId(); 16560 if (ast.filter) { 16561 right = self.filter(ast.callee.name); 16562 args = []; 16563 forEach(ast.arguments, function(expr) { 16564 var argument = self.nextId(); 16565 self.recurse(expr, argument); 16566 args.push(argument); 16567 }); 16568 expression = right + '(' + args.join(',') + ')'; 16569 self.assign(intoId, expression); 16570 recursionFn(intoId); 16571 } else { 16572 right = self.nextId(); 16573 left = {}; 16574 args = []; 16575 self.recurse(ast.callee, right, left, function() { 16576 self.if_(self.notNull(right), function() { 16577 forEach(ast.arguments, function(expr) { 16578 self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) { 16579 args.push(argument); 16580 }); 16581 }); 16582 if (left.name) { 16583 expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')'; 16584 } else { 16585 expression = right + '(' + args.join(',') + ')'; 16586 } 16587 self.assign(intoId, expression); 16588 }, function() { 16589 self.assign(intoId, 'undefined'); 16590 }); 16591 recursionFn(intoId); 16592 }); 16593 } 16594 break; 16595 case AST.AssignmentExpression: 16596 right = this.nextId(); 16597 left = {}; 16598 this.recurse(ast.left, undefined, left, function() { 16599 self.if_(self.notNull(left.context), function() { 16600 self.recurse(ast.right, right); 16601 expression = self.member(left.context, left.name, left.computed) + ast.operator + right; 16602 self.assign(intoId, expression); 16603 recursionFn(intoId || expression); 16604 }); 16605 }, 1); 16606 break; 16607 case AST.ArrayExpression: 16608 args = []; 16609 forEach(ast.elements, function(expr) { 16610 self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) { 16611 args.push(argument); 16612 }); 16613 }); 16614 expression = '[' + args.join(',') + ']'; 16615 this.assign(intoId, expression); 16616 recursionFn(intoId || expression); 16617 break; 16618 case AST.ObjectExpression: 16619 args = []; 16620 computed = false; 16621 forEach(ast.properties, function(property) { 16622 if (property.computed) { 16623 computed = true; 16624 } 16625 }); 16626 if (computed) { 16627 intoId = intoId || this.nextId(); 16628 this.assign(intoId, '{}'); 16629 forEach(ast.properties, function(property) { 16630 if (property.computed) { 16631 left = self.nextId(); 16632 self.recurse(property.key, left); 16633 } else { 16634 left = property.key.type === AST.Identifier ? 16635 property.key.name : 16636 ('' + property.key.value); 16637 } 16638 right = self.nextId(); 16639 self.recurse(property.value, right); 16640 self.assign(self.member(intoId, left, property.computed), right); 16641 }); 16642 } else { 16643 forEach(ast.properties, function(property) { 16644 self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) { 16645 args.push(self.escape( 16646 property.key.type === AST.Identifier ? property.key.name : 16647 ('' + property.key.value)) + 16648 ':' + expr); 16649 }); 16650 }); 16651 expression = '{' + args.join(',') + '}'; 16652 this.assign(intoId, expression); 16653 } 16654 recursionFn(intoId || expression); 16655 break; 16656 case AST.ThisExpression: 16657 this.assign(intoId, 's'); 16658 recursionFn(intoId || 's'); 16659 break; 16660 case AST.LocalsExpression: 16661 this.assign(intoId, 'l'); 16662 recursionFn(intoId || 'l'); 16663 break; 16664 case AST.NGValueParameter: 16665 this.assign(intoId, 'v'); 16666 recursionFn(intoId || 'v'); 16667 break; 16668 } 16669 }, 16670 16671 getHasOwnProperty: function(element, property) { 16672 var key = element + '.' + property; 16673 var own = this.current().own; 16674 if (!own.hasOwnProperty(key)) { 16675 own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')'); 16676 } 16677 return own[key]; 16678 }, 16679 16680 assign: function(id, value) { 16681 if (!id) return; 16682 this.current().body.push(id, '=', value, ';'); 16683 return id; 16684 }, 16685 16686 filter: function(filterName) { 16687 if (!this.state.filters.hasOwnProperty(filterName)) { 16688 this.state.filters[filterName] = this.nextId(true); 16689 } 16690 return this.state.filters[filterName]; 16691 }, 16692 16693 ifDefined: function(id, defaultValue) { 16694 return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')'; 16695 }, 16696 16697 plus: function(left, right) { 16698 return 'plus(' + left + ',' + right + ')'; 16699 }, 16700 16701 return_: function(id) { 16702 this.current().body.push('return ', id, ';'); 16703 }, 16704 16705 if_: function(test, alternate, consequent) { 16706 if (test === true) { 16707 alternate(); 16708 } else { 16709 var body = this.current().body; 16710 body.push('if(', test, '){'); 16711 alternate(); 16712 body.push('}'); 16713 if (consequent) { 16714 body.push('else{'); 16715 consequent(); 16716 body.push('}'); 16717 } 16718 } 16719 }, 16720 16721 not: function(expression) { 16722 return '!(' + expression + ')'; 16723 }, 16724 16725 isNull: function(expression) { 16726 return expression + '==null'; 16727 }, 16728 16729 notNull: function(expression) { 16730 return expression + '!=null'; 16731 }, 16732 16733 nonComputedMember: function(left, right) { 16734 var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/; 16735 var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g; 16736 if (SAFE_IDENTIFIER.test(right)) { 16737 return left + '.' + right; 16738 } else { 16739 return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]'; 16740 } 16741 }, 16742 16743 computedMember: function(left, right) { 16744 return left + '[' + right + ']'; 16745 }, 16746 16747 member: function(left, right, computed) { 16748 if (computed) return this.computedMember(left, right); 16749 return this.nonComputedMember(left, right); 16750 }, 16751 16752 getStringValue: function(item) { 16753 this.assign(item, 'getStringValue(' + item + ')'); 16754 }, 16755 16756 lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { 16757 var self = this; 16758 return function() { 16759 self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck); 16760 }; 16761 }, 16762 16763 lazyAssign: function(id, value) { 16764 var self = this; 16765 return function() { 16766 self.assign(id, value); 16767 }; 16768 }, 16769 16770 stringEscapeRegex: /[^ a-zA-Z0-9]/g, 16771 16772 stringEscapeFn: function(c) { 16773 return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); 16774 }, 16775 16776 escape: function(value) { 16777 if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\''; 16778 if (isNumber(value)) return value.toString(); 16779 if (value === true) return 'true'; 16780 if (value === false) return 'false'; 16781 if (value === null) return 'null'; 16782 if (typeof value === 'undefined') return 'undefined'; 16783 16784 throw $parseMinErr('esc', 'IMPOSSIBLE'); 16785 }, 16786 16787 nextId: function(skip, init) { 16788 var id = 'v' + (this.state.nextId++); 16789 if (!skip) { 16790 this.current().vars.push(id + (init ? '=' + init : '')); 16791 } 16792 return id; 16793 }, 16794 16795 current: function() { 16796 return this.state[this.state.computing]; 16797 } 16798}; 16799 16800 16801function ASTInterpreter($filter) { 16802 this.$filter = $filter; 16803} 16804 16805ASTInterpreter.prototype = { 16806 compile: function(ast) { 16807 var self = this; 16808 findConstantAndWatchExpressions(ast, self.$filter); 16809 var assignable; 16810 var assign; 16811 if ((assignable = assignableAST(ast))) { 16812 assign = this.recurse(assignable); 16813 } 16814 var toWatch = getInputs(ast.body); 16815 var inputs; 16816 if (toWatch) { 16817 inputs = []; 16818 forEach(toWatch, function(watch, key) { 16819 var input = self.recurse(watch); 16820 input.isPure = watch.isPure; 16821 watch.input = input; 16822 inputs.push(input); 16823 watch.watchId = key; 16824 }); 16825 } 16826 var expressions = []; 16827 forEach(ast.body, function(expression) { 16828 expressions.push(self.recurse(expression.expression)); 16829 }); 16830 var fn = ast.body.length === 0 ? noop : 16831 ast.body.length === 1 ? expressions[0] : 16832 function(scope, locals) { 16833 var lastValue; 16834 forEach(expressions, function(exp) { 16835 lastValue = exp(scope, locals); 16836 }); 16837 return lastValue; 16838 }; 16839 if (assign) { 16840 fn.assign = function(scope, value, locals) { 16841 return assign(scope, locals, value); 16842 }; 16843 } 16844 if (inputs) { 16845 fn.inputs = inputs; 16846 } 16847 return fn; 16848 }, 16849 16850 recurse: function(ast, context, create) { 16851 var left, right, self = this, args; 16852 if (ast.input) { 16853 return this.inputs(ast.input, ast.watchId); 16854 } 16855 switch (ast.type) { 16856 case AST.Literal: 16857 return this.value(ast.value, context); 16858 case AST.UnaryExpression: 16859 right = this.recurse(ast.argument); 16860 return this['unary' + ast.operator](right, context); 16861 case AST.BinaryExpression: 16862 left = this.recurse(ast.left); 16863 right = this.recurse(ast.right); 16864 return this['binary' + ast.operator](left, right, context); 16865 case AST.LogicalExpression: 16866 left = this.recurse(ast.left); 16867 right = this.recurse(ast.right); 16868 return this['binary' + ast.operator](left, right, context); 16869 case AST.ConditionalExpression: 16870 return this['ternary?:']( 16871 this.recurse(ast.test), 16872 this.recurse(ast.alternate), 16873 this.recurse(ast.consequent), 16874 context 16875 ); 16876 case AST.Identifier: 16877 return self.identifier(ast.name, context, create); 16878 case AST.MemberExpression: 16879 left = this.recurse(ast.object, false, !!create); 16880 if (!ast.computed) { 16881 right = ast.property.name; 16882 } 16883 if (ast.computed) right = this.recurse(ast.property); 16884 return ast.computed ? 16885 this.computedMember(left, right, context, create) : 16886 this.nonComputedMember(left, right, context, create); 16887 case AST.CallExpression: 16888 args = []; 16889 forEach(ast.arguments, function(expr) { 16890 args.push(self.recurse(expr)); 16891 }); 16892 if (ast.filter) right = this.$filter(ast.callee.name); 16893 if (!ast.filter) right = this.recurse(ast.callee, true); 16894 return ast.filter ? 16895 function(scope, locals, assign, inputs) { 16896 var values = []; 16897 for (var i = 0; i < args.length; ++i) { 16898 values.push(args[i](scope, locals, assign, inputs)); 16899 } 16900 var value = right.apply(undefined, values, inputs); 16901 return context ? {context: undefined, name: undefined, value: value} : value; 16902 } : 16903 function(scope, locals, assign, inputs) { 16904 var rhs = right(scope, locals, assign, inputs); 16905 var value; 16906 if (rhs.value != null) { 16907 var values = []; 16908 for (var i = 0; i < args.length; ++i) { 16909 values.push(args[i](scope, locals, assign, inputs)); 16910 } 16911 value = rhs.value.apply(rhs.context, values); 16912 } 16913 return context ? {value: value} : value; 16914 }; 16915 case AST.AssignmentExpression: 16916 left = this.recurse(ast.left, true, 1); 16917 right = this.recurse(ast.right); 16918 return function(scope, locals, assign, inputs) { 16919 var lhs = left(scope, locals, assign, inputs); 16920 var rhs = right(scope, locals, assign, inputs); 16921 lhs.context[lhs.name] = rhs; 16922 return context ? {value: rhs} : rhs; 16923 }; 16924 case AST.ArrayExpression: 16925 args = []; 16926 forEach(ast.elements, function(expr) { 16927 args.push(self.recurse(expr)); 16928 }); 16929 return function(scope, locals, assign, inputs) { 16930 var value = []; 16931 for (var i = 0; i < args.length; ++i) { 16932 value.push(args[i](scope, locals, assign, inputs)); 16933 } 16934 return context ? {value: value} : value; 16935 }; 16936 case AST.ObjectExpression: 16937 args = []; 16938 forEach(ast.properties, function(property) { 16939 if (property.computed) { 16940 args.push({key: self.recurse(property.key), 16941 computed: true, 16942 value: self.recurse(property.value) 16943 }); 16944 } else { 16945 args.push({key: property.key.type === AST.Identifier ? 16946 property.key.name : 16947 ('' + property.key.value), 16948 computed: false, 16949 value: self.recurse(property.value) 16950 }); 16951 } 16952 }); 16953 return function(scope, locals, assign, inputs) { 16954 var value = {}; 16955 for (var i = 0; i < args.length; ++i) { 16956 if (args[i].computed) { 16957 value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs); 16958 } else { 16959 value[args[i].key] = args[i].value(scope, locals, assign, inputs); 16960 } 16961 } 16962 return context ? {value: value} : value; 16963 }; 16964 case AST.ThisExpression: 16965 return function(scope) { 16966 return context ? {value: scope} : scope; 16967 }; 16968 case AST.LocalsExpression: 16969 return function(scope, locals) { 16970 return context ? {value: locals} : locals; 16971 }; 16972 case AST.NGValueParameter: 16973 return function(scope, locals, assign) { 16974 return context ? {value: assign} : assign; 16975 }; 16976 } 16977 }, 16978 16979 'unary+': function(argument, context) { 16980 return function(scope, locals, assign, inputs) { 16981 var arg = argument(scope, locals, assign, inputs); 16982 if (isDefined(arg)) { 16983 arg = +arg; 16984 } else { 16985 arg = 0; 16986 } 16987 return context ? {value: arg} : arg; 16988 }; 16989 }, 16990 'unary-': function(argument, context) { 16991 return function(scope, locals, assign, inputs) { 16992 var arg = argument(scope, locals, assign, inputs); 16993 if (isDefined(arg)) { 16994 arg = -arg; 16995 } else { 16996 arg = -0; 16997 } 16998 return context ? {value: arg} : arg; 16999 }; 17000 }, 17001 'unary!': function(argument, context) { 17002 return function(scope, locals, assign, inputs) { 17003 var arg = !argument(scope, locals, assign, inputs); 17004 return context ? {value: arg} : arg; 17005 }; 17006 }, 17007 'binary+': function(left, right, context) { 17008 return function(scope, locals, assign, inputs) { 17009 var lhs = left(scope, locals, assign, inputs); 17010 var rhs = right(scope, locals, assign, inputs); 17011 var arg = plusFn(lhs, rhs); 17012 return context ? {value: arg} : arg; 17013 }; 17014 }, 17015 'binary-': function(left, right, context) { 17016 return function(scope, locals, assign, inputs) { 17017 var lhs = left(scope, locals, assign, inputs); 17018 var rhs = right(scope, locals, assign, inputs); 17019 var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0); 17020 return context ? {value: arg} : arg; 17021 }; 17022 }, 17023 'binary*': function(left, right, context) { 17024 return function(scope, locals, assign, inputs) { 17025 var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs); 17026 return context ? {value: arg} : arg; 17027 }; 17028 }, 17029 'binary/': function(left, right, context) { 17030 return function(scope, locals, assign, inputs) { 17031 var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs); 17032 return context ? {value: arg} : arg; 17033 }; 17034 }, 17035 'binary%': function(left, right, context) { 17036 return function(scope, locals, assign, inputs) { 17037 var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs); 17038 return context ? {value: arg} : arg; 17039 }; 17040 }, 17041 'binary===': function(left, right, context) { 17042 return function(scope, locals, assign, inputs) { 17043 var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs); 17044 return context ? {value: arg} : arg; 17045 }; 17046 }, 17047 'binary!==': function(left, right, context) { 17048 return function(scope, locals, assign, inputs) { 17049 var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs); 17050 return context ? {value: arg} : arg; 17051 }; 17052 }, 17053 'binary==': function(left, right, context) { 17054 return function(scope, locals, assign, inputs) { 17055 // eslint-disable-next-line eqeqeq 17056 var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs); 17057 return context ? {value: arg} : arg; 17058 }; 17059 }, 17060 'binary!=': function(left, right, context) { 17061 return function(scope, locals, assign, inputs) { 17062 // eslint-disable-next-line eqeqeq 17063 var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs); 17064 return context ? {value: arg} : arg; 17065 }; 17066 }, 17067 'binary<': function(left, right, context) { 17068 return function(scope, locals, assign, inputs) { 17069 var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs); 17070 return context ? {value: arg} : arg; 17071 }; 17072 }, 17073 'binary>': function(left, right, context) { 17074 return function(scope, locals, assign, inputs) { 17075 var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs); 17076 return context ? {value: arg} : arg; 17077 }; 17078 }, 17079 'binary<=': function(left, right, context) { 17080 return function(scope, locals, assign, inputs) { 17081 var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs); 17082 return context ? {value: arg} : arg; 17083 }; 17084 }, 17085 'binary>=': function(left, right, context) { 17086 return function(scope, locals, assign, inputs) { 17087 var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs); 17088 return context ? {value: arg} : arg; 17089 }; 17090 }, 17091 'binary&&': function(left, right, context) { 17092 return function(scope, locals, assign, inputs) { 17093 var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs); 17094 return context ? {value: arg} : arg; 17095 }; 17096 }, 17097 'binary||': function(left, right, context) { 17098 return function(scope, locals, assign, inputs) { 17099 var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs); 17100 return context ? {value: arg} : arg; 17101 }; 17102 }, 17103 'ternary?:': function(test, alternate, consequent, context) { 17104 return function(scope, locals, assign, inputs) { 17105 var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs); 17106 return context ? {value: arg} : arg; 17107 }; 17108 }, 17109 value: function(value, context) { 17110 return function() { return context ? {context: undefined, name: undefined, value: value} : value; }; 17111 }, 17112 identifier: function(name, context, create) { 17113 return function(scope, locals, assign, inputs) { 17114 var base = locals && (name in locals) ? locals : scope; 17115 if (create && create !== 1 && base && base[name] == null) { 17116 base[name] = {}; 17117 } 17118 var value = base ? base[name] : undefined; 17119 if (context) { 17120 return {context: base, name: name, value: value}; 17121 } else { 17122 return value; 17123 } 17124 }; 17125 }, 17126 computedMember: function(left, right, context, create) { 17127 return function(scope, locals, assign, inputs) { 17128 var lhs = left(scope, locals, assign, inputs); 17129 var rhs; 17130 var value; 17131 if (lhs != null) { 17132 rhs = right(scope, locals, assign, inputs); 17133 rhs = getStringValue(rhs); 17134 if (create && create !== 1) { 17135 if (lhs && !(lhs[rhs])) { 17136 lhs[rhs] = {}; 17137 } 17138 } 17139 value = lhs[rhs]; 17140 } 17141 if (context) { 17142 return {context: lhs, name: rhs, value: value}; 17143 } else { 17144 return value; 17145 } 17146 }; 17147 }, 17148 nonComputedMember: function(left, right, context, create) { 17149 return function(scope, locals, assign, inputs) { 17150 var lhs = left(scope, locals, assign, inputs); 17151 if (create && create !== 1) { 17152 if (lhs && lhs[right] == null) { 17153 lhs[right] = {}; 17154 } 17155 } 17156 var value = lhs != null ? lhs[right] : undefined; 17157 if (context) { 17158 return {context: lhs, name: right, value: value}; 17159 } else { 17160 return value; 17161 } 17162 }; 17163 }, 17164 inputs: function(input, watchId) { 17165 return function(scope, value, locals, inputs) { 17166 if (inputs) return inputs[watchId]; 17167 return input(scope, value, locals); 17168 }; 17169 } 17170}; 17171 17172/** 17173 * @constructor 17174 */ 17175function Parser(lexer, $filter, options) { 17176 this.ast = new AST(lexer, options); 17177 this.astCompiler = options.csp ? new ASTInterpreter($filter) : 17178 new ASTCompiler($filter); 17179} 17180 17181Parser.prototype = { 17182 constructor: Parser, 17183 17184 parse: function(text) { 17185 var ast = this.getAst(text); 17186 var fn = this.astCompiler.compile(ast.ast); 17187 fn.literal = isLiteral(ast.ast); 17188 fn.constant = isConstant(ast.ast); 17189 fn.oneTime = ast.oneTime; 17190 return fn; 17191 }, 17192 17193 getAst: function(exp) { 17194 var oneTime = false; 17195 exp = exp.trim(); 17196 17197 if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { 17198 oneTime = true; 17199 exp = exp.substring(2); 17200 } 17201 return { 17202 ast: this.ast.ast(exp), 17203 oneTime: oneTime 17204 }; 17205 } 17206}; 17207 17208function getValueOf(value) { 17209 return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value); 17210} 17211 17212/////////////////////////////////// 17213 17214/** 17215 * @ngdoc service 17216 * @name $parse 17217 * @kind function 17218 * 17219 * @description 17220 * 17221 * Converts AngularJS {@link guide/expression expression} into a function. 17222 * 17223 * ```js 17224 * var getter = $parse('user.name'); 17225 * var setter = getter.assign; 17226 * var context = {user:{name:'AngularJS'}}; 17227 * var locals = {user:{name:'local'}}; 17228 * 17229 * expect(getter(context)).toEqual('AngularJS'); 17230 * setter(context, 'newValue'); 17231 * expect(context.user.name).toEqual('newValue'); 17232 * expect(getter(context, locals)).toEqual('local'); 17233 * ``` 17234 * 17235 * 17236 * @param {string} expression String expression to compile. 17237 * @returns {function(context, locals)} a function which represents the compiled expression: 17238 * 17239 * * `context` – `{object}` – an object against which any expressions embedded in the strings 17240 * are evaluated against (typically a scope object). 17241 * * `locals` – `{object=}` – local variables context object, useful for overriding values in 17242 * `context`. 17243 * 17244 * The returned function also has the following properties: 17245 * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript 17246 * literal. 17247 * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript 17248 * constant literals. 17249 * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be 17250 * set to a function to change its value on the given context. 17251 * 17252 */ 17253 17254 17255/** 17256 * @ngdoc provider 17257 * @name $parseProvider 17258 * @this 17259 * 17260 * @description 17261 * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} 17262 * service. 17263 */ 17264function $ParseProvider() { 17265 var cache = createMap(); 17266 var literals = { 17267 'true': true, 17268 'false': false, 17269 'null': null, 17270 'undefined': undefined 17271 }; 17272 var identStart, identContinue; 17273 17274 /** 17275 * @ngdoc method 17276 * @name $parseProvider#addLiteral 17277 * @description 17278 * 17279 * Configure $parse service to add literal values that will be present as literal at expressions. 17280 * 17281 * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name. 17282 * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`. 17283 * 17284 **/ 17285 this.addLiteral = function(literalName, literalValue) { 17286 literals[literalName] = literalValue; 17287 }; 17288 17289 /** 17290 * @ngdoc method 17291 * @name $parseProvider#setIdentifierFns 17292 * 17293 * @description 17294 * 17295 * Allows defining the set of characters that are allowed in AngularJS expressions. The function 17296 * `identifierStart` will get called to know if a given character is a valid character to be the 17297 * first character for an identifier. The function `identifierContinue` will get called to know if 17298 * a given character is a valid character to be a follow-up identifier character. The functions 17299 * `identifierStart` and `identifierContinue` will receive as arguments the single character to be 17300 * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in 17301 * mind that the `string` parameter can be two characters long depending on the character 17302 * representation. It is expected for the function to return `true` or `false`, whether that 17303 * character is allowed or not. 17304 * 17305 * Since this function will be called extensively, keep the implementation of these functions fast, 17306 * as the performance of these functions have a direct impact on the expressions parsing speed. 17307 * 17308 * @param {function=} identifierStart The function that will decide whether the given character is 17309 * a valid identifier start character. 17310 * @param {function=} identifierContinue The function that will decide whether the given character is 17311 * a valid identifier continue character. 17312 */ 17313 this.setIdentifierFns = function(identifierStart, identifierContinue) { 17314 identStart = identifierStart; 17315 identContinue = identifierContinue; 17316 return this; 17317 }; 17318 17319 this.$get = ['$filter', function($filter) { 17320 var noUnsafeEval = csp().noUnsafeEval; 17321 var $parseOptions = { 17322 csp: noUnsafeEval, 17323 literals: copy(literals), 17324 isIdentifierStart: isFunction(identStart) && identStart, 17325 isIdentifierContinue: isFunction(identContinue) && identContinue 17326 }; 17327 $parse.$$getAst = $$getAst; 17328 return $parse; 17329 17330 function $parse(exp, interceptorFn) { 17331 var parsedExpression, cacheKey; 17332 17333 switch (typeof exp) { 17334 case 'string': 17335 exp = exp.trim(); 17336 cacheKey = exp; 17337 17338 parsedExpression = cache[cacheKey]; 17339 17340 if (!parsedExpression) { 17341 var lexer = new Lexer($parseOptions); 17342 var parser = new Parser(lexer, $filter, $parseOptions); 17343 parsedExpression = parser.parse(exp); 17344 17345 cache[cacheKey] = addWatchDelegate(parsedExpression); 17346 } 17347 return addInterceptor(parsedExpression, interceptorFn); 17348 17349 case 'function': 17350 return addInterceptor(exp, interceptorFn); 17351 17352 default: 17353 return addInterceptor(noop, interceptorFn); 17354 } 17355 } 17356 17357 function $$getAst(exp) { 17358 var lexer = new Lexer($parseOptions); 17359 var parser = new Parser(lexer, $filter, $parseOptions); 17360 return parser.getAst(exp).ast; 17361 } 17362 17363 function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) { 17364 17365 if (newValue == null || oldValueOfValue == null) { // null/undefined 17366 return newValue === oldValueOfValue; 17367 } 17368 17369 if (typeof newValue === 'object') { 17370 17371 // attempt to convert the value to a primitive type 17372 // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can 17373 // be cheaply dirty-checked 17374 newValue = getValueOf(newValue); 17375 17376 if (typeof newValue === 'object' && !compareObjectIdentity) { 17377 // objects/arrays are not supported - deep-watching them would be too expensive 17378 return false; 17379 } 17380 17381 // fall-through to the primitive equality check 17382 } 17383 17384 //Primitive or NaN 17385 // eslint-disable-next-line no-self-compare 17386 return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); 17387 } 17388 17389 function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { 17390 var inputExpressions = parsedExpression.inputs; 17391 var lastResult; 17392 17393 if (inputExpressions.length === 1) { 17394 var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails 17395 inputExpressions = inputExpressions[0]; 17396 return scope.$watch(function expressionInputWatch(scope) { 17397 var newInputValue = inputExpressions(scope); 17398 if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) { 17399 lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]); 17400 oldInputValueOf = newInputValue && getValueOf(newInputValue); 17401 } 17402 return lastResult; 17403 }, listener, objectEquality, prettyPrintExpression); 17404 } 17405 17406 var oldInputValueOfValues = []; 17407 var oldInputValues = []; 17408 for (var i = 0, ii = inputExpressions.length; i < ii; i++) { 17409 oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails 17410 oldInputValues[i] = null; 17411 } 17412 17413 return scope.$watch(function expressionInputsWatch(scope) { 17414 var changed = false; 17415 17416 for (var i = 0, ii = inputExpressions.length; i < ii; i++) { 17417 var newInputValue = inputExpressions[i](scope); 17418 if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) { 17419 oldInputValues[i] = newInputValue; 17420 oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue); 17421 } 17422 } 17423 17424 if (changed) { 17425 lastResult = parsedExpression(scope, undefined, undefined, oldInputValues); 17426 } 17427 17428 return lastResult; 17429 }, listener, objectEquality, prettyPrintExpression); 17430 } 17431 17432 function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { 17433 var isDone = parsedExpression.literal ? isAllDefined : isDefined; 17434 var unwatch, lastValue; 17435 17436 var exp = parsedExpression.$$intercepted || parsedExpression; 17437 var post = parsedExpression.$$interceptor || identity; 17438 17439 var useInputs = parsedExpression.inputs && !exp.inputs; 17440 17441 // Prop
vendor: 2,577 bytes, lines 17441-17517
17441ogate the literal/inputs/constant attributes 17442 // ... but not oneTime since we are handling it 17443 oneTimeWatch.literal = parsedExpression.literal; 17444 oneTimeWatch.constant = parsedExpression.constant; 17445 oneTimeWatch.inputs = parsedExpression.inputs; 17446 17447 // Allow other delegates to run on this wrapped expression 17448 addWatchDelegate(oneTimeWatch); 17449 17450 unwatch = scope.$watch(oneTimeWatch, listener, objectEquality, prettyPrintExpression); 17451 17452 return unwatch; 17453 17454 function unwatchIfDone() { 17455 if (isDone(lastValue)) { 17456 unwatch(); 17457 } 17458 } 17459 17460 function oneTimeWatch(scope, locals, assign, inputs) { 17461 lastValue = useInputs && inputs ? inputs[0] : exp(scope, locals, assign, inputs); 17462 if (isDone(lastValue)) { 17463 scope.$$postDigest(unwatchIfDone); 17464 } 17465 return post(lastValue); 17466 } 17467 } 17468 17469 function isAllDefined(value) { 17470 var allDefined = true; 17471 forEach(value, function(val) { 17472 if (!isDefined(val)) allDefined = false; 17473 }); 17474 return allDefined; 17475 } 17476 17477 function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { 17478 var unwatch = scope.$watch(function constantWatch(scope) { 17479 unwatch(); 17480 return parsedExpression(scope); 17481 }, listener, objectEquality); 17482 return unwatch; 17483 } 17484 17485 function addWatchDelegate(parsedExpression) { 17486 if (parsedExpression.constant) { 17487 parsedExpression.$$watchDelegate = constantWatchDelegate; 17488 } else if (parsedExpression.oneTime) { 17489 parsedExpression.$$watchDelegate = oneTimeWatchDelegate; 17490 } else if (parsedExpression.inputs) { 17491 parsedExpression.$$watchDelegate = inputsWatchDelegate; 17492 } 17493 17494 return parsedExpression; 17495 } 17496 17497 function chainInterceptors(first, second) { 17498 function chainedInterceptor(value) { 17499 return second(first(value)); 17500 } 17501 chainedInterceptor.$stateful = first.$stateful || second.$stateful; 17502 chainedInterceptor.$$pure = first.$$pure && second.$$pure; 17503 17504 return chainedInterceptor; 17505 } 17506 17507 function addInterceptor(parsedExpression, interceptorFn) { 17508 if (!interceptorFn) return parsedExpression; 17509 17510 // Extract any existing interceptors out of the parsedExpression 17511 // to ensure the original parsedExpression is always the $$intercepted 17512 if (parsedExpression.$$interceptor) { 17513 interceptorFn = chainInterceptors(parsedExpression.$$interceptor, interceptorFn); 17514 parsedExpression = parsedExpression.$$intercepted; 17515 } 17516 17517 var useInputs = false;
17518 17519 var fn = function interceptedExpression(scope, locals, assign, inputs) { 17520 var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs); 17521 return interceptorFn(value); 17522 }; 17523 17524 // Maintain references to the interceptor/intercepted 17525 fn.$$intercepted = parsedExpression; 17526 fn.$$interceptor = interceptorFn; 17527 17528 // Propo
vendor: 24,161 bytes, lines 17528-18240
17528gate the literal/oneTime/constant attributes 17529 fn.literal = parsedExpression.literal; 17530 fn.oneTime = parsedExpression.oneTime; 17531 fn.constant = parsedExpression.constant; 17532 17533 // Treat the interceptor like filters. 17534 // If it is not $stateful then only watch its inputs. 17535 // If the expression itself has no inputs then use the full expression as an input. 17536 if (!interceptorFn.$stateful) { 17537 useInputs = !parsedExpression.inputs; 17538 fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression]; 17539 17540 if (!interceptorFn.$$pure) { 17541 fn.inputs = fn.inputs.map(function(e) { 17542 // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a 17543 // non-pure interceptor function. 17544 if (e.isPure === PURITY_RELATIVE) { 17545 return function depurifier(s) { return e(s); }; 17546 } 17547 return e; 17548 }); 17549 } 17550 } 17551 17552 return addWatchDelegate(fn); 17553 } 17554 }]; 17555} 17556 17557/** 17558 * @ngdoc service 17559 * @name $q 17560 * @requires $rootScope 17561 * 17562 * @description 17563 * A service that helps you run functions asynchronously, and use their return values (or exceptions) 17564 * when they are done processing. 17565 * 17566 * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred 17567 * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). 17568 * 17569 * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred 17570 * implementations, and the other which resembles ES6 (ES2015) promises to some degree. 17571 * 17572 * ## $q constructor 17573 * 17574 * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver` 17575 * function as the first argument. This is similar to the native Promise implementation from ES6, 17576 * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). 17577 * 17578 * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are 17579 * available yet. 17580 * 17581 * It can be used like so: 17582 * 17583 * ```js 17584 * // for the purpose of this example let's assume that variables `$q` and `okToGreet` 17585 * // are available in the current lexical scope (they could have been injected or passed in). 17586 * 17587 * function asyncGreet(name) { 17588 * // perform some asynchronous operation, resolve or reject the promise when appropriate. 17589 * return $q(function(resolve, reject) { 17590 * setTimeout(function() { 17591 * if (okToGreet(name)) { 17592 * resolve('Hello, ' + name + '!'); 17593 * } else { 17594 * reject('Greeting ' + name + ' is not allowed.'); 17595 * } 17596 * }, 1000); 17597 * }); 17598 * } 17599 * 17600 * var promise = asyncGreet('Robin Hood'); 17601 * promise.then(function(greeting) { 17602 * alert('Success: ' + greeting); 17603 * }, function(reason) { 17604 * alert('Failed: ' + reason); 17605 * }); 17606 * ``` 17607 * 17608 * Note: progress/notify callbacks are not currently supported via the ES6-style interface. 17609 * 17610 * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise. 17611 * 17612 * However, the more traditional CommonJS-style usage is still available, and documented below. 17613 * 17614 * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an 17615 * interface for interacting with an object that represents the result of an action that is 17616 * performed asynchronously, and may or may not be finished at any given point in time. 17617 * 17618 * From the perspective of dealing with error handling, deferred and promise APIs are to 17619 * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. 17620 * 17621 * ```js 17622 * // for the purpose of this example let's assume that variables `$q` and `okToGreet` 17623 * // are available in the current lexical scope (they could have been injected or passed in). 17624 * 17625 * function asyncGreet(name) { 17626 * var deferred = $q.defer(); 17627 * 17628 * setTimeout(function() { 17629 * deferred.notify('About to greet ' + name + '.'); 17630 * 17631 * if (okToGreet(name)) { 17632 * deferred.resolve('Hello, ' + name + '!'); 17633 * } else { 17634 * deferred.reject('Greeting ' + name + ' is not allowed.'); 17635 * } 17636 * }, 1000); 17637 * 17638 * return deferred.promise; 17639 * } 17640 * 17641 * var promise = asyncGreet('Robin Hood'); 17642 * promise.then(function(greeting) { 17643 * alert('Success: ' + greeting); 17644 * }, function(reason) { 17645 * alert('Failed: ' + reason); 17646 * }, function(update) { 17647 * alert('Got notification: ' + update); 17648 * }); 17649 * ``` 17650 * 17651 * At first it might not be obvious why this extra complexity is worth the trouble. The payoff 17652 * comes in the way of guarantees that promise and deferred APIs make, see 17653 * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. 17654 * 17655 * Additionally the promise api allows for composition that is very hard to do with the 17656 * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. 17657 * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the 17658 * section on serial or parallel joining of promises. 17659 * 17660 * ## The Deferred API 17661 * 17662 * A new instance of deferred is constructed by calling `$q.defer()`. 17663 * 17664 * The purpose of the deferred object is to expose the associated Promise instance as well as APIs 17665 * that can be used for signaling the successful or unsuccessful completion, as well as the status 17666 * of the task. 17667 * 17668 * **Methods** 17669 * 17670 * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection 17671 * constructed via `$q.reject`, the promise will be rejected instead. 17672 * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to 17673 * resolving it with a rejection constructed via `$q.reject`. 17674 * - `notify(value)` - provides updates on the status of the promise's execution. This may be called 17675 * multiple times before the promise is either resolved or rejected. 17676 * 17677 * **Properties** 17678 * 17679 * - promise – `{Promise}` – promise object associated with this deferred. 17680 * 17681 * 17682 * ## The Promise API 17683 * 17684 * A new promise instance is created when a deferred instance is created and can be retrieved by 17685 * calling `deferred.promise`. 17686 * 17687 * The purpose of the promise object is to allow for interested parties to get access to the result 17688 * of the deferred task when it completes. 17689 * 17690 * **Methods** 17691 * 17692 * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or 17693 * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously 17694 * as soon as the result is available. The callbacks are called with a single argument: the result 17695 * or rejection reason. Additionally, the notify callback may be called zero or more times to 17696 * provide a progress indication, before the promise is resolved or rejected. 17697 * 17698 * This method *returns a new promise* which is resolved or rejected via the return value of the 17699 * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved 17700 * with the value which is resolved in that promise using 17701 * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)). 17702 * It also notifies via the return value of the `notifyCallback` method. The promise cannot be 17703 * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback 17704 * arguments are optional. 17705 * 17706 * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` 17707 * 17708 * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise, 17709 * but to do so without modifying the final value. This is useful to release resources or do some 17710 * clean-up that needs to be done whether the promise was rejected or resolved. See the [full 17711 * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for 17712 * more information. 17713 * 17714 * ## Chaining promises 17715 * 17716 * Because calling the `then` method of a promise returns a new derived promise, it is easily 17717 * possible to create a chain of promises: 17718 * 17719 * ```js 17720 * promiseB = promiseA.then(function(result) { 17721 * return result + 1; 17722 * }); 17723 * 17724 * // promiseB will be resolved immediately after promiseA is resolved and its value 17725 * // will be the result of promiseA incremented by 1 17726 * ``` 17727 * 17728 * It is possible to create chains of any length and since a promise can be resolved with another 17729 * promise (which will defer its resolution further), it is possible to pause/defer resolution of 17730 * the promises at any point in the chain. This makes it possible to implement powerful APIs like 17731 * $http's response interceptors. 17732 * 17733 * 17734 * ## Differences between Kris Kowal's Q and $q 17735 * 17736 * There are two main differences: 17737 * 17738 * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation 17739 * mechanism in AngularJS, which means faster propagation of resolution or rejection into your 17740 * models and avoiding unnecessary browser repaints, which would result in flickering UI. 17741 * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains 17742 * all the important functionality needed for common async tasks. 17743 * 17744 * ## Testing 17745 * 17746 * ```js 17747 * it('should simulate promise', inject(function($q, $rootScope) { 17748 * var deferred = $q.defer(); 17749 * var promise = deferred.promise; 17750 * var resolvedValue; 17751 * 17752 * promise.then(function(value) { resolvedValue = value; }); 17753 * expect(resolvedValue).toBeUndefined(); 17754 * 17755 * // Simulate resolving of promise 17756 * deferred.resolve(123); 17757 * // Note that the 'then' function does not get called synchronously. 17758 * // This is because we want the promise API to always be async, whether or not 17759 * // it got called synchronously or asynchronously. 17760 * expect(resolvedValue).toBeUndefined(); 17761 * 17762 * // Propagate promise resolution to 'then' functions using $apply(). 17763 * $rootScope.$apply(); 17764 * expect(resolvedValue).toEqual(123); 17765 * })); 17766 * ``` 17767 * 17768 * @param {function(function, function)} resolver Function which is responsible for resolving or 17769 * rejecting the newly created promise. The first parameter is a function which resolves the 17770 * promise, the second parameter is a function which rejects the promise. 17771 * 17772 * @returns {Promise} The newly created promise. 17773 */ 17774/** 17775 * @ngdoc provider 17776 * @name $qProvider 17777 * @this 17778 * 17779 * @description 17780 */ 17781function $QProvider() { 17782 var errorOnUnhandledRejections = true; 17783 this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { 17784 return qFactory(function(callback) { 17785 $rootScope.$evalAsync(callback); 17786 }, $exceptionHandler, errorOnUnhandledRejections); 17787 }]; 17788 17789 /** 17790 * @ngdoc method 17791 * @name $qProvider#errorOnUnhandledRejections 17792 * @kind function 17793 * 17794 * @description 17795 * Retrieves or overrides whether to generate an error when a rejected promise is not handled. 17796 * This feature is enabled by default. 17797 * 17798 * @param {boolean=} value Whether to generate an error when a rejected promise is not handled. 17799 * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for 17800 * chaining otherwise. 17801 */ 17802 this.errorOnUnhandledRejections = function(value) { 17803 if (isDefined(value)) { 17804 errorOnUnhandledRejections = value; 17805 return this; 17806 } else { 17807 return errorOnUnhandledRejections; 17808 } 17809 }; 17810} 17811 17812/** @this */ 17813function $$QProvider() { 17814 var errorOnUnhandledRejections = true; 17815 this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) { 17816 return qFactory(function(callback) { 17817 $browser.defer(callback); 17818 }, $exceptionHandler, errorOnUnhandledRejections); 17819 }]; 17820 17821 this.errorOnUnhandledRejections = function(value) { 17822 if (isDefined(value)) { 17823 errorOnUnhandledRejections = value; 17824 return this; 17825 } else { 17826 return errorOnUnhandledRejections; 17827 } 17828 }; 17829} 17830 17831/** 17832 * Constructs a promise manager. 17833 * 17834 * @param {function(function)} nextTick Function for executing functions in the next turn. 17835 * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for 17836 * debugging purposes. 17837 * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled 17838 * promises rejections. 17839 * @returns {object} Promise manager. 17840 */ 17841function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) { 17842 var $qMinErr = minErr('$q', TypeError); 17843 var queueSize = 0; 17844 var checkQueue = []; 17845 17846 /** 17847 * @ngdoc method 17848 * @name ng.$q#defer 17849 * @kind function 17850 * 17851 * @description 17852 * Creates a `Deferred` object which represents a task which will finish in the future. 17853 * 17854 * @returns {Deferred} Returns a new instance of deferred. 17855 */ 17856 function defer() { 17857 return new Deferred(); 17858 } 17859 17860 function Deferred() { 17861 var promise = this.promise = new Promise(); 17862 //Non prototype methods necessary to support unbound execution :/ 17863 this.resolve = function(val) { resolvePromise(promise, val); }; 17864 this.reject = function(reason) { rejectPromise(promise, reason); }; 17865 this.notify = function(progress) { notifyPromise(promise, progress); }; 17866 } 17867 17868 17869 function Promise() { 17870 this.$$state = { status: 0 }; 17871 } 17872 17873 extend(Promise.prototype, { 17874 then: function(onFulfilled, onRejected, progressBack) { 17875 if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) { 17876 return this; 17877 } 17878 var result = new Promise(); 17879 17880 this.$$state.pending = this.$$state.pending || []; 17881 this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); 17882 if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); 17883 17884 return result; 17885 }, 17886 17887 'catch': function(callback) { 17888 return this.then(null, callback); 17889 }, 17890 17891 'finally': function(callback, progressBack) { 17892 return this.then(function(value) { 17893 return handleCallback(value, resolve, callback); 17894 }, function(error) { 17895 return handleCallback(error, reject, callback); 17896 }, progressBack); 17897 } 17898 }); 17899 17900 function processQueue(state) { 17901 var fn, promise, pending; 17902 17903 pending = state.pending; 17904 state.processScheduled = false; 17905 state.pending = undefined; 17906 try { 17907 for (var i = 0, ii = pending.length; i < ii; ++i) { 17908 markQStateExceptionHandled(state); 17909 promise = pending[i][0]; 17910 fn = pending[i][state.status]; 17911 try { 17912 if (isFunction(fn)) { 17913 resolvePromise(promise, fn(state.value)); 17914 } else if (state.status === 1) { 17915 resolvePromise(promise, state.value); 17916 } else { 17917 rejectPromise(promise, state.value); 17918 } 17919 } catch (e) { 17920 rejectPromise(promise, e); 17921 // This error is explicitly marked for being passed to the $exceptionHandler 17922 if (e && e.$$passToExceptionHandler === true) { 17923 exceptionHandler(e); 17924 } 17925 } 17926 } 17927 } finally { 17928 --queueSize; 17929 if (errorOnUnhandledRejections && queueSize === 0) { 17930 nextTick(processChecks); 17931 } 17932 } 17933 } 17934 17935 function processChecks() { 17936 // eslint-disable-next-line no-unmodified-loop-condition 17937 while (!queueSize && checkQueue.length) { 17938 var toCheck = checkQueue.shift(); 17939 if (!isStateExceptionHandled(toCheck)) { 17940 markQStateExceptionHandled(toCheck); 17941 var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value); 17942 if (isError(toCheck.value)) { 17943 exceptionHandler(toCheck.value, errorMessage); 17944 } else { 17945 exceptionHandler(errorMessage); 17946 } 17947 } 17948 } 17949 } 17950 17951 function scheduleProcessQueue(state) { 17952 if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) { 17953 if (queueSize === 0 && checkQueue.length === 0) { 17954 nextTick(processChecks); 17955 } 17956 checkQueue.push(state); 17957 } 17958 if (state.processScheduled || !state.pending) return; 17959 state.processScheduled = true; 17960 ++queueSize; 17961 nextTick(function() { processQueue(state); }); 17962 } 17963 17964 function resolvePromise(promise, val) { 17965 if (promise.$$state.status) return; 17966 if (val === promise) { 17967 $$reject(promise, $qMinErr( 17968 'qcycle', 17969 'Expected promise to be resolved with value other than itself \'{0}\'', 17970 val)); 17971 } else { 17972 $$resolve(promise, val); 17973 } 17974 17975 } 17976 17977 function $$resolve(promise, val) { 17978 var then; 17979 var done = false; 17980 try { 17981 if (isObject(val) || isFunction(val)) then = val.then; 17982 if (isFunction(then)) { 17983 promise.$$state.status = -1; 17984 then.call(val, doResolve, doReject, doNotify); 17985 } else { 17986 promise.$$state.value = val; 17987 promise.$$state.status = 1; 17988 scheduleProcessQueue(promise.$$state); 17989 } 17990 } catch (e) { 17991 doReject(e); 17992 } 17993 17994 function doResolve(val) { 17995 if (done) return; 17996 done = true; 17997 $$resolve(promise, val); 17998 } 17999 function doReject(val) { 18000 if (done) return; 18001 done = true; 18002 $$reject(promise, val); 18003 } 18004 function doNotify(progress) { 18005 notifyPromise(promise, progress); 18006 } 18007 } 18008 18009 function rejectPromise(promise, reason) { 18010 if (promise.$$state.status) return; 18011 $$reject(promise, reason); 18012 } 18013 18014 function $$reject(promise, reason) { 18015 promise.$$state.value = reason; 18016 promise.$$state.status = 2; 18017 scheduleProcessQueue(promise.$$state); 18018 } 18019 18020 function notifyPromise(promise, progress) { 18021 var callbacks = promise.$$state.pending; 18022 18023 if ((promise.$$state.status <= 0) && callbacks && callbacks.length) { 18024 nextTick(function() { 18025 var callback, result; 18026 for (var i = 0, ii = callbacks.length; i < ii; i++) { 18027 result = callbacks[i][0]; 18028 callback = callbacks[i][3]; 18029 try { 18030 notifyPromise(result, isFunction(callback) ? callback(progress) : progress); 18031 } catch (e) { 18032 exceptionHandler(e); 18033 } 18034 } 18035 }); 18036 } 18037 } 18038 18039 /** 18040 * @ngdoc method 18041 * @name $q#reject 18042 * @kind function 18043 * 18044 * @description 18045 * Creates a promise that is resolved as rejected with the specified `reason`. This api should be 18046 * used to forward rejection in a chain of promises. If you are dealing with the last promise in 18047 * a promise chain, you don't need to worry about it. 18048 * 18049 * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of 18050 * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via 18051 * a promise error callback and you want to forward the error to the promise derived from the 18052 * current promise, you have to "rethrow" the error by returning a rejection constructed via 18053 * `reject`. 18054 * 18055 * ```js 18056 * promiseB = promiseA.then(function(result) { 18057 * // success: do something and resolve promiseB 18058 * // with the old or a new result 18059 * return result; 18060 * }, function(reason) { 18061 * // error: handle the error if possible and 18062 * // resolve promiseB with newPromiseOrValue, 18063 * // otherwise forward the rejection to promiseB 18064 * if (canHandle(reason)) { 18065 * // handle the error and recover 18066 * return newPromiseOrValue; 18067 * } 18068 * return $q.reject(reason); 18069 * }); 18070 * ``` 18071 * 18072 * @param {*} reason Constant, message, exception or an object representing the rejection reason. 18073 * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. 18074 */ 18075 function reject(reason) { 18076 var result = new Promise(); 18077 rejectPromise(result, reason); 18078 return result; 18079 } 18080 18081 function handleCallback(value, resolver, callback) { 18082 var callbackOutput = null; 18083 try { 18084 if (isFunction(callback)) callbackOutput = callback(); 18085 } catch (e) { 18086 return reject(e); 18087 } 18088 if (isPromiseLike(callbackOutput)) { 18089 return callbackOutput.then(function() { 18090 return resolver(value); 18091 }, reject); 18092 } else { 18093 return resolver(value); 18094 } 18095 } 18096 18097 /** 18098 * @ngdoc method 18099 * @name $q#when 18100 * @kind function 18101 * 18102 * @description 18103 * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. 18104 * This is useful when you are dealing with an object that might or might not be a promise, or if 18105 * the promise comes from a source that can't be trusted. 18106 * 18107 * @param {*} value Value or a promise 18108 * @param {Function=} successCallback 18109 * @param {Function=} errorCallback 18110 * @param {Function=} progressCallback 18111 * @returns {Promise} Returns a promise of the passed value or promise 18112 */ 18113 18114 18115 function when(value, callback, errback, progressBack) { 18116 var result = new Promise(); 18117 resolvePromise(result, value); 18118 return result.then(callback, errback, progressBack); 18119 } 18120 18121 /** 18122 * @ngdoc method 18123 * @name $q#resolve 18124 * @kind function 18125 * 18126 * @description 18127 * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6. 18128 * 18129 * @param {*} value Value or a promise 18130 * @param {Function=} successCallback 18131 * @param {Function=} errorCallback 18132 * @param {Function=} progressCallback 18133 * @returns {Promise} Returns a promise of the passed value or promise 18134 */ 18135 var resolve = when; 18136 18137 /** 18138 * @ngdoc method 18139 * @name $q#all 18140 * @kind function 18141 * 18142 * @description 18143 * Combines multiple promises into a single promise that is resolved when all of the input 18144 * promises are resolved. 18145 * 18146 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. 18147 * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, 18148 * each value corresponding to the promise at the same index/key in the `promises` array/hash. 18149 * If any of the promises is resolved with a rejection, this resulting promise will be rejected 18150 * with the same rejection value. 18151 */ 18152 18153 function all(promises) { 18154 var result = new Promise(), 18155 counter = 0, 18156 results = isArray(promises) ? [] : {}; 18157 18158 forEach(promises, function(promise, key) { 18159 counter++; 18160 when(promise).then(function(value) { 18161 results[key] = value; 18162 if (!(--counter)) resolvePromise(result, results); 18163 }, function(reason) { 18164 rejectPromise(result, reason); 18165 }); 18166 }); 18167 18168 if (counter === 0) { 18169 resolvePromise(result, results); 18170 } 18171 18172 return result; 18173 } 18174 18175 /** 18176 * @ngdoc method 18177 * @name $q#race 18178 * @kind function 18179 * 18180 * @description 18181 * Returns a promise that resolves or rejects as soon as one of those promises 18182 * resolves or rejects, with the value or reason from that promise. 18183 * 18184 * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. 18185 * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises` 18186 * resolves or rejects, with the value or reason from that promise. 18187 */ 18188 18189 function race(promises) { 18190 var deferred = defer(); 18191 18192 forEach(promises, function(promise) { 18193 when(promise).then(deferred.resolve, deferred.reject); 18194 }); 18195 18196 return deferred.promise; 18197 } 18198 18199 function $Q(resolver) { 18200 if (!isFunction(resolver)) { 18201 throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver); 18202 } 18203 18204 var promise = new Promise(); 18205 18206 function resolveFn(value) { 18207 resolvePromise(promise, value); 18208 } 18209 18210 function rejectFn(reason) { 18211 rejectPromise(promise, reason); 18212 } 18213 18214 resolver(resolveFn, rejectFn); 18215 18216 return promise; 18217 } 18218 18219 // Let's make the instanceof operator work for promises, so that 18220 // `new $q(fn) instanceof $q` would evaluate to true. 18221 $Q.prototype = Promise.prototype; 18222 18223 $Q.defer = defer; 18224 $Q.reject = reject; 18225 $Q.when = when; 18226 $Q.resolve = resolve; 18227 $Q.all = all; 18228 $Q.race = race; 18229 18230 return $Q; 18231} 18232 18233function isStateExceptionHandled(state) { 18234 return !!state.pur; 18235} 18236function markQStateExceptionHandled(state) { 18237 state.pur = true; 18238} 18239function markQExceptionHandled(q) { 18240
18240markQStateExceptionHandled(q.$$state);
vendor: 61,593 bytes, lines 18240-19795
18240 18241} 18242 18243/** @this */ 18244function $$RAFProvider() { //rAF 18245 this.$get = ['$window', '$timeout', function($window, $timeout) { 18246 var requestAnimationFrame = $window.requestAnimationFrame || 18247 $window.webkitRequestAnimationFrame; 18248 18249 var cancelAnimationFrame = $window.cancelAnimationFrame || 18250 $window.webkitCancelAnimationFrame || 18251 $window.webkitCancelRequestAnimationFrame; 18252 18253 var rafSupported = !!requestAnimationFrame; 18254 var raf = rafSupported 18255 ? function(fn) { 18256 var id = requestAnimationFrame(fn); 18257 return function() { 18258 cancelAnimationFrame(id); 18259 }; 18260 } 18261 : function(fn) { 18262 var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 18263 return function() { 18264 $timeout.cancel(timer); 18265 }; 18266 }; 18267 18268 raf.supported = rafSupported; 18269 18270 return raf; 18271 }]; 18272} 18273 18274/** 18275 * DESIGN NOTES 18276 * 18277 * The design decisions behind the scope are heavily favored for speed and memory consumption. 18278 * 18279 * The typical use of scope is to watch the expressions, which most of the time return the same 18280 * value as last time so we optimize the operation. 18281 * 18282 * Closures construction is expensive in terms of speed as well as memory: 18283 * - No closures, instead use prototypical inheritance for API 18284 * - Internal state needs to be stored on scope directly, which means that private state is 18285 * exposed as $$____ properties 18286 * 18287 * Loop operations are optimized by using while(count--) { ... } 18288 * - This means that in order to keep the same order of execution as addition we have to add 18289 * items to the array at the beginning (unshift) instead of at the end (push) 18290 * 18291 * Child scopes are created and removed often 18292 * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists 18293 * 18294 * There are fewer watches than observers. This is why you don't want the observer to be implemented 18295 * in the same way as watch. Watch requires return of the initialization function which is expensive 18296 * to construct. 18297 */ 18298 18299 18300/** 18301 * @ngdoc provider 18302 * @name $rootScopeProvider 18303 * @description 18304 * 18305 * Provider for the $rootScope service. 18306 */ 18307 18308/** 18309 * @ngdoc method 18310 * @name $rootScopeProvider#digestTtl 18311 * @description 18312 * 18313 * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and 18314 * assuming that the model is unstable. 18315 * 18316 * The current default is 10 iterations. 18317 * 18318 * In complex applications it's possible that the dependencies between `$watch`s will result in 18319 * several digest iterations. However if an application needs more than the default 10 digest 18320 * iterations for its model to stabilize then you should investigate what is causing the model to 18321 * continuously change during the digest. 18322 * 18323 * Increasing the TTL could have performance implications, so you should not change it without 18324 * proper justification. 18325 * 18326 * @param {number} limit The number of digest iterations. 18327 */ 18328 18329 18330/** 18331 * @ngdoc service 18332 * @name $rootScope 18333 * @this 18334 * 18335 * @description 18336 * 18337 * Every application has a single root {@link ng.$rootScope.Scope scope}. 18338 * All other scopes are descendant scopes of the root scope. Scopes provide separation 18339 * between the model and the view, via a mechanism for watching the model for changes. 18340 * They also provide event emission/broadcast and subscription facility. See the 18341 * {@link guide/scope developer guide on scopes}. 18342 */ 18343function $RootScopeProvider() { 18344 var TTL = 10; 18345 var $rootScopeMinErr = minErr('$rootScope'); 18346 var lastDirtyWatch = null; 18347 var applyAsyncId = null; 18348 18349 this.digestTtl = function(value) { 18350 if (arguments.length) { 18351 TTL = value; 18352 } 18353 return TTL; 18354 }; 18355 18356 function createChildScopeClass(parent) { 18357 function ChildScope() { 18358 this.$$watchers = this.$$nextSibling = 18359 this.$$childHead = this.$$childTail = null; 18360 this.$$listeners = {}; 18361 this.$$listenerCount = {}; 18362 this.$$watchersCount = 0; 18363 this.$id = nextUid(); 18364 this.$$ChildScope = null; 18365 this.$$suspended = false; 18366 } 18367 ChildScope.prototype = parent; 18368 return ChildScope; 18369 } 18370 18371 this.$get = ['$exceptionHandler', '$parse', '$browser', 18372 function($exceptionHandler, $parse, $browser) { 18373 18374 function destroyChildScope($event) { 18375 $event.currentScope.$$destroyed = true; 18376 } 18377 18378 function cleanUpScope($scope) { 18379 18380 // Support: IE 9 only 18381 if (msie === 9) { 18382 // There is a memory leak in IE9 if all child scopes are not disconnected 18383 // completely when a scope is destroyed. So this code will recurse up through 18384 // all this scopes children 18385 // 18386 // See issue https://github.com/angular/angular.js/issues/10706 18387 if ($scope.$$childHead) { 18388 cleanUpScope($scope.$$childHead); 18389 } 18390 if ($scope.$$nextSibling) { 18391 cleanUpScope($scope.$$nextSibling); 18392 } 18393 } 18394 18395 // The code below works around IE9 and V8's memory leaks 18396 // 18397 // See: 18398 // - https://code.google.com/p/v8/issues/detail?id=2073#c26 18399 // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 18400 // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 18401 18402 $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead = 18403 $scope.$$childTail = $scope.$root = $scope.$$watchers = null; 18404 } 18405 18406 /** 18407 * @ngdoc type 18408 * @name $rootScope.Scope 18409 * 18410 * @description 18411 * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the 18412 * {@link auto.$injector $injector}. Child scopes are created using the 18413 * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when 18414 * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for 18415 * an in-depth introduction and usage examples. 18416 * 18417 * 18418 * ## Inheritance 18419 * A scope can inherit from a parent scope, as in this example: 18420 * ```js 18421 var parent = $rootScope; 18422 var child = parent.$new(); 18423 18424 parent.salutation = "Hello"; 18425 expect(child.salutation).toEqual('Hello'); 18426 18427 child.salutation = "Welcome"; 18428 expect(child.salutation).toEqual('Welcome'); 18429 expect(parent.salutation).toEqual('Hello'); 18430 * ``` 18431 * 18432 * When interacting with `Scope` in tests, additional helper methods are available on the 18433 * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional 18434 * details. 18435 * 18436 * 18437 * @param {Object.<string, function()>=} providers Map of service factory which need to be 18438 * provided for the current scope. Defaults to {@link ng}. 18439 * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should 18440 * append/override services provided by `providers`. This is handy 18441 * when unit-testing and having the need to override a default 18442 * service. 18443 * @returns {Object} Newly created scope. 18444 * 18445 */ 18446 function Scope() { 18447 this.$id = nextUid(); 18448 this.$$phase = this.$parent = this.$$watchers = 18449 this.$$nextSibling = this.$$prevSibling = 18450 this.$$childHead = this.$$childTail = null; 18451 this.$root = this; 18452 this.$$destroyed = false; 18453 this.$$suspended = false; 18454 this.$$listeners = {}; 18455 this.$$listenerCount = {}; 18456 this.$$watchersCount = 0; 18457 this.$$isolateBindings = null; 18458 } 18459 18460 /** 18461 * @ngdoc property 18462 * @name $rootScope.Scope#$id 18463 * 18464 * @description 18465 * Unique scope ID (monotonically increasing) useful for debugging. 18466 */ 18467 18468 /** 18469 * @ngdoc property 18470 * @name $rootScope.Scope#$parent 18471 * 18472 * @description 18473 * Reference to the parent scope. 18474 */ 18475 18476 /** 18477 * @ngdoc property 18478 * @name $rootScope.Scope#$root 18479 * 18480 * @description 18481 * Reference to the root scope. 18482 */ 18483 18484 Scope.prototype = { 18485 constructor: Scope, 18486 /** 18487 * @ngdoc method 18488 * @name $rootScope.Scope#$new 18489 * @kind function 18490 * 18491 * @description 18492 * Creates a new child {@link ng.$rootScope.Scope scope}. 18493 * 18494 * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. 18495 * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. 18496 * 18497 * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is 18498 * desired for the scope and its child scopes to be permanently detached from the parent and 18499 * thus stop participating in model change detection and listener notification by invoking. 18500 * 18501 * @param {boolean} isolate If true, then the scope does not prototypically inherit from the 18502 * parent scope. The scope is isolated, as it can not see parent scope properties. 18503 * When creating widgets, it is useful for the widget to not accidentally read parent 18504 * state. 18505 * 18506 * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` 18507 * of the newly created scope. Defaults to `this` scope if not provided. 18508 * This is used when creating a transclude scope to correctly place it 18509 * in the scope hierarchy while maintaining the correct prototypical 18510 * inheritance. 18511 * 18512 * @returns {Object} The newly created child scope. 18513 * 18514 */ 18515 $new: function(isolate, parent) { 18516 var child; 18517 18518 parent = parent || this; 18519 18520 if (isolate) { 18521 child = new Scope(); 18522 child.$root = this.$root; 18523 } else { 18524 // Only create a child scope class if somebody asks for one, 18525 // but cache it to allow the VM to optimize lookups. 18526 if (!this.$$ChildScope) { 18527 this.$$ChildScope = createChildScopeClass(this); 18528 } 18529 child = new this.$$ChildScope(); 18530 } 18531 child.$parent = parent; 18532 child.$$prevSibling = parent.$$childTail; 18533 if (parent.$$childHead) { 18534 parent.$$childTail.$$nextSibling = child; 18535 parent.$$childTail = child; 18536 } else { 18537 parent.$$childHead = parent.$$childTail = child; 18538 } 18539 18540 // When the new scope is not isolated or we inherit from `this`, and 18541 // the parent scope is destroyed, the property `$$destroyed` is inherited 18542 // prototypically. In all other cases, this property needs to be set 18543 // when the parent scope is destroyed. 18544 // The listener needs to be added after the parent is set 18545 if (isolate || parent !== this) child.$on('$destroy', destroyChildScope); 18546 18547 return child; 18548 }, 18549 18550 /** 18551 * @ngdoc method 18552 * @name $rootScope.Scope#$watch 18553 * @kind function 18554 * 18555 * @description 18556 * Registers a `listener` callback to be executed whenever the `watchExpression` changes. 18557 * 18558 * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest 18559 * $digest()} and should return the value that will be watched. (`watchExpression` should not change 18560 * its value when executed multiple times with the same input because it may be executed multiple 18561 * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be 18562 * [idempotent](http://en.wikipedia.org/wiki/Idempotence).) 18563 * - The `listener` is called only when the value from the current `watchExpression` and the 18564 * previous call to `watchExpression` are not equal (with the exception of the initial run, 18565 * see below). Inequality is determined according to reference inequality, 18566 * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) 18567 * via the `!==` Javascript operator, unless `objectEquality == true` 18568 * (see next point) 18569 * - When `objectEquality == true`, inequality of the `watchExpression` is determined 18570 * according to the {@link angular.equals} function. To save the value of the object for 18571 * later comparison, the {@link angular.copy} function is used. This therefore means that 18572 * watching complex objects will have adverse memory and performance implications. 18573 * - This should not be used to watch for changes in objects that are (or contain) 18574 * [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}. 18575 * - The watch `listener` may change the model, which may trigger other `listener`s to fire. 18576 * This is achieved by rerunning the watchers until no changes are detected. The rerun 18577 * iteration limit is 10 to prevent an infinite loop deadlock. 18578 * 18579 * 18580 * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, 18581 * you can register a `watchExpression` function with no `listener`. (Be prepared for 18582 * multiple calls to your `watchExpression` because it will execute multiple times in a 18583 * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.) 18584 * 18585 * After a watcher is registered with the scope, the `listener` fn is called asynchronously 18586 * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the 18587 * watcher. In rare cases, this is undesirable because the listener is called when the result 18588 * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you 18589 * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the 18590 * listener was called due to initialization. 18591 * 18592 * 18593 * 18594 * @example 18595 * ```js 18596 // let's assume that scope was dependency injected as the $rootScope 18597 var scope = $rootScope; 18598 scope.name = 'misko'; 18599 scope.counter = 0; 18600 18601 expect(scope.counter).toEqual(0); 18602 scope.$watch('name', function(newValue, oldValue) { 18603 scope.counter = scope.counter + 1; 18604 }); 18605 expect(scope.counter).toEqual(0); 18606 18607 scope.$digest(); 18608 // the listener is always called during the first $digest loop after it was registered 18609 expect(scope.counter).toEqual(1); 18610 18611 scope.$digest(); 18612 // but now it will not be called unless the value changes 18613 expect(scope.counter).toEqual(1); 18614 18615 scope.name = 'adam'; 18616 scope.$digest(); 18617 expect(scope.counter).toEqual(2); 18618 18619 18620 18621 // Using a function as a watchExpression 18622 var food; 18623 scope.foodCounter = 0; 18624 expect(scope.foodCounter).toEqual(0); 18625 scope.$watch( 18626 // This function returns the value being watched. It is called for each turn of the $digest loop 18627 function() { return food; }, 18628 // This is the change listener, called when the value returned from the above function changes 18629 function(newValue, oldValue) { 18630 if ( newValue !== oldValue ) { 18631 // Only increment the counter if the value changed 18632 scope.foodCounter = scope.foodCounter + 1; 18633 } 18634 } 18635 ); 18636 // No digest has been run so the counter will be zero 18637 expect(scope.foodCounter).toEqual(0); 18638 18639 // Run the digest but since food has not changed count will still be zero 18640 scope.$digest(); 18641 expect(scope.foodCounter).toEqual(0); 18642 18643 // Update food and run digest. Now the counter will increment 18644 food = 'cheeseburger'; 18645 scope.$digest(); 18646 expect(scope.foodCounter).toEqual(1); 18647 18648 * ``` 18649 * 18650 * 18651 * 18652 * @param {(function()|string)} watchExpression Expression that is evaluated on each 18653 * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers 18654 * a call to the `listener`. 18655 * 18656 * - `string`: Evaluated as {@link guide/expression expression} 18657 * - `function(scope)`: called with current `scope` as a parameter. 18658 * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value 18659 * of `watchExpression` changes. 18660 * 18661 * - `newVal` contains the current value of the `watchExpression` 18662 * - `oldVal` contains the previous value of the `watchExpression` 18663 * - `scope` refers to the current scope 18664 * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of 18665 * comparing for reference equality. 18666 * @returns {function()} Returns a deregistration function for this listener. 18667 */ 18668 $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) { 18669 var get = $parse(watchExp); 18670 var fn = isFunction(listener) ? listener : noop; 18671 18672 if (get.$$watchDelegate) { 18673 return get.$$watchDelegate(this, fn, objectEquality, get, watchExp); 18674 } 18675 var scope = this, 18676 array = scope.$$watchers, 18677 watcher = { 18678 fn: fn, 18679 last: initWatchVal, 18680 get: get, 18681 exp: prettyPrintExpression || watchExp, 18682 eq: !!objectEquality 18683 }; 18684 18685 lastDirtyWatch = null; 18686 18687 if (!array) { 18688 array = scope.$$watchers = []; 18689 array.$$digestWatchIndex = -1; 18690 } 18691 // we use unshift since we use a while loop in $digest for speed. 18692 // the while loop reads in reverse order. 18693 array.unshift(watcher); 18694 array.$$digestWatchIndex++; 18695 incrementWatchersCount(this, 1); 18696 18697 return function deregisterWatch() { 18698 var index = arrayRemove(array, watcher); 18699 if (index >= 0) { 18700 incrementWatchersCount(scope, -1); 18701 if (index < array.$$digestWatchIndex) { 18702 array.$$digestWatchIndex--; 18703 } 18704 } 18705 lastDirtyWatch = null; 18706 }; 18707 }, 18708 18709 /** 18710 * @ngdoc method 18711 * @name $rootScope.Scope#$watchGroup 18712 * @kind function 18713 * 18714 * @description 18715 * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. 18716 * If any one expression in the collection changes the `listener` is executed. 18717 * 18718 * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return 18719 * values are examined for changes on every call to `$digest`. 18720 * - The `listener` is called whenever any expression in the `watchExpressions` array changes. 18721 * 18722 * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually 18723 * watched using {@link ng.$rootScope.Scope#$watch $watch()} 18724 * 18725 * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any 18726 * expression in `watchExpressions` changes 18727 * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching 18728 * those of `watchExpression` 18729 * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching 18730 * those of `watchExpression` 18731 * The `scope` refers to the current scope. 18732 * @returns {function()} Returns a de-registration function for all listeners. 18733 */ 18734 $watchGroup: function(watchExpressions, listener) { 18735 var oldValues = new Array(watchExpressions.length); 18736 var newValues = new Array(watchExpressions.length); 18737 var deregisterFns = []; 18738 var self = this; 18739 var changeReactionScheduled = false; 18740 var firstRun = true; 18741 18742 if (!watchExpressions.length) { 18743 // No expressions means we call the listener ASAP 18744 var shouldCall = true; 18745 self.$evalAsync(function() { 18746 if (shouldCall) listener(newValues, newValues, self); 18747 }); 18748 return function deregisterWatchGroup() { 18749 shouldCall = false; 18750 }; 18751 } 18752 18753 if (watchExpressions.length === 1) { 18754 // Special case size of one 18755 return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) { 18756 newValues[0] = value; 18757 oldValues[0] = oldValue; 18758 listener(newValues, (value === oldValue) ? newValues : oldValues, scope); 18759 }); 18760 } 18761 18762 forEach(watchExpressions, function(expr, i) { 18763 var unwatchFn = self.$watch(expr, function watchGroupSubAction(value) { 18764 newValues[i] = value; 18765 if (!changeReactionScheduled) { 18766 changeReactionScheduled = true; 18767 self.$evalAsync(watchGroupAction); 18768 } 18769 }); 18770 deregisterFns.push(unwatchFn); 18771 }); 18772 18773 function watchGroupAction() { 18774 changeReactionScheduled = false; 18775 18776 try { 18777 if (firstRun) { 18778 firstRun = false; 18779 listener(newValues, newValues, self); 18780 } else { 18781 listener(newValues, oldValues, self); 18782 } 18783 } finally { 18784 for (var i = 0; i < watchExpressions.length; i++) { 18785 oldValues[i] = newValues[i]; 18786 } 18787 } 18788 } 18789 18790 return function deregisterWatchGroup() { 18791 while (deregisterFns.length) { 18792 deregisterFns.shift()(); 18793 } 18794 }; 18795 }, 18796 18797 18798 /** 18799 * @ngdoc method 18800 * @name $rootScope.Scope#$watchCollection 18801 * @kind function 18802 * 18803 * @description 18804 * Shallow watches the properties of an object and fires whenever any of the properties change 18805 * (for arrays, this implies watching the array items; for object maps, this implies watching 18806 * the properties). If a change is detected, the `listener` callback is fired. 18807 * 18808 * - The `obj` collection is observed via standard $watch operation and is examined on every 18809 * call to $digest() to see if any items have been added, removed, or moved. 18810 * - The `listener` is called whenever anything within the `obj` has changed. Examples include 18811 * adding, removing, and moving items belonging to an object or array. 18812 * 18813 * 18814 * @example 18815 * ```js 18816 $scope.names = ['igor', 'matias', 'misko', 'james']; 18817 $scope.dataCount = 4; 18818 18819 $scope.$watchCollection('names', function(newNames, oldNames) { 18820 $scope.dataCount = newNames.length; 18821 }); 18822 18823 expect($scope.dataCount).toEqual(4); 18824 $scope.$digest(); 18825 18826 //still at 4 ... no changes 18827 expect($scope.dataCount).toEqual(4); 18828 18829 $scope.names.pop(); 18830 $scope.$digest(); 18831 18832 //now there's been a change 18833 expect($scope.dataCount).toEqual(3); 18834 * ``` 18835 * 18836 * 18837 * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The 18838 * expression value should evaluate to an object or an array which is observed on each 18839 * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the 18840 * collection will trigger a call to the `listener`. 18841 * 18842 * @param {function(newCollection, oldCollection, scope)} listener a callback function called 18843 * when a change is detected. 18844 * - The `newCollection` object is the newly modified data obtained from the `obj` expression 18845 * - The `oldCollection` object is a copy of the former collection data. 18846 * Due to performance considerations, the`oldCollection` value is computed only if the 18847 * `listener` function declares two or more arguments. 18848 * - The `scope` argument refers to the current scope. 18849 * 18850 * @returns {function()} Returns a de-registration function for this listener. When the 18851 * de-registration function is executed, the internal watch operation is terminated. 18852 */ 18853 $watchCollection: function(obj, listener) { 18854 // Mark the interceptor as 18855 // ... $$pure when literal since the instance will change when any input changes 18856 $watchCollectionInterceptor.$$pure = $parse(obj).literal; 18857 // ... $stateful when non-literal since we must read the state of the collection 18858 $watchCollectionInterceptor.$stateful = !$watchCollectionInterceptor.$$pure; 18859 18860 var self = this; 18861 // the current value, updated on each dirty-check run 18862 var newValue; 18863 // a shallow copy of the newValue from the last dirty-check run, 18864 // updated to match newValue during dirty-check run 18865 var oldValue; 18866 // a shallow copy of the newValue from when the last change happened 18867 var veryOldValue; 18868 // only track veryOldValue if the listener is asking for it 18869 var trackVeryOldValue = (listener.length > 1); 18870 var changeDetected = 0; 18871 var changeDetector = $parse(obj, $watchCollectionInterceptor); 18872 var internalArray = []; 18873 var internalObject = {}; 18874 var initRun = true; 18875 var oldLength = 0; 18876 18877 function $watchCollectionInterceptor(_value) { 18878 newValue = _value; 18879 var newLength, key, bothNaN, newItem, oldItem; 18880 18881 // If the new value is undefined, then return undefined as the watch may be a one-time watch 18882 if (isUndefined(newValue)) return; 18883 18884 if (!isObject(newValue)) { // if primitive 18885 if (oldValue !== newValue) { 18886 oldValue = newValue; 18887 changeDetected++; 18888 } 18889 } else if (isArrayLike(newValue)) { 18890 if (oldValue !== internalArray) { 18891 // we are transitioning from something which was not an array into array. 18892 oldValue = internalArray; 18893 oldLength = oldValue.length = 0; 18894 changeDetected++; 18895 } 18896 18897 newLength = newValue.length; 18898 18899 if (oldLength !== newLength) { 18900 // if lengths do not match we need to trigger change notification 18901 changeDetected++; 18902 oldValue.length = oldLength = newLength; 18903 } 18904 // copy the items to oldValue and look for changes. 18905 for (var i = 0; i < newLength; i++) { 18906 oldItem = oldValue[i]; 18907 newItem = newValue[i]; 18908 18909 // eslint-disable-next-line no-self-compare 18910 bothNaN = (oldItem !== oldItem) && (newItem !== newItem); 18911 if (!bothNaN && (oldItem !== newItem)) { 18912 changeDetected++; 18913 oldValue[i] = newItem; 18914 } 18915 } 18916 } else { 18917 if (oldValue !== internalObject) { 18918 // we are transitioning from something which was not an object into object. 18919 oldValue = internalObject = {}; 18920 oldLength = 0; 18921 changeDetected++; 18922 } 18923 // copy the items to oldValue and look for changes. 18924 newLength = 0; 18925 for (key in newValue) { 18926 if (hasOwnProperty.call(newValue, key)) { 18927 newLength++; 18928 newItem = newValue[key]; 18929 oldItem = oldValue[key]; 18930 18931 if (key in oldValue) { 18932 // eslint-disable-next-line no-self-compare 18933 bothNaN = (oldItem !== oldItem) && (newItem !== newItem); 18934 if (!bothNaN && (oldItem !== newItem)) { 18935 changeDetected++; 18936 oldValue[key] = newItem; 18937 } 18938 } else { 18939 oldLength++; 18940 oldValue[key] = newItem; 18941 changeDetected++; 18942 } 18943 } 18944 } 18945 if (oldLength > newLength) { 18946 // we used to have more keys, need to find them and destroy them. 18947 changeDetected++; 18948 for (key in oldValue) { 18949 if (!hasOwnProperty.call(newValue, key)) { 18950 oldLength--; 18951 delete oldValue[key]; 18952 } 18953 } 18954 } 18955 } 18956 return changeDetected; 18957 } 18958 18959 function $watchCollectionAction() { 18960 if (initRun) { 18961 initRun = false; 18962 listener(newValue, newValue, self); 18963 } else { 18964 listener(newValue, veryOldValue, self); 18965 } 18966 18967 // make a copy for the next time a collection is changed 18968 if (trackVeryOldValue) { 18969 if (!isObject(newValue)) { 18970 //primitive 18971 veryOldValue = newValue; 18972 } else if (isArrayLike(newValue)) { 18973 veryOldValue = new Array(newValue.length); 18974 for (var i = 0; i < newValue.length; i++) { 18975 veryOldValue[i] = newValue[i]; 18976 } 18977 } else { // if object 18978 veryOldValue = {}; 18979 for (var key in newValue) { 18980 if (hasOwnProperty.call(newValue, key)) { 18981 veryOldValue[key] = newValue[key]; 18982 } 18983 } 18984 } 18985 } 18986 } 18987 18988 return this.$watch(changeDetector, $watchCollectionAction); 18989 }, 18990 18991 /** 18992 * @ngdoc method 18993 * @name $rootScope.Scope#$digest 18994 * @kind function 18995 * 18996 * @description 18997 * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and 18998 * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change 18999 * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} 19000 * until no more listeners are firing. This means that it is possible to get into an infinite 19001 * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of 19002 * iterations exceeds 10. 19003 * 19004 * Usually, you don't call `$digest()` directly in 19005 * {@link ng.directive:ngController controllers} or in 19006 * {@link ng.$compileProvider#directive directives}. 19007 * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within 19008 * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. 19009 * 19010 * If you want to be notified whenever `$digest()` is called, 19011 * you can register a `watchExpression` function with 19012 * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. 19013 * 19014 * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. 19015 * 19016 * @example 19017 * ```js 19018 var scope = ...; 19019 scope.name = 'misko'; 19020 scope.counter = 0; 19021 19022 expect(scope.counter).toEqual(0); 19023 scope.$watch('name', function(newValue, oldValue) { 19024 scope.counter = scope.counter + 1; 19025 }); 19026 expect(scope.counter).toEqual(0); 19027 19028 scope.$digest(); 19029 // the listener is always called during the first $digest loop after it was registered 19030 expect(scope.counter).toEqual(1); 19031 19032 scope.$digest(); 19033 // but now it will not be called unless the value changes 19034 expect(scope.counter).toEqual(1); 19035 19036 scope.name = 'adam'; 19037 scope.$digest(); 19038 expect(scope.counter).toEqual(2); 19039 * ``` 19040 * 19041 */ 19042 $digest: function() { 19043 var watch, value, last, fn, get, 19044 watchers, 19045 dirty, ttl = TTL, 19046 next, current, target = asyncQueue.length ? $rootScope : this, 19047 watchLog = [], 19048 logIdx, asyncTask; 19049 19050 beginPhase('$digest'); 19051 // Check for changes to browser url that happened in sync before the call to $digest 19052 $browser.$$checkUrlChange(); 19053 19054 if (this === $rootScope && applyAsyncId !== null) { 19055 // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then 19056 // cancel the scheduled $apply and flush the queue of expressions to be evaluated. 19057 $browser.defer.cancel(applyAsyncId); 19058 flushApplyAsync(); 19059 } 19060 19061 lastDirtyWatch = null; 19062 19063 do { // "while dirty" loop 19064 dirty = false; 19065 current = target; 19066 19067 // It's safe for asyncQueuePosition to be a local variable here because this loop can't 19068 // be reentered recursively. Calling $digest from a function passed to $evalAsync would 19069 // lead to a '$digest already in progress' error. 19070 for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) { 19071 try { 19072 asyncTask = asyncQueue[asyncQueuePosition]; 19073 fn = asyncTask.fn; 19074 fn(asyncTask.scope, asyncTask.locals); 19075 } catch (e) { 19076 $exceptionHandler(e); 19077 } 19078 lastDirtyWatch = null; 19079 } 19080 asyncQueue.length = 0; 19081 19082 traverseScopesLoop: 19083 do { // "traverse the scopes" loop 19084 if ((watchers = !current.$$suspended && current.$$watchers)) { 19085 // process our watches 19086 watchers.$$digestWatchIndex = watchers.length; 19087 while (watchers.$$digestWatchIndex--) { 19088 try { 19089 watch = watchers[watchers.$$digestWatchIndex]; 19090 // Most common watches are on primitives, in which case we can short 19091 // circuit it with === operator, only when === fails do we use .equals 19092 if (watch) { 19093 get = watch.get; 19094 if ((value = get(current)) !== (last = watch.last) && 19095 !(watch.eq 19096 ? equals(value, last) 19097 : (isNumberNaN(value) && isNumberNaN(last)))) { 19098 dirty = true; 19099 lastDirtyWatch = watch; 19100 watch.last = watch.eq ? copy(value, null) : value; 19101 fn = watch.fn; 19102 fn(value, ((last === initWatchVal) ? value : last), current); 19103 if (ttl < 5) { 19104 logIdx = 4 - ttl; 19105 if (!watchLog[logIdx]) watchLog[logIdx] = []; 19106 watchLog[logIdx].push({ 19107 msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp, 19108 newVal: value, 19109 oldVal: last 19110 }); 19111 } 19112 } else if (watch === lastDirtyWatch) { 19113 // If the most recently dirty watcher is now clean, short circuit since the remaining watchers 19114 // have already been tested. 19115 dirty = false; 19116 break traverseScopesLoop; 19117 } 19118 } 19119 } catch (e) { 19120 $exceptionHandler(e); 19121 } 19122 } 19123 } 19124 19125 // Insanity Warning: scope depth-first traversal 19126 // yes, this code is a bit crazy, but it works and we have tests to prove it! 19127 // this piece should be kept in sync with the traversal in $broadcast 19128 // (though it differs due to having the extra check for $$suspended and does not 19129 // check $$listenerCount) 19130 if (!(next = ((!current.$$suspended && current.$$watchersCount && current.$$childHead) || 19131 (current !== target && current.$$nextSibling)))) { 19132 while (current !== target && !(next = current.$$nextSibling)) { 19133 current = current.$parent; 19134 } 19135 } 19136 } while ((current = next)); 19137 19138 // `break traverseScopesLoop;` takes us to here 19139 19140 if ((dirty || asyncQueue.length) && !(ttl--)) { 19141 clearPhase(); 19142 throw $rootScopeMinErr('infdig', 19143 '{0} $digest() iterations reached. Aborting!\n' + 19144 'Watchers fired in the last 5 iterations: {1}', 19145 TTL, watchLog); 19146 } 19147 19148 } while (dirty || asyncQueue.length); 19149 19150 clearPhase(); 19151 19152 // postDigestQueuePosition isn't local here because this loop can be reentered recursively. 19153 while (postDigestQueuePosition < postDigestQueue.length) { 19154 try { 19155 postDigestQueue[postDigestQueuePosition++](); 19156 } catch (e) { 19157 $exceptionHandler(e); 19158 } 19159 } 19160 postDigestQueue.length = postDigestQueuePosition = 0; 19161 19162 // Check for changes to browser url that happened during the $digest 19163 // (for which no event is fired; e.g. via `history.pushState()`) 19164 $browser.$$checkUrlChange(); 19165 }, 19166 19167 /** 19168 * @ngdoc method 19169 * @name $rootScope.Scope#$suspend 19170 * @kind function 19171 * 19172 * @description 19173 * Suspend watchers of this scope subtree so that they will not be invoked during digest. 19174 * 19175 * This can be used to optimize your application when you know that running those watchers 19176 * is redundant. 19177 * 19178 * **Warning** 19179 * 19180 * Suspending scopes from the digest cycle can have unwanted and difficult to debug results. 19181 * Only use this approach if you are confident that you know what you are doing and have 19182 * ample tests to ensure that bindings get updated as you expect. 19183 * 19184 * Some of the things to consider are: 19185 * 19186 * * Any external event on a directive/component will not trigger a digest while the hosting 19187 * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`. 19188 * * Transcluded content exists on a scope that inherits from outside a directive but exists 19189 * as a child of the directive's containing scope. If the containing scope is suspended the 19190 * transcluded scope will also be suspended, even if the scope from which the transcluded 19191 * scope inherits is not suspended. 19192 * * Multiple directives trying to manage the suspended status of a scope can confuse each other: 19193 * * A call to `$suspend()` on an already suspended scope is a no-op. 19194 * * A call to `$resume()` on a non-suspended scope is a no-op. 19195 * * If two directives suspend a scope, then one of them resumes the scope, the scope will no 19196 * longer be suspended. This could result in the other directive believing a scope to be 19197 * suspended when it is not. 19198 * * If a parent scope is suspended then all its descendants will be also excluded from future 19199 * digests whether or not they have been suspended themselves. Note that this also applies to 19200 * isolate child scopes. 19201 * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers 19202 * for that scope and its descendants. When digesting we only check whether the current scope is 19203 * locally suspended, rather than checking whether it has a suspended ancestor. 19204 * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be 19205 * included in future digests until all its ancestors have been resumed. 19206 * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()` 19207 * against the `$rootScope` and so will still trigger a global digest even if the promise was 19208 * initiated by a component that lives on a suspended scope. 19209 */ 19210 $suspend: function() { 19211 this.$$suspended = true; 19212 }, 19213 19214 /** 19215 * @ngdoc method 19216 * @name $rootScope.Scope#$isSuspended 19217 * @kind function 19218 * 19219 * @description 19220 * Call this method to determine if this scope has been explicitly suspended. It will not 19221 * tell you whether an ancestor has been suspended. 19222 * To determine if this scope will be excluded from a digest triggered at the $rootScope, 19223 * for example, you must check all its ancestors: 19224 * 19225 * ``` 19226 * function isExcludedFromDigest(scope) { 19227 * while(scope) { 19228 * if (scope.$isSuspended()) return true; 19229 * scope = scope.$parent; 19230 * } 19231 * return false; 19232 * ``` 19233 * 19234 * Be aware that a scope may not be included in digests if it has a suspended ancestor, 19235 * even if `$isSuspended()` returns false. 19236 * 19237 * @returns true if the current scope has been suspended. 19238 */ 19239 $isSuspended: function() { 19240 return this.$$suspended; 19241 }, 19242 19243 /** 19244 * @ngdoc method 19245 * @name $rootScope.Scope#$resume 19246 * @kind function 19247 * 19248 * @description 19249 * Resume watchers of this scope subtree in case it was suspended. 19250 * 19251 * See {@link $rootScope.Scope#$suspend} for information about the dangers of using this approach. 19252 */ 19253 $resume: function() { 19254 this.$$suspended = false; 19255 }, 19256 19257 /** 19258 * @ngdoc event 19259 * @name $rootScope.Scope#$destroy 19260 * @eventType broadcast on scope being destroyed 19261 * 19262 * @description 19263 * Broadcasted when a scope and its children are being destroyed. 19264 * 19265 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to 19266 * clean up DOM bindings before an element is removed from the DOM. 19267 */ 19268 19269 /** 19270 * @ngdoc method 19271 * @name $rootScope.Scope#$destroy 19272 * @kind function 19273 * 19274 * @description 19275 * Removes the current scope (and all of its children) from the parent scope. Removal implies 19276 * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer 19277 * propagate to the current scope and its children. Removal also implies that the current 19278 * scope is eligible for garbage collection. 19279 * 19280 * The `$destroy()` is usually used by directives such as 19281 * {@link ng.directive:ngRepeat ngRepeat} for managing the 19282 * unrolling of the loop. 19283 * 19284 * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. 19285 * Application code can register a `$destroy` event handler that will give it a chance to 19286 * perform any necessary cleanup. 19287 * 19288 * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to 19289 * clean up DOM bindings before an element is removed from the DOM. 19290 */ 19291 $destroy: function() { 19292 // We can't destroy a scope that has been already destroyed. 19293 if (this.$$destroyed) return; 19294 var parent = this.$parent; 19295 19296 this.$broadcast('$destroy'); 19297 this.$$destroyed = true; 19298 19299 if (this === $rootScope) { 19300 //Remove handlers attached to window when $rootScope is removed 19301 $browser.$$applicationDestroyed(); 19302 } 19303 19304 incrementWatchersCount(this, -this.$$watchersCount); 19305 for (var eventName in this.$$listenerCount) { 19306 decrementListenerCount(this, this.$$listenerCount[eventName], eventName); 19307 } 19308 19309 // sever all the references to parent scopes (after this cleanup, the current scope should 19310 // not be retained by any of our references and should be eligible for garbage collection) 19311 if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling; 19312 if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling; 19313 if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; 19314 if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; 19315 19316 // Disable listeners, watchers and apply/digest methods 19317 this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; 19318 this.$on = this.$watch = this.$watchGroup = function() { return noop; }; 19319 this.$$listeners = {}; 19320 19321 // Disconnect the next sibling to prevent `cleanUpScope` destroying those too 19322 this.$$nextSibling = null; 19323 cleanUpScope(this); 19324 }, 19325 19326 /** 19327 * @ngdoc method 19328 * @name $rootScope.Scope#$eval 19329 * @kind function 19330 * 19331 * @description 19332 * Executes the `expression` on the current scope and returns the result. Any exceptions in 19333 * the expression are propagated (uncaught). This is useful when evaluating AngularJS 19334 * expressions. 19335 * 19336 * @example 19337 * ```js 19338 var scope = ng.$rootScope.Scope(); 19339 scope.a = 1; 19340 scope.b = 2; 19341 19342 expect(scope.$eval('a+b')).toEqual(3); 19343 expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); 19344 * ``` 19345 * 19346 * @param {(string|function())=} expression An AngularJS expression to be executed. 19347 * 19348 * - `string`: execute using the rules as defined in {@link guide/expression expression}. 19349 * - `function(scope)`: execute the function with the current `scope` parameter. 19350 * 19351 * @param {(object)=} locals Local variables object, useful for overriding values in scope. 19352 * @returns {*} The result of evaluating the expression. 19353 */ 19354 $eval: function(expr, locals) { 19355 return $parse(expr)(this, locals); 19356 }, 19357 19358 /** 19359 * @ngdoc method 19360 * @name $rootScope.Scope#$evalAsync 19361 * @kind function 19362 * 19363 * @description 19364 * Executes the expression on the current scope at a later point in time. 19365 * 19366 * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only 19367 * that: 19368 * 19369 * - it will execute after the function that scheduled the evaluation (preferably before DOM 19370 * rendering). 19371 * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after 19372 * `expression` execution. 19373 * 19374 * Any exceptions from the execution of the expression are forwarded to the 19375 * {@link ng.$exceptionHandler $exceptionHandler} service. 19376 * 19377 * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle 19378 * will be scheduled. However, it is encouraged to always call code that changes the model 19379 * from within an `$apply` call. That includes code evaluated via `$evalAsync`. 19380 * 19381 * @param {(string|function())=} expression An AngularJS expression to be executed. 19382 * 19383 * - `string`: execute using the rules as defined in {@link guide/expression expression}. 19384 * - `function(scope)`: execute the function with the current `scope` parameter. 19385 * 19386 * @param {(object)=} locals Local variables object, useful for overriding values in scope. 19387 */ 19388 $evalAsync: function(expr, locals) { 19389 // if we are outside of an $digest loop and this is the first time we are scheduling async 19390 // task also schedule async auto-flush 19391 if (!$rootScope.$$phase && !asyncQueue.length) { 19392 $browser.defer(function() { 19393 if (asyncQueue.length) { 19394 $rootScope.$digest(); 19395 } 19396 }, null, '$evalAsync'); 19397 } 19398 19399 asyncQueue.push({scope: this, fn: $parse(expr), locals: locals}); 19400 }, 19401 19402 $$postDigest: function(fn) { 19403 postDigestQueue.push(fn); 19404 }, 19405 19406 /** 19407 * @ngdoc method 19408 * @name $rootScope.Scope#$apply 19409 * @kind function 19410 * 19411 * @description 19412 * `$apply()` is used to execute an expression in AngularJS from outside of the AngularJS 19413 * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). 19414 * Because we are calling into the AngularJS framework we need to perform proper scope life 19415 * cycle of {@link ng.$exceptionHandler exception handling}, 19416 * {@link ng.$rootScope.Scope#$digest executing watches}. 19417 * 19418 * **Life cycle: Pseudo-Code of `$apply()`** 19419 * 19420 * ```js 19421 function $apply(expr) { 19422 try { 19423 return $eval(expr); 19424 } catch (e) { 19425 $exceptionHandler(e); 19426 } finally { 19427 $root.$digest(); 19428 } 19429 } 19430 * ``` 19431 * 19432 * 19433 * Scope's `$apply()` method transitions through the following stages: 19434 * 19435 * 1. The {@link guide/expression expression} is executed using the 19436 * {@link ng.$rootScope.Scope#$eval $eval()} method. 19437 * 2. Any exceptions from the execution of the expression are forwarded to the 19438 * {@link ng.$exceptionHandler $exceptionHandler} service. 19439 * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the 19440 * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. 19441 * 19442 * 19443 * @param {(string|function())=} exp An AngularJS expression to be executed. 19444 * 19445 * - `string`: execute using the rules as defined in {@link guide/expression expression}. 19446 * - `function(scope)`: execute the function with current `scope` parameter. 19447 * 19448 * @returns {*} The result of evaluating the expression. 19449 */ 19450 $apply: function(expr) { 19451 try { 19452 beginPhase('$apply'); 19453 try { 19454 return this.$eval(expr); 19455 } finally { 19456 clearPhase(); 19457 } 19458 } catch (e) { 19459 $exceptionHandler(e); 19460 } finally { 19461 try { 19462 $rootScope.$digest(); 19463 } catch (e) { 19464 $exceptionHandler(e); 19465 // eslint-disable-next-line no-unsafe-finally 19466 throw e; 19467 } 19468 } 19469 }, 19470 19471 /** 19472 * @ngdoc method 19473 * @name $rootScope.Scope#$applyAsync 19474 * @kind function 19475 * 19476 * @description 19477 * Schedule the invocation of $apply to occur at a later time. The actual time difference 19478 * varies across browsers, but is typically around ~10 milliseconds. 19479 * 19480 * This can be used to queue up multiple expressions which need to be evaluated in the same 19481 * digest. 19482 * 19483 * @param {(string|function())=} exp An AngularJS expression to be executed. 19484 * 19485 * - `string`: execute using the rules as defined in {@link guide/expression expression}. 19486 * - `function(scope)`: execute the function with current `scope` parameter. 19487 */ 19488 $applyAsync: function(expr) { 19489 var scope = this; 19490 if (expr) { 19491 applyAsyncQueue.push($applyAsyncExpression); 19492 } 19493 expr = $parse(expr); 19494 scheduleApplyAsync(); 19495 19496 function $applyAsyncExpression() { 19497 scope.$eval(expr); 19498 } 19499 }, 19500 19501 /** 19502 * @ngdoc method 19503 * @name $rootScope.Scope#$on 19504 * @kind function 19505 * 19506 * @description 19507 * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for 19508 * discussion of event life cycle. 19509 * 19510 * The event listener function format is: `function(event, args...)`. The `event` object 19511 * passed into the listener has the following attributes: 19512 * 19513 * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or 19514 * `$broadcast`-ed. 19515 * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the 19516 * event propagates through the scope hierarchy, this property is set to null. 19517 * - `name` - `{string}`: name of the event. 19518 * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel 19519 * further event propagation (available only for events that were `$emit`-ed). 19520 * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag 19521 * to true. 19522 * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. 19523 * 19524 * @param {string} name Event name to listen on. 19525 * @param {function(event, ...args)} listener Function to call when the event is emitted. 19526 * @returns {function()} Returns a deregistration function for this listener. 19527 */ 19528 $on: function(name, listener) { 19529 var namedListeners = this.$$listeners[name]; 19530 if (!namedListeners) { 19531 this.$$listeners[name] = namedListeners = []; 19532 } 19533 namedListeners.push(listener); 19534 19535 var current = this; 19536 do { 19537 if (!current.$$listenerCount[name]) { 19538 current.$$listenerCount[name] = 0; 19539 } 19540 current.$$listenerCount[name]++; 19541 } while ((current = current.$parent)); 19542 19543 var self = this; 19544 return function() { 19545 var indexOfListener = namedListeners.indexOf(listener); 19546 if (indexOfListener !== -1) { 19547 // Use delete in the hope of the browser deallocating the memory for the array entry, 19548 // while not shifting the array indexes of other listeners. 19549 // See issue https://github.com/angular/angular.js/issues/16135 19550 delete namedListeners[indexOfListener]; 19551 decrementListenerCount(self, 1, name); 19552 } 19553 }; 19554 }, 19555 19556 19557 /** 19558 * @ngdoc method 19559 * @name $rootScope.Scope#$emit 19560 * @kind function 19561 * 19562 * @description 19563 * Dispatches an event `name` upwards through the scope hierarchy notifying the 19564 * registered {@link ng.$rootScope.Scope#$on} listeners. 19565 * 19566 * The event life cycle starts at the scope on which `$emit` was called. All 19567 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get 19568 * notified. Afterwards, the event traverses upwards toward the root scope and calls all 19569 * registered listeners along the way. The event will stop propagating if one of the listeners 19570 * cancels it. 19571 * 19572 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed 19573 * onto the {@link ng.$exceptionHandler $exceptionHandler} service. 19574 * 19575 * @param {string} name Event name to emit. 19576 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. 19577 * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). 19578 */ 19579 $emit: function(name, args) { 19580 var empty = [], 19581 namedListeners, 19582 scope = this, 19583 stopPropagation = false, 19584 event = { 19585 name: name, 19586 targetScope: scope, 19587 stopPropagation: function() {stopPropagation = true;}, 19588 preventDefault: function() { 19589 event.defaultPrevented = true; 19590 }, 19591 defaultPrevented: false 19592 }, 19593 listenerArgs = concat([event], arguments, 1), 19594 i, length; 19595 19596 do { 19597 namedListeners = scope.$$listeners[name] || empty; 19598 event.currentScope = scope; 19599 for (i = 0, length = namedListeners.length; i < length; i++) { 19600 19601 // if listeners were deregistered, defragment the array 19602 if (!namedListeners[i]) { 19603 namedListeners.splice(i, 1); 19604 i--; 19605 length--; 19606 continue; 19607 } 19608 try { 19609 //allow all listeners attached to the current scope to run 19610 namedListeners[i].apply(null, listenerArgs); 19611 } catch (e) { 19612 $exceptionHandler(e); 19613 } 19614 } 19615 //if any listener on the current scope stops propagation, prevent bubbling 19616 if (stopPropagation) { 19617 break; 19618 } 19619 //traverse upwards 19620 scope = scope.$parent; 19621 } while (scope); 19622 19623 event.currentScope = null; 19624 19625 return event; 19626 }, 19627 19628 19629 /** 19630 * @ngdoc method 19631 * @name $rootScope.Scope#$broadcast 19632 * @kind function 19633 * 19634 * @description 19635 * Dispatches an event `name` downwards to all child scopes (and their children) notifying the 19636 * registered {@link ng.$rootScope.Scope#$on} listeners. 19637 * 19638 * The event life cycle starts at the scope on which `$broadcast` was called. All 19639 * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get 19640 * notified. Afterwards, the event propagates to all direct and indirect scopes of the current 19641 * scope and calls all registered listeners along the way. The event cannot be canceled. 19642 * 19643 * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed 19644 * onto the {@link ng.$exceptionHandler $exceptionHandler} service. 19645 * 19646 * @param {string} name Event name to broadcast. 19647 * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. 19648 * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} 19649 */ 19650 $broadcast: function(name, args) { 19651 var target = this, 19652 current = target, 19653 next = target, 19654 event = { 19655 name: name, 19656 targetScope: target, 19657 preventDefault: function() { 19658 event.defaultPrevented = true; 19659 }, 19660 defaultPrevented: false 19661 }; 19662 19663 if (!target.$$listenerCount[name]) return event; 19664 19665 var listenerArgs = concat([event], arguments, 1), 19666 listeners, i, length; 19667 19668 //down while you can, then up and next sibling or up and next sibling until back at root 19669 while ((current = next)) { 19670 event.currentScope = current; 19671 listeners = current.$$listeners[name] || []; 19672 for (i = 0, length = listeners.length; i < length; i++) { 19673 // if listeners were deregistered, defragment the array 19674 if (!listeners[i]) { 19675 listeners.splice(i, 1); 19676 i--; 19677 length--; 19678 continue; 19679 } 19680 19681 try { 19682 listeners[i].apply(null, listenerArgs); 19683 } catch (e) { 19684 $exceptionHandler(e); 19685 } 19686 } 19687 19688 // Insanity Warning: scope depth-first traversal 19689 // yes, this code is a bit crazy, but it works and we have tests to prove it! 19690 // this piece should be kept in sync with the traversal in $digest 19691 // (though it differs due to having the extra check for $$listenerCount and 19692 // does not check $$suspended) 19693 if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || 19694 (current !== target && current.$$nextSibling)))) { 19695 while (current !== target && !(next = current.$$nextSibling)) { 19696 current = current.$parent; 19697 } 19698 } 19699 } 19700 19701 event.currentScope = null; 19702 return event; 19703 } 19704 }; 19705 19706 var $rootScope = new Scope(); 19707 19708 //The internal queues. Expose them on the $rootScope for debugging/testing purposes. 19709 var asyncQueue = $rootScope.$$asyncQueue = []; 19710 var postDigestQueue = $rootScope.$$postDigestQueue = []; 19711 var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; 19712 19713 var postDigestQueuePosition = 0; 19714 19715 return $rootScope; 19716 19717 19718 function beginPhase(phase) { 19719 if ($rootScope.$$phase) { 19720 throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); 19721 } 19722 19723 $rootScope.$$phase = phase; 19724 } 19725 19726 function clearPhase() { 19727 $rootScope.$$phase = null; 19728 } 19729 19730 function incrementWatchersCount(current, count) { 19731 do { 19732 current.$$watchersCount += count; 19733 } while ((current = current.$parent)); 19734 } 19735 19736 function decrementListenerCount(current, count, name) { 19737 do { 19738 current.$$listenerCount[name] -= count; 19739 19740 if (current.$$listenerCount[name] === 0) { 19741 delete current.$$listenerCount[name]; 19742 } 19743 } while ((current = current.$parent)); 19744 } 19745 19746 /** 19747 * function used as an initial value for watchers. 19748 * because it's unique we can easily tell it apart from other values 19749 */ 19750 function initWatchVal() {} 19751 19752 function flushApplyAsync() { 19753 while (applyAsyncQueue.length) { 19754 try { 19755 applyAsyncQueue.shift()(); 19756 } catch (e) { 19757 $exceptionHandler(e); 19758 } 19759 } 19760 applyAsyncId = null; 19761 } 19762 19763 function scheduleApplyAsync() { 19764 if (applyAsyncId === null) { 19765 applyAsyncId = $browser.defer(function() { 19766 $rootScope.$apply(flushApplyAsync); 19767 }, null, '$applyAsync'); 19768 } 19769 } 19770 }]; 19771} 19772 19773/** 19774 * @ngdoc service 19775 * @name $rootElement 19776 * 19777 * @description 19778 * The root element of AngularJS application. This is either the element where {@link 19779 * ng.directive:ngApp ngApp} was declared or the element passed into 19780 * {@link angular.bootstrap}. The element represents the root element of application. It is also the 19781 * location where the application's {@link auto.$injector $injector} service gets 19782 * published, and can be retrieved using `$rootElement.injector()`. 19783 */ 19784 19785 19786// the implementation is in angular.bootstrap 19787 19788/** 19789 * @this 19790 * @description 19791 * Private service to sanitize uris for links and images. Used by $compile and $sanitize. 19792 */ 19793function $$SanitizeUriProvider() { 19794 19795 var aHrefSanitization
19795Whitelist = /^\s*(https?|s?ftp|mailto|tel|file):/, 19796 imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/; 19797 19798 /** 19799 * @description 19800 * Retrieves or overrides the default regular expression that is used for whitelisting of safe 19801 * urls during a[href] sanitization. 19802 * 19803 * The sanitization is a security measure aimed at prevent XSS attacks via HTML anchor links. 19804 * 19805 * Any url due to be assigned to an `a[href]` attribute via interpolation is marked as requiring 19806 * the $sce.URL security context. When interpolation occurs a call is made to `$sce.trustAsUrl(url)` 19807 * which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize the potentially malicious URL. 19808 * 19809 * If the URL matches the `aHrefSanitizationWhitelist` regular expression, it is returned unchanged. 19810 * 19811 * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written 19812 * to the DOM it is inactive and potentially malicious code will not be executed. 19813 * 19814 * @param {RegExp=} regexp New regexp to whitelist urls with. 19815 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for 19816 * chaining otherwise. 19817 */ 19818 this.aHrefSanitizationWhitelist = function(regexp) { 19819 if (isDefined(regexp)) { 19820 aHrefSanitizationWhitelist = regexp; 19821 return this; 19822 } 19823 return aHrefSanitizationWhitelist; 19824 }; 19825 19826 19827 /** 19828 * @description 19829 * Retrieves or overrides the default regular expression that is used for whitelisting of safe 19830 * urls during img[src] sanitization. 19831 * 19832 * The sanitization is a security measure aimed at prevent XSS attacks via HTML image src links. 19833 * 19834 * Any URL due to be assigned to an `img[src]` attribute via interpolation is marked as requiring 19835 * the $sce.MEDIA_URL security context. When interpolation occurs a call is made to 19836 * `$sce.trustAsMediaUrl(url)` which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize 19837 * the potentially malicious URL. 19838 * 19839 * If the URL matches the `aImgSanitizationWhitelist` regular expression, it is returned unchanged. 19840 * 19841 * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written 19842 * to the DOM it is inactive and potentially malicious code will not be executed. 19843 * 19844 * @param {RegExp=} regexp New regexp to whitelist urls with. 19845 * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for 19846 * chaining otherwise. 19847 */ 19848 this.imgSrcSanitizationWhitelist = function(regexp) { 19849 if (isDefined(regexp)) { 19850 imgSrcSanitizationWhitelist = regexp; 19851 return this; 19852 } 19853 return imgSrcSanitizationWhitelist; 19854 }; 19855 19856 this.$get = function() { 19857 return function sanitizeUri(uri, isMediaUrl) { 19858 // if (!uri) return uri; 19859 var regex = isMediaUrl ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitel
vendor: 5,203 bytes, lines 19859-19987
19859ist; 19860 var normalizedVal = urlResolve(uri && uri.trim()).href; 19861 if (normalizedVal !== '' && !normalizedVal.match(regex)) { 19862 return 'unsafe:' + normalizedVal; 19863 } 19864 return uri; 19865 }; 19866 }; 19867} 19868 19869/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 19870 * Any commits to this file should be reviewed with security in mind. * 19871 * Changes to this file can potentially create security vulnerabilities. * 19872 * An approval from 2 Core members with history of modifying * 19873 * this file is required. * 19874 * * 19875 * Does the change somehow allow for arbitrary javascript to be executed? * 19876 * Or allows for someone to change the prototype of built-in objects? * 19877 * Or gives undesired access to variables likes document or window? * 19878 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ 19879 19880/* exported $SceProvider, $SceDelegateProvider */ 19881 19882var $sceMinErr = minErr('$sce'); 19883 19884var SCE_CONTEXTS = { 19885 // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding). 19886 HTML: 'html', 19887 19888 // Style statements or stylesheets. Currently unused in AngularJS. 19889 CSS: 'css', 19890 19891 // An URL used in a context where it refers to the source of media, which are not expected to be run 19892 // as scripts, such as an image, audio, video, etc. 19893 MEDIA_URL: 'mediaUrl', 19894 19895 // An URL used in a context where it does not refer to a resource that loads code. 19896 // A value that can be trusted as a URL can also trusted as a MEDIA_URL. 19897 URL: 'url', 19898 19899 // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as 19900 // code. (e.g. ng-include, script src binding, templateUrl) 19901 // A value that can be trusted as a RESOURCE_URL, can also trusted as a URL and a MEDIA_URL. 19902 RESOURCE_URL: 'resourceUrl', 19903 19904 // Script. Currently unused in AngularJS. 19905 JS: 'js' 19906}; 19907 19908// Helper functions follow. 19909 19910var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g; 19911 19912function snakeToCamel(name) { 19913 return name 19914 .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace); 19915} 19916 19917function adjustMatcher(matcher) { 19918 if (matcher === 'self') { 19919 return matcher; 19920 } else if (isString(matcher)) { 19921 // Strings match exactly except for 2 wildcards - '*' and '**'. 19922 // '*' matches any character except those from the set ':/.?&'. 19923 // '**' matches any character (like .* in a RegExp). 19924 // More than 2 *'s raises an error as it's ill defined. 19925 if (matcher.indexOf('***') > -1) { 19926 throw $sceMinErr('iwcard', 19927 'Illegal sequence *** in string matcher. String: {0}', matcher); 19928 } 19929 matcher = escapeForRegexp(matcher). 19930 replace(/\\\*\\\*/g, '.*'). 19931 replace(/\\\*/g, '[^:/.?&;]*'); 19932 return new RegExp('^' + matcher + '$'); 19933 } else if (isRegExp(matcher)) { 19934 // The only other type of matcher allowed is a Regexp. 19935 // Match entire URL / disallow partial matches. 19936 // Flags are reset (i.e. no global, ignoreCase or multiline) 19937 return new RegExp('^' + matcher.source + '$'); 19938 } else { 19939 throw $sceMinErr('imatcher', 19940 'Matchers may only be "self", string patterns or RegExp objects'); 19941 } 19942} 19943 19944 19945function adjustMatchers(matchers) { 19946 var adjustedMatchers = []; 19947 if (isDefined(matchers)) { 19948 forEach(matchers, function(matcher) { 19949 adjustedMatchers.push(adjustMatcher(matcher)); 19950 }); 19951 } 19952 return adjustedMatchers; 19953} 19954 19955 19956/** 19957 * @ngdoc service 19958 * @name $sceDelegate 19959 * @kind function 19960 * 19961 * @description 19962 * 19963 * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict 19964 * Contextual Escaping (SCE)} services to AngularJS. 19965 * 19966 * For an overview of this service and the functionnality it provides in AngularJS, see the main 19967 * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how 19968 * SCE works in their application, which shouldn't be needed in most cases. 19969 * 19970 * <div class="alert alert-danger"> 19971 * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or 19972 * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners, 19973 * changes to this service will also influence users, so be extra careful and document your changes. 19974 * </div> 19975 * 19976 * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of 19977 * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is 19978 * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to 19979 * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things 19980 * work because `$sce` delegates to `$sceDelegate` for these operations. 19981 * 19982 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. 19983 * 19984 * The default instance of `$sceDelegate` should work out of the box with little pain. While you 19985 * can override it completely to change the behavior of `$sce`, the common case would 19986 * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting 19987 * your own
19987whitelists and blacklists for trusting URLs used for loading AngularJS resources such as 19988 * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist 19989 * $sceDelegateProvider.resourceUrlWhitelist} and {@link 19990 * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} 19991 */ 19992 19993/** 19994 * @ngdoc provider 19995 * @name $sceDelegateProvider 19996 * @this 19997 * 19998 * @description 19999 * 20000 * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate 20001 * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}. 20002 * 20003 * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure 20004 * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all 20005 * places that use the `$sce.RESOURCE_URL` context). See 20006 * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} 20007 * and 20008 * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}, 20009 * 20010 * For the general details about this service in AngularJS, read the main page for {@link ng.$sce 20011 * Strict Contextual Escaping (SCE)}. 20012 * 20013 * **Example**: Consider the following case. <a name="example"></a> 20014 * 20015 * - your app is hosted at url `http://myapp.example.com/` 20016 * - but some of your templates are hosted on other domains you control such as 20017 * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. 20018 * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. 20019 * 20020 * Here is what a secure configuration for this scenario might look like: 20021 * 20022 * ``` 20023 * angular.module('myApp', []).config(function($sceDelegateProvider) { 20024 * $sceDelegateProvider.resourceUrlWhitelist([ 20025 * // Allow same origin resource loads. 20026 * 'self', 20027 * // Allow loading from our assets domain. Notice the difference between * and **. 20028 * 'http://srv*.assets.example.com/**' 20029 * ]); 20030 * 20031 * // The blacklist overrides the whitelist so the open redirect here is blocked. 20032 * $sceDelegateProvider.resourceUrlBlacklist([ 20033 * 'http://myapp.example.com/clickThru**' 20034 * ]); 20035 * }); 20036 * ``` 20037 * Note that an empty whitelist will block every resource URL from being loaded, and will require 20038 * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates 20039 * requested by {@link ng.$templateRequest $templateRequest} that are present in 20040 * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism 20041 * to populate your templates in that cache at config time, then it is a good idea to remove 'self' 20042 * from that whitelist. This helps to mitigate the security impact of certain types of issues, like 20043 * for instance attacker-controlled `ng-includes`. 20044 */ 20045 20046function $SceDelegateProvider() { 20047 this.SCE_CONTEXTS = SCE_CONTEXTS; 20048 20049 // Resource URLs can also be trusted by policy. 20050 var resourceUrlWhitelist = ['self'], 20051 resourceUrlBlacklist = []; 20052 20053 /** 20054 * @ngdoc method 20055 * @name $sceDelegateProvider#resourceUrlWhitelist 20056 * @kind function 20057 * 20058 * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value 20059 * provided. This must be an array or null. A snapshot of this array is used so further 20060 * changes to the array are ignored. 20061 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items 20062 * allowed in this array. 20063 * 20064 * @return {Array} The currently set whitelist array. 20065 * 20066 * @description 20067 * Sets/Gets the whitelist of trusted resource URLs. 20068 * 20069 * The **default value** when no whitelist has been explicitly set is `['self']` allowing only 20070 * same origin resource requests. 20071 * 20072 * <div class="alert alert-warning"> 20073 * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin 20074 * with other apps! It is a good idea to limit it to only your application's directory. 20075 * </div> 20076 */ 20077 this.resourceUrlWhitelist = function(value) { 20078 if (arguments.length) { 20079 resourceUrlWhitelist = adjustMatchers(value); 20080 } 20081 return resourceUrlWhitelist; 20082 }; 20083 20084 /** 20085 * @ngdoc method 20086 * @name $sceDelegateProvider#resourceUrlBlacklist 20087 * @kind function 20088 * 20089 * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value 20090 * provided. This must be an array or null. A snapshot of this array is used so further 20091 * changes to the array are ignored.</p><p> 20092 * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items 20093 * allowed in this array.</p><p>
20094 * The typical usage for the blacklist is to **block 20095 * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as 20096 * these would otherwise be trusted but actually return content from the redirected domain. 20097 * </p><p> 20098 * Finally, **the blacklist overrides the whitelist** and has the final say. 20099 * 20100 * @return {Array} The currently set blacklist array. 20101 * 20102 * @description 20103 * Sets/Gets the blacklist of trusted resource URLs. 20104 * 20105 * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there 20106 * is no blacklist.) 20107 */ 20108 20109 this.resourceUrlBlacklist = function(value) { 20110 if (arguments.length) { 20111 resourceUrlBlacklist = adjustMatchers(value); 20112 } 20113 return resourceUrlBlacklist; 20114 }; 20115 20116 this.$get = ['$injector', '$$sanitizeUri', function($injector, $$sanitizeUri) { 20117 20118 var htmlSanitizer = function htmlSanitizer(html) { 20119 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); 20120 }; 20121 20122 if ($injector.has('$sanitize')) { 20123 htmlSanitizer = $injector.get('$sanitize'); 20124 } 20125 20126 20127 function matchUrl(matcher, parsedUrl) { 20128 if (matcher === 'self') { 20129 return urlIsSameOrigin(parsedUrl) || urlIsSameOriginAsBaseUrl(parsedUrl); 20130 } else { 20131 // definitely a regex. See adjustMatchers() 20132 return !!matcher.exec(parsedUrl.href); 20133 } 20134 } 20135 20136 function isResourceUrlAllowedByPolicy(url) { 20137 var parsedUrl = urlResolve(url.toString()); 20138 var i, n, allowed = false;
vendor: 5,029 bytes, lines 20139-20259
20139 // Ensure that at least one item from the whitelist allows this url. 20140 for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { 20141 if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { 20142 allowed = true; 20143 break; 20144 } 20145 } 20146 if (allowed) { 20147 // Ensure that no item from the blacklist blocked this url. 20148 for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { 20149 if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { 20150 allowed = false; 20151 break; 20152 } 20153 } 20154 } 20155 return allowed; 20156 } 20157 20158 function generateHolderType(Base) { 20159 var holderType = function TrustedValueHolderType(trustedValue) { 20160 this.$$unwrapTrustedValue = function() { 20161 return trustedValue; 20162 }; 20163 }; 20164 if (Base) { 20165 holderType.prototype = new Base(); 20166 } 20167 holderType.prototype.valueOf = function sceValueOf() { 20168 return this.$$unwrapTrustedValue(); 20169 }; 20170 holderType.prototype.toString = function sceToString() { 20171 return this.$$unwrapTrustedValue().toString(); 20172 }; 20173 return holderType; 20174 } 20175 20176 var trustedValueHolderBase = generateHolderType(), 20177 byType = {}; 20178 20179 byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); 20180 byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); 20181 byType[SCE_CONTEXTS.MEDIA_URL] = generateHolderType(trustedValueHolderBase); 20182 byType[SCE_CONTEXTS.URL] = generateHolderType(byType[SCE_CONTEXTS.MEDIA_URL]); 20183 byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); 20184 byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); 20185 20186 /** 20187 * @ngdoc method 20188 * @name $sceDelegate#trustAs 20189 * 20190 * @description 20191 * Returns a trusted representation of the parameter for the specified context. This trusted 20192 * object will later on be used as-is, without any security check, by bindings or directives 20193 * that require this security context. 20194 * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass 20195 * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as 20196 * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the 20197 * sanitizer loaded, passing the value itself will render all the HTML that does not pose a 20198 * security risk. 20199 * 20200 * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those 20201 * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual 20202 * escaping. 20203 * 20204 * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`, 20205 * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`. 20206 * 20207 * @param {*} value The value that should be considered trusted. 20208 * @return {*} A trusted representation of value, that can be used in the given context. 20209 */ 20210 function trustAs(type, trustedValue) { 20211 var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); 20212 if (!Constructor) { 20213 throw $sceMinErr('icontext', 20214 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', 20215 type, trustedValue); 20216 } 20217 if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') { 20218 return trustedValue; 20219 } 20220 // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting 20221 // mutable objects, we ensure here that the value passed in is actually a string. 20222 if (typeof trustedValue !== 'string') { 20223 throw $sceMinErr('itype', 20224 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', 20225 type); 20226 } 20227 return new Constructor(trustedValue); 20228 } 20229 20230 /** 20231 * @ngdoc method 20232 * @name $sceDelegate#valueOf 20233 * 20234 * @description 20235 * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs 20236 * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link 20237 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. 20238 * 20239 * If the passed parameter is not a value that had been returned by {@link 20240 * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is. 20241 * 20242 * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} 20243 * call or anything else. 20244 * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs 20245 * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns 20246 * `value` unchanged. 20247 */ 20248 function valueOf(maybeTrusted) { 20249 if (maybeTrusted instanceof trustedValueHolderBase) { 20250 return maybeTrusted.$$unwrapTrustedValue(); 20251 } else { 20252 return maybeTrusted; 20253 } 20254 } 20255 20256 /** 20257 * @ngdoc method 20258 * @name $sceDelegate#getTrusted 20259 *
20260 * @description 20261 * Given an object and a security context in which to assign it, returns a value that's safe to 20262 * use in this context, which was represented by the parameter. To do so, this function either 20263 * unwraps the safe type it has been given (for instance, a {@link ng.$sceDelegate#trustAs 20264 * `$sceDelegate.trustAs`} result), or it might try to sanitize the value given, depending on 20265 * the context and sanitizer availablility. 20266 * 20267 * The contexts that can be sanitized are $sce.MEDIA_URL, $sce.URL and $sce.HTML. The first two are available 20268 * by default, and the third one relies on the `$sanitize` service (which may be loaded through 20269 * the `ngSanitize` module). Furthermore, for $sce.RESOURCE_URL context, a plain string may be 20270 * accepted if the resource url policy defined by {@link ng.$sceDelegateProvider#resourceUrlWhitelist 20271 * `$sceDelegateProvider.resourceUrlWhitelist`} and {@link ng.$sceDelegateProvider#resourceUrlBlacklist 20272 * `$sceDelegateProvider.resourceUrlBlacklist`} accepts that resource. 20273 * 20274 * This function will throw if the safe type isn't appropriate for this context, or if the 20275 * value given cannot be accepted in the context (which might be caused by sanitization not 20276 * being available, or the value not being recognized as safe). 20277 * 20278 * <div class="alert alert-danger"> 20279 * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting 20280 * (XSS) vulnerability in your application. 20281 * </div> 20282 * 20283 * @param {string} type The context in which this value is to be used (such as `$sce.HTML`). 20284 * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs 20285 * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.) 20286 * @return {*} A version of the value that's safe to use in the given context, or throws an 20287 * exception if this is impossible. 20288 */ 20289 function getTrusted(type, maybeTrusted) { 20290 if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') { 20291 return maybeTrusted; 20292 } 20293 var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); 20294 // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return 20295 // as-is. 20296 if (constructor && maybeTrusted instanceof constructor) { 20297 return maybeTrusted.$$unwrapTrustedValue(); 20298 } 20299 20300 // If maybeTrusted is a trusted class instance but not of the correct trusted type 20301 // then unwrap it and allow it to pass through to the rest of the checks 20302 if (isFunction(maybeTrusted.$$unwrapTrustedValue)) { 20303 maybeTrusted = maybeTrusted.$$unwrapTrustedValue(); 20304 } 20305 20306 // If we get here, then we will either sanitize the value or throw an exception. 20307 if (type === SCE_CONTEXTS.MEDIA_URL || type === SCE_CONTEXTS.URL) { 20308 // we attempt to sanitize non-resource URLs 20309 return $$sanitizeUri(maybeTrusted, type === SCE_CONTEXTS.MEDIA_URL); 20310 } else if (type === SCE_CONTEXTS.RESOURCE_URL) { 20311 if (isResourceUrlAllowedByPolicy(maybeTrusted)) { 20312 return maybeTrusted; 20313 } else { 20314 throw $sceMinErr('insecurl', 20315 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', 20316 maybeTrusted.toString()); 20317 } 20318 } else if (type === SCE_CONTEXTS.HTML) { 20319 // htmlSanitizer throws its own error when no sanitizer is available. 20320 return htmlSanitizer(maybeTrusted); 20321 } 20322 // Default error when the $sce service has no way to make the input safe. 20323 throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); 20324 } 20325 20326 return { trustAs: trustAs, 20327 getTrusted: getTrusted, 20328 valueOf: valueOf }; 20329 }]; 20330} 20331 20332 20333/** 20334 * @ngdoc provider 20335 * @name $sceProvider 20336 * @this 20337 * 20338 * @description 20339 * 20340 * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. 20341 * - enable/disable Strict Contextual Escaping (SCE) in a module 20342 * - override the default implementation with a custom delegate 20343 * 20344 * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. 20345 */ 20346 20347/** 20348 * @ngdoc service 20349 * @name $sce 20350 * @kind function 20351 * 20352 * @description 20353 * 20354 * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. 20355 * 20356 * ## Strict Contextual Escaping 20357 * 20358 * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render 20359 * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and 20360 * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier. 20361 * 20362 * ### Overview 20363 * 20364 * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in 20365 * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically 20366 * run security checks on them (sanitizations, whitelists, depending on context), or throw when it 20367 * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML 20368 *
vendor: 4,337 bytes, lines 20368-20447
20368 can be sanitized, but template URLs cannot, for instance. 20369 * 20370 * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML: 20371 * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it 20372 * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and 20373 * render the input as-is, you will need to mark it as trusted for that context before attempting 20374 * to bind it. 20375 * 20376 * As of version 1.2, AngularJS ships with SCE enabled by default. 20377 * 20378 * ### In practice 20379 * 20380 * Here's an example of a binding in a privileged context: 20381 * 20382 * ``` 20383 * <input ng-model="userHtml" aria-label="User input"> 20384 * <div ng-bind-html="userHtml"></div> 20385 * ``` 20386 * 20387 * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE 20388 * disabled, this application allows the user to render arbitrary HTML into the DIV, which would 20389 * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog 20390 * articles, etc. via bindings. (HTML is just one example of a context where rendering user 20391 * controlled input creates security vulnerabilities.) 20392 * 20393 * For the case of HTML, you might use a library, either on the client side, or on the server side, 20394 * to sanitize unsafe HTML before binding to the value and rendering it in the document. 20395 * 20396 * How would you ensure that every place that used these types of bindings was bound to a value that 20397 * was sanitized by your library (or returned as safe for rendering by your server?) How can you 20398 * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some 20399 * properties/fields and forgot to update the binding to the sanitized value? 20400 * 20401 * To be secure by default, AngularJS makes sure bindings go through that sanitization, or 20402 * any similar validation process, unless there's a good reason to trust the given value in this 20403 * context. That trust is formalized with a function call. This means that as a developer, you 20404 * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues, 20405 * you just need to ensure the values you mark as trusted indeed are safe - because they were 20406 * received from your server, sanitized by your library, etc. You can organize your codebase to 20407 * help with this - perhaps allowing only the files in a specific directory to do this. 20408 * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then 20409 * becomes a more manageable task. 20410 * 20411 * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} 20412 * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to 20413 * build the trusted versions of your values. 20414 * 20415 * ### How does it work? 20416 * 20417 * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted 20418 * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as 20419 * a way to enforce the required security context in your data sink. Directives use {@link 20420 * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs 20421 * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also, 20422 * when binding without directives, AngularJS will understand the context of your bindings 20423 * automatically. 20424 * 20425 * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link 20426 * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly 20427 * simplified): 20428 * 20429 * ``` 20430 * var ngBindHtmlDirective = ['$sce', function($sce) { 20431 * return function(scope, element, attr) { 20432 * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { 20433 * element.html(value || ''); 20434 * }); 20435 * }; 20436 * }]; 20437 * ``` 20438 * 20439 * ### Impact on loading templates 20440 * 20441 * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as 20442 * `templateUrl`'s specified by {@link guide/directive directives}. 20443 * 20444 * By default, AngularJS only loads templates from the same domain and protocol as the application 20445 * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl 20446 * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or 20447 * protocols, you may either
20447{@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist 20448 * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. 20449 * 20450 * *Please note*: 20451 * The browser's 20452 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) 20453 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) 20454 * policy apply in addition to this and may further restrict whether the template is successfully 20455 * loaded. This means that without the right CORS policy, loading templates from a different domain 20456 * won't work on all browsers. Also, loading templates from `file://` URL does not work on some 20457 * browsers. 20458 * 20459 * ### This feels like too much overhead 20460 * 20461 * It's important to remember that SCE only applies to interpolation expressions. 20462 * 20463 * If your expressions are constant literals, they're automatically trusted and you don't need to 20464 * call `$sce.trustAs` on them (e.g. 20465 * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works (remember to include the 20466 * `ngSanitize` module). The `$sceDelegate` will also use the `$sanitize` service if it is available 20467 * when binding untrusted values to `$sce.HTML` context. 20468 * AngularJS provides an implementation in `angular-sanitize.js`, and if you 20469 * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in 20470 * your application. 20471 * 20472 * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load 20473 * templates in `ng-include` from your application's domain without having to even know about SCE. 20474 * It blocks loading templates from other domains or loading templates over http from an https 20475 * served document. You can change these by setting your own custom {@link 20476 * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link 20477 * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. 20478 * 20479 * This significantly reduces the overhead. It is far easier to pay the small overhead and have an 20480 * application that's secure and can be audited to verify that with much more ease than bolting 20481 * security onto an application later. 20482 * 20483 * <a name="contexts"></a> 20484 * ### What trusted context types are supported? 20485 * 20486 * | Context | Notes | 20487 * |---------------------|----------------| 20488 * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | 20489 * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | 20490 * | `$sce.MEDIA_URL` | For URLs that are safe to render as media. Is automatically converted from string by sanitizing when needed. | 20491 * | `$sce.URL` | For URLs that are safe to follow as links. Is automatically converted from string by sanitizing when needed. Note that `$sce.URL` makes a stronger statement about the URL than `$sce.MEDIA_URL` does and therefore contexts requiring values trusted for `$sce.URL` can be used anywhere that values trusted for `$sce.MEDIA_URL` are required.| 20492 * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` or `$sce.MEDIA_URL` do and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` or `$sce.MEDIA_URL` are required. <br><br> The {@link $sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider#resourceUrlWhitelist()} and {@link $sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider#resourceUrlBlacklist()} can be used to restrict trusted origins for `RESOURCE_URL` | 20493 * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | 20494 * 20495 * 20496 * <div class="alert alert-warning"> 20497 * Be aware that, before AngularJS 1.7.0, `a[href]` and `img[src]` used to sanitize their 20498 * interpolated values directly rather than rely upon {@link ng.$sce#getTrusted `$sce.getTrusted`}. 20499 * 20500 * **As of 1.7.0, this is no longer the case.** 20501 * 20502 * Now such interpolations are marked as requiring `$sce.URL` (for `a[href]`) or `$sce.MEDIA_URL` 20503 * (for `img[src]`), so that the sanitization happens (via `$sce.getTrusted...`) when the `$interpolate` 20504 * service evaluates the expressions. 20505 * </div> 20506 * 20507 * There are no CSS or JS context bindings in AngularJS currently, so their corresponding `$sce.trustAs` 20508 * functions aren't useful yet. This might evolve. 20509 * 20510 * ### Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a> 20511 *
20512 * Each element in these arrays must be one of the following: 20513 * 20514 * - **'self'** 20515 * - The special **string**, `'self'`, can be used to match against all URLs of the **same 20516 * domain** as the application document using the **same protocol**. 20517 * - **String** (except the special value `'self'`) 20518 * - The string is matched against the full *normalized / absolute URL* of the resource 20519 * being tested (substring matches are not good enough.) 20520 * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters 20521 * match themselves. 20522 * - `*`: matches zero or more occurrences of any character other than one of the following 6 20523 * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use 20524 * in a whitelist
vendor: 32,676 bytes, lines 20524-21328
20524. 20525 * - `**`: matches zero or more occurrences of *any* character. As such, it's not 20526 * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g. 20527 * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might 20528 * not have been the intention.) Its usage at the very end of the path is ok. (e.g. 20529 * http://foo.example.com/templates/**). 20530 * - **RegExp** (*see caveat below*) 20531 * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax 20532 * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to 20533 * accidentally introduce a bug when one updates a complex expression (imho, all regexes should 20534 * have good test coverage). For instance, the use of `.` in the regex is correct only in a 20535 * small number of cases. A `.` character in the regex used when matching the scheme or a 20536 * subdomain could be matched against a `:` or literal `.` that was likely not intended. It 20537 * is highly recommended to use the string patterns and only fall back to regular expressions 20538 * as a last resort. 20539 * - The regular expression must be an instance of RegExp (i.e. not a string.) It is 20540 * matched against the **entire** *normalized / absolute URL* of the resource being tested 20541 * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags 20542 * present on the RegExp (such as multiline, global, ignoreCase) are ignored. 20543 * - If you are generating your JavaScript from some other templating engine (not 20544 * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), 20545 * remember to escape your regular expression (and be aware that you might need more than 20546 * one level of escaping depending on your templating engine and the way you interpolated 20547 * the value.) Do make use of your platform's escaping mechanism as it might be good 20548 * enough before coding your own. E.g. Ruby has 20549 * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) 20550 * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). 20551 * Javascript lacks a similar built in function for escaping. Take a look at Google 20552 * Closure library's [goog.string.regExpEscape(s)]( 20553 * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). 20554 * 20555 * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. 20556 * 20557 * ### Show me an example using SCE. 20558 * 20559 * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service"> 20560 * <file name="index.html"> 20561 * <div ng-controller="AppController as myCtrl"> 20562 * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br> 20563 * <b>User comments</b><br> 20564 * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when 20565 * $sanitize is available. If $sanitize isn't available, this results in an error instead of an 20566 * exploit. 20567 * <div class="well"> 20568 * <div ng-repeat="userComment in myCtrl.userComments"> 20569 * <b>{{userComment.name}}</b>: 20570 * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span> 20571 * <br> 20572 * </div> 20573 * </div> 20574 * </div> 20575 * </file> 20576 * 20577 * <file name="script.js"> 20578 * angular.module('mySceApp', ['ngSanitize']) 20579 * .controller('AppController', ['$http', '$templateCache', '$sce', 20580 * function AppController($http, $templateCache, $sce) { 20581 * var self = this; 20582 * $http.get('test_data.json', {cache: $templateCache}).then(function(response) { 20583 * self.userComments = response.data; 20584 * }); 20585 * self.explicitlyTrustedHtml = $sce.trustAsHtml( 20586 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' + 20587 * 'sanitization."">Hover over this text.</span>'); 20588 * }]); 20589 * </file> 20590 * 20591 * <file name="test_data.json"> 20592 * [ 20593 * { "name": "Alice", 20594 * "htmlComment": 20595 * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>" 20596 * }, 20597 * { "name": "Bob", 20598 * "htmlComment": "<i>Yes!</i> Am I the only other one?" 20599 * } 20600 * ] 20601 * </file> 20602 * 20603 * <file name="protractor.js" type="protractor"> 20604 * describe('SCE doc demo', function() { 20605 * it('should sanitize untrusted values', function() { 20606 * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML')) 20607 * .toBe('<span>Is <i>anyone</i> reading this?</span>'); 20608 * }); 20609 * 20610 * it('should NOT sanitize explicitly trusted values', function() { 20611 * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe( 20612 * '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' + 20613 * 'sanitization."">Hover over this text.</span>'); 20614 * }); 20615 * }); 20616 * </file> 20617 * </example> 20618 * 20619 * 20620 * 20621 * ## Can I disable SCE completely? 20622 * 20623 * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits 20624 * for little coding overhead. It will be much harder to take an SCE disabled application and 20625 * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE 20626 * for cases where you have a lot of existing code that was written before SCE was introduced and 20627 * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if 20628 * you are writing a library, you will cause security bugs applications using it. 20629 * 20630 * That said, here's how you can completely disable SCE: 20631 * 20632 * ``` 20633 * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { 20634 * // Completely disable SCE. For demonstration purposes only! 20635 * // Do not use in new projects or libraries. 20636 * $sceProvider.enabled(false); 20637 * }); 20638 * ``` 20639 * 20640 */ 20641 20642function $SceProvider() { 20643 var enabled = true; 20644 20645 /** 20646 * @ngdoc method 20647 * @name $sceProvider#enabled 20648 * @kind function 20649 * 20650 * @param {boolean=} value If provided, then enables/disables SCE application-wide. 20651 * @return {boolean} True if SCE is enabled, false otherwise. 20652 * 20653 * @description 20654 * Enables/disables SCE and returns the current value. 20655 */ 20656 this.enabled = function(value) { 20657 if (arguments.length) { 20658 enabled = !!value; 20659 } 20660 return enabled; 20661 }; 20662 20663 20664 /* Design notes on the default implementation for SCE. 20665 * 20666 * The API contract for the SCE delegate 20667 * ------------------------------------- 20668 * The SCE delegate object must provide the following 3 methods: 20669 * 20670 * - trustAs(contextEnum, value) 20671 * This method is used to tell the SCE service that the provided value is OK to use in the 20672 * contexts specified by contextEnum. It must return an object that will be accepted by 20673 * getTrusted() for a compatible contextEnum and return this value. 20674 * 20675 * - valueOf(value) 20676 * For values that were not produced by trustAs(), return them as is. For values that were 20677 * produced by trustAs(), return the corresponding input value to trustAs. Basically, if 20678 * trustAs is wrapping the given values into some type, this operation unwraps it when given 20679 * such a value. 20680 * 20681 * - getTrusted(contextEnum, value) 20682 * This function should return the value that is safe to use in the context specified by 20683 * contextEnum or throw and exception otherwise. 20684 * 20685 * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be 20686 * opaque or wrapped in some holder object. That happens to be an implementation detail. For 20687 * instance, an implementation could maintain a registry of all trusted objects by context. In 20688 * such a case, trustAs() would return the same object that was passed in. getTrusted() would 20689 * return the same object passed in if it was found in the registry under a compatible context or 20690 * throw an exception otherwise. An implementation might only wrap values some of the time based 20691 * on some criteria. getTrusted() might return a value and not throw an exception for special 20692 * constants or objects even if not wrapped. All such implementations fulfill this contract. 20693 * 20694 * 20695 * A note on the inheritance model for SCE contexts 20696 * ------------------------------------------------ 20697 * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This 20698 * is purely an implementation details. 20699 * 20700 * The contract is simply this: 20701 * 20702 * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) 20703 * will also succeed. 20704 * 20705 * Inheritance happens to capture this in a natural way. In some future, we may not use 20706 * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to 20707 * be aware of this detail. 20708 */ 20709 20710 this.$get = ['$parse', '$sceDelegate', function( 20711 $parse, $sceDelegate) { 20712 // Support: IE 9-11 only 20713 // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow 20714 // the "expression(javascript expression)" syntax which is insecure. 20715 if (enabled && msie < 8) { 20716 throw $sceMinErr('iequirks', 20717 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' + 20718 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' + 20719 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); 20720 } 20721 20722 var sce = shallowCopy(SCE_CONTEXTS); 20723 20724 /** 20725 * @ngdoc method 20726 * @name $sce#isEnabled 20727 * @kind function 20728 * 20729 * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you 20730 * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. 20731 * 20732 * @description 20733 * Returns a boolean indicating if SCE is enabled. 20734 */ 20735 sce.isEnabled = function() { 20736 return enabled; 20737 }; 20738 sce.trustAs = $sceDelegate.trustAs; 20739 sce.getTrusted = $sceDelegate.getTrusted; 20740 sce.valueOf = $sceDelegate.valueOf; 20741 20742 if (!enabled) { 20743 sce.trustAs = sce.getTrusted = function(type, value) { return value; }; 20744 sce.valueOf = identity; 20745 } 20746 20747 /** 20748 * @ngdoc method 20749 * @name $sce#parseAs 20750 * 20751 * @description 20752 * Converts AngularJS {@link guide/expression expression} into a function. This is like {@link 20753 * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it 20754 * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, 20755 * *result*)} 20756 * 20757 * @param {string} type The SCE context in which this result will be used. 20758 * @param {string} expression String expression to compile. 20759 * @return {function(context, locals)} A function which represents the compiled expression: 20760 * 20761 * * `context` – `{object}` – an object against which any expressions embedded in the 20762 * strings are evaluated against (typically a scope object). 20763 * * `locals` – `{object=}` – local variables context object, useful for overriding values 20764 * in `context`. 20765 */ 20766 sce.parseAs = function sceParseAs(type, expr) { 20767 var parsed = $parse(expr); 20768 if (parsed.literal && parsed.constant) { 20769 return parsed; 20770 } else { 20771 return $parse(expr, function(value) { 20772 return sce.getTrusted(type, value); 20773 }); 20774 } 20775 }; 20776 20777 /** 20778 * @ngdoc method 20779 * @name $sce#trustAs 20780 * 20781 * @description 20782 * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a 20783 * wrapped object that represents your value, and the trust you have in its safety for the given 20784 * context. AngularJS can then use that value as-is in bindings of the specified secure context. 20785 * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute 20786 * interpolations. See {@link ng.$sce $sce} for strict contextual escaping. 20787 * 20788 * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`, 20789 * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`. 20790 * 20791 * @param {*} value The value that that should be considered trusted. 20792 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 20793 * in the context you specified. 20794 */ 20795 20796 /** 20797 * @ngdoc method 20798 * @name $sce#trustAsHtml 20799 * 20800 * @description 20801 * Shorthand method. `$sce.trustAsHtml(value)` → 20802 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} 20803 * 20804 * @param {*} value The value to mark as trusted for `$sce.HTML` context. 20805 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 20806 * in `$sce.HTML` context (like `ng-bind-html`). 20807 */ 20808 20809 /** 20810 * @ngdoc method 20811 * @name $sce#trustAsCss 20812 * 20813 * @description 20814 * Shorthand method. `$sce.trustAsCss(value)` → 20815 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`} 20816 * 20817 * @param {*} value The value to mark as trusted for `$sce.CSS` context. 20818 * @return {*} A wrapped version of value that can be used as a trusted variant 20819 * of your `value` in `$sce.CSS` context. This context is currently unused, so there are 20820 * almost no reasons to use this function so far. 20821 */ 20822 20823 /** 20824 * @ngdoc method 20825 * @name $sce#trustAsUrl 20826 * 20827 * @description 20828 * Shorthand method. `$sce.trustAsUrl(value)` → 20829 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} 20830 * 20831 * @param {*} value The value to mark as trusted for `$sce.URL` context. 20832 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 20833 * in `$sce.URL` context. That context is currently unused, so there are almost no reasons 20834 * to use this function so far. 20835 */ 20836 20837 /** 20838 * @ngdoc method 20839 * @name $sce#trustAsResourceUrl 20840 * 20841 * @description 20842 * Shorthand method. `$sce.trustAsResourceUrl(value)` → 20843 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} 20844 * 20845 * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context. 20846 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 20847 * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute 20848 * bindings, ...) 20849 */ 20850 20851 /** 20852 * @ngdoc method 20853 * @name $sce#trustAsJs 20854 * 20855 * @description 20856 * Shorthand method. `$sce.trustAsJs(value)` → 20857 * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} 20858 * 20859 * @param {*} value The value to mark as trusted for `$sce.JS` context. 20860 * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` 20861 * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to 20862 * use this function so far. 20863 */ 20864 20865 /** 20866 * @ngdoc method 20867 * @name $sce#getTrusted 20868 * 20869 * @description 20870 * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, 20871 * takes any input, and either returns a value that's safe to use in the specified context, 20872 * or throws an exception. This function is aware of trusted values created by the `trustAs` 20873 * function and its shorthands, and when contexts are appropriate, returns the unwrapped value 20874 * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a 20875 * safe value (e.g., no sanitization is available or possible.) 20876 * 20877 * @param {string} type The context in which this value is to be used. 20878 * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs 20879 * `$sce.trustAs`} call, or anything else (which will not be considered trusted.) 20880 * @return {*} A version of the value that's safe to use in the given context, or throws an 20881 * exception if this is impossible. 20882 */ 20883 20884 /** 20885 * @ngdoc method 20886 * @name $sce#getTrustedHtml 20887 * 20888 * @description 20889 * Shorthand method. `$sce.getTrustedHtml(value)` → 20890 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} 20891 * 20892 * @param {*} value The value to pass to `$sce.getTrusted`. 20893 * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)` 20894 */ 20895 20896 /** 20897 * @ngdoc method 20898 * @name $sce#getTrustedCss 20899 * 20900 * @description 20901 * Shorthand method. `$sce.getTrustedCss(value)` → 20902 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} 20903 * 20904 * @param {*} value The value to pass to `$sce.getTrusted`. 20905 * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)` 20906 */ 20907 20908 /** 20909 * @ngdoc method 20910 * @name $sce#getTrustedUrl 20911 * 20912 * @description 20913 * Shorthand method. `$sce.getTrustedUrl(value)` → 20914 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} 20915 * 20916 * @param {*} value The value to pass to `$sce.getTrusted`. 20917 * @return {*} The return value of `$sce.getTrusted($sce.URL, value)` 20918 */ 20919 20920 /** 20921 * @ngdoc method 20922 * @name $sce#getTrustedResourceUrl 20923 * 20924 * @description 20925 * Shorthand method. `$sce.getTrustedResourceUrl(value)` → 20926 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} 20927 * 20928 * @param {*} value The value to pass to `$sceDelegate.getTrusted`. 20929 * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` 20930 */ 20931 20932 /** 20933 * @ngdoc method 20934 * @name $sce#getTrustedJs 20935 * 20936 * @description 20937 * Shorthand method. `$sce.getTrustedJs(value)` → 20938 * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} 20939 * 20940 * @param {*} value The value to pass to `$sce.getTrusted`. 20941 * @return {*} The return value of `$sce.getTrusted($sce.JS, value)` 20942 */ 20943 20944 /** 20945 * @ngdoc method 20946 * @name $sce#parseAsHtml 20947 * 20948 * @description 20949 * Shorthand method. `$sce.parseAsHtml(expression string)` → 20950 * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} 20951 * 20952 * @param {string} expression String expression to compile. 20953 * @return {function(context, locals)} A function which represents the compiled expression: 20954 * 20955 * * `context` – `{object}` – an object against which any expressions embedded in the 20956 * strings are evaluated against (typically a scope object). 20957 * * `locals` – `{object=}` – local variables context object, useful for overriding values 20958 * in `context`. 20959 */ 20960 20961 /** 20962 * @ngdoc method 20963 * @name $sce#parseAsCss 20964 * 20965 * @description 20966 * Shorthand method. `$sce.parseAsCss(value)` → 20967 * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} 20968 * 20969 * @param {string} expression String expression to compile. 20970 * @return {function(context, locals)} A function which represents the compiled expression: 20971 * 20972 * * `context` – `{object}` – an object against which any expressions embedded in the 20973 * strings are evaluated against (typically a scope object). 20974 * * `locals` – `{object=}` – local variables context object, useful for overriding values 20975 * in `context`. 20976 */ 20977 20978 /** 20979 * @ngdoc method 20980 * @name $sce#parseAsUrl 20981 * 20982 * @description 20983 * Shorthand method. `$sce.parseAsUrl(value)` → 20984 * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} 20985 * 20986 * @param {string} expression String expression to compile. 20987 * @return {function(context, locals)} A function which represents the compiled expression: 20988 * 20989 * * `context` – `{object}` – an object against which any expressions embedded in the 20990 * strings are evaluated against (typically a scope object). 20991 * * `locals` – `{object=}` – local variables context object, useful for overriding values 20992 * in `context`. 20993 */ 20994 20995 /** 20996 * @ngdoc method 20997 * @name $sce#parseAsResourceUrl 20998 * 20999 * @description 21000 * Shorthand method. `$sce.parseAsResourceUrl(value)` → 21001 * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} 21002 * 21003 * @param {string} expression String expression to compile. 21004 * @return {function(context, locals)} A function which represents the compiled expression: 21005 * 21006 * * `context` – `{object}` – an object against which any expressions embedded in the 21007 * strings are evaluated against (typically a scope object). 21008 * * `locals` – `{object=}` – local variables context object, useful for overriding values 21009 * in `context`. 21010 */ 21011 21012 /** 21013 * @ngdoc method 21014 * @name $sce#parseAsJs 21015 * 21016 * @description 21017 * Shorthand method. `$sce.parseAsJs(value)` → 21018 * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} 21019 * 21020 * @param {string} expression String expression to compile. 21021 * @return {function(context, locals)} A function which represents the compiled expression: 21022 * 21023 * * `context` – `{object}` – an object against which any expressions embedded in the 21024 * strings are evaluated against (typically a scope object). 21025 * * `locals` – `{object=}` – local variables context object, useful for overriding values 21026 * in `context`. 21027 */ 21028 21029 // Shorthand delegations. 21030 var parse = sce.parseAs, 21031 getTrusted = sce.getTrusted, 21032 trustAs = sce.trustAs; 21033 21034 forEach(SCE_CONTEXTS, function(enumValue, name) { 21035 var lName = lowercase(name); 21036 sce[snakeToCamel('parse_as_' + lName)] = function(expr) { 21037 return parse(enumValue, expr); 21038 }; 21039 sce[snakeToCamel('get_trusted_' + lName)] = function(value) { 21040 return getTrusted(enumValue, value); 21041 }; 21042 sce[snakeToCamel('trust_as_' + lName)] = function(value) { 21043 return trustAs(enumValue, value); 21044 }; 21045 }); 21046 21047 return sce; 21048 }]; 21049} 21050 21051/* exported $SnifferProvider */ 21052 21053/** 21054 * !!! This is an undocumented "private" service !!! 21055 * 21056 * @name $sniffer 21057 * @requires $window 21058 * @requires $document 21059 * @this 21060 * 21061 * @property {boolean} history Does the browser support html5 history api ? 21062 * @property {boolean} transitions Does the browser support CSS transition events ? 21063 * @property {boolean} animations Does the browser support CSS animation events ? 21064 * 21065 * @description 21066 * This is very simple implementation of testing browser's features. 21067 */ 21068function $SnifferProvider() { 21069 this.$get = ['$window', '$document', function($window, $document) { 21070 var eventSupport = {}, 21071 // Chrome Packaged Apps are not allowed to access `history.pushState`. 21072 // If not sandboxed, they can be detected by the presence of `chrome.app.runtime` 21073 // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by 21074 // the presence of an extension runtime ID and the absence of other Chrome runtime APIs 21075 // (see https://developer.chrome.com/apps/manifest/sandbox). 21076 // (NW.js apps have access to Chrome APIs, but do support `history`.) 21077 isNw = $window.nw && $window.nw.process, 21078 isChromePackagedApp = 21079 !isNw && 21080 $window.chrome && 21081 ($window.chrome.app && $window.chrome.app.runtime || 21082 !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id), 21083 hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState, 21084 android = 21085 toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), 21086 boxee = /Boxee/i.test(($window.navigator || {}).userAgent), 21087 document = $document[0] || {}, 21088 bodyStyle = document.body && document.body.style, 21089 transitions = false, 21090 animations = false; 21091 21092 if (bodyStyle) { 21093 // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x 21094 // Mentioned browsers need a -webkit- prefix for transitions & animations. 21095 transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle); 21096 animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle); 21097 } 21098 21099 21100 return { 21101 // Android has history.pushState, but it does not update location correctly 21102 // so let's not use the history API at all. 21103 // http://code.google.com/p/android/issues/detail?id=17471 21104 // https://github.com/angular/angular.js/issues/904 21105 21106 // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has 21107 // so let's not use the history API also 21108 // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined 21109 history: !!(hasHistoryPushState && !(android < 4) && !boxee), 21110 hasEvent: function(event) { 21111 // Support: IE 9-11 only 21112 // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have 21113 // it. In particular the event is not fired when backspace or delete key are pressed or 21114 // when cut operation is performed. 21115 // IE10+ implements 'input' event but it erroneously fires under various situations, 21116 // e.g. when placeholder changes, or a form is focused. 21117 if (event === 'input' && msie) return false; 21118 21119 if (isUndefined(eventSupport[event])) { 21120 var divElm = document.createElement('div'); 21121 eventSupport[event] = 'on' + event in divElm; 21122 } 21123 21124 return eventSupport[event]; 21125 }, 21126 csp: csp(), 21127 transitions: transitions, 21128 animations: animations, 21129 android: android 21130 }; 21131 }]; 21132} 21133 21134/** 21135 * ! This is a private undocumented service ! 21136 * 21137 * @name $$taskTrackerFactory 21138 * @description 21139 * A function to create `TaskTracker` instances. 21140 * 21141 * A `TaskTracker` can keep track of pending tasks (grouped by type) and can notify interested 21142 * parties when all pending tasks (or tasks of a specific type) have been completed. 21143 * 21144 * @param {$log} log - A logger instance (such as `$log`). Used to log error during callback 21145 * execution. 21146 * 21147 * @this 21148 */ 21149function $$TaskTrackerFactoryProvider() { 21150 this.$get = valueFn(function(log) { return new TaskTracker(log); }); 21151} 21152 21153function TaskTracker(log) { 21154 var self = this; 21155 var taskCounts = {}; 21156 var taskCallbacks = []; 21157 21158 var ALL_TASKS_TYPE = self.ALL_TASKS_TYPE = '$$all$$'; 21159 var DEFAULT_TASK_TYPE = self.DEFAULT_TASK_TYPE = '$$default$$'; 21160 21161 /** 21162 * Execute the specified function and decrement the appropriate `taskCounts` counter. 21163 * If the counter reaches 0, all corresponding `taskCallbacks` are executed. 21164 * 21165 * @param {Function} fn - The function to execute. 21166 * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task that is being completed. 21167 */ 21168 self.completeTask = completeTask; 21169 21170 /** 21171 * Increase the task count for the specified task type (or the default task type if non is 21172 * specified). 21173 * 21174 * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task whose count will be increased. 21175 */ 21176 self.incTaskCount = incTaskCount; 21177 21178 /** 21179 * Execute the specified callback when all pending tasks have been completed. 21180 * 21181 * If there are no pending tasks, the callback is executed immediately. You can optionally limit 21182 * the tasks that will be waited for to a specific type, by passing a `taskType`. 21183 * 21184 * @param {function} callback - The function to call when there are no pending tasks. 21185 * @param {string=} [taskType=ALL_TASKS_TYPE] - The type of tasks that will be waited for. 21186 */ 21187 self.notifyWhenNoPendingTasks = notifyWhenNoPendingTasks; 21188 21189 function completeTask(fn, taskType) { 21190 taskType = taskType || DEFAULT_TASK_TYPE; 21191 21192 try { 21193 fn(); 21194 } finally { 21195 decTaskCount(taskType); 21196 21197 var countForType = taskCounts[taskType]; 21198 var countForAll = taskCounts[ALL_TASKS_TYPE]; 21199 21200 // If at least one of the queues (`ALL_TASKS_TYPE` or `taskType`) is empty, run callbacks. 21201 if (!countForAll || !countForType) { 21202 var getNextCallback = !countForAll ? getLastCallback : getLastCallbackForType; 21203 var nextCb; 21204 21205 while ((nextCb = getNextCallback(taskType))) { 21206 try { 21207 nextCb(); 21208 } catch (e) { 21209 log.error(e); 21210 } 21211 } 21212 } 21213 } 21214 } 21215 21216 function decTaskCount(taskType) { 21217 taskType = taskType || DEFAULT_TASK_TYPE; 21218 if (taskCounts[taskType]) { 21219 taskCounts[taskType]--; 21220 taskCounts[ALL_TASKS_TYPE]--; 21221 } 21222 } 21223 21224 function getLastCallback() { 21225 var cbInfo = taskCallbacks.pop(); 21226 return cbInfo && cbInfo.cb; 21227 } 21228 21229 function getLastCallbackForType(taskType) { 21230 for (var i = taskCallbacks.length - 1; i >= 0; --i) { 21231 var cbInfo = taskCallbacks[i]; 21232 if (cbInfo.type === taskType) { 21233 taskCallbacks.splice(i, 1); 21234 return cbInfo.cb; 21235 } 21236 } 21237 } 21238 21239 function incTaskCount(taskType) { 21240 taskType = taskType || DEFAULT_TASK_TYPE; 21241 taskCounts[taskType] = (taskCounts[taskType] || 0) + 1; 21242 taskCounts[ALL_TASKS_TYPE] = (taskCounts[ALL_TASKS_TYPE] || 0) + 1; 21243 } 21244 21245 function notifyWhenNoPendingTasks(callback, taskType) { 21246 taskType = taskType || ALL_TASKS_TYPE; 21247 if (!taskCounts[taskType]) { 21248 callback(); 21249 } else { 21250 taskCallbacks.push({type: taskType, cb: callback}); 21251 } 21252 } 21253} 21254 21255var $templateRequestMinErr = minErr('$templateRequest'); 21256 21257/** 21258 * @ngdoc provider 21259 * @name $templateRequestProvider 21260 * @this 21261 * 21262 * @description 21263 * Used to configure the options passed to the {@link $http} service when making a template request. 21264 * 21265 * For example, it can be used for specifying the "Accept" header that is sent to the server, when 21266 * requesting a template. 21267 */ 21268function $TemplateRequestProvider() { 21269 21270 var httpOptions; 21271 21272 /** 21273 * @ngdoc method 21274 * @name $templateRequestProvider#httpOptions 21275 * @description 21276 * The options to be passed to the {@link $http} service when making the request. 21277 * You can use this to override options such as the "Accept" header for template requests. 21278 * 21279 * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the 21280 * options if not overridden here. 21281 * 21282 * @param {string=} value new value for the {@link $http} options. 21283 * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter. 21284 */ 21285 this.httpOptions = function(val) { 21286 if (val) { 21287 httpOptions = val; 21288 return this; 21289 } 21290 return httpOptions; 21291 }; 21292 21293 /** 21294 * @ngdoc service 21295 * @name $templateRequest 21296 * 21297 * @description 21298 * The `$templateRequest` service runs security checks then downloads the provided template using 21299 * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request 21300 * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the 21301 * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the 21302 * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted 21303 * when `tpl` is of type string and `$templateCache` has the matching entry. 21304 * 21305 * If you want to pass custom options to the `$http` service, such as setting the Accept header you 21306 * can configure this via {@link $templateRequestProvider#httpOptions}. 21307 * 21308 * `$templateRequest` is used internally by {@link $compile}, {@link ngRoute.$route}, and directives such 21309 * as {@link ngInclude} to download and cache templates. 21310 * 21311 * 3rd party modules should use `$templateRequest` if their services or directives are loading 21312 * templates. 21313 * 21314 * @param {string|TrustedResourceUrl} tpl The HTTP request template URL 21315 * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty 21316 * 21317 * @return {Promise} a promise for the HTTP response data of the given URL. 21318 * 21319 * @property {number} totalPendingRequests total amount of pending template requests being downloaded. 21320 */ 21321 this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce', 21322 function($exceptionHandler, $templateCache, $http, $q, $sce) { 21323 21324 function handleRequestFn(tpl, ignoreRequestError) { 21325 handleRequestFn.totalPendingRequests++; 21326 21327 // We consider the template cache holds only trusted templates, so 21328 // there's no need to go through
21328whitelisting again for keys that already 21329 // are included in there. This also makes AngularJS accept any script 21330 // directive, no matter its name. However, we still need to unwrap trusted 21331 //
vendor: 9,763 bytes, lines 21331-21620
21331 types. 21332 if (!isString(tpl) || isUndefined($templateCache.get(tpl))) { 21333 tpl = $sce.getTrustedResourceUrl(tpl); 21334 } 21335 21336 var transformResponse = $http.defaults && $http.defaults.transformResponse; 21337 21338 if (isArray(transformResponse)) { 21339 transformResponse = transformResponse.filter(function(transformer) { 21340 return transformer !== defaultHttpResponseTransform; 21341 }); 21342 } else if (transformResponse === defaultHttpResponseTransform) { 21343 transformResponse = null; 21344 } 21345 21346 return $http.get(tpl, extend({ 21347 cache: $templateCache, 21348 transformResponse: transformResponse 21349 }, httpOptions)) 21350 .finally(function() { 21351 handleRequestFn.totalPendingRequests--; 21352 }) 21353 .then(function(response) { 21354 return $templateCache.put(tpl, response.data); 21355 }, handleError); 21356 21357 function handleError(resp) { 21358 if (!ignoreRequestError) { 21359 resp = $templateRequestMinErr('tpload', 21360 'Failed to load template: {0} (HTTP status: {1} {2})', 21361 tpl, resp.status, resp.statusText); 21362 21363 $exceptionHandler(resp); 21364 } 21365 21366 return $q.reject(resp); 21367 } 21368 } 21369 21370 handleRequestFn.totalPendingRequests = 0; 21371 21372 return handleRequestFn; 21373 } 21374 ]; 21375} 21376 21377/** @this */ 21378function $$TestabilityProvider() { 21379 this.$get = ['$rootScope', '$browser', '$location', 21380 function($rootScope, $browser, $location) { 21381 21382 /** 21383 * @name $testability 21384 * 21385 * @description 21386 * The private $$testability service provides a collection of methods for use when debugging 21387 * or by automated test and debugging tools. 21388 */ 21389 var testability = {}; 21390 21391 /** 21392 * @name $$testability#findBindings 21393 * 21394 * @description 21395 * Returns an array of elements that are bound (via ng-bind or {{}}) 21396 * to expressions matching the input. 21397 * 21398 * @param {Element} element The element root to search from. 21399 * @param {string} expression The binding expression to match. 21400 * @param {boolean} opt_exactMatch If true, only returns exact matches 21401 * for the expression. Filters and whitespace are ignored. 21402 */ 21403 testability.findBindings = function(element, expression, opt_exactMatch) { 21404 var bindings = element.getElementsByClassName('ng-binding'); 21405 var matches = []; 21406 forEach(bindings, function(binding) { 21407 var dataBinding = angular.element(binding).data('$binding'); 21408 if (dataBinding) { 21409 forEach(dataBinding, function(bindingName) { 21410 if (opt_exactMatch) { 21411 var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)'); 21412 if (matcher.test(bindingName)) { 21413 matches.push(binding); 21414 } 21415 } else { 21416 if (bindingName.indexOf(expression) !== -1) { 21417 matches.push(binding); 21418 } 21419 } 21420 }); 21421 } 21422 }); 21423 return matches; 21424 }; 21425 21426 /** 21427 * @name $$testability#findModels 21428 * 21429 * @description 21430 * Returns an array of elements that are two-way found via ng-model to 21431 * expressions matching the input. 21432 * 21433 * @param {Element} element The element root to search from. 21434 * @param {string} expression The model expression to match. 21435 * @param {boolean} opt_exactMatch If true, only returns exact matches 21436 * for the expression. 21437 */ 21438 testability.findModels = function(element, expression, opt_exactMatch) { 21439 var prefixes = ['ng-', 'data-ng-', 'ng\\:']; 21440 for (var p = 0; p < prefixes.length; ++p) { 21441 var attributeEquals = opt_exactMatch ? '=' : '*='; 21442 var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]'; 21443 var elements = element.querySelectorAll(selector); 21444 if (elements.length) { 21445 return elements; 21446 } 21447 } 21448 }; 21449 21450 /** 21451 * @name $$testability#getLocation 21452 * 21453 * @description 21454 * Shortcut for getting the location in a browser agnostic way. Returns 21455 * the path, search, and hash. (e.g. /path?a=b#hash) 21456 */ 21457 testability.getLocation = function() { 21458 return $location.url(); 21459 }; 21460 21461 /** 21462 * @name $$testability#setLocation 21463 * 21464 * @description 21465 * Shortcut for navigating to a location without doing a full page reload. 21466 * 21467 * @param {string} url The location url (path, search and hash, 21468 * e.g. /path?a=b#hash) to go to. 21469 */ 21470 testability.setLocation = function(url) { 21471 if (url !== $location.url()) { 21472 $location.url(url); 21473 $rootScope.$digest(); 21474 } 21475 }; 21476 21477 /** 21478 * @name $$testability#whenStable 21479 * 21480 * @description 21481 * Calls the callback when all pending tasks are completed. 21482 * 21483 * Types of tasks waited for include: 21484 * - Pending timeouts (via {@link $timeout}). 21485 * - Pending HTTP requests (via {@link $http}). 21486 * - In-progress route transitions (via {@link $route}). 21487 * - Pending tasks scheduled via {@link $rootScope#$applyAsync}. 21488 * - Pending tasks scheduled via {@link $rootScope#$evalAsync}. 21489 * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises). 21490 * 21491 * @param {function} callback 21492 */ 21493 testability.whenStable = function(callback) { 21494 $browser.notifyWhenNoOutstandingRequests(callback); 21495 }; 21496 21497 return testability; 21498 }]; 21499} 21500 21501var $timeoutMinErr = minErr('$timeout'); 21502 21503/** @this */ 21504function $TimeoutProvider() { 21505 this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', 21506 function($rootScope, $browser, $q, $$q, $exceptionHandler) { 21507 21508 var deferreds = {}; 21509 21510 21511 /** 21512 * @ngdoc service 21513 * @name $timeout 21514 * 21515 * @description 21516 * AngularJS's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch 21517 * block and delegates any exceptions to 21518 * {@link ng.$exceptionHandler $exceptionHandler} service. 21519 * 21520 * The return value of calling `$timeout` is a promise, which will be resolved when 21521 * the delay has passed and the timeout function, if provided, is executed. 21522 * 21523 * To cancel a timeout request, call `$timeout.cancel(promise)`. 21524 * 21525 * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to 21526 * synchronously flush the queue of deferred functions. 21527 * 21528 * If you only want a promise that will be resolved after some specified delay 21529 * then you can call `$timeout` without the `fn` function. 21530 * 21531 * @param {function()=} fn A function, whose execution should be delayed. 21532 * @param {number=} [delay=0] Delay in milliseconds. 21533 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise 21534 * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. 21535 * @param {...*=} Pass additional parameters to the executed function. 21536 * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise 21537 * will be resolved with the return value of the `fn` function. 21538 * 21539 */ 21540 function timeout(fn, delay, invokeApply) { 21541 if (!isFunction(fn)) { 21542 invokeApply = delay; 21543 delay = fn; 21544 fn = noop; 21545 } 21546 21547 var args = sliceArgs(arguments, 3), 21548 skipApply = (isDefined(invokeApply) && !invokeApply), 21549 deferred = (skipApply ? $$q : $q).defer(), 21550 promise = deferred.promise, 21551 timeoutId; 21552 21553 timeoutId = $browser.defer(function() { 21554 try { 21555 deferred.resolve(fn.apply(null, args)); 21556 } catch (e) { 21557 deferred.reject(e); 21558 $exceptionHandler(e); 21559 } finally { 21560 delete deferreds[promise.$$timeoutId]; 21561 } 21562 21563 if (!skipApply) $rootScope.$apply(); 21564 }, delay, '$timeout'); 21565 21566 promise.$$timeoutId = timeoutId; 21567 deferreds[timeoutId] = deferred; 21568 21569 return promise; 21570 } 21571 21572 21573 /** 21574 * @ngdoc method 21575 * @name $timeout#cancel 21576 * 21577 * @description 21578 * Cancels a task associated with the `promise`. As a result of this, the promise will be 21579 * resolved with a rejection. 21580 * 21581 * @param {Promise=} promise Promise returned by the `$timeout` function. 21582 * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully 21583 * canceled. 21584 */ 21585 timeout.cancel = function(promise) { 21586 if (!promise) return false; 21587 21588 if (!promise.hasOwnProperty('$$timeoutId')) { 21589 throw $timeoutMinErr('badprom', 21590 '`$timeout.cancel()` called with a promise that was not generated by `$timeout()`.'); 21591 } 21592 21593 if (!deferreds.hasOwnProperty(promise.$$timeoutId)) return false; 21594 21595 var id = promise.$$timeoutId; 21596 var deferred = deferreds[id]; 21597 21598 // Timeout cancels should not report an unhandled promise. 21599 markQExceptionHandled(deferred.promise); 21600 deferred.reject('canceled'); 21601 delete deferreds[id]; 21602 21603 return $browser.defer.cancel(id); 21604 }; 21605 21606 return timeout; 21607 }]; 21608} 21609 21610// NOTE: The usage of window and document instead of $window and $document here is 21611// deliberate. This service depends on the specific behavior of anchor nodes created by the 21612// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and 21613// cause us to break tests. In addition, when the browser resolves a URL for XHR, it 21614// doesn't know about mocked locations and resolves URLs to the real document - which is 21615// exactly the behavior needed here. There is little value is mocking these out for this 21616// service. 21617var urlParsingNode = window.document.createElement('a'); 21618var originUrl = urlResolve(window.location.href); 21619var baseUrlParsingNode; 21620
21621 21622/** 21623 * 21624 * Implementation Notes for non-IE browsers 21625 * ---------------------------------------- 21626 * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, 21627 * results both in the normalizing and parsing of the URL. Normalizing means that a relative 21628 * URL will be resolved into an absolute URL in the context of the application document. 21629 * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related 21630 * properties are all populated to reflect the normalized URL. This approach has wide 21631 * compatibility - Safari 1+, Mozilla 1+ etc. See 21632 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html 21633 * 21634 * Implementation Notes for IE 21635 * --------------------------- 21636 * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other 21637 * browsers. However, the parsed components will not be set if the URL assigned did not specify 21638 * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We 21639 * work around that by performing the parsing in a 2nd step by taking a previously normalized 21640 * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the 21641 * properties such as protocol, hostname, port, etc. 21642 * 21643 * References: 21644 * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement 21645 * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html 21646 * http://url.spec.whatwg.org/#urlutils 21647 * https://github.com/angular/angular.js/pull/2902 21648 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ 21649 * 21650 * @kind function 21651 * @param {string|object} url The URL to be parsed. If `url` is not a string, it will be returned 21652 * unchanged. 21653 * @description Normalizes and parses a URL. 21654 * @returns {object} Returns the normalized URL as a dictionary. 21655 * 21656 * | member name | Description | 21657 * |---------------|------------------------------------------------------------------------| 21658 * | href | A normalized version of the provided URL if it was not an absolute URL | 21659 * | protocol | The protocol without the trailing colon | 21660 * | host | The host and port (if the port is non-default) of the normalizedUrl | 21661 * | search | The search params, minus the question mark | 21662 * | hash | The hash string, minus the hash symbol | 21663 * | hostname | The hostname | 21664 * | port | The port, without ":" | 21665 * | pathname | The pathname, beginning with "/" | 21666 * 21667 */ 21668function urlResolve(url) { 21669 if (!isString(url)) return url; 21670 21671 var href = url; 21672 21673 // Support: IE 9-11 only 21674 if (msie) { 21675 // Normalize before parse. Refer Implementation Notes on why this is 21676 // done in two steps on IE. 21677 urlParsingNode.setAttribute('href', href); 21678 href = urlParsingNode.href; 21679 } 21680 21681 urlParsingNode.setAttribute('href', href); 21682 21683 return { 21684 href: urlParsingNode.href, 21685 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', 21686 host: urlParsingNode.host, 21687 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', 21688 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', 21689 hostname: urlParsingNode.hostname, 21690 port: urlParsingNode.port, 21691 pathname: (urlParsingNode.pathname.charAt(0) === '/') 21692 ? urlParsingNode.pathname 21693 : '/' + urlParsingNode.pathname 21694 }; 21695} 21696 21697/** 21698 * Parse a request URL and determine whether this is a same-origin request as the application 21699 * document. 21700 * 21701 * @param {string|object} requestUrl The url of the request as a string that will be resolved 21702 * or a parsed URL object. 21703 * @returns {boolean} Whether the request is for the same origin as the application document. 21704 */ 21705function urlIsSameOrigin(requestUrl) { 21706 return urlsAreSameOrigin(requestUrl, originUrl); 21707} 21708 21709/** 21710 * Parse a request URL and determine whether it is same-origin as the current document base URL. 21711 *
21712 * Note: The base URL is usually the same as the document location (`location.href`) but can 21713 * be overriden by using the `<base>` tag. 21714 * 21715 * @param {string|object} requestUrl The url of the request as a string that will be resolved 21716 * or a parsed URL object. 21717 * @returns {boolean} Whether the URL is same-origin as the document base URL. 21718 */ 21719function urlIsSameOriginAsBaseUrl(requestUrl) { 21720 return urlsAreSameOrigin(requestUrl, getBaseUrl()); 21721} 21722 21723/** 21724 * Create a function that can check a URL's origin against a list of allowed/whitelisted origins. 21725 * The current location's origin is implicitly trusted. 21726 * 21727 * @param {string[]} whitelistedOriginUrls - A list of URLs (strings), whose origins are trusted. 21728 * 21729 * @returns {Function} - A function that receives a URL (string or parsed URL object) and returns 21730 * whether it is of an allowed origin. 21731 */ 21732function urlIsAllowedOriginFactory(whitelistedOriginUrls) { 21733 var parsedAllowedOriginUrls = [originUrl].concat(whitelistedOriginUrls.map(urlResolve)); 21734 21735 /** 21736 * Check whether the specified URL (string or parsed URL object) has an origin that is allowed 21737 * based on a list of whiteli
vendor: 88,804 bytes, lines 21737-24134
21737sted-origin URLs. The current location's origin is implicitly 21738 * trusted. 21739 * 21740 * @param {string|Object} requestUrl - The URL to be checked (provided as a string that will be 21741 * resolved or a parsed URL object). 21742 * 21743 * @returns {boolean} - Whether the specified URL is of an allowed origin. 21744 */ 21745 return function urlIsAllowedOrigin(requestUrl) { 21746 var parsedUrl = urlResolve(requestUrl); 21747 return parsedAllowedOriginUrls.some(urlsAreSameOrigin.bind(null, parsedUrl)); 21748 }; 21749} 21750 21751/** 21752 * Determine if two URLs share the same origin. 21753 * 21754 * @param {string|Object} url1 - First URL to compare as a string or a normalized URL in the form of 21755 * a dictionary object returned by `urlResolve()`. 21756 * @param {string|object} url2 - Second URL to compare as a string or a normalized URL in the form 21757 * of a dictionary object returned by `urlResolve()`. 21758 * 21759 * @returns {boolean} - True if both URLs have the same origin, and false otherwise. 21760 */ 21761function urlsAreSameOrigin(url1, url2) { 21762 url1 = urlResolve(url1); 21763 url2 = urlResolve(url2); 21764 21765 return (url1.protocol === url2.protocol && 21766 url1.host === url2.host); 21767} 21768 21769/** 21770 * Returns the current document base URL. 21771 * @returns {string} 21772 */ 21773function getBaseUrl() { 21774 if (window.document.baseURI) { 21775 return window.document.baseURI; 21776 } 21777 21778 // `document.baseURI` is available everywhere except IE 21779 if (!baseUrlParsingNode) { 21780 baseUrlParsingNode = window.document.createElement('a'); 21781 baseUrlParsingNode.href = '.'; 21782 21783 // Work-around for IE bug described in Implementation Notes. The fix in `urlResolve()` is not 21784 // suitable here because we need to track changes to the base URL. 21785 baseUrlParsingNode = baseUrlParsingNode.cloneNode(false); 21786 } 21787 return baseUrlParsingNode.href; 21788} 21789 21790/** 21791 * @ngdoc service 21792 * @name $window 21793 * @this 21794 * 21795 * @description 21796 * A reference to the browser's `window` object. While `window` 21797 * is globally available in JavaScript, it causes testability problems, because 21798 * it is a global variable. In AngularJS we always refer to it through the 21799 * `$window` service, so it may be overridden, removed or mocked for testing. 21800 * 21801 * Expressions, like the one defined for the `ngClick` directive in the example 21802 * below, are evaluated with respect to the current scope. Therefore, there is 21803 * no risk of inadvertently coding in a dependency on a global value in such an 21804 * expression. 21805 * 21806 * @example 21807 <example module="windowExample" name="window-service"> 21808 <file name="index.html"> 21809 <script> 21810 angular.module('windowExample', []) 21811 .controller('ExampleController', ['$scope', '$window', function($scope, $window) { 21812 $scope.greeting = 'Hello, World!'; 21813 $scope.doGreeting = function(greeting) { 21814 $window.alert(greeting); 21815 }; 21816 }]); 21817 </script> 21818 <div ng-controller="ExampleController"> 21819 <input type="text" ng-model="greeting" aria-label="greeting" /> 21820 <button ng-click="doGreeting(greeting)">ALERT</button> 21821 </div> 21822 </file> 21823 <file name="protractor.js" type="protractor"> 21824 it('should display the greeting in the input box', function() { 21825 element(by.model('greeting')).sendKeys('Hello, E2E Tests'); 21826 // If we click the button it will block the test runner 21827 // element(':button').click(); 21828 }); 21829 </file> 21830 </example> 21831 */ 21832function $WindowProvider() { 21833 this.$get = valueFn(window); 21834} 21835 21836/** 21837 * @name $$cookieReader 21838 * @requires $document 21839 * 21840 * @description 21841 * This is a private service for reading cookies used by $http and ngCookies 21842 * 21843 * @return {Object} a key/value map of the current cookies 21844 */ 21845function $$CookieReader($document) { 21846 var rawDocument = $document[0] || {}; 21847 var lastCookies = {}; 21848 var lastCookieString = ''; 21849 21850 function safeGetCookie(rawDocument) { 21851 try { 21852 return rawDocument.cookie || ''; 21853 } catch (e) { 21854 return ''; 21855 } 21856 } 21857 21858 function safeDecodeURIComponent(str) { 21859 try { 21860 return decodeURIComponent(str); 21861 } catch (e) { 21862 return str; 21863 } 21864 } 21865 21866 return function() { 21867 var cookieArray, cookie, i, index, name; 21868 var currentCookieString = safeGetCookie(rawDocument); 21869 21870 if (currentCookieString !== lastCookieString) { 21871 lastCookieString = currentCookieString; 21872 cookieArray = lastCookieString.split('; '); 21873 lastCookies = {}; 21874 21875 for (i = 0; i < cookieArray.length; i++) { 21876 cookie = cookieArray[i]; 21877 index = cookie.indexOf('='); 21878 if (index > 0) { //ignore nameless cookies 21879 name = safeDecodeURIComponent(cookie.substring(0, index)); 21880 // the first value that is seen for a cookie is the most 21881 // specific one. values for the same cookie name that 21882 // follow are for less specific paths. 21883 if (isUndefined(lastCookies[name])) { 21884 lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); 21885 } 21886 } 21887 } 21888 } 21889 return lastCookies; 21890 }; 21891} 21892 21893$$CookieReader.$inject = ['$document']; 21894 21895/** @this */ 21896function $$CookieReaderProvider() { 21897 this.$get = $$CookieReader; 21898} 21899 21900/* global currencyFilter: true, 21901 dateFilter: true, 21902 filterFilter: true, 21903 jsonFilter: true, 21904 limitToFilter: true, 21905 lowercaseFilter: true, 21906 numberFilter: true, 21907 orderByFilter: true, 21908 uppercaseFilter: true, 21909 */ 21910 21911/** 21912 * @ngdoc provider 21913 * @name $filterProvider 21914 * @description 21915 * 21916 * Filters are just functions which transform input to an output. However filters need to be 21917 * Dependency Injected. To achieve this a filter definition consists of a factory function which is 21918 * annotated with dependencies and is responsible for creating a filter function. 21919 * 21920 * <div class="alert alert-warning"> 21921 * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. 21922 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace 21923 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores 21924 * (`myapp_subsection_filterx`). 21925 * </div> 21926 * 21927 * ```js 21928 * // Filter registration 21929 * function MyModule($provide, $filterProvider) { 21930 * // create a service to demonstrate injection (not always needed) 21931 * $provide.value('greet', function(name){ 21932 * return 'Hello ' + name + '!'; 21933 * }); 21934 * 21935 * // register a filter factory which uses the 21936 * // greet service to demonstrate DI. 21937 * $filterProvider.register('greet', function(greet){ 21938 * // return the filter function which uses the greet service 21939 * // to generate salutation 21940 * return function(text) { 21941 * // filters need to be forgiving so check input validity 21942 * return text && greet(text) || text; 21943 * }; 21944 * }); 21945 * } 21946 * ``` 21947 * 21948 * The filter function is registered with the `$injector` under the filter name suffix with 21949 * `Filter`. 21950 * 21951 * ```js 21952 * it('should be the same instance', inject( 21953 * function($filterProvider) { 21954 * $filterProvider.register('reverse', function(){ 21955 * return ...; 21956 * }); 21957 * }, 21958 * function($filter, reverseFilter) { 21959 * expect($filter('reverse')).toBe(reverseFilter); 21960 * }); 21961 * ``` 21962 * 21963 * 21964 * For more information about how AngularJS filters work, and how to create your own filters, see 21965 * {@link guide/filter Filters} in the AngularJS Developer Guide. 21966 */ 21967 21968/** 21969 * @ngdoc service 21970 * @name $filter 21971 * @kind function 21972 * @description 21973 * Filters are used for formatting data displayed to the user. 21974 * 21975 * They can be used in view templates, controllers or services. AngularJS comes 21976 * with a collection of [built-in filters](api/ng/filter), but it is easy to 21977 * define your own as well. 21978 * 21979 * The general syntax in templates is as follows: 21980 * 21981 * ```html 21982 * {{ expression [| filter_name[:parameter_value] ... ] }} 21983 * ``` 21984 * 21985 * @param {String} name Name of the filter function to retrieve 21986 * @return {Function} the filter function 21987 * @example 21988 <example name="$filter" module="filterExample"> 21989 <file name="index.html"> 21990 <div ng-controller="MainCtrl"> 21991 <h3>{{ originalText }}</h3> 21992 <h3>{{ filteredText }}</h3> 21993 </div> 21994 </file> 21995 21996 <file name="script.js"> 21997 angular.module('filterExample', []) 21998 .controller('MainCtrl', function($scope, $filter) { 21999 $scope.originalText = 'hello'; 22000 $scope.filteredText = $filter('uppercase')($scope.originalText); 22001 }); 22002 </file> 22003 </example> 22004 */ 22005$FilterProvider.$inject = ['$provide']; 22006/** @this */ 22007function $FilterProvider($provide) { 22008 var suffix = 'Filter'; 22009 22010 /** 22011 * @ngdoc method 22012 * @name $filterProvider#register 22013 * @param {string|Object} name Name of the filter function, or an object map of filters where 22014 * the keys are the filter names and the values are the filter factories. 22015 * 22016 * <div class="alert alert-warning"> 22017 * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. 22018 * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace 22019 * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores 22020 * (`myapp_subsection_filterx`). 22021 * </div> 22022 * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered. 22023 * @returns {Object} Registered filter instance, or if a map of filters was provided then a map 22024 * of the registered filter instances. 22025 */ 22026 function register(name, factory) { 22027 if (isObject(name)) { 22028 var filters = {}; 22029 forEach(name, function(filter, key) { 22030 filters[key] = register(key, filter); 22031 }); 22032 return filters; 22033 } else { 22034 return $provide.factory(name + suffix, factory); 22035 } 22036 } 22037 this.register = register; 22038 22039 this.$get = ['$injector', function($injector) { 22040 return function(name) { 22041 return $injector.get(name + suffix); 22042 }; 22043 }]; 22044 22045 //////////////////////////////////////// 22046 22047 /* global 22048 currencyFilter: false, 22049 dateFilter: false, 22050 filterFilter: false, 22051 jsonFilter: false, 22052 limitToFilter: false, 22053 lowercaseFilter: false, 22054 numberFilter: false, 22055 orderByFilter: false, 22056 uppercaseFilter: false 22057 */ 22058 22059 register('currency', currencyFilter); 22060 register('date', dateFilter); 22061 register('filter', filterFilter); 22062 register('json', jsonFilter); 22063 register('limitTo', limitToFilter); 22064 register('lowercase', lowercaseFilter); 22065 register('number', numberFilter); 22066 register('orderBy', orderByFilter); 22067 register('uppercase', uppercaseFilter); 22068} 22069 22070/** 22071 * @ngdoc filter 22072 * @name filter 22073 * @kind function 22074 * 22075 * @description 22076 * Selects a subset of items from `array` and returns it as a new array. 22077 * 22078 * @param {Array} array The source array. 22079 * <div class="alert alert-info"> 22080 * **Note**: If the array contains objects that reference themselves, filtering is not possible. 22081 * </div> 22082 * @param {string|Object|function()} expression The predicate to be used for selecting items from 22083 * `array`. 22084 * 22085 * Can be one of: 22086 * 22087 * - `string`: The string is used for matching against the contents of the `array`. All strings or 22088 * objects with string properties in `array` that match this string will be returned. This also 22089 * applies to nested object properties. 22090 * The predicate can be negated by prefixing the string with `!`. 22091 * 22092 * - `Object`: A pattern object can be used to filter specific properties on objects contained 22093 * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items 22094 * which have property `name` containing "M" and property `phone` containing "1". A special 22095 * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match 22096 * against any property of the object or its nested object properties. That's equivalent to the 22097 * simple substring match with a `string` as described above. The special property name can be 22098 * overwritten, using the `anyPropertyKey` parameter. 22099 * The predicate can be negated by prefixing the string with `!`. 22100 * For example `{name: "!M"}` predicate will return an array of items which have property `name` 22101 * not containing "M". 22102 * 22103 * Note that a named property will match properties on the same level only, while the special 22104 * `$` property will match properties on the same level or deeper. E.g. an array item like 22105 * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but 22106 * **will** be matched by `{$: 'John'}`. 22107 * 22108 * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters. 22109 * The function is called for each element of the array, with the element, its index, and 22110 * the entire array itself as arguments. 22111 * 22112 * The final result is an array of those elements that the predicate returned true for. 22113 * 22114 * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in 22115 * determining if values retrieved using `expression` (when it is not a function) should be 22116 * considered a match based on the expected value (from the filter expression) and actual 22117 * value (from the object in the array). 22118 * 22119 * Can be one of: 22120 * 22121 * - `function(actual, expected)`: 22122 * The function will be given the object value and the predicate value to compare and 22123 * should return true if both values should be considered equal. 22124 * 22125 * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`. 22126 * This is essentially strict comparison of expected and actual. 22127 * 22128 * - `false`: A short hand for a function which will look for a substring match in a case 22129 * insensitive way. Primitive values are converted to strings. Objects are not compared against 22130 * primitives, unless they have a custom `toString` method (e.g. `Date` objects). 22131 * 22132 * 22133 * Defaults to `false`. 22134 * 22135 * @param {string} [anyPropertyKey] The special property name that matches against any property. 22136 * By default `$`. 22137 * 22138 * @example 22139 <example name="filter-filter"> 22140 <file name="index.html"> 22141 <div ng-init="friends = [{name:'John', phone:'555-1276'}, 22142 {name:'Mary', phone:'800-BIG-MARY'}, 22143 {name:'Mike', phone:'555-4321'}, 22144 {name:'Adam', phone:'555-5678'}, 22145 {name:'Julie', phone:'555-8765'}, 22146 {name:'Juliette', phone:'555-5678'}]"></div> 22147 22148 <label>Search: <input ng-model="searchText"></label> 22149 <table id="searchTextResults"> 22150 <tr><th>Name</th><th>Phone</th></tr> 22151 <tr ng-repeat="friend in friends | filter:searchText"> 22152 <td>{{friend.name}}</td> 22153 <td>{{friend.phone}}</td> 22154 </tr> 22155 </table> 22156 <hr> 22157 <label>Any: <input ng-model="search.$"></label> <br> 22158 <label>Name only <input ng-model="search.name"></label><br> 22159 <label>Phone only <input ng-model="search.phone"></label><br> 22160 <label>Equality <input type="checkbox" ng-model="strict"></label><br> 22161 <table id="searchObjResults"> 22162 <tr><th>Name</th><th>Phone</th></tr> 22163 <tr ng-repeat="friendObj in friends | filter:search:strict"> 22164 <td>{{friendObj.name}}</td> 22165 <td>{{friendObj.phone}}</td> 22166 </tr> 22167 </table> 22168 </file> 22169 <file name="protractor.js" type="protractor"> 22170 var expectFriendNames = function(expectedNames, key) { 22171 element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { 22172 arr.forEach(function(wd, i) { 22173 expect(wd.getText()).toMatch(expectedNames[i]); 22174 }); 22175 }); 22176 }; 22177 22178 it('should search across all fields when filtering with a string', function() { 22179 var searchText = element(by.model('searchText')); 22180 searchText.clear(); 22181 searchText.sendKeys('m'); 22182 expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); 22183 22184 searchText.clear(); 22185 searchText.sendKeys('76'); 22186 expectFriendNames(['John', 'Julie'], 'friend'); 22187 }); 22188 22189 it('should search in specific fields when filtering with a predicate object', function() { 22190 var searchAny = element(by.model('search.$')); 22191 searchAny.clear(); 22192 searchAny.sendKeys('i'); 22193 expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); 22194 }); 22195 it('should use a equal comparison when comparator is true', function() { 22196 var searchName = element(by.model('search.name')); 22197 var strict = element(by.model('strict')); 22198 searchName.clear(); 22199 searchName.sendKeys('Julie'); 22200 strict.click(); 22201 expectFriendNames(['Julie'], 'friendObj'); 22202 }); 22203 </file> 22204 </example> 22205 */ 22206 22207function filterFilter() { 22208 return function(array, expression, comparator, anyPropertyKey) { 22209 if (!isArrayLike(array)) { 22210 if (array == null) { 22211 return array; 22212 } else { 22213 throw minErr('filter')('notarray', 'Expected array but received: {0}', array); 22214 } 22215 } 22216 22217 anyPropertyKey = anyPropertyKey || '$'; 22218 var expressionType = getTypeForFilter(expression); 22219 var predicateFn; 22220 var matchAgainstAnyProp; 22221 22222 switch (expressionType) { 22223 case 'function': 22224 predicateFn = expression; 22225 break; 22226 case 'boolean': 22227 case 'null': 22228 case 'number': 22229 case 'string': 22230 matchAgainstAnyProp = true; 22231 // falls through 22232 case 'object': 22233 predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp); 22234 break; 22235 default: 22236 return array; 22237 } 22238 22239 return Array.prototype.filter.call(array, predicateFn); 22240 }; 22241} 22242 22243// Helper functions for `filterFilter` 22244function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) { 22245 var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression); 22246 var predicateFn; 22247 22248 if (comparator === true) { 22249 comparator = equals; 22250 } else if (!isFunction(comparator)) { 22251 comparator = function(actual, expected) { 22252 if (isUndefined(actual)) { 22253 // No substring matching against `undefined` 22254 return false; 22255 } 22256 if ((actual === null) || (expected === null)) { 22257 // No substring matching against `null`; only match against `null` 22258 return actual === expected; 22259 } 22260 if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) { 22261 // Should not compare primitives against objects, unless they have custom `toString` method 22262 return false; 22263 } 22264 22265 actual = lowercase('' + actual); 22266 expected = lowercase('' + expected); 22267 return actual.indexOf(expected) !== -1; 22268 }; 22269 } 22270 22271 predicateFn = function(item) { 22272 if (shouldMatchPrimitives && !isObject(item)) { 22273 return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false); 22274 } 22275 return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp); 22276 }; 22277 22278 return predicateFn; 22279} 22280 22281function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) { 22282 var actualType = getTypeForFilter(actual); 22283 var expectedType = getTypeForFilter(expected); 22284 22285 if ((expectedType === 'string') && (expected.charAt(0) === '!')) { 22286 return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp); 22287 } else if (isArray(actual)) { 22288 // In case `actual` is an array, consider it a match 22289 // if ANY of it's items matches `expected` 22290 return actual.some(function(item) { 22291 return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp); 22292 }); 22293 } 22294 22295 switch (actualType) { 22296 case 'object': 22297 var key; 22298 if (matchAgainstAnyProp) { 22299 for (key in actual) { 22300 // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined 22301 // See: https://github.com/angular/angular.js/issues/15644 22302 if (key.charAt && (key.charAt(0) !== '$') && 22303 deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) { 22304 return true; 22305 } 22306 } 22307 return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false); 22308 } else if (expectedType === 'object') { 22309 for (key in expected) { 22310 var expectedVal = expected[key]; 22311 if (isFunction(expectedVal) || isUndefined(expectedVal)) { 22312 continue; 22313 } 22314 22315 var matchAnyProperty = key === anyPropertyKey; 22316 var actualVal = matchAnyProperty ? actual : actual[key]; 22317 if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) { 22318 return false; 22319 } 22320 } 22321 return true; 22322 } else { 22323 return comparator(actual, expected); 22324 } 22325 case 'function': 22326 return false; 22327 default: 22328 return comparator(actual, expected); 22329 } 22330} 22331 22332// Used for easily differentiating between `null` and actual `object` 22333function getTypeForFilter(val) { 22334 return (val === null) ? 'null' : typeof val; 22335} 22336 22337var MAX_DIGITS = 22; 22338var DECIMAL_SEP = '.'; 22339var ZERO_CHAR = '0'; 22340 22341/** 22342 * @ngdoc filter 22343 * @name currency 22344 * @kind function 22345 * 22346 * @description 22347 * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default 22348 * symbol for current locale is used. 22349 * 22350 * @param {number} amount Input to filter. 22351 * @param {string=} symbol Currency symbol or identifier to be displayed. 22352 * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale 22353 * @returns {string} Formatted number. 22354 * 22355 * 22356 * @example 22357 <example module="currencyExample" name="currency-filter"> 22358 <file name="index.html"> 22359 <script> 22360 angular.module('currencyExample', []) 22361 .controller('ExampleController', ['$scope', function($scope) { 22362 $scope.amount = 1234.56; 22363 }]); 22364 </script> 22365 <div ng-controller="ExampleController"> 22366 <input type="number" ng-model="amount" aria-label="amount"> <br> 22367 default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br> 22368 custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br> 22369 no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span> 22370 </div> 22371 </file> 22372 <file name="protractor.js" type="protractor"> 22373 it('should init with 1234.56', function() { 22374 expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); 22375 expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56'); 22376 expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235'); 22377 }); 22378 it('should update', function() { 22379 if (browser.params.browser === 'safari') { 22380 // Safari does not understand the minus key. See 22381 // https://github.com/angular/protractor/issues/481 22382 return; 22383 } 22384 element(by.model('amount')).clear(); 22385 element(by.model('amount')).sendKeys('-1234'); 22386 expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00'); 22387 expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00'); 22388 expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234'); 22389 }); 22390 </file> 22391 </example> 22392 */ 22393currencyFilter.$inject = ['$locale']; 22394function currencyFilter($locale) { 22395 var formats = $locale.NUMBER_FORMATS; 22396 return function(amount, currencySymbol, fractionSize) { 22397 if (isUndefined(currencySymbol)) { 22398 currencySymbol = formats.CURRENCY_SYM; 22399 } 22400 22401 if (isUndefined(fractionSize)) { 22402 fractionSize = formats.PATTERNS[1].maxFrac; 22403 } 22404 22405 // If the currency symbol is empty, trim whitespace around the symbol 22406 var currencySymbolRe = !currencySymbol ? /\s*\u00A4\s*/g : /\u00A4/g; 22407 22408 // if null or undefined pass it through 22409 return (amount == null) 22410 ? amount 22411 : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). 22412 replace(currencySymbolRe, currencySymbol); 22413 }; 22414} 22415 22416/** 22417 * @ngdoc filter 22418 * @name number 22419 * @kind function 22420 * 22421 * @description 22422 * Formats a number as text. 22423 * 22424 * If the input is null or undefined, it will just be returned. 22425 * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively. 22426 * If the input is not a number an empty string is returned. 22427 * 22428 * 22429 * @param {number|string} number Number to format. 22430 * @param {(number|string)=} fractionSize Number of decimal places to round the number to. 22431 * If this is not provided then the fraction size is computed from the current locale's number 22432 * formatting pattern. In the case of the default locale, it will be 3. 22433 * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current 22434 * locale (e.g., in the en_US locale it will have "." as the decimal separator and 22435 * include "," group separators after each third digit). 22436 * 22437 * @example 22438 <example module="numberFilterExample" name="number-filter"> 22439 <file name="index.html"> 22440 <script> 22441 angular.module('numberFilterExample', []) 22442 .controller('ExampleController', ['$scope', function($scope) { 22443 $scope.val = 1234.56789; 22444 }]); 22445 </script> 22446 <div ng-controller="ExampleController"> 22447 <label>Enter number: <input ng-model='val'></label><br> 22448 Default formatting: <span id='number-default'>{{val | number}}</span><br> 22449 No fractions: <span>{{val | number:0}}</span><br> 22450 Negative number: <span>{{-val | number:4}}</span> 22451 </div> 22452 </file> 22453 <file name="protractor.js" type="protractor"> 22454 it('should format numbers', function() { 22455 expect(element(by.id('number-default')).getText()).toBe('1,234.568'); 22456 expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); 22457 expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); 22458 }); 22459 22460 it('should update', function() { 22461 element(by.model('val')).clear(); 22462 element(by.model('val')).sendKeys('3374.333'); 22463 expect(element(by.id('number-default')).getText()).toBe('3,374.333'); 22464 expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); 22465 expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); 22466 }); 22467 </file> 22468 </example> 22469 */ 22470numberFilter.$inject = ['$locale']; 22471function numberFilter($locale) { 22472 var formats = $locale.NUMBER_FORMATS; 22473 return function(number, fractionSize) { 22474 22475 // if null or undefined pass it through 22476 return (number == null) 22477 ? number 22478 : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, 22479 fractionSize); 22480 }; 22481} 22482 22483/** 22484 * Parse a number (as a string) into three components that can be used 22485 * for formatting the number. 22486 * 22487 * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/) 22488 * 22489 * @param {string} numStr The number to parse 22490 * @return {object} An object describing this number, containing the following keys: 22491 * - d : an array of digits containing leading zeros as necessary 22492 * - i : the number of the digits in `d` that are to the left of the decimal point 22493 * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d` 22494 * 22495 */ 22496function parse(numStr) { 22497 var exponent = 0, digits, numberOfIntegerDigits; 22498 var i, j, zeros; 22499 22500 // Decimal point? 22501 if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) { 22502 numStr = numStr.replace(DECIMAL_SEP, ''); 22503 } 22504 22505 // Exponential form? 22506 if ((i = numStr.search(/e/i)) > 0) { 22507 // Work out the exponent. 22508 if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i; 22509 numberOfIntegerDigits += +numStr.slice(i + 1); 22510 numStr = numStr.substring(0, i); 22511 } else if (numberOfIntegerDigits < 0) { 22512 // There was no decimal point or exponent so it is an integer. 22513 numberOfIntegerDigits = numStr.length; 22514 } 22515 22516 // Count the number of leading zeros. 22517 for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ } 22518 22519 if (i === (zeros = numStr.length)) { 22520 // The digits are all zero. 22521 digits = [0]; 22522 numberOfIntegerDigits = 1; 22523 } else { 22524 // Count the number of trailing zeros 22525 zeros--; 22526 while (numStr.charAt(zeros) === ZERO_CHAR) zeros--; 22527 22528 // Trailing zeros are insignificant so ignore them 22529 numberOfIntegerDigits -= i; 22530 digits = []; 22531 // Convert string to array of digits without leading/trailing zeros. 22532 for (j = 0; i <= zeros; i++, j++) { 22533 digits[j] = +numStr.charAt(i); 22534 } 22535 } 22536 22537 // If the number overflows the maximum allowed digits then use an exponent. 22538 if (numberOfIntegerDigits > MAX_DIGITS) { 22539 digits = digits.splice(0, MAX_DIGITS - 1); 22540 exponent = numberOfIntegerDigits - 1; 22541 numberOfIntegerDigits = 1; 22542 } 22543 22544 return { d: digits, e: exponent, i: numberOfIntegerDigits }; 22545} 22546 22547/** 22548 * Round the parsed number to the specified number of decimal places 22549 * This function changed the parsedNumber in-place 22550 */ 22551function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { 22552 var digits = parsedNumber.d; 22553 var fractionLen = digits.length - parsedNumber.i; 22554 22555 // determine fractionSize if it is not specified; `+fractionSize` converts it to a number 22556 fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; 22557 22558 // The index of the digit to where rounding is to occur 22559 var roundAt = fractionSize + parsedNumber.i; 22560 var digit = digits[roundAt]; 22561 22562 if (roundAt > 0) { 22563 // Drop fractional digits beyond `roundAt` 22564 digits.splice(Math.max(parsedNumber.i, roundAt)); 22565 22566 // Set non-fractional digits beyond `roundAt` to 0 22567 for (var j = roundAt; j < digits.length; j++) { 22568 digits[j] = 0; 22569 } 22570 } else { 22571 // We rounded to zero so reset the parsedNumber 22572 fractionLen = Math.max(0, fractionLen); 22573 parsedNumber.i = 1; 22574 digits.length = Math.max(1, roundAt = fractionSize + 1); 22575 digits[0] = 0; 22576 for (var i = 1; i < roundAt; i++) digits[i] = 0; 22577 } 22578 22579 if (digit >= 5) { 22580 if (roundAt - 1 < 0) { 22581 for (var k = 0; k > roundAt; k--) { 22582 digits.unshift(0); 22583 parsedNumber.i++; 22584 } 22585 digits.unshift(1); 22586 parsedNumber.i++; 22587 } else { 22588 digits[roundAt - 1]++; 22589 } 22590 } 22591 22592 // Pad out with zeros to get the required fraction length 22593 for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); 22594 22595 22596 // Do any carrying, e.g. a digit was rounded up to 10 22597 var carry = digits.reduceRight(function(carry, d, i, digits) { 22598 d = d + carry; 22599 digits[i] = d % 10; 22600 return Math.floor(d / 10); 22601 }, 0); 22602 if (carry) { 22603 digits.unshift(carry); 22604 parsedNumber.i++; 22605 } 22606} 22607 22608/** 22609 * Format a number into a string 22610 * @param {number} number The number to format 22611 * @param {{ 22612 * minFrac, // the minimum number of digits required in the fraction part of the number 22613 * maxFrac, // the maximum number of digits required in the fraction part of the number 22614 * gSize, // number of digits in each group of separated digits 22615 * lgSize, // number of digits in the last group of digits before the decimal separator 22616 * negPre, // the string to go in front of a negative number (e.g. `-` or `(`)) 22617 * posPre, // the string to go in front of a positive number 22618 * negSuf, // the string to go after a negative number (e.g. `)`) 22619 * posSuf // the string to go after a positive number 22620 * }} pattern 22621 * @param {string} groupSep The string to separate groups of number (e.g. `,`) 22622 * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`) 22623 * @param {[type]} fractionSize The size of the fractional part of the number 22624 * @return {string} The number formatted as a string 22625 */ 22626function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { 22627 22628 if (!(isString(number) || isNumber(number)) || isNaN(number)) return ''; 22629 22630 var isInfinity = !isFinite(number); 22631 var isZero = false; 22632 var numStr = Math.abs(number) + '', 22633 formattedText = '', 22634 parsedNumber; 22635 22636 if (isInfinity) { 22637 formattedText = '\u221e'; 22638 } else { 22639 parsedNumber = parse(numStr); 22640 22641 roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac); 22642 22643 var digits = parsedNumber.d; 22644 var integerLen = parsedNumber.i; 22645 var exponent = parsedNumber.e; 22646 var decimals = []; 22647 isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true); 22648 22649 // pad zeros for small numbers 22650 while (integerLen < 0) { 22651 digits.unshift(0); 22652 integerLen++; 22653 } 22654 22655 // extract decimals digits 22656 if (integerLen > 0) { 22657 decimals = digits.splice(integerLen, digits.length); 22658 } else { 22659 decimals = digits; 22660 digits = [0]; 22661 } 22662 22663 // format the integer digits with grouping separators 22664 var groups = []; 22665 if (digits.length >= pattern.lgSize) { 22666 groups.unshift(digits.splice(-pattern.lgSize, digits.length).join('')); 22667 } 22668 while (digits.length > pattern.gSize) { 22669 groups.unshift(digits.splice(-pattern.gSize, digits.length).join('')); 22670 } 22671 if (digits.length) { 22672 groups.unshift(digits.join('')); 22673 } 22674 formattedText = groups.join(groupSep); 22675 22676 // append the decimal digits 22677 if (decimals.length) { 22678 formattedText += decimalSep + decimals.join(''); 22679 } 22680 22681 if (exponent) { 22682 formattedText += 'e+' + exponent; 22683 } 22684 } 22685 if (number < 0 && !isZero) { 22686 return pattern.negPre + formattedText + pattern.negSuf; 22687 } else { 22688 return pattern.posPre + formattedText + pattern.posSuf; 22689 } 22690} 22691 22692function padNumber(num, digits, trim, negWrap) { 22693 var neg = ''; 22694 if (num < 0 || (negWrap && num <= 0)) { 22695 if (negWrap) { 22696 num = -num + 1; 22697 } else { 22698 num = -num; 22699 neg = '-'; 22700 } 22701 } 22702 num = '' + num; 22703 while (num.length < digits) num = ZERO_CHAR + num; 22704 if (trim) { 22705 num = num.substr(num.length - digits); 22706 } 22707 return neg + num; 22708} 22709 22710 22711function dateGetter(name, size, offset, trim, negWrap) { 22712 offset = offset || 0; 22713 return function(date) { 22714 var value = date['get' + name](); 22715 if (offset > 0 || value > -offset) { 22716 value += offset; 22717 } 22718 if (value === 0 && offset === -12) value = 12; 22719 return padNumber(value, size, trim, negWrap); 22720 }; 22721} 22722 22723function dateStrGetter(name, shortForm, standAlone) { 22724 return function(date, formats) { 22725 var value = date['get' + name](); 22726 var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : ''); 22727 var get = uppercase(propPrefix + name); 22728 22729 return formats[get][value]; 22730 }; 22731} 22732 22733function timeZoneGetter(date, formats, offset) { 22734 var zone = -1 * offset; 22735 var paddedZone = (zone >= 0) ? '+' : ''; 22736 22737 paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + 22738 padNumber(Math.abs(zone % 60), 2); 22739 22740 return paddedZone; 22741} 22742 22743function getFirstThursdayOfYear(year) { 22744 // 0 = index of January 22745 var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); 22746 // 4 = index of Thursday (+1 to account for 1st = 5) 22747 // 11 = index of *next* Thursday (+1 account for 1st = 12) 22748 return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); 22749} 22750 22751function getThursdayThisWeek(datetime) { 22752 return new Date(datetime.getFullYear(), datetime.getMonth(), 22753 // 4 = index of Thursday 22754 datetime.getDate() + (4 - datetime.getDay())); 22755} 22756 22757function weekGetter(size) { 22758 return function(date) { 22759 var firstThurs = getFirstThursdayOfYear(date.getFullYear()), 22760 thisThurs = getThursdayThisWeek(date); 22761 22762 var diff = +thisThurs - +firstThurs, 22763 result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week 22764 22765 return padNumber(result, size); 22766 }; 22767} 22768 22769function ampmGetter(date, formats) { 22770 return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; 22771} 22772 22773function eraGetter(date, formats) { 22774 return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1]; 22775} 22776 22777function longEraGetter(date, formats) { 22778 return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1]; 22779} 22780 22781var DATE_FORMATS = { 22782 yyyy: dateGetter('FullYear', 4, 0, false, true), 22783 yy: dateGetter('FullYear', 2, 0, true, true), 22784 y: dateGetter('FullYear', 1, 0, false, true), 22785 MMMM: dateStrGetter('Month'), 22786 MMM: dateStrGetter('Month', true), 22787 MM: dateGetter('Month', 2, 1), 22788 M: dateGetter('Month', 1, 1), 22789 LLLL: dateStrGetter('Month', false, true), 22790 dd: dateGetter('Date', 2), 22791 d: dateGetter('Date', 1), 22792 HH: dateGetter('Hours', 2), 22793 H: dateGetter('Hours', 1), 22794 hh: dateGetter('Hours', 2, -12), 22795 h: dateGetter('Hours', 1, -12), 22796 mm: dateGetter('Minutes', 2), 22797 m: dateGetter('Minutes', 1), 22798 ss: dateGetter('Seconds', 2), 22799 s: dateGetter('Seconds', 1), 22800 // while ISO 8601 requires fractions to be prefixed with `.` or `,` 22801 // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions 22802 sss: dateGetter('Milliseconds', 3), 22803 EEEE: dateStrGetter('Day'), 22804 EEE: dateStrGetter('Day', true), 22805 a: ampmGetter, 22806 Z: timeZoneGetter, 22807 ww: weekGetter(2), 22808 w: weekGetter(1), 22809 G: eraGetter, 22810 GG: eraGetter, 22811 GGG: eraGetter, 22812 GGGG: longEraGetter 22813}; 22814 22815var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/, 22816 NUMBER_STRING = /^-?\d+$/; 22817 22818/** 22819 * @ngdoc filter 22820 * @name date 22821 * @kind function 22822 * 22823 * @description 22824 * Formats `date` to a string based on the requested `format`. 22825 * 22826 * `format` string can be composed of the following elements: 22827 * 22828 * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) 22829 * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) 22830 * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) 22831 * * `'MMMM'`: Month in year (January-December) 22832 * * `'MMM'`: Month in year (Jan-Dec) 22833 * * `'MM'`: Month in year, padded (01-12) 22834 * * `'M'`: Month in year (1-12) 22835 * * `'LLLL'`: Stand-alone month in year (January-December) 22836 * * `'dd'`: Day in month, padded (01-31) 22837 * * `'d'`: Day in month (1-31) 22838 * * `'EEEE'`: Day in Week,(Sunday-Saturday) 22839 * * `'EEE'`: Day in Week, (Sun-Sat) 22840 * * `'HH'`: Hour in day, padded (00-23) 22841 * * `'H'`: Hour in day (0-23) 22842 * * `'hh'`: Hour in AM/PM, padded (01-12) 22843 * * `'h'`: Hour in AM/PM, (1-12) 22844 * * `'mm'`: Minute in hour, padded (00-59) 22845 * * `'m'`: Minute in hour (0-59) 22846 * * `'ss'`: Second in minute, padded (00-59) 22847 * * `'s'`: Second in minute (0-59) 22848 * * `'sss'`: Millisecond in second, padded (000-999) 22849 * * `'a'`: AM/PM marker 22850 * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) 22851 * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year 22852 * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year 22853 * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD') 22854 * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini') 22855 * 22856 * `format` string can also be one of the following predefined 22857 * {@link guide/i18n localizable formats}: 22858 * 22859 * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale 22860 * (e.g. Sep 3, 2010 12:05:08 PM) 22861 * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM) 22862 * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale 22863 * (e.g. Friday, September 3, 2010) 22864 * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) 22865 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) 22866 * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) 22867 * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM) 22868 * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM) 22869 * 22870 * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. 22871 * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence 22872 * (e.g. `"h 'o''clock'"`). 22873 * 22874 * Any other characters in the `format` string will be output as-is. 22875 * 22876 * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or 22877 * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its 22878 * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is 22879 * specified in the string input, the time is considered to be in the local timezone. 22880 * @param {string=} format Formatting rules (see Description). If not specified, 22881 * `mediumDate` is used. 22882 * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the 22883 * continental US time zone abbreviations, but for general use, use a time zone offset, for 22884 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian) 22885 * If not specified, the timezone of the browser will be used. 22886 * @returns {string} Formatted string or the input if input is not recognized as date/millis. 22887 * 22888 * @example 22889 <example name="filter-date"> 22890 <file name="index.html"> 22891 <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: 22892 <span>{{1288323623006 | date:'medium'}}</span><br> 22893 <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: 22894 <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br> 22895 <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: 22896 <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br> 22897 <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>: 22898 <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br> 22899 </file> 22900 <file name="protractor.js" type="protractor"> 22901 it('should format date', function() { 22902 expect(element(by.binding("1288323623006 | date:'medium'")).getText()). 22903 toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); 22904 expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). 22905 toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/); 22906 expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). 22907 toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); 22908 expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()). 22909 toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/); 22910 }); 22911 </file> 22912 </example> 22913 */ 22914dateFilter.$inject = ['$locale']; 22915function dateFilter($locale) { 22916 22917 22918 var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; 22919 // 1 2 3 4 5 6 7 8 9 10 11 22920 function jsonStringToDate(string) { 22921 var match; 22922 if ((match = string.match(R_ISO8601_STR))) { 22923 var date = new Date(0), 22924 tzHour = 0, 22925 tzMin = 0, 22926 dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, 22927 timeSetter = match[8] ? date.setUTCHours : date.setHours; 22928 22929 if (match[9]) { 22930 tzHour = toInt(match[9] + match[10]); 22931 tzMin = toInt(match[9] + match[11]); 22932 } 22933 dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); 22934 var h = toInt(match[4] || 0) - tzHour; 22935 var m = toInt(match[5] || 0) - tzMin; 22936 var s = toInt(match[6] || 0); 22937 var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000); 22938 timeSetter.call(date, h, m, s, ms); 22939 return date; 22940 } 22941 return string; 22942 } 22943 22944 22945 return function(date, format, timezone) { 22946 var text = '', 22947 parts = [], 22948 fn, match; 22949 22950 format = format || 'mediumDate'; 22951 format = $locale.DATETIME_FORMATS[format] || format; 22952 if (isString(date)) { 22953 date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date); 22954 } 22955 22956 if (isNumber(date)) { 22957 date = new Date(date); 22958 } 22959 22960 if (!isDate(date) || !isFinite(date.getTime())) { 22961 return date; 22962 } 22963 22964 while (format) { 22965 match = DATE_FORMATS_SPLIT.exec(format); 22966 if (match) { 22967 parts = concat(parts, match, 1); 22968 format = parts.pop(); 22969 } else { 22970 parts.push(format); 22971 format = null; 22972 } 22973 } 22974 22975 var dateTimezoneOffset = date.getTimezoneOffset(); 22976 if (timezone) { 22977 dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); 22978 date = convertTimezoneToLocal(date, timezone, true); 22979 } 22980 forEach(parts, function(value) { 22981 fn = DATE_FORMATS[value]; 22982 text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset) 22983 : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\''); 22984 }); 22985 22986 return text; 22987 }; 22988} 22989 22990 22991/** 22992 * @ngdoc filter 22993 * @name json 22994 * @kind function 22995 * 22996 * @description 22997 * Allows you to convert a JavaScript object into JSON string. 22998 * 22999 * This filter is mostly useful for debugging. When using the double curly {{value}} notation 23000 * the binding is automatically converted to JSON. 23001 * 23002 * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. 23003 * @param {number=} spacing The number of spaces to use per indentation, defaults to 2. 23004 * @returns {string} JSON string. 23005 * 23006 * 23007 * @example 23008 <example name="filter-json"> 23009 <file name="index.html"> 23010 <pre id="default-spacing">{{ {'name':'value'} | json }}</pre> 23011 <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre> 23012 </file> 23013 <file name="protractor.js" type="protractor"> 23014 it('should jsonify filtered objects', function() { 23015 expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/); 23016 expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/); 23017 }); 23018 </file> 23019 </example> 23020 * 23021 */ 23022function jsonFilter() { 23023 return function(object, spacing) { 23024 if (isUndefined(spacing)) { 23025 spacing = 2; 23026 } 23027 return toJson(object, spacing); 23028 }; 23029} 23030 23031 23032/** 23033 * @ngdoc filter 23034 * @name lowercase 23035 * @kind function 23036 * @description 23037 * Converts string to lowercase. 23038 * 23039 * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example. 23040 * 23041 * @see angular.lowercase 23042 */ 23043var lowercaseFilter = valueFn(lowercase); 23044 23045 23046/** 23047 * @ngdoc filter 23048 * @name uppercase 23049 * @kind function 23050 * @description 23051 * Converts string to uppercase. 23052 * @example 23053 <example module="uppercaseFilterExample" name="filter-uppercase"> 23054 <file name="index.html"> 23055 <script> 23056 angular.module('uppercaseFilterExample', []) 23057 .controller('ExampleController', ['$scope', function($scope) { 23058 $scope.title = 'This is a title'; 23059 }]); 23060 </script> 23061 <div ng-controller="ExampleController"> 23062 <!-- This title should be formatted normally --> 23063 <h1>{{title}}</h1> 23064 <!-- This title should be capitalized --> 23065 <h1>{{title | uppercase}}</h1> 23066 </div> 23067 </file> 23068 </example> 23069 */ 23070var uppercaseFilter = valueFn(uppercase); 23071 23072/** 23073 * @ngdoc filter 23074 * @name limitTo 23075 * @kind function 23076 * 23077 * @description 23078 * Creates a new array or string containing only a specified number of elements. The elements are 23079 * taken from either the beginning or the end of the source array, string or number, as specified by 23080 * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported 23081 * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, 23082 * it is converted to a string. 23083 * 23084 * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited. 23085 * @param {string|number} limit - The length of the returned array or string. If the `limit` number 23086 * is positive, `limit` number of items from the beginning of the source array/string are copied. 23087 * If the number is negative, `limit` number of items from the end of the source array/string 23088 * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined, 23089 * the input will be returned unchanged. 23090 * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index, 23091 * `begin` indicates an offset from the end of `input`. Defaults to `0`. 23092 * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had 23093 * less than `limit` elements. 23094 * 23095 * @example 23096 <example module="limitToExample" name="limit-to-filter"> 23097 <file name="index.html"> 23098 <script> 23099 angular.module('limitToExample', []) 23100 .controller('ExampleController', ['$scope', function($scope) { 23101 $scope.numbers = [1,2,3,4,5,6,7,8,9]; 23102 $scope.letters = "abcdefghi"; 23103 $scope.longNumber = 2345432342; 23104 $scope.numLimit = 3; 23105 $scope.letterLimit = 3; 23106 $scope.longNumberLimit = 3; 23107 }]); 23108 </script> 23109 <div ng-controller="ExampleController"> 23110 <label> 23111 Limit {{numbers}} to: 23112 <input type="number" step="1" ng-model="numLimit"> 23113 </label> 23114 <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> 23115 <label> 23116 Limit {{letters}} to: 23117 <input type="number" step="1" ng-model="letterLimit"> 23118 </label> 23119 <p>Output letters: {{ letters | limitTo:letterLimit }}</p> 23120 <label> 23121 Limit {{longNumber}} to: 23122 <input type="number" step="1" ng-model="longNumberLimit"> 23123 </label> 23124 <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p> 23125 </div> 23126 </file> 23127 <file name="protractor.js" type="protractor"> 23128 var numLimitInput = element(by.model('numLimit')); 23129 var letterLimitInput = element(by.model('letterLimit')); 23130 var longNumberLimitInput = element(by.model('longNumberLimit')); 23131 var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); 23132 var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); 23133 var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit')); 23134 23135 it('should limit the number array to first three items', function() { 23136 expect(numLimitInput.getAttribute('value')).toBe('3'); 23137 expect(letterLimitInput.getAttribute('value')).toBe('3'); 23138 expect(longNumberLimitInput.getAttribute('value')).toBe('3'); 23139 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); 23140 expect(limitedLetters.getText()).toEqual('Output letters: abc'); 23141 expect(limitedLongNumber.getText()).toEqual('Output long number: 234'); 23142 }); 23143 23144 // There is a bug in safari and protractor that doesn't like the minus key 23145 // it('should update the output when -3 is entered', function() { 23146 // numLimitInput.clear(); 23147 // numLimitInput.sendKeys('-3'); 23148 // letterLimitInput.clear(); 23149 // letterLimitInput.sendKeys('-3'); 23150 // longNumberLimitInput.clear(); 23151 // longNumberLimitInput.sendKeys('-3'); 23152 // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); 23153 // expect(limitedLetters.getText()).toEqual('Output letters: ghi'); 23154 // expect(limitedLongNumber.getText()).toEqual('Output long number: 342'); 23155 // }); 23156 23157 it('should not exceed the maximum size of input array', function() { 23158 numLimitInput.clear(); 23159 numLimitInput.sendKeys('100'); 23160 letterLimitInput.clear(); 23161 letterLimitInput.sendKeys('100'); 23162 longNumberLimitInput.clear(); 23163 longNumberLimitInput.sendKeys('100'); 23164 expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); 23165 expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); 23166 expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342'); 23167 }); 23168 </file> 23169 </example> 23170*/ 23171function limitToFilter() { 23172 return function(input, limit, begin) { 23173 if (Math.abs(Number(limit)) === Infinity) { 23174 limit = Number(limit); 23175 } else { 23176 limit = toInt(limit); 23177 } 23178 if (isNumberNaN(limit)) return input; 23179 23180 if (isNumber(input)) input = input.toString(); 23181 if (!isArrayLike(input)) return input; 23182 23183 begin = (!begin || isNaN(begin)) ? 0 : toInt(begin); 23184 begin = (begin < 0) ? Math.max(0, input.length + begin) : begin; 23185 23186 if (limit >= 0) { 23187 return sliceFn(input, begin, begin + limit); 23188 } else { 23189 if (begin === 0) { 23190 return sliceFn(input, limit, input.length); 23191 } else { 23192 return sliceFn(input, Math.max(0, begin + limit), begin); 23193 } 23194 } 23195 }; 23196} 23197 23198function sliceFn(input, begin, end) { 23199 if (isString(input)) return input.slice(begin, end); 23200 23201 return slice.call(input, begin, end); 23202} 23203 23204/** 23205 * @ngdoc filter 23206 * @name orderBy 23207 * @kind function 23208 * 23209 * @description 23210 * Returns an array containing the items from the specified `collection`, ordered by a `comparator` 23211 * function based on the values computed using the `expression` predicate. 23212 * 23213 * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in 23214 * `[{id: 'bar'}, {id: 'foo'}]`. 23215 * 23216 * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray, 23217 * String, etc). 23218 * 23219 * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker 23220 * for the preceding one. The `expression` is evaluated against each item and the output is used 23221 * for comparing with other items. 23222 * 23223 * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in 23224 * ascending order. 23225 * 23226 * The comparison is done using the `comparator` function. If none is specified, a default, built-in 23227 * comparator is used (see below for details - in a nutshell, it compares numbers numerically and 23228 * strings alphabetically). 23229 * 23230 * ### Under the hood 23231 * 23232 * Ordering the specified `collection` happens in two phases: 23233 * 23234 * 1. All items are passed through the predicate (or predicates), and the returned values are saved 23235 * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed 23236 * through a predicate that extracts the value of the `label` property, would be transformed to: 23237 * ``` 23238 * { 23239 * value: 'foo', 23240 * type: 'string', 23241 * index: ... 23242 * } 23243 * ``` 23244 * **Note:** `null` values use `'null'` as their type. 23245 * 2. The comparator function is used to sort the items, based on the derived values, types and 23246 * indices. 23247 * 23248 * If you use a custom comparator, it will be called with pairs of objects of the form 23249 * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal 23250 * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the 23251 * second, or `1` otherwise. 23252 * 23253 * In order to ensure that the sorting will be deterministic across platforms, if none of the 23254 * specified predicates can distinguish between two items, `orderBy` will automatically introduce a 23255 * dummy predicate that returns the item's index as `value`. 23256 * (If you are using a custom comparator, make sure it can handle this predicate as well.) 23257 * 23258 * If a custom comparator still can't distinguish between two items, then they will be sorted based 23259 * on their index using the built-in comparator. 23260 * 23261 * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted 23262 * value for an item, `orderBy` will try to convert that object to a primitive value, before passing 23263 * it to the comparator. The following rules govern the conversion: 23264 * 23265 * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be 23266 * used instead.<br /> 23267 * (If the object has a `valueOf()` method that returns another object, then the returned object 23268 * will be used in subsequent steps.) 23269 * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that 23270 * returns a primitive, its return value will be used instead.<br /> 23271 * (If the object has a `toString()` method that returns another object, then the returned object 23272 * will be used in subsequent steps.) 23273 * 3. No conversion; the object itself is used. 23274 * 23275 * ### The default comparator 23276 * 23277 * The default, built-in comparator should be sufficient for most usecases. In short, it compares 23278 * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to 23279 * using their index in the original collection, sorts values of different types by type and puts 23280 * `undefined` and `null` values at the end of the sorted list. 23281 * 23282 * More specifically, it follows these steps to determine the relative order of items: 23283 * 23284 * 1. If the compared values are of different types: 23285 * - If one of the values is undefined, consider it "greater than" the other. 23286 * - Else if one of the values is null, consider it "greater than" the other. 23287 * - Else compare the types themselves alphabetically. 23288 * 2. If both values are of type `string`, compare them alphabetically in a case- and 23289 * locale-insensitive way. 23290 * 3. If both values are objects, compare their indices instead. 23291 * 4. Otherwise, return: 23292 * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`). 23293 * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator). 23294 * - `1`, otherwise. 23295 * 23296 * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being 23297 * saved as numbers and not strings. 23298 * **Note:** For the purpose of sorting, `null` and `undefined` are considered "greater than" 23299 * any other value (with undefined "greater than" null). This effectively means that `null` 23300 * and `undefined` values end up at the end of a list sorted in ascending order. 23301 * **Note:** `null` values use `'null'` as their type to be able to distinguish them from objects. 23302 * 23303 * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort. 23304 * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of 23305 * predicates) to be used by the comparator to determine the order of elements. 23306 * 23307 * Can be one of: 23308 * 23309 * - `Function`: A getter function. This function will be called with each item as argument and 23310 * the return value will be used for sorting. 23311 * - `string`: An AngularJS expression. This expression will be evaluated against each item and the 23312 * result will be used for sorting. For example, use `'label'` to sort by a property called 23313 * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label` 23314 * property.<br /> 23315 * (The result of a constant expression is interpreted as a property name to be used for 23316 * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a 23317 * property called `special name`.)<br /> 23318 * An expression can be optionally prefixed with `+` or `-` to control the sorting direction, 23319 * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided, 23320 * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons. 23321 * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the 23322 * relative order of two items, the next predicate is used as a tie-breaker. 23323 * 23324 * **Note:** If the predicate is missing or empty then it defaults to `'+'`. 23325 * 23326 * @param {boolean=} reverse - If `true`, reverse the sorting order. 23327 * @param {(Function)=} comparator - The comparator function used to determine the relative order of 23328 * value pairs. If omitted, the built-in comparator will be used. 23329 * 23330 * @returns {Array} - The sorted array. 23331 * 23332 * 23333 * @example 23334 * ### Ordering a table with `ngRepeat` 23335 * 23336 * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by 23337 * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means 23338 * it defaults to the built-in comparator. 23339 * 23340 <example name="orderBy-static" module="orderByExample1"> 23341 <file name="index.html"> 23342 <div ng-controller="ExampleController"> 23343 <table class="friends"> 23344 <tr> 23345 <th>Name</th> 23346 <th>Phone Number</th> 23347 <th>Age</th> 23348 </tr> 23349 <tr ng-repeat="friend in friends | orderBy:'-age'"> 23350 <td>{{friend.name}}</td> 23351 <td>{{friend.phone}}</td> 23352 <td>{{friend.age}}</td> 23353 </tr> 23354 </table> 23355 </div> 23356 </file> 23357 <file name="script.js"> 23358 angular.module('orderByExample1', []) 23359 .controller('ExampleController', ['$scope', function($scope) { 23360 $scope.friends = [ 23361 {name: 'John', phone: '555-1212', age: 10}, 23362 {name: 'Mary', phone: '555-9876', age: 19}, 23363 {name: 'Mike', phone: '555-4321', age: 21}, 23364 {name: 'Adam', phone: '555-5678', age: 35}, 23365 {name: 'Julie', phone: '555-8765', age: 29} 23366 ]; 23367 }]); 23368 </file> 23369 <file name="style.css"> 23370 .friends { 23371 border-collapse: collapse; 23372 } 23373 23374 .friends th { 23375 border-bottom: 1px solid; 23376 } 23377 .friends td, .friends th { 23378 border-left: 1px solid; 23379 padding: 5px 10px; 23380 } 23381 .friends td:first-child, .friends th:first-child { 23382 border-left: none; 23383 } 23384 </file> 23385 <file name="protractor.js" type="protractor"> 23386 // Element locators 23387 var names = element.all(by.repeater('friends').column('friend.name')); 23388 23389 it('should sort friends by age in reverse order', function() { 23390 expect(names.get(0).getText()).toBe('Adam'); 23391 expect(names.get(1).getText()).toBe('Julie'); 23392 expect(names.get(2).getText()).toBe('Mike'); 23393 expect(names.get(3).getText()).toBe('Mary'); 23394 expect(names.get(4).getText()).toBe('John'); 23395 }); 23396 </file> 23397 </example> 23398 * <hr /> 23399 * 23400 * @example 23401 * ### Changing parameters dynamically 23402 * 23403 * All parameters can be changed dynamically. The next example shows how you can make the columns of 23404 * a table sortable, by binding the `expression` and `reverse` parameters to scope properties. 23405 * 23406 <example name="orderBy-dynamic" module="orderByExample2"> 23407 <file name="index.html"> 23408 <div ng-controller="ExampleController"> 23409 <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre> 23410 <hr/> 23411 <button ng-click="propertyName = null; reverse = false">Set to unsorted</button> 23412 <hr/> 23413 <table class="friends"> 23414 <tr> 23415 <th> 23416 <button ng-click="sortBy('name')">Name</button> 23417 <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span> 23418 </th> 23419 <th> 23420 <button ng-click="sortBy('phone')">Phone Number</button> 23421 <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span> 23422 </th> 23423 <th> 23424 <button ng-click="sortBy('age')">Age</button> 23425 <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span> 23426 </th> 23427 </tr> 23428 <tr ng-repeat="friend in friends | orderBy:propertyName:reverse"> 23429 <td>{{friend.name}}</td> 23430 <td>{{friend.phone}}</td> 23431 <td>{{friend.age}}</td> 23432 </tr> 23433 </table> 23434 </div> 23435 </file> 23436 <file name="script.js"> 23437 angular.module('orderByExample2', []) 23438 .controller('ExampleController', ['$scope', function($scope) { 23439 var friends = [ 23440 {name: 'John', phone: '555-1212', age: 10}, 23441 {name: 'Mary', phone: '555-9876', age: 19}, 23442 {name: 'Mike', phone: '555-4321', age: 21}, 23443 {name: 'Adam', phone: '555-5678', age: 35}, 23444 {name: 'Julie', phone: '555-8765', age: 29} 23445 ]; 23446 23447 $scope.propertyName = 'age'; 23448 $scope.reverse = true; 23449 $scope.friends = friends; 23450 23451 $scope.sortBy = function(propertyName) { 23452 $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false; 23453 $scope.propertyName = propertyName; 23454 }; 23455 }]); 23456 </file> 23457 <file name="style.css"> 23458 .friends { 23459 border-collapse: collapse; 23460 } 23461 23462 .friends th { 23463 border-bottom: 1px solid; 23464 } 23465 .friends td, .friends th { 23466 border-left: 1px solid; 23467 padding: 5px 10px; 23468 } 23469 .friends td:first-child, .friends th:first-child { 23470 border-left: none; 23471 } 23472 23473 .sortorder:after { 23474 content: '\25b2'; // BLACK UP-POINTING TRIANGLE 23475 } 23476 .sortorder.reverse:after { 23477 content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE 23478 } 23479 </file> 23480 <file name="protractor.js" type="protractor"> 23481 // Element locators 23482 var unsortButton = element(by.partialButtonText('unsorted')); 23483 var nameHeader = element(by.partialButtonText('Name')); 23484 var phoneHeader = element(by.partialButtonText('Phone')); 23485 var ageHeader = element(by.partialButtonText('Age')); 23486 var firstName = element(by.repeater('friends').column('friend.name').row(0)); 23487 var lastName = element(by.repeater('friends').column('friend.name').row(4)); 23488 23489 it('should sort friends by some property, when clicking on the column header', function() { 23490 expect(firstName.getText()).toBe('Adam'); 23491 expect(lastName.getText()).toBe('John'); 23492 23493 phoneHeader.click(); 23494 expect(firstName.getText()).toBe('John'); 23495 expect(lastName.getText()).toBe('Mary'); 23496 23497 nameHeader.click(); 23498 expect(firstName.getText()).toBe('Adam'); 23499 expect(lastName.getText()).toBe('Mike'); 23500 23501 ageHeader.click(); 23502 expect(firstName.getText()).toBe('John'); 23503 expect(lastName.getText()).toBe('Adam'); 23504 }); 23505 23506 it('should sort friends in reverse order, when clicking on the same column', function() { 23507 expect(firstName.getText()).toBe('Adam'); 23508 expect(lastName.getText()).toBe('John'); 23509 23510 ageHeader.click(); 23511 expect(firstName.getText()).toBe('John'); 23512 expect(lastName.getText()).toBe('Adam'); 23513 23514 ageHeader.click(); 23515 expect(firstName.getText()).toBe('Adam'); 23516 expect(lastName.getText()).toBe('John'); 23517 }); 23518 23519 it('should restore the original order, when clicking "Set to unsorted"', function() { 23520 expect(firstName.getText()).toBe('Adam'); 23521 expect(lastName.getText()).toBe('John'); 23522 23523 unsortButton.click(); 23524 expect(firstName.getText()).toBe('John'); 23525 expect(lastName.getText()).toBe('Julie'); 23526 }); 23527 </file> 23528 </example> 23529 * <hr /> 23530 * 23531 * @example 23532 * ### Using `orderBy` inside a controller 23533 * 23534 * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and 23535 * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory 23536 * and retrieve the `orderBy` filter with `$filter('orderBy')`.) 23537 * 23538 <example name="orderBy-call-manually" module="orderByExample3"> 23539 <file name="index.html"> 23540 <div ng-controller="ExampleController"> 23541 <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre> 23542 <hr/> 23543 <button ng-click="sortBy(null)">Set to unsorted</button> 23544 <hr/> 23545 <table class="friends"> 23546 <tr> 23547 <th> 23548 <button ng-click="sortBy('name')">Name</button> 23549 <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span> 23550 </th> 23551 <th> 23552 <button ng-click="sortBy('phone')">Phone Number</button> 23553 <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span> 23554 </th> 23555 <th> 23556 <button ng-click="sortBy('age')">Age</button> 23557 <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span> 23558 </th> 23559 </tr> 23560 <tr ng-repeat="friend in friends"> 23561 <td>{{friend.name}}</td> 23562 <td>{{friend.phone}}</td> 23563 <td>{{friend.age}}</td> 23564 </tr> 23565 </table> 23566 </div> 23567 </file> 23568 <file name="script.js"> 23569 angular.module('orderByExample3', []) 23570 .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) { 23571 var friends = [ 23572 {name: 'John', phone: '555-1212', age: 10}, 23573 {name: 'Mary', phone: '555-9876', age: 19}, 23574 {name: 'Mike', phone: '555-4321', age: 21}, 23575 {name: 'Adam', phone: '555-5678', age: 35}, 23576 {name: 'Julie', phone: '555-8765', age: 29} 23577 ]; 23578 23579 $scope.propertyName = 'age'; 23580 $scope.reverse = true; 23581 $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse); 23582 23583 $scope.sortBy = function(propertyName) { 23584 $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName) 23585 ? !$scope.reverse : false; 23586 $scope.propertyName = propertyName; 23587 $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse); 23588 }; 23589 }]); 23590 </file> 23591 <file name="style.css"> 23592 .friends { 23593 border-collapse: collapse; 23594 } 23595 23596 .friends th { 23597 border-bottom: 1px solid; 23598 } 23599 .friends td, .friends th { 23600 border-left: 1px solid; 23601 padding: 5px 10px; 23602 } 23603 .friends td:first-child, .friends th:first-child { 23604 border-left: none; 23605 } 23606 23607 .sortorder:after { 23608 content: '\25b2'; // BLACK UP-POINTING TRIANGLE 23609 } 23610 .sortorder.reverse:after { 23611 content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE 23612 } 23613 </file> 23614 <file name="protractor.js" type="protractor"> 23615 // Element locators 23616 var unsortButton = element(by.partialButtonText('unsorted')); 23617 var nameHeader = element(by.partialButtonText('Name')); 23618 var phoneHeader = element(by.partialButtonText('Phone')); 23619 var ageHeader = element(by.partialButtonText('Age')); 23620 var firstName = element(by.repeater('friends').column('friend.name').row(0)); 23621 var lastName = element(by.repeater('friends').column('friend.name').row(4)); 23622 23623 it('should sort friends by some property, when clicking on the column header', function() { 23624 expect(firstName.getText()).toBe('Adam'); 23625 expect(lastName.getText()).toBe('John'); 23626 23627 phoneHeader.click(); 23628 expect(firstName.getText()).toBe('John'); 23629 expect(lastName.getText()).toBe('Mary'); 23630 23631 nameHeader.click(); 23632 expect(firstName.getText()).toBe('Adam'); 23633 expect(lastName.getText()).toBe('Mike'); 23634 23635 ageHeader.click(); 23636 expect(firstName.getText()).toBe('John'); 23637 expect(lastName.getText()).toBe('Adam'); 23638 }); 23639 23640 it('should sort friends in reverse order, when clicking on the same column', function() { 23641 expect(firstName.getText()).toBe('Adam'); 23642 expect(lastName.getText()).toBe('John'); 23643 23644 ageHeader.click(); 23645 expect(firstName.getText()).toBe('John'); 23646 expect(lastName.getText()).toBe('Adam'); 23647 23648 ageHeader.click(); 23649 expect(firstName.getText()).toBe('Adam'); 23650 expect(lastName.getText()).toBe('John'); 23651 }); 23652 23653 it('should restore the original order, when clicking "Set to unsorted"', function() { 23654 expect(firstName.getText()).toBe('Adam'); 23655 expect(lastName.getText()).toBe('John'); 23656 23657 unsortButton.click(); 23658 expect(firstName.getText()).toBe('John'); 23659 expect(lastName.getText()).toBe('Julie'); 23660 }); 23661 </file> 23662 </example> 23663 * <hr /> 23664 * 23665 * @example 23666 * ### Using a custom comparator 23667 * 23668 * If you have very specific requirements about the way items are sorted, you can pass your own 23669 * comparator function. For example, you might need to compare some strings in a locale-sensitive 23670 * way. (When specifying a custom comparator, you also need to pass a value for the `reverse` 23671 * argument - passing `false` retains the default sorting order, i.e. ascending.) 23672 * 23673 <example name="orderBy-custom-comparator" module="orderByExample4"> 23674 <file name="index.html"> 23675 <div ng-controller="ExampleController"> 23676 <div class="friends-container custom-comparator"> 23677 <h3>Locale-sensitive Comparator</h3> 23678 <table class="friends"> 23679 <tr> 23680 <th>Name</th> 23681 <th>Favorite Letter</th> 23682 </tr> 23683 <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator"> 23684 <td>{{friend.name}}</td> 23685 <td>{{friend.favoriteLetter}}</td> 23686 </tr> 23687 </table> 23688 </div> 23689 <div class="friends-container default-comparator"> 23690 <h3>Default Comparator</h3> 23691 <table class="friends"> 23692 <tr> 23693 <th>Name</th> 23694 <th>Favorite Letter</th> 23695 </tr> 23696 <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'"> 23697 <td>{{friend.name}}</td> 23698 <td>{{friend.favoriteLetter}}</td> 23699 </tr> 23700 </table> 23701 </div> 23702 </div> 23703 </file> 23704 <file name="script.js"> 23705 angular.module('orderByExample4', []) 23706 .controller('ExampleController', ['$scope', function($scope) { 23707 $scope.friends = [ 23708 {name: 'John', favoriteLetter: 'Ä'}, 23709 {name: 'Mary', favoriteLetter: 'Ü'}, 23710 {name: 'Mike', favoriteLetter: 'Ö'}, 23711 {name: 'Adam', favoriteLetter: 'H'}, 23712 {name: 'Julie', favoriteLetter: 'Z'} 23713 ]; 23714 23715 $scope.localeSensitiveComparator = function(v1, v2) { 23716 // If we don't get strings, just compare by index 23717 if (v1.type !== 'string' || v2.type !== 'string') { 23718 return (v1.index < v2.index) ? -1 : 1; 23719 } 23720 23721 // Compare strings alphabetically, taking locale into account 23722 return v1.value.localeCompare(v2.value); 23723 }; 23724 }]); 23725 </file> 23726 <file name="style.css"> 23727 .friends-container { 23728 display: inline-block; 23729 margin: 0 30px; 23730 } 23731 23732 .friends { 23733 border-collapse: collapse; 23734 } 23735 23736 .friends th { 23737 border-bottom: 1px solid; 23738 } 23739 .friends td, .friends th { 23740 border-left: 1px solid; 23741 padding: 5px 10px; 23742 } 23743 .friends td:first-child, .friends th:first-child { 23744 border-left: none; 23745 } 23746 </file> 23747 <file name="protractor.js" type="protractor"> 23748 // Element locators 23749 var container = element(by.css('.custom-comparator')); 23750 var names = container.all(by.repeater('friends').column('friend.name')); 23751 23752 it('should sort friends by favorite letter (in correct alphabetical order)', function() { 23753 expect(names.get(0).getText()).toBe('John'); 23754 expect(names.get(1).getText()).toBe('Adam'); 23755 expect(names.get(2).getText()).toBe('Mike'); 23756 expect(names.get(3).getText()).toBe('Mary'); 23757 expect(names.get(4).getText()).toBe('Julie'); 23758 }); 23759 </file> 23760 </example> 23761 * 23762 */ 23763orderByFilter.$inject = ['$parse']; 23764function orderByFilter($parse) { 23765 return function(array, sortPredicate, reverseOrder, compareFn) { 23766 23767 if (array == null) return array; 23768 if (!isArrayLike(array)) { 23769 throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array); 23770 } 23771 23772 if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; } 23773 if (sortPredicate.length === 0) { sortPredicate = ['+']; } 23774 23775 var predicates = processPredicates(sortPredicate); 23776 23777 var descending = reverseOrder ? -1 : 1; 23778 23779 // Define the `compare()` function. Use a default comparator if none is specified. 23780 var compare = isFunction(compareFn) ? compareFn : defaultCompare; 23781 23782 // The next three lines are a version of a Swartzian Transform idiom from Perl 23783 // (sometimes called the Decorate-Sort-Undecorate idiom) 23784 // See https://en.wikipedia.org/wiki/Schwartzian_transform 23785 var compareValues = Array.prototype.map.call(array, getComparisonObject); 23786 compareValues.sort(doComparison); 23787 array = compareValues.map(function(item) { return item.value; }); 23788 23789 return array; 23790 23791 function getComparisonObject(value, index) { 23792 // NOTE: We are adding an extra `tieBreaker` value based on the element's index. 23793 // This will be used to keep the sort stable when none of the input predicates can 23794 // distinguish between two elements. 23795 return { 23796 value: value, 23797 tieBreaker: {value: index, type: 'number', index: index}, 23798 predicateValues: predicates.map(function(predicate) { 23799 return getPredicateValue(predicate.get(value), index); 23800 }) 23801 }; 23802 } 23803 23804 function doComparison(v1, v2) { 23805 for (var i = 0, ii = predicates.length; i < ii; i++) { 23806 var result = compare(v1.predicateValues[i], v2.predicateValues[i]); 23807 if (result) { 23808 return result * predicates[i].descending * descending; 23809 } 23810 } 23811 23812 return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending; 23813 } 23814 }; 23815 23816 function processPredicates(sortPredicates) { 23817 return sortPredicates.map(function(predicate) { 23818 var descending = 1, get = identity; 23819 23820 if (isFunction(predicate)) { 23821 get = predicate; 23822 } else if (isString(predicate)) { 23823 if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) { 23824 descending = predicate.charAt(0) === '-' ? -1 : 1; 23825 predicate = predicate.substring(1); 23826 } 23827 if (predicate !== '') { 23828 get = $parse(predicate); 23829 if (get.constant) { 23830 var key = get(); 23831 get = function(value) { return value[key]; }; 23832 } 23833 } 23834 } 23835 return {get: get, descending: descending}; 23836 }); 23837 } 23838 23839 function isPrimitive(value) { 23840 switch (typeof value) { 23841 case 'number': /* falls through */ 23842 case 'boolean': /* falls through */ 23843 case 'string': 23844 return true; 23845 default: 23846 return false; 23847 } 23848 } 23849 23850 function objectValue(value) { 23851 // If `valueOf` is a valid function use that 23852 if (isFunction(value.valueOf)) { 23853 value = value.valueOf(); 23854 if (isPrimitive(value)) return value; 23855 } 23856 // If `toString` is a valid function and not the one from `Object.prototype` use that 23857 if (hasCustomToString(value)) { 23858 value = value.toString(); 23859 if (isPrimitive(value)) return value; 23860 } 23861 23862 return value; 23863 } 23864 23865 function getPredicateValue(value, index) { 23866 var type = typeof value; 23867 if (value === null) { 23868 type = 'null'; 23869 } else if (type === 'object') { 23870 value = objectValue(value); 23871 } 23872 return {value: value, type: type, index: index}; 23873 } 23874 23875 function defaultCompare(v1, v2) { 23876 var result = 0; 23877 var type1 = v1.type; 23878 var type2 = v2.type; 23879 23880 if (type1 === type2) { 23881 var value1 = v1.value; 23882 var value2 = v2.value; 23883 23884 if (type1 === 'string') { 23885 // Compare strings case-insensitively 23886 value1 = value1.toLowerCase(); 23887 value2 = value2.toLowerCase(); 23888 } else if (type1 === 'object') { 23889 // For basic objects, use the position of the object 23890 // in the collection instead of the value 23891 if (isObject(value1)) value1 = v1.index; 23892 if (isObject(value2)) value2 = v2.index; 23893 } 23894 23895 if (value1 !== value2) { 23896 result = value1 < value2 ? -1 : 1; 23897 } 23898 } else { 23899 result = (type1 === 'undefined') ? 1 : 23900 (type2 === 'undefined') ? -1 : 23901 (type1 === 'null') ? 1 : 23902 (type2 === 'null') ? -1 : 23903 (type1 < type2) ? -1 : 1; 23904 } 23905 23906 return result; 23907 } 23908} 23909 23910function ngDirective(directive) { 23911 if (isFunction(directive)) { 23912 directive = { 23913 link: directive 23914 }; 23915 } 23916 directive.restrict = directive.restrict || 'AC'; 23917 return valueFn(directive); 23918} 23919 23920/** 23921 * @ngdoc directive 23922 * @name a 23923 * @restrict E 23924 * 23925 * @description 23926 * Modifies the default behavior of the html a tag so that the default action is prevented when 23927 * the href attribute is empty. 23928 * 23929 * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive. 23930 */ 23931var htmlAnchorDirective = valueFn({ 23932 restrict: 'E', 23933 compile: function(element, attr) { 23934 if (!attr.href && !attr.xlinkHref) { 23935 return function(scope, element) { 23936 // If the linked element is not an anchor tag anymore, do nothing 23937 if (element[0].nodeName.toLowerCase() !== 'a') return; 23938 23939 // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. 23940 var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? 23941 'xlink:href' : 'href'; 23942 element.on('click', function(event) { 23943 // if we have no href url, then don't navigate anywhere. 23944 if (!element.attr(href)) { 23945 event.preventDefault(); 23946 } 23947 }); 23948 }; 23949 } 23950 } 23951}); 23952 23953/** 23954 * @ngdoc directive 23955 * @name ngHref 23956 * @restrict A 23957 * @priority 99 23958 * 23959 * @description 23960 * Using AngularJS markup like `{{hash}}` in an href attribute will 23961 * make the link go to the wrong URL if the user clicks it before 23962 * AngularJS has a chance to replace the `{{hash}}` markup with its 23963 * value. Until AngularJS replaces the markup the link will be broken 23964 * and will most likely return a 404 error. The `ngHref` directive 23965 * solves this problem. 23966 * 23967 * The wrong way to write it: 23968 * ```html 23969 * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a> 23970 * ``` 23971 * 23972 * The correct way to write it: 23973 * ```html 23974 * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a> 23975 * ``` 23976 * 23977 * @element A 23978 * @param {template} ngHref any string which can contain `{{}}` markup. 23979 * 23980 * @example 23981 * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes 23982 * in links and their different behaviors: 23983 <example name="ng-href"> 23984 <file name="index.html"> 23985 <input ng-model="value" /><br /> 23986 <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> 23987 <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> 23988 <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> 23989 <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> 23990 <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> 23991 <a id="link-6" ng-href="{{value}}">link</a> (link, change location) 23992 </file> 23993 <file name="protractor.js" type="protractor"> 23994 it('should execute ng-click but not reload when href without value', function() { 23995 element(by.id('link-1')).click(); 23996 expect(element(by.model('value')).getAttribute('value')).toEqual('1'); 23997 expect(element(by.id('link-1')).getAttribute('href')).toBe(''); 23998 }); 23999 24000 it('should execute ng-click but not reload when href empty string', function() { 24001 element(by.id('link-2')).click(); 24002 expect(element(by.model('value')).getAttribute('value')).toEqual('2'); 24003 expect(element(by.id('link-2')).getAttribute('href')).toBe(''); 24004 }); 24005 24006 it('should execute ng-click and change url when ng-href specified', function() { 24007 expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); 24008 24009 element(by.id('link-3')).click(); 24010 24011 // At this point, we navigate away from an AngularJS page, so we need 24012 // to use browser.driver to get the base webdriver. 24013 24014 browser.wait(function() { 24015 return browser.driver.getCurrentUrl().then(function(url) { 24016 return url.match(/\/123$/); 24017 }); 24018 }, 5000, 'page should navigate to /123'); 24019 }); 24020 24021 it('should execute ng-click but not reload when href empty string and name specified', function() { 24022 element(by.id('link-4')).click(); 24023 expect(element(by.model('value')).getAttribute('value')).toEqual('4'); 24024 expect(element(by.id('link-4')).getAttribute('href')).toBe(''); 24025 }); 24026 24027 it('should execute ng-click but not reload when no href but name specified', function() { 24028 element(by.id('link-5')).click(); 24029 expect(element(by.model('value')).getAttribute('value')).toEqual('5'); 24030 expect(element(by.id('link-5')).getAttribute('href')).toBe(null); 24031 }); 24032 24033 it('should only change url when only ng-href', function() { 24034 element(by.model('value')).clear(); 24035 element(by.model('value')).sendKeys('6'); 24036 expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); 24037 24038 element(by.id('link-6')).click(); 24039 24040 // At this point, we navigate away from an AngularJS page, so we need 24041 // to use browser.driver to get the base webdriver. 24042 browser.wait(function() { 24043 return browser.driver.getCurrentUrl().then(function(url) { 24044 return url.match(/\/6$/); 24045 }); 24046 }, 5000, 'page should navigate to /6'); 24047 }); 24048 </file> 24049 </example> 24050 */ 24051 24052/** 24053 * @ngdoc directive 24054 * @name ngSrc 24055 * @restrict A 24056 * @priority 99 24057 * 24058 * @description 24059 * Using AngularJS markup like `{{hash}}` in a `src` attribute doesn't 24060 * work right: The browser will fetch from the URL with the literal 24061 * text `{{hash}}` until AngularJS replaces the expression inside 24062 * `{{hash}}`. The `ngSrc` directive solves this problem. 24063 * 24064 * The buggy way to write it: 24065 * ```html 24066 * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/> 24067 * ``` 24068 * 24069 * The correct way to write it: 24070 * ```html 24071 * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" /> 24072 * ``` 24073 * 24074 * @element IMG 24075 * @param {template} ngSrc any string which can contain `{{}}` markup. 24076 */ 24077 24078/** 24079 * @ngdoc directive 24080 * @name ngSrcset 24081 * @restrict A 24082 * @priority 99 24083 * 24084 * @description 24085 * Using AngularJS markup like `{{hash}}` in a `srcset` attribute doesn't 24086 * work right: The browser will fetch from the URL with the literal 24087 * text `{{hash}}` until AngularJS replaces the expression inside 24088 * `{{hash}}`. The `ngSrcset` directive solves this problem. 24089 * 24090 * The buggy way to write it: 24091 * ```html 24092 * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/> 24093 * ``` 24094 * 24095 * The correct way to write it: 24096 * ```html 24097 * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" /> 24098 * ``` 24099 * 24100 * @element IMG 24101 * @param {template} ngSrcset any string which can contain `{{}}` markup. 24102 */ 24103 24104/** 24105 * @ngdoc directive 24106 * @name ngDisabled 24107 * @restrict A 24108 * @priority 100 24109 * 24110 * @description 24111 * 24112 * This directive sets the `disabled` attribute on the element (typically a form control, 24113 * e.g. `input`, `button`, `select` etc.) if the 24114 * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy. 24115 * 24116 * A special directive is necessary because we cannot use interpolation inside the `disabled` 24117 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 24118 * 24119 * @example 24120 <example name="ng-disabled"> 24121 <file name="index.html"> 24122 <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/> 24123 <button ng-model="button" ng-disabled="checked">Button</button> 24124 </file> 24125 <file name="protractor.js" type="protractor"> 24126 it('should toggle button', function() { 24127 expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); 24128 element(by.model('checked')).click(); 24129 expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); 24130 }); 24131 </file> 24132 </example> 24133 * 24134 * @
24134element INPUT 24135 * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, 24136 * then the `disabled` attribute will be set on the element 24137 */ 24138 24139 24140/** 24141 * @ngdoc directive 24142 * @name ngChecked 24143 * @restrict A 24144 * @priority 100 24145 * 24146 * @description 24147 * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy. 24148 * 24149 * Note that this directive should not be used together with {@link ngModel `ngModel`}, 24150 * as this can lead to unexpected behavior. 24151 * 24152 * A special directive is necessary because we cannot use interpolation inside the `checked` 24153 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 24154 * 24155 * @example 24156 <example name="ng-checked"> 24157 <file name="index.html"> 24158 <label>Check me to check both: <input type="checkbox" ng-model="leader"></label><br/> 24159 <input id="checkFollower" type="checkbox" ng-checked="leader" aria-label="Follower input"> 24160 </file> 24161 <file name="protractor.js" type="protractor"> 24162 it('should check both checkBoxes', function() { 24163 expect(element(by.id('checkFollower')).getAttribute('checked')).toBeFalsy(); 24164 element(by.model('leader')).click(); 24165 expect(element(by.id('checkFollower')).getAttribute('checked')).toBeTruthy(); 24166 }); 24167 </file> 24168 </example> 24169 * 24170 * @element INPUT 24171 * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, 24172 * then the `checked` attribute will be set on the element 24173 */ 24174 24175 24176/** 24177 * @ngdoc directive 24178 * @name ngReadonly 24179 * @restrict A 24180 * @priority 100 24181 * 24182 * @description 24183 * 24184 * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy. 24185 * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on 24186 * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information. 24187 * 24188 * A special directive is necessary because we cannot use interpolation inside the `readonly` 24189 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 24190 * 24191 * @example 24192 <example name="ng-readonly"> 24193 <file name="index.html"> 24194 <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/> 24195 <input type="text" ng-readonly="checked" value="I'm AngularJS" aria-label="Readonly field" /> 24196 </file> 24197 <file name="protractor.js" type="protractor"> 24198 it('should toggle readonly attr', function() { 24199 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); 24200 element(by.model('checked')).click(); 24201 expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); 24202 }); 24203 </file> 24204 </example> 24205 * 24206 * @element INPUT 24207 * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, 24208 * then special attribute "readonly" will be set on the element 24209 */ 24210 24211 24212/** 24213 * @ngdoc directive 24214 * @name ngSelected 24215 * @restrict A 24216 * @priority 100 24217 * 24218 * @description 24219 * 24220 * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy. 24221 * 24222 * A special directive is necessary because we cannot use interpolation inside the `selected` 24223 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 24224 * 24225 * <div class="alert alert-warning"> 24226 * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only 24227 * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you 24228 * should not use `ngSelected` on the options, as `ngModel` will set the select value and 24229 * selected options. 24230 * </div> 24231 * 24232 * @example 24233 <example name="ng-selected"> 24234 <file name="index.html"> 24235 <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/> 24236 <select aria-label="ngSelected demo"> 24237 <option>Hello!</option> 24238 <option id="greet" ng-selected="selected">Greetings!</option> 24239 </select> 24240 </file> 24241 <file name="protractor.js" type="protractor"> 24242 it('should select Greetings!', function() { 24243 expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
vendor: 4,409 bytes, lines 24244-24384
24244 element(by.model('selected')).click(); 24245 expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); 24246 }); 24247 </file> 24248 </example> 24249 * 24250 * @element OPTION 24251 * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, 24252 * then special attribute "selected" will be set on the element 24253 */ 24254 24255/** 24256 * @ngdoc directive 24257 * @name ngOpen 24258 * @restrict A 24259 * @priority 100 24260 * 24261 * @description 24262 * 24263 * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy. 24264 * 24265 * A special directive is necessary because we cannot use interpolation inside the `open` 24266 * attribute. See the {@link guide/interpolation interpolation guide} for more info. 24267 * 24268 * ## A note about browser compatibility 24269 * 24270 * Internet Explorer and Edge do not support the `details` element, it is 24271 * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead. 24272 * 24273 * @example 24274 <example name="ng-open"> 24275 <file name="index.html"> 24276 <label>Toggle details: <input type="checkbox" ng-model="open"></label><br/> 24277 <details id="details" ng-open="open"> 24278 <summary>List</summary> 24279 <ul> 24280 <li>Apple</li> 24281 <li>Orange</li> 24282 <li>Durian</li> 24283 </ul> 24284 </details> 24285 </file> 24286 <file name="protractor.js" type="protractor"> 24287 it('should toggle open', function() { 24288 expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); 24289 element(by.model('open')).click(); 24290 expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); 24291 }); 24292 </file> 24293 </example> 24294 * 24295 * @element DETAILS 24296 * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, 24297 * then special attribute "open" will be set on the element 24298 */ 24299 24300var ngAttributeAliasDirectives = {}; 24301 24302// boolean attrs are evaluated 24303forEach(BOOLEAN_ATTR, function(propName, attrName) { 24304 // binding to multiple is not supported 24305 if (propName === 'multiple') return; 24306 24307 function defaultLinkFn(scope, element, attr) { 24308 scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { 24309 attr.$set(attrName, !!value); 24310 }); 24311 } 24312 24313 var normalized = directiveNormalize('ng-' + attrName); 24314 var linkFn = defaultLinkFn; 24315 24316 if (propName === 'checked') { 24317 linkFn = function(scope, element, attr) { 24318 // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input 24319 if (attr.ngModel !== attr[normalized]) { 24320 defaultLinkFn(scope, element, attr); 24321 } 24322 }; 24323 } 24324 24325 ngAttributeAliasDirectives[normalized] = function() { 24326 return { 24327 restrict: 'A', 24328 priority: 100, 24329 link: linkFn 24330 }; 24331 }; 24332}); 24333 24334// aliased input attrs are evaluated 24335forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { 24336 ngAttributeAliasDirectives[ngAttr] = function() { 24337 return { 24338 priority: 100, 24339 link: function(scope, element, attr) { 24340 //special case ngPattern when a literal regular expression value 24341 //is used as the expression (this way we don't have to watch anything). 24342 if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') { 24343 var match = attr.ngPattern.match(REGEX_STRING_REGEXP); 24344 if (match) { 24345 attr.$set('ngPattern', new RegExp(match[1], match[2])); 24346 return; 24347 } 24348 } 24349 24350 scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { 24351 attr.$set(ngAttr, value); 24352 }); 24353 } 24354 }; 24355 }; 24356}); 24357 24358// ng-src, ng-srcset, ng-href are interpolated 24359forEach(['src', 'srcset', 'href'], function(attrName) { 24360 var normalized = directiveNormalize('ng-' + attrName); 24361 ngAttributeAliasDirectives[normalized] = function() { 24362 return { 24363 priority: 99, // it needs to run after the attributes are interpolated 24364 link: function(scope, element, attr) { 24365 var propName = attrName, 24366 name = attrName; 24367 24368 if (attrName === 'href' && 24369 toString.call(element.prop('href')) === '[object SVGAnimatedString]') { 24370 name = 'xlinkHref'; 24371 attr.$attr[name] = 'xlink:href'; 24372 propName = null; 24373 } 24374 24375 attr.$observe(normalized, function(value) { 24376 if (!value) { 24377 if (attrName === 'href') { 24378 attr.$set(name, null); 24379 } 24380 return; 24381 } 24382 24383 attr.$set(name, value); 24384
24385 // Support: IE 9-11 only 24386 // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist 24387 // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need 24388 // to set the property as well to achieve the desired effect. 24389 // We use attr[attrName] value since $set might have sanitized the url. 24390 if (msie && propName) element.prop(propName, attr[name]); 24391 }); 24392 } 24393 }; 24394 }
vendor: 73,457 bytes, lines 24394-26032
24394; 24395}); 24396 24397/* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS 24398 */ 24399var nullFormCtrl = { 24400 $addControl: noop, 24401 $getControls: valueFn([]), 24402 $$renameControl: nullFormRenameControl, 24403 $removeControl: noop, 24404 $setValidity: noop, 24405 $setDirty: noop, 24406 $setPristine: noop, 24407 $setSubmitted: noop, 24408 $$setSubmitted: noop 24409}, 24410PENDING_CLASS = 'ng-pending', 24411SUBMITTED_CLASS = 'ng-submitted'; 24412 24413function nullFormRenameControl(control, name) { 24414 control.$name = name; 24415} 24416 24417/** 24418 * @ngdoc type 24419 * @name form.FormController 24420 * 24421 * @property {boolean} $pristine True if user has not interacted with the form yet. 24422 * @property {boolean} $dirty True if user has already interacted with the form. 24423 * @property {boolean} $valid True if all of the containing forms and controls are valid. 24424 * @property {boolean} $invalid True if at least one containing control or form is invalid. 24425 * @property {boolean} $submitted True if user has submitted the form even if its invalid. 24426 * 24427 * @property {Object} $pending An object hash, containing references to controls or forms with 24428 * pending validators, where: 24429 * 24430 * - keys are validations tokens (error names). 24431 * - values are arrays of controls or forms that have a pending validator for the given error name. 24432 * 24433 * See {@link form.FormController#$error $error} for a list of built-in validation tokens. 24434 * 24435 * @property {Object} $error An object hash, containing references to controls or forms with failing 24436 * validators, where: 24437 * 24438 * - keys are validation tokens (error names), 24439 * - values are arrays of controls or forms that have a failing validator for the given error name. 24440 * 24441 * Built-in validation tokens: 24442 * - `email` 24443 * - `max` 24444 * - `maxlength` 24445 * - `min` 24446 * - `minlength` 24447 * - `number` 24448 * - `pattern` 24449 * - `required` 24450 * - `url` 24451 * - `date` 24452 * - `datetimelocal` 24453 * - `time` 24454 * - `week` 24455 * - `month` 24456 * 24457 * @description 24458 * `FormController` keeps track of all its controls and nested forms as well as the state of them, 24459 * such as being valid/invalid or dirty/pristine. 24460 * 24461 * Each {@link ng.directive:form form} directive creates an instance 24462 * of `FormController`. 24463 * 24464 */ 24465//asks for $scope to fool the BC controller module 24466FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; 24467function FormController($element, $attrs, $scope, $animate, $interpolate) { 24468 this.$$controls = []; 24469 24470 // init state 24471 this.$error = {}; 24472 this.$$success = {}; 24473 this.$pending = undefined; 24474 this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope); 24475 this.$dirty = false; 24476 this.$pristine = true; 24477 this.$valid = true; 24478 this.$invalid = false; 24479 this.$submitted = false; 24480 this.$$parentForm = nullFormCtrl; 24481 24482 this.$$element = $element; 24483 this.$$animate = $animate; 24484 24485 setupValidity(this); 24486} 24487 24488FormController.prototype = { 24489 /** 24490 * @ngdoc method 24491 * @name form.FormController#$rollbackViewValue 24492 * 24493 * @description 24494 * Rollback all form controls pending updates to the `$modelValue`. 24495 * 24496 * Updates may be pending by a debounced event or because the input is waiting for a some future 24497 * event defined in `ng-model-options`. This method is typically needed by the reset button of 24498 * a form that uses `ng-model-options` to pend updates. 24499 */ 24500 $rollbackViewValue: function() { 24501 forEach(this.$$controls, function(control) { 24502 control.$rollbackViewValue(); 24503 }); 24504 }, 24505 24506 /** 24507 * @ngdoc method 24508 * @name form.FormController#$commitViewValue 24509 * 24510 * @description 24511 * Commit all form controls pending updates to the `$modelValue`. 24512 * 24513 * Updates may be pending by a debounced event or because the input is waiting for a some future 24514 * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` 24515 * usually handles calling this in response to input events. 24516 */ 24517 $commitViewValue: function() { 24518 forEach(this.$$controls, function(control) { 24519 control.$commitViewValue(); 24520 }); 24521 }, 24522 24523 /** 24524 * @ngdoc method 24525 * @name form.FormController#$addControl 24526 * @param {object} control control object, either a {@link form.FormController} or an 24527 * {@link ngModel.NgModelController} 24528 * 24529 * @description 24530 * Register a control with the form. Input elements using ngModelController do this automatically 24531 * when they are linked. 24532 * 24533 * Note that the current state of the control will not be reflected on the new parent form. This 24534 * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine` 24535 * state. 24536 * 24537 * However, if the method is used programmatically, for example by adding dynamically created controls, 24538 * or controls that have been previously removed without destroying their corresponding DOM element, 24539 * it's the developers responsibility to make sure the current state propagates to the parent form. 24540 * 24541 * For example, if an input control is added that is already `$dirty` and has `$error` properties, 24542 * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form. 24543 */ 24544 $addControl: function(control) { 24545 // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored 24546 // and not added to the scope. Now we throw an error. 24547 assertNotHasOwnProperty(control.$name, 'input'); 24548 this.$$controls.push(control); 24549 24550 if (control.$name) { 24551 this[control.$name] = control; 24552 } 24553 24554 control.$$parentForm = this; 24555 }, 24556 24557 /** 24558 * @ngdoc method 24559 * @name form.FormController#$getControls 24560 * @returns {Array} the controls that are currently part of this form 24561 * 24562 * @description 24563 * This method returns a **shallow copy** of the controls that are currently part of this form. 24564 * The controls can be instances of {@link form.FormController `FormController`} 24565 * ({@link ngForm "child-forms"}) and of {@link ngModel.NgModelController `NgModelController`}. 24566 * If you need access to the controls of child-forms, you have to call `$getControls()` 24567 * recursively on them. 24568 * This can be used for example to iterate over all controls to validate them. 24569 * 24570 * The controls can be accessed normally, but adding to, or removing controls from the array has 24571 * no effect on the form. Instead, use {@link form.FormController#$addControl `$addControl()`} and 24572 * {@link form.FormController#$removeControl `$removeControl()`} for this use-case. 24573 * Likewise, adding a control to, or removing a control from the form is not reflected 24574 * in the shallow copy. That means you should get a fresh copy from `$getControls()` every time 24575 * you need access to the controls. 24576 */ 24577 $getControls: function() { 24578 return shallowCopy(this.$$controls); 24579 }, 24580 24581 // Private API: rename a form control 24582 $$renameControl: function(control, newName) { 24583 var oldName = control.$name; 24584 24585 if (this[oldName] === control) { 24586 delete this[oldName]; 24587 } 24588 this[newName] = control; 24589 control.$name = newName; 24590 }, 24591 24592 /** 24593 * @ngdoc method 24594 * @name form.FormController#$removeControl 24595 * @param {object} control control object, either a {@link form.FormController} or an 24596 * {@link ngModel.NgModelController} 24597 * 24598 * @description 24599 * Deregister a control from the form. 24600 * 24601 * Input elements using ngModelController do this automatically when they are destroyed. 24602 * 24603 * Note that only the removed control's validation state (`$errors`etc.) will be removed from the 24604 * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be 24605 * different from case to case. For example, removing the only `$dirty` control from a form may or 24606 * may not mean that the form is still `$dirty`. 24607 */ 24608 $removeControl: function(control) { 24609 if (control.$name && this[control.$name] === control) { 24610 delete this[control.$name]; 24611 } 24612 forEach(this.$pending, function(value, name) { 24613 // eslint-disable-next-line no-invalid-this 24614 this.$setValidity(name, null, control); 24615 }, this); 24616 forEach(this.$error, function(value, name) { 24617 // eslint-disable-next-line no-invalid-this 24618 this.$setValidity(name, null, control); 24619 }, this); 24620 forEach(this.$$success, function(value, name) { 24621 // eslint-disable-next-line no-invalid-this 24622 this.$setValidity(name, null, control); 24623 }, this); 24624 24625 arrayRemove(this.$$controls, control); 24626 control.$$parentForm = nullFormCtrl; 24627 }, 24628 24629 /** 24630 * @ngdoc method 24631 * @name form.FormController#$setDirty 24632 * 24633 * @description 24634 * Sets the form to a dirty state. 24635 * 24636 * This method can be called to add the 'ng-dirty' class and set the form to a dirty 24637 * state (ng-dirty class). This method will also propagate to parent forms. 24638 */ 24639 $setDirty: function() { 24640 this.$$animate.removeClass(this.$$element, PRISTINE_CLASS); 24641 this.$$animate.addClass(this.$$element, DIRTY_CLASS); 24642 this.$dirty = true; 24643 this.$pristine = false; 24644 this.$$parentForm.$setDirty(); 24645 }, 24646 24647 /** 24648 * @ngdoc method 24649 * @name form.FormController#$setPristine 24650 * 24651 * @description 24652 * Sets the form to its pristine state. 24653 * 24654 * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes 24655 * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted` 24656 * state to false. 24657 * 24658 * This method will also propagate to all the controls contained in this form. 24659 * 24660 * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after 24661 * saving or resetting it. 24662 */ 24663 $setPristine: function() { 24664 this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); 24665 this.$dirty = false; 24666 this.$pristine = true; 24667 this.$submitted = false; 24668 forEach(this.$$controls, function(control) { 24669 control.$setPristine(); 24670 }); 24671 }, 24672 24673 /** 24674 * @ngdoc method 24675 * @name form.FormController#$setUntouched 24676 * 24677 * @description 24678 * Sets the form to its untouched state. 24679 * 24680 * This method can be called to remove the 'ng-touched' class and set the form controls to their 24681 * untouched state (ng-untouched class). 24682 * 24683 * Setting a form controls back to their untouched state is often useful when setting the form 24684 * back to its pristine state. 24685 */ 24686 $setUntouched: function() { 24687 forEach(this.$$controls, function(control) { 24688 control.$setUntouched(); 24689 }); 24690 }, 24691 24692 /** 24693 * @ngdoc method 24694 * @name form.FormController#$setSubmitted 24695 * 24696 * @description 24697 * Sets the form to its `$submitted` state. This will also set `$submitted` on all child and 24698 * parent forms of the form. 24699 */ 24700 $setSubmitted: function() { 24701 var rootForm = this; 24702 while (rootForm.$$parentForm && (rootForm.$$parentForm !== nullFormCtrl)) { 24703 rootForm = rootForm.$$parentForm; 24704 } 24705 rootForm.$$setSubmitted(); 24706 }, 24707 24708 $$setSubmitted: function() { 24709 this.$$animate.addClass(this.$$element, SUBMITTED_CLASS); 24710 this.$submitted = true; 24711 forEach(this.$$controls, function(control) { 24712 if (control.$$setSubmitted) { 24713 control.$$setSubmitted(); 24714 } 24715 }); 24716 } 24717}; 24718 24719/** 24720 * @ngdoc method 24721 * @name form.FormController#$setValidity 24722 * 24723 * @description 24724 * Change the validity state of the form, and notify the parent form (if any). 24725 * 24726 * Application developers will rarely need to call this method directly. It is used internally, by 24727 * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a 24728 * control's validity state to the parent `FormController`. 24729 * 24730 * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be 24731 * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for 24732 * unfulfilled `$asyncValidators`), so that it is available for data-binding. The 24733 * `validationErrorKey` should be in camelCase and will get converted into dash-case for 24734 * class name. Example: `myError` will result in `ng-valid-my-error` and 24735 * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`. 24736 * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending 24737 * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`. 24738 * Skipped is used by AngularJS when validators do not run because of parse errors and when 24739 * `$asyncValidators` do not run because any of the `$validators` failed. 24740 * @param {NgModelController | FormController} controller - The controller whose validity state is 24741 * triggering the change. 24742 */ 24743addSetValidityMethod({ 24744 clazz: FormController, 24745 set: function(object, property, controller) { 24746 var list = object[property]; 24747 if (!list) { 24748 object[property] = [controller]; 24749 } else { 24750 var index = list.indexOf(controller); 24751 if (index === -1) { 24752 list.push(controller); 24753 } 24754 } 24755 }, 24756 unset: function(object, property, controller) { 24757 var list = object[property]; 24758 if (!list) { 24759 return; 24760 } 24761 arrayRemove(list, controller); 24762 if (list.length === 0) { 24763 delete object[property]; 24764 } 24765 } 24766}); 24767 24768/** 24769 * @ngdoc directive 24770 * @name ngForm 24771 * @restrict EAC 24772 * 24773 * @description 24774 * Helper directive that makes it possible to create control groups inside a 24775 * {@link ng.directive:form `form`} directive. 24776 * These "child forms" can be used, for example, to determine the validity of a sub-group of 24777 * controls. 24778 * 24779 * <div class="alert alert-danger"> 24780 * **Note**: `ngForm` cannot be used as a replacement for `<form>`, because it lacks its 24781 * [built-in HTML functionality](https://html.spec.whatwg.org/#the-form-element). 24782 * Specifically, you cannot submit `ngForm` like a `<form>` tag. That means, 24783 * you cannot send data to the server with `ngForm`, or integrate it with 24784 * {@link ng.directive:ngSubmit `ngSubmit`}. 24785 * </div> 24786 * 24787 * @param {string=} ngForm|name Name of the form. If specified, the form controller will 24788 * be published into the related scope, under this name. 24789 * 24790 */ 24791 24792 /** 24793 * @ngdoc directive 24794 * @name form 24795 * @restrict E 24796 * 24797 * @description 24798 * Directive that instantiates 24799 * {@link form.FormController FormController}. 24800 * 24801 * If the `name` attribute is specified, the form controller is published onto the current scope under 24802 * this name. 24803 * 24804 * ## Alias: {@link ng.directive:ngForm `ngForm`} 24805 * 24806 * In AngularJS, forms can be nested. This means that the outer form is valid when all of the child 24807 * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so 24808 * AngularJS provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to 24809 * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group 24810 * of controls needs to be determined. 24811 * 24812 * ## CSS classes 24813 * - `ng-valid` is set if the form is valid. 24814 * - `ng-invalid` is set if the form is invalid. 24815 * - `ng-pending` is set if the form is pending. 24816 * - `ng-pristine` is set if the form is pristine. 24817 * - `ng-dirty` is set if the form is dirty. 24818 * - `ng-submitted` is set if the form was submitted. 24819 * 24820 * Keep in mind that ngAnimate can detect each of these classes when added and removed. 24821 * 24822 * 24823 * ## Submitting a form and preventing the default action 24824 * 24825 * Since the role of forms in client-side AngularJS applications is different than in classical 24826 * roundtrip apps, it is desirable for the browser not to translate the form submission into a full 24827 * page reload that sends the data to the server. Instead some javascript logic should be triggered 24828 * to handle the form submission in an application-specific way. 24829 * 24830 * For this reason, AngularJS prevents the default action (form submission to the server) unless the 24831 * `<form>` element has an `action` attribute specified. 24832 * 24833 * You can use one of the following two ways to specify what javascript method should be called when 24834 * a form is submitted: 24835 * 24836 * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element 24837 * - {@link ng.directive:ngClick ngClick} directive on the first 24838 * button or input field of type submit (input[type=submit]) 24839 * 24840 * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} 24841 * or {@link ng.directive:ngClick ngClick} directives. 24842 * This is because of the following form submission rules in the HTML specification: 24843 * 24844 * - If a form has only one input field then hitting enter in this field triggers form submit 24845 * (`ngSubmit`) 24846 * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter 24847 * doesn't trigger submit 24848 * - if a form has one or more input fields and one or more buttons or input[type=submit] then 24849 * hitting enter in any of the input fields will trigger the click handler on the *first* button or 24850 * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) 24851 * 24852 * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is 24853 * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` 24854 * to have access to the updated model. 24855 * 24856 * @animations 24857 * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. 24858 * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any 24859 * other validations that are performed within the form. Animations in ngForm are similar to how 24860 * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well 24861 * as JS animations. 24862 * 24863 * The following example shows a simple way to utilize CSS transitions to style a form element 24864 * that has been rendered as invalid after it has been validated: 24865 * 24866 * <pre> 24867 * //be sure to include ngAnimate as a module to hook into more 24868 * //advanced animations 24869 * .my-form { 24870 * transition:0.5s linear all; 24871 * background: white; 24872 * } 24873 * .my-form.ng-invalid { 24874 * background: red; 24875 * color:white; 24876 * } 24877 * </pre> 24878 * 24879 * @example 24880 <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample"> 24881 <file name="index.html"> 24882 <script> 24883 angular.module('formExample', []) 24884 .controller('FormController', ['$scope', function($scope) { 24885 $scope.userType = 'guest'; 24886 }]); 24887 </script> 24888 <style> 24889 .my-form { 24890 transition:all linear 0.5s; 24891 background: transparent; 24892 } 24893 .my-form.ng-invalid { 24894 background: red; 24895 } 24896 </style> 24897 <form name="myForm" ng-controller="FormController" class="my-form"> 24898 userType: <input name="input" ng-model="userType" required> 24899 <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> 24900 <code>userType = {{userType}}</code><br> 24901 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br> 24902 <code>myForm.input.$error = {{myForm.input.$error}}</code><br> 24903 <code>myForm.$valid = {{myForm.$valid}}</code><br> 24904 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br> 24905 </form> 24906 </file> 24907 <file name="protractor.js" type="protractor"> 24908 it('should initialize to model', function() { 24909 var userType = element(by.binding('userType')); 24910 var valid = element(by.binding('myForm.input.$valid')); 24911 24912 expect(userType.getText()).toContain('guest'); 24913 expect(valid.getText()).toContain('true'); 24914 }); 24915 24916 it('should be invalid if empty', function() { 24917 var userType = element(by.binding('userType')); 24918 var valid = element(by.binding('myForm.input.$valid')); 24919 var userInput = element(by.model('userType')); 24920 24921 userInput.clear(); 24922 userInput.sendKeys(''); 24923 24924 expect(userType.getText()).toEqual('userType ='); 24925 expect(valid.getText()).toContain('false'); 24926 }); 24927 </file> 24928 </example> 24929 * 24930 * @param {string=} name Name of the form. If specified, the form controller will be published into 24931 * related scope, under this name. 24932 */ 24933var formDirectiveFactory = function(isNgForm) { 24934 return ['$timeout', '$parse', function($timeout, $parse) { 24935 var formDirective = { 24936 name: 'form', 24937 restrict: isNgForm ? 'EAC' : 'E', 24938 require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form 24939 controller: FormController, 24940 compile: function ngFormCompile(formElement, attr) { 24941 // Setup initial state of the control 24942 formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); 24943 24944 var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false); 24945 24946 return { 24947 pre: function ngFormPreLink(scope, formElement, attr, ctrls) { 24948 var controller = ctrls[0]; 24949 24950 // if `action` attr is not present on the form, prevent the default action (submission) 24951 if (!('action' in attr)) { 24952 // we can't use jq events because if a form is destroyed during submission the default 24953 // action is not prevented. see #1238 24954 // 24955 // IE 9 is not affected because it doesn't fire a submit event and try to do a full 24956 // page reload if the form was destroyed by submission of the form via a click handler 24957 // on a button in the form. Looks like an IE9 specific bug. 24958 var handleFormSubmission = function(event) { 24959 scope.$apply(function() { 24960 controller.$commitViewValue(); 24961 controller.$setSubmitted(); 24962 }); 24963 24964 event.preventDefault(); 24965 }; 24966 24967 formElement[0].addEventListener('submit', handleFormSubmission); 24968 24969 // unregister the preventDefault listener so that we don't not leak memory but in a 24970 // way that will achieve the prevention of the default action. 24971 formElement.on('$destroy', function() { 24972 $timeout(function() { 24973 formElement[0].removeEventListener('submit', handleFormSubmission); 24974 }, 0, false); 24975 }); 24976 } 24977 24978 var parentFormCtrl = ctrls[1] || controller.$$parentForm; 24979 parentFormCtrl.$addControl(controller); 24980 24981 var setter = nameAttr ? getSetter(controller.$name) : noop; 24982 24983 if (nameAttr) { 24984 setter(scope, controller); 24985 attr.$observe(nameAttr, function(newValue) { 24986 if (controller.$name === newValue) return; 24987 setter(scope, undefined); 24988 controller.$$parentForm.$$renameControl(controller, newValue); 24989 setter = getSetter(controller.$name); 24990 setter(scope, controller); 24991 }); 24992 } 24993 formElement.on('$destroy', function() { 24994 controller.$$parentForm.$removeControl(controller); 24995 setter(scope, undefined); 24996 extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards 24997 }); 24998 } 24999 }; 25000 } 25001 }; 25002 25003 return formDirective; 25004 25005 function getSetter(expression) { 25006 if (expression === '') { 25007 //create an assignable expression, so forms with an empty name can be renamed later 25008 return $parse('this[""]').assign; 25009 } 25010 return $parse(expression).assign || noop; 25011 } 25012 }]; 25013}; 25014 25015var formDirective = formDirectiveFactory(); 25016var ngFormDirective = formDirectiveFactory(true); 25017 25018 25019 25020// helper methods 25021function setupValidity(instance) { 25022 instance.$$classCache = {}; 25023 instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS)); 25024} 25025function addSetValidityMethod(context) { 25026 var clazz = context.clazz, 25027 set = context.set, 25028 unset = context.unset; 25029 25030 clazz.prototype.$setValidity = function(validationErrorKey, state, controller) { 25031 if (isUndefined(state)) { 25032 createAndSet(this, '$pending', validationErrorKey, controller); 25033 } else { 25034 unsetAndCleanup(this, '$pending', validationErrorKey, controller); 25035 } 25036 if (!isBoolean(state)) { 25037 unset(this.$error, validationErrorKey, controller); 25038 unset(this.$$success, validationErrorKey, controller); 25039 } else { 25040 if (state) { 25041 unset(this.$error, validationErrorKey, controller); 25042 set(this.$$success, validationErrorKey, controller); 25043 } else { 25044 set(this.$error, validationErrorKey, controller); 25045 unset(this.$$success, validationErrorKey, controller); 25046 } 25047 } 25048 if (this.$pending) { 25049 cachedToggleClass(this, PENDING_CLASS, true); 25050 this.$valid = this.$invalid = undefined; 25051 toggleValidationCss(this, '', null); 25052 } else { 25053 cachedToggleClass(this, PENDING_CLASS, false); 25054 this.$valid = isObjectEmpty(this.$error); 25055 this.$invalid = !this.$valid; 25056 toggleValidationCss(this, '', this.$valid); 25057 } 25058 25059 // re-read the state as the set/unset methods could have 25060 // combined state in this.$error[validationError] (used for forms), 25061 // where setting/unsetting only increments/decrements the value, 25062 // and does not replace it. 25063 var combinedState; 25064 if (this.$pending && this.$pending[validationErrorKey]) { 25065 combinedState = undefined; 25066 } else if (this.$error[validationErrorKey]) { 25067 combinedState = false; 25068 } else if (this.$$success[validationErrorKey]) { 25069 combinedState = true; 25070 } else { 25071 combinedState = null; 25072 } 25073 25074 toggleValidationCss(this, validationErrorKey, combinedState); 25075 this.$$parentForm.$setValidity(validationErrorKey, combinedState, this); 25076 }; 25077 25078 function createAndSet(ctrl, name, value, controller) { 25079 if (!ctrl[name]) { 25080 ctrl[name] = {}; 25081 } 25082 set(ctrl[name], value, controller); 25083 } 25084 25085 function unsetAndCleanup(ctrl, name, value, controller) { 25086 if (ctrl[name]) { 25087 unset(ctrl[name], value, controller); 25088 } 25089 if (isObjectEmpty(ctrl[name])) { 25090 ctrl[name] = undefined; 25091 } 25092 } 25093 25094 function cachedToggleClass(ctrl, className, switchValue) { 25095 if (switchValue && !ctrl.$$classCache[className]) { 25096 ctrl.$$animate.addClass(ctrl.$$element, className); 25097 ctrl.$$classCache[className] = true; 25098 } else if (!switchValue && ctrl.$$classCache[className]) { 25099 ctrl.$$animate.removeClass(ctrl.$$element, className); 25100 ctrl.$$classCache[className] = false; 25101 } 25102 } 25103 25104 function toggleValidationCss(ctrl, validationErrorKey, isValid) { 25105 validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; 25106 25107 cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true); 25108 cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false); 25109 } 25110} 25111 25112function isObjectEmpty(obj) { 25113 if (obj) { 25114 for (var prop in obj) { 25115 if (obj.hasOwnProperty(prop)) { 25116 return false; 25117 } 25118 } 25119 } 25120 return true; 25121} 25122 25123/* global 25124 VALID_CLASS: false, 25125 INVALID_CLASS: false, 25126 PRISTINE_CLASS: false, 25127 DIRTY_CLASS: false, 25128 ngModelMinErr: false 25129*/ 25130 25131// Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231 25132var ISO_DATE_REGEXP = /^\d{4,}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)$/; 25133// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987) 25134// Note: We are being more lenient, because browsers are too. 25135// 1. Scheme 25136// 2. Slashes 25137// 3. Username 25138// 4. Password 25139// 5. Hostname 25140// 6. Port 25141// 7. Path 25142// 8. Query 25143// 9. Fragment 25144// 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999 25145var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i; 25146// eslint-disable-next-line max-len 25147var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/; 25148var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/; 25149var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/; 25150var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; 25151var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/; 25152var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/; 25153var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; 25154 25155var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown'; 25156var PARTIAL_VALIDATION_TYPES = createMap(); 25157forEach('date,datetime-local,month,time,week'.split(','), function(type) { 25158 PARTIAL_VALIDATION_TYPES[type] = true; 25159}); 25160 25161var inputType = { 25162 25163 /** 25164 * @ngdoc input 25165 * @name input[text] 25166 * 25167 * @description 25168 * Standard HTML text input with AngularJS data binding, inherited by most of the `input` elements. 25169 * 25170 * 25171 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 25172 * @param {string=} name Property name of the form under which the control is published. 25173 * @param {string=} required Adds `required` validation error key if the value is not entered. 25174 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25175 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25176 * `required` when you want to data-bind to the `required` attribute. 25177 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 25178 * minlength. 25179 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 25180 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of 25181 * any length. 25182 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string 25183 * that contains the regular expression body that will be converted to a regular expression 25184 * as in the ngPattern directive. 25185 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 25186 * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. 25187 * If the expression evaluates to a RegExp object, then this is used directly. 25188 * If the expression evaluates to a string, then it will be converted to a RegExp 25189 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 25190 * `new RegExp('^abc$')`.<br /> 25191 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 25192 * start at the index of the last search's match, thus not taking the whole input value into 25193 * account. 25194 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 25195 * interaction with the input element. 25196 * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input. 25197 * This parameter is ignored for input[type=password] controls, which will never trim the 25198 * input. 25199 * 25200 * @example 25201 <example name="text-input-directive" module="textInputExample"> 25202 <file name="index.html"> 25203 <script> 25204 angular.module('textInputExample', []) 25205 .controller('ExampleController', ['$scope', function($scope) { 25206 $scope.example = { 25207 text: 'guest', 25208 word: /^\s*\w*\s*$/ 25209 }; 25210 }]); 25211 </script> 25212 <form name="myForm" ng-controller="ExampleController"> 25213 <label>Single word: 25214 <input type="text" name="input" ng-model="example.text" 25215 ng-pattern="example.word" required ng-trim="false"> 25216 </label> 25217 <div role="alert"> 25218 <span class="error" ng-show="myForm.input.$error.required"> 25219 Required!</span> 25220 <span class="error" ng-show="myForm.input.$error.pattern"> 25221 Single word only!</span> 25222 </div> 25223 <code>text = {{example.text}}</code><br/> 25224 <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/> 25225 <code>myForm.input.$error = {{myForm.input.$error}}</code><br/> 25226 <code>myForm.$valid = {{myForm.$valid}}</code><br/> 25227 <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/> 25228 </form> 25229 </file> 25230 <file name="protractor.js" type="protractor"> 25231 var text = element(by.binding('example.text')); 25232 var valid = element(by.binding('myForm.input.$valid')); 25233 var input = element(by.model('example.text')); 25234 25235 it('should initialize to model', function() { 25236 expect(text.getText()).toContain('guest'); 25237 expect(valid.getText()).toContain('true'); 25238 }); 25239 25240 it('should be invalid if empty', function() { 25241 input.clear(); 25242 input.sendKeys(''); 25243 25244 expect(text.getText()).toEqual('text ='); 25245 expect(valid.getText()).toContain('false'); 25246 }); 25247 25248 it('should be invalid if multi word', function() { 25249 input.clear(); 25250 input.sendKeys('hello world'); 25251 25252 expect(valid.getText()).toContain('false'); 25253 }); 25254 </file> 25255 </example> 25256 */ 25257 'text': textInputType, 25258 25259 /** 25260 * @ngdoc input 25261 * @name input[date] 25262 * 25263 * @description 25264 * Input with date validation and transformation. In browsers that do not yet support 25265 * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 25266 * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many 25267 * modern browsers do not yet support this input type, it is important to provide cues to users on the 25268 * expected input format via a placeholder or label. 25269 * 25270 * The model must always be a Date object, otherwise AngularJS will throw an error. 25271 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 25272 * 25273 * The timezone to be used to read/write the `Date` instance in the model can be defined using 25274 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 25275 * 25276 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 25277 * @param {string=} name Property name of the form under which the control is published. 25278 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a 25279 * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute 25280 * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5 25281 * constraint validation. 25282 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be 25283 * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute 25284 * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5 25285 * constraint validation. 25286 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string 25287 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 25288 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string 25289 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 25290 * @param {string=} required Sets `required` validation error key if the value is not entered. 25291 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25292 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25293 * `required` when you want to data-bind to the `required` attribute. 25294 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 25295 * interaction with the input element. 25296 * 25297 * @example 25298 <example name="date-input-directive" module="dateInputExample"> 25299 <file name="index.html"> 25300 <script> 25301 angular.module('dateInputExample', []) 25302 .controller('DateController', ['$scope', function($scope) { 25303 $scope.example = { 25304 value: new Date(2013, 9, 22) 25305 }; 25306 }]); 25307 </script> 25308 <form name="myForm" ng-controller="DateController as dateCtrl"> 25309 <label for="exampleInput">Pick a date in 2013:</label> 25310 <input type="date" id="exampleInput" name="input" ng-model="example.value" 25311 placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required /> 25312 <div role="alert"> 25313 <span class="error" ng-show="myForm.input.$error.required"> 25314 Required!</span> 25315 <span class="error" ng-show="myForm.input.$error.date"> 25316 Not a valid date!</span> 25317 </div> 25318 <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/> 25319 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 25320 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 25321 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 25322 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 25323 </form> 25324 </file> 25325 <file name="protractor.js" type="protractor"> 25326 var value = element(by.binding('example.value | date: "yyyy-MM-dd"')); 25327 var valid = element(by.binding('myForm.input.$valid')); 25328 25329 // currently protractor/webdriver does not support 25330 // sending keys to all known HTML5 input controls 25331 // for various browsers (see https://github.com/angular/protractor/issues/562). 25332 function setInput(val) { 25333 // set the value of the element and force validation. 25334 var scr = "var ipt = document.getElementById('exampleInput'); " + 25335 "ipt.value = '" + val + "';" + 25336 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 25337 browser.executeScript(scr); 25338 } 25339 25340 it('should initialize to model', function() { 25341 expect(value.getText()).toContain('2013-10-22'); 25342 expect(valid.getText()).toContain('myForm.input.$valid = true'); 25343 }); 25344 25345 it('should be invalid if empty', function() { 25346 setInput(''); 25347 expect(value.getText()).toEqual('value ='); 25348 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25349 }); 25350 25351 it('should be invalid if over max', function() { 25352 setInput('2015-01-01'); 25353 expect(value.getText()).toContain(''); 25354 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25355 }); 25356 </file> 25357 </example> 25358 */ 25359 'date': createDateInputType('date', DATE_REGEXP, 25360 createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']), 25361 'yyyy-MM-dd'), 25362 25363 /** 25364 * @ngdoc input 25365 * @name input[datetime-local] 25366 * 25367 * @description 25368 * Input with datetime validation and transformation. In browsers that do not yet support 25369 * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 25370 * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. 25371 * 25372 * The model must always be a Date object, otherwise AngularJS will throw an error. 25373 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 25374 * 25375 * The timezone to be used to read/write the `Date` instance in the model can be defined using 25376 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 25377 * 25378 * The format of the displayed time can be adjusted with the 25379 * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat` 25380 * and `timeStripZeroSeconds`. 25381 * 25382 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 25383 * @param {string=} name Property name of the form under which the control is published. 25384 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 25385 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation 25386 * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`). 25387 * Note that `min` will also add native HTML5 constraint validation. 25388 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 25389 * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation 25390 * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`). 25391 * Note that `max` will also add native HTML5 constraint validation. 25392 * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string 25393 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 25394 * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string 25395 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 25396 * @param {string=} required Sets `required` validation error key if the value is not entered. 25397 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25398 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25399 * `required` when you want to data-bind to the `required` attribute. 25400 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 25401 * interaction with the input element. 25402 * 25403 * @example 25404 <example name="datetimelocal-input-directive" module="dateExample"> 25405 <file name="index.html"> 25406 <script> 25407 angular.module('dateExample', []) 25408 .controller('DateController', ['$scope', function($scope) { 25409 $scope.example = { 25410 value: new Date(2010, 11, 28, 14, 57) 25411 }; 25412 }]); 25413 </script> 25414 <form name="myForm" ng-controller="DateController as dateCtrl"> 25415 <label for="exampleInput">Pick a date between in 2013:</label> 25416 <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value" 25417 placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required /> 25418 <div role="alert"> 25419 <span class="error" ng-show="myForm.input.$error.required"> 25420 Required!</span> 25421 <span class="error" ng-show="myForm.input.$error.datetimelocal"> 25422 Not a valid date!</span> 25423 </div> 25424 <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/> 25425 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 25426 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 25427 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 25428 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 25429 </form> 25430 </file> 25431 <file name="protractor.js" type="protractor"> 25432 var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"')); 25433 var valid = element(by.binding('myForm.input.$valid')); 25434 25435 // currently protractor/webdriver does not support 25436 // sending keys to all known HTML5 input controls 25437 // for various browsers (https://github.com/angular/protractor/issues/562). 25438 function setInput(val) { 25439 // set the value of the element and force validation. 25440 var scr = "var ipt = document.getElementById('exampleInput'); " + 25441 "ipt.value = '" + val + "';" + 25442 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 25443 browser.executeScript(scr); 25444 } 25445 25446 it('should initialize to model', function() { 25447 expect(value.getText()).toContain('2010-12-28T14:57:00'); 25448 expect(valid.getText()).toContain('myForm.input.$valid = true'); 25449 }); 25450 25451 it('should be invalid if empty', function() { 25452 setInput(''); 25453 expect(value.getText()).toEqual('value ='); 25454 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25455 }); 25456 25457 it('should be invalid if over max', function() { 25458 setInput('2015-01-01T23:59:00'); 25459 expect(value.getText()).toContain(''); 25460 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25461 }); 25462 </file> 25463 </example> 25464 */ 25465 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP, 25466 createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']), 25467 'yyyy-MM-ddTHH:mm:ss.sss'), 25468 25469 /** 25470 * @ngdoc input 25471 * @name input[time] 25472 * 25473 * @description 25474 * Input with time validation and transformation. In browsers that do not yet support 25475 * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 25476 * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a 25477 * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`. 25478 * 25479 * The model must always be a Date object, otherwise AngularJS will throw an error. 25480 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 25481 * 25482 * The timezone to be used to read/write the `Date` instance in the model can be defined using 25483 * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions}. By default, 25484 * this is the timezone of the browser. 25485 * 25486 * The format of the displayed time can be adjusted with the 25487 * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat` 25488 * and `timeStripZeroSeconds`. 25489 * 25490 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 25491 * @param {string=} name Property name of the form under which the control is published. 25492 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 25493 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this 25494 * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add 25495 * native HTML5 constraint validation. 25496 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 25497 * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this 25498 * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add 25499 * native HTML5 constraint validation. 25500 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the 25501 * `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 25502 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the 25503 * `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 25504 * @param {string=} required Sets `required` validation error key if the value is not entered. 25505 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25506 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25507 * `required` when you want to data-bind to the `required` attribute. 25508 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 25509 * interaction with the input element. 25510 * 25511 * @example 25512 <example name="time-input-directive" module="timeExample"> 25513 <file name="index.html"> 25514 <script> 25515 angular.module('timeExample', []) 25516 .controller('DateController', ['$scope', function($scope) { 25517 $scope.example = { 25518 value: new Date(1970, 0, 1, 14, 57, 0) 25519 }; 25520 }]); 25521 </script> 25522 <form name="myForm" ng-controller="DateController as dateCtrl"> 25523 <label for="exampleInput">Pick a time between 8am and 5pm:</label> 25524 <input type="time" id="exampleInput" name="input" ng-model="example.value" 25525 placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required /> 25526 <div role="alert"> 25527 <span class="error" ng-show="myForm.input.$error.required"> 25528 Required!</span> 25529 <span class="error" ng-show="myForm.input.$error.time"> 25530 Not a valid date!</span> 25531 </div> 25532 <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/> 25533 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 25534 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 25535 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 25536 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 25537 </form> 25538 </file> 25539 <file name="protractor.js" type="protractor"> 25540 var value = element(by.binding('example.value | date: "HH:mm:ss"')); 25541 var valid = element(by.binding('myForm.input.$valid')); 25542 25543 // currently protractor/webdriver does not support 25544 // sending keys to all known HTML5 input controls 25545 // for various browsers (https://github.com/angular/protractor/issues/562). 25546 function setInput(val) { 25547 // set the value of the element and force validation. 25548 var scr = "var ipt = document.getElementById('exampleInput'); " + 25549 "ipt.value = '" + val + "';" + 25550 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 25551 browser.executeScript(scr); 25552 } 25553 25554 it('should initialize to model', function() { 25555 expect(value.getText()).toContain('14:57:00'); 25556 expect(valid.getText()).toContain('myForm.input.$valid = true'); 25557 }); 25558 25559 it('should be invalid if empty', function() { 25560 setInput(''); 25561 expect(value.getText()).toEqual('value ='); 25562 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25563 }); 25564 25565 it('should be invalid if over max', function() { 25566 setInput('23:59:00'); 25567 expect(value.getText()).toContain(''); 25568 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25569 }); 25570 </file> 25571 </example> 25572 */ 25573 'time': createDateInputType('time', TIME_REGEXP, 25574 createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']), 25575 'HH:mm:ss.sss'), 25576 25577 /** 25578 * @ngdoc input 25579 * @name input[week] 25580 * 25581 * @description 25582 * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support 25583 * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 25584 * week format (yyyy-W##), for example: `2013-W02`. 25585 * 25586 * The model must always be a Date object, otherwise AngularJS will throw an error. 25587 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 25588 * 25589 * The value of the resulting Date object will be set to Thursday at 00:00:00 of the requested week, 25590 * due to ISO-8601 week numbering standards. Information on ISO's system for numbering the weeks of the 25591 * year can be found at: https://en.wikipedia.org/wiki/ISO_8601#Week_dates 25592 * 25593 * The timezone to be used to read/write the `Date` instance in the model can be defined using 25594 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 25595 * 25596 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 25597 * @param {string=} name Property name of the form under which the control is published. 25598 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 25599 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this 25600 * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add 25601 * native HTML5 constraint validation. 25602 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 25603 * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this 25604 * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add 25605 * native HTML5 constraint validation. 25606 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string 25607 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 25608 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string 25609 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 25610 * @param {string=} required Sets `required` validation error key if the value is not entered. 25611 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25612 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25613 * `required` when you want to data-bind to the `required` attribute. 25614 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 25615 * interaction with the input element. 25616 * 25617 * @example 25618 <example name="week-input-directive" module="weekExample"> 25619 <file name="index.html"> 25620 <script> 25621 angular.module('weekExample', []) 25622 .controller('DateController', ['$scope', function($scope) { 25623 $scope.example = { 25624 value: new Date(2013, 0, 3) 25625 }; 25626 }]); 25627 </script> 25628 <form name="myForm" ng-controller="DateController as dateCtrl"> 25629 <label>Pick a date between in 2013: 25630 <input id="exampleInput" type="week" name="input" ng-model="example.value" 25631 placeholder="YYYY-W##" min="2012-W32" 25632 max="2013-W52" required /> 25633 </label> 25634 <div role="alert"> 25635 <span class="error" ng-show="myForm.input.$error.required"> 25636 Required!</span> 25637 <span class="error" ng-show="myForm.input.$error.week"> 25638 Not a valid date!</span> 25639 </div> 25640 <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/> 25641 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 25642 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 25643 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 25644 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 25645 </form> 25646 </file> 25647 <file name="protractor.js" type="protractor"> 25648 var value = element(by.binding('example.value | date: "yyyy-Www"')); 25649 var valid = element(by.binding('myForm.input.$valid')); 25650 25651 // currently protractor/webdriver does not support 25652 // sending keys to all known HTML5 input controls 25653 // for various browsers (https://github.com/angular/protractor/issues/562). 25654 function setInput(val) { 25655 // set the value of the element and force validation. 25656 var scr = "var ipt = document.getElementById('exampleInput'); " + 25657 "ipt.value = '" + val + "';" + 25658 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 25659 browser.executeScript(scr); 25660 } 25661 25662 it('should initialize to model', function() { 25663 expect(value.getText()).toContain('2013-W01'); 25664 expect(valid.getText()).toContain('myForm.input.$valid = true'); 25665 }); 25666 25667 it('should be invalid if empty', function() { 25668 setInput(''); 25669 expect(value.getText()).toEqual('value ='); 25670 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25671 }); 25672 25673 it('should be invalid if over max', function() { 25674 setInput('2015-W01'); 25675 expect(value.getText()).toContain(''); 25676 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25677 }); 25678 </file> 25679 </example> 25680 */ 25681 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'), 25682 25683 /** 25684 * @ngdoc input 25685 * @name input[month] 25686 * 25687 * @description 25688 * Input with month validation and transformation. In browsers that do not yet support 25689 * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 25690 * month format (yyyy-MM), for example: `2009-01`. 25691 * 25692 * The model must always be a Date object, otherwise AngularJS will throw an error. 25693 * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. 25694 * If the model is not set to the first of the month, the next view to model update will set it 25695 * to the first of the month. 25696 * 25697 * The timezone to be used to read/write the `Date` instance in the model can be defined using 25698 * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. 25699 * 25700 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 25701 * @param {string=} name Property name of the form under which the control is published. 25702 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 25703 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this 25704 * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add 25705 * native HTML5 constraint validation. 25706 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 25707 * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this 25708 * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add 25709 * native HTML5 constraint validation. 25710 * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string 25711 * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. 25712 * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string 25713 * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. 25714 25715 * @param {string=} required Sets `required` validation error key if the value is not entered. 25716 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25717 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25718 * `required` when you want to data-bind to the `required` attribute. 25719 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 25720 * interaction with the input element. 25721 * 25722 * @example 25723 <example name="month-input-directive" module="monthExample"> 25724 <file name="index.html"> 25725 <script> 25726 angular.module('monthExample', []) 25727 .controller('DateController', ['$scope', function($scope) { 25728 $scope.example = { 25729 value: new Date(2013, 9, 1) 25730 }; 25731 }]); 25732 </script> 25733 <form name="myForm" ng-controller="DateController as dateCtrl"> 25734 <label for="exampleInput">Pick a month in 2013:</label> 25735 <input id="exampleInput" type="month" name="input" ng-model="example.value" 25736 placeholder="yyyy-MM" min="2013-01" max="2013-12" required /> 25737 <div role="alert"> 25738 <span class="error" ng-show="myForm.input.$error.required"> 25739 Required!</span> 25740 <span class="error" ng-show="myForm.input.$error.month"> 25741 Not a valid month!</span> 25742 </div> 25743 <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/> 25744 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 25745 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 25746 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 25747 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 25748 </form> 25749 </file> 25750 <file name="protractor.js" type="protractor"> 25751 var value = element(by.binding('example.value | date: "yyyy-MM"')); 25752 var valid = element(by.binding('myForm.input.$valid')); 25753 25754 // currently protractor/webdriver does not support 25755 // sending keys to all known HTML5 input controls 25756 // for various browsers (https://github.com/angular/protractor/issues/562). 25757 function setInput(val) { 25758 // set the value of the element and force validation. 25759 var scr = "var ipt = document.getElementById('exampleInput'); " + 25760 "ipt.value = '" + val + "';" + 25761 "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; 25762 browser.executeScript(scr); 25763 } 25764 25765 it('should initialize to model', function() { 25766 expect(value.getText()).toContain('2013-10'); 25767 expect(valid.getText()).toContain('myForm.input.$valid = true'); 25768 }); 25769 25770 it('should be invalid if empty', function() { 25771 setInput(''); 25772 expect(value.getText()).toEqual('value ='); 25773 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25774 }); 25775 25776 it('should be invalid if over max', function() { 25777 setInput('2015-01'); 25778 expect(value.getText()).toContain(''); 25779 expect(valid.getText()).toContain('myForm.input.$valid = false'); 25780 }); 25781 </file> 25782 </example> 25783 */ 25784 'month': createDateInputType('month', MONTH_REGEXP, 25785 createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), 25786 'yyyy-MM'), 25787 25788 /** 25789 * @ngdoc input 25790 * @name input[number] 25791 * 25792 * @description 25793 * Text input with number validation and transformation. Sets the `number` validation 25794 * error if not a valid number. 25795 * 25796 * <div class="alert alert-warning"> 25797 * The model must always be of type `number` otherwise AngularJS will throw an error. 25798 * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt} 25799 * error docs for more information and an example of how to convert your model if necessary. 25800 * </div> 25801 * 25802 * 25803 * 25804 * @knownIssue 25805 * 25806 * ### HTML5 constraint validation and `allowInvalid` 25807 * 25808 * In browsers that follow the 25809 * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29), 25810 * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}. 25811 * If a non-number is entered in the input, the browser will report the value as an empty string, 25812 * which means the view / model values in `ngModel` and subsequently the scope value 25813 * will also be an empty string. 25814 * 25815 * @knownIssue 25816 * 25817 * ### Large numbers and `step` validation 25818 * 25819 * The `step` validation will not work correctly for very large numbers (e.g. 9999999999) due to 25820 * Javascript's arithmetic limitations. If you need to handle large numbers, purpose-built 25821 * libraries (e.g. https://github.com/MikeMcl/big.js/), can be included into AngularJS by 25822 * {@link guide/forms#modifying-built-in-validators overwriting the validators} 25823 * for `number` and / or `step`, or by {@link guide/forms#custom-validation applying custom validators} 25824 * to an `input[text]` element. The source for `input[number]` type can be used as a starting 25825 * point for both implementations. 25826 * 25827 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 25828 * @param {string=} name Property name of the form under which the control is published. 25829 * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. 25830 * Can be interpolated. 25831 * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. 25832 * Can be interpolated. 25833 * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`, 25834 * but does not trigger HTML5 native validation. Takes an expression. 25835 * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`, 25836 * but does not trigger HTML5 native validation. Takes an expression. 25837 * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint. 25838 * Can be interpolated. 25839 * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint, 25840 * but does not trigger HTML5 native validation. Takes an expression. 25841 * @param {string=} required Sets `required` validation error key if the value is not entered. 25842 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25843 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25844 * `required` when you want to data-bind to the `required` attribute. 25845 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 25846 * minlength. 25847 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 25848 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of 25849 * any length. 25850 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string 25851 * that contains the regular expression body that will be converted to a regular expression 25852 * as in the ngPattern directive. 25853 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 25854 * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. 25855 * If the expression evaluates to a RegExp object, then this is used directly. 25856 * If the expression evaluates to a string, then it will be converted to a RegExp 25857 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 25858 * `new RegExp('^abc$')`.<br /> 25859 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 25860 * start at the index of the last search's match, thus not taking the whole input value into 25861 * account. 25862 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 25863 * interaction with the input element. 25864 * 25865 * @example 25866 <example name="number-input-directive" module="numberExample"> 25867 <file name="index.html"> 25868 <script> 25869 angular.module('numberExample', []) 25870 .controller('ExampleController', ['$scope', function($scope) { 25871 $scope.example = { 25872 value: 12 25873 }; 25874 }]); 25875 </script> 25876 <form name="myForm" ng-controller="ExampleController"> 25877 <label>Number: 25878 <input type="number" name="input" ng-model="example.value" 25879 min="0" max="99" required> 25880 </label> 25881 <div role="alert"> 25882 <span class="error" ng-show="myForm.input.$error.required"> 25883 Required!</span> 25884 <span class="error" ng-show="myForm.input.$error.number"> 25885 Not valid number!</span> 25886 </div> 25887 <tt>value = {{example.value}}</tt><br/> 25888 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 25889 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 25890 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 25891 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 25892 </form> 25893 </file> 25894 <file name="protractor.js" type="protractor"> 25895 var value = element(by.binding('example.value')); 25896 var valid = element(by.binding('myForm.input.$valid')); 25897 var input = element(by.model('example.value')); 25898 25899 it('should initialize to model', function() { 25900 expect(value.getText()).toContain('12'); 25901 expect(valid.getText()).toContain('true'); 25902 }); 25903 25904 it('should be invalid if empty', function() { 25905 input.clear(); 25906 input.sendKeys(''); 25907 expect(value.getText()).toEqual('value ='); 25908 expect(valid.getText()).toContain('false'); 25909 }); 25910 25911 it('should be invalid if over max', function() { 25912 input.clear(); 25913 input.sendKeys('123'); 25914 expect(value.getText()).toEqual('value ='); 25915 expect(valid.getText()).toContain('false'); 25916 }); 25917 </file> 25918 </example> 25919 */ 25920 'number': numberInputType, 25921 25922 25923 /** 25924 * @ngdoc input 25925 * @name input[url] 25926 * 25927 * @description 25928 * Text input with URL validation. Sets the `url` validation error key if the content is not a 25929 * valid URL. 25930 * 25931 * <div class="alert alert-warning"> 25932 * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex 25933 * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify 25934 * the built-in validators (see the {@link guide/forms Forms guide}) 25935 * </div> 25936 * 25937 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 25938 * @param {string=} name Property name of the form under which the control is published. 25939 * @param {string=} required Sets `required` validation error key if the value is not entered. 25940 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 25941 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 25942 * `required` when you want to data-bind to the `required` attribute. 25943 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 25944 * minlength. 25945 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 25946 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of 25947 * any length. 25948 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string 25949 * that contains the regular expression body that will be converted to a regular expression 25950 * as in the ngPattern directive. 25951 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 25952 * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. 25953 * If the expression evaluates to a RegExp object, then this is used directly. 25954 * If the expression evaluates to a string, then it will be converted to a RegExp 25955 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 25956 * `new RegExp('^abc$')`.<br /> 25957 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 25958 * start at the index of the last search's match, thus not taking the whole input value into 25959 * account. 25960 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 25961 * interaction with the input element. 25962 * 25963 * @example 25964 <example name="url-input-directive" module="urlExample"> 25965 <file name="index.html"> 25966 <script> 25967 angular.module('urlExample', []) 25968 .controller('ExampleController', ['$scope', function($scope) { 25969 $scope.url = { 25970 text: 'http://google.com' 25971 }; 25972 }]); 25973 </script> 25974 <form name="myForm" ng-controller="ExampleController"> 25975 <label>URL: 25976 <input type="url" name="input" ng-model="url.text" required> 25977 <label> 25978 <div role="alert"> 25979 <span class="error" ng-show="myForm.input.$error.required"> 25980 Required!</span> 25981 <span class="error" ng-show="myForm.input.$error.url"> 25982 Not valid url!</span> 25983 </div> 25984 <tt>text = {{url.text}}</tt><br/> 25985 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 25986 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 25987 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 25988 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 25989 <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> 25990 </form> 25991 </file> 25992 <file name="protractor.js" type="protractor"> 25993 var text = element(by.binding('url.text')); 25994 var valid = element(by.binding('myForm.input.$valid')); 25995 var input = element(by.model('url.text')); 25996 25997 it('should initialize to model', function() { 25998 expect(text.getText()).toContain('http://google.com'); 25999 expect(valid.getText()).toContain('true'); 26000 }); 26001 26002 it('should be invalid if empty', function() { 26003 input.clear(); 26004 input.sendKeys(''); 26005 26006 expect(text.getText()).toEqual('text ='); 26007 expect(valid.getText()).toContain('false'); 26008 }); 26009 26010 it('should be invalid if not url', function() { 26011 input.clear(); 26012 input.sendKeys('box'); 26013 26014 expect(valid.getText()).toContain('false'); 26015 }); 26016 </file> 26017 </example> 26018 */ 26019 'url': urlInputType, 26020 26021 26022 /** 26023 * @ngdoc input 26024 * @name input[email] 26025 * 26026 * @description 26027 * Text input with email validation. Sets the `email` validation error key if not a valid email 26028 * address. 26029 * 26030 * <div class="alert alert-warning"> 26031 * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex 26032 * used in Chromium
26032. If you need stricter validation (e.g. requiring a top-level domain), you can 26033 * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
vendor: 23,787 bytes, lines 26033-26620
26033 26034 * </div> 26035 * 26036 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 26037 * @param {string=} name Property name of the form under which the control is published. 26038 * @param {string=} required Sets `required` validation error key if the value is not entered. 26039 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 26040 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 26041 * `required` when you want to data-bind to the `required` attribute. 26042 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 26043 * minlength. 26044 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 26045 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of 26046 * any length. 26047 * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string 26048 * that contains the regular expression body that will be converted to a regular expression 26049 * as in the ngPattern directive. 26050 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 26051 * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. 26052 * If the expression evaluates to a RegExp object, then this is used directly. 26053 * If the expression evaluates to a string, then it will be converted to a RegExp 26054 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 26055 * `new RegExp('^abc$')`.<br /> 26056 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 26057 * start at the index of the last search's match, thus not taking the whole input value into 26058 * account. 26059 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 26060 * interaction with the input element. 26061 * 26062 * @example 26063 <example name="email-input-directive" module="emailExample"> 26064 <file name="index.html"> 26065 <script> 26066 angular.module('emailExample', []) 26067 .controller('ExampleController', ['$scope', function($scope) { 26068 $scope.email = { 26069 text: '[email protected]' 26070 }; 26071 }]); 26072 </script> 26073 <form name="myForm" ng-controller="ExampleController"> 26074 <label>Email: 26075 <input type="email" name="input" ng-model="email.text" required> 26076 </label> 26077 <div role="alert"> 26078 <span class="error" ng-show="myForm.input.$error.required"> 26079 Required!</span> 26080 <span class="error" ng-show="myForm.input.$error.email"> 26081 Not valid email!</span> 26082 </div> 26083 <tt>text = {{email.text}}</tt><br/> 26084 <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> 26085 <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> 26086 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 26087 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 26088 <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> 26089 </form> 26090 </file> 26091 <file name="protractor.js" type="protractor"> 26092 var text = element(by.binding('email.text')); 26093 var valid = element(by.binding('myForm.input.$valid')); 26094 var input = element(by.model('email.text')); 26095 26096 it('should initialize to model', function() { 26097 expect(text.getText()).toContain('[email protected]'); 26098 expect(valid.getText()).toContain('true'); 26099 }); 26100 26101 it('should be invalid if empty', function() { 26102 input.clear(); 26103 input.sendKeys(''); 26104 expect(text.getText()).toEqual('text ='); 26105 expect(valid.getText()).toContain('false'); 26106 }); 26107 26108 it('should be invalid if not email', function() { 26109 input.clear(); 26110 input.sendKeys('xxx'); 26111 26112 expect(valid.getText()).toContain('false'); 26113 }); 26114 </file> 26115 </example> 26116 */ 26117 'email': emailInputType, 26118 26119 26120 /** 26121 * @ngdoc input 26122 * @name input[radio] 26123 * 26124 * @description 26125 * HTML radio button. 26126 * 26127 * **Note:**<br> 26128 * All inputs controlled by {@link ngModel ngModel} (including those of type `radio`) will use the 26129 * value of their `name` attribute to determine the property under which their 26130 * {@link ngModel.NgModelController NgModelController} will be published on the parent 26131 * {@link form.FormController FormController}. Thus, if you use the same `name` for multiple 26132 * inputs of a form (e.g. a group of radio inputs), only _one_ `NgModelController` will be 26133 * published on the parent `FormController` under that name. The rest of the controllers will 26134 * continue to work as expected, but you won't be able to access them as properties on the parent 26135 * `FormController`. 26136 * 26137 * <div class="alert alert-info"> 26138 * <p> 26139 * In plain HTML forms, the `name` attribute is used to identify groups of radio inputs, so 26140 * that the browser can manage their state (checked/unchecked) based on the state of other 26141 * inputs in the same group. 26142 * </p> 26143 * <p> 26144 * In AngularJS forms, this is not necessary. The input's state will be updated based on the 26145 * value of the underlying model data. 26146 * </p> 26147 * </div> 26148 * 26149 * <div class="alert alert-success"> 26150 * If you omit the `name` attribute on a radio input, `ngModel` will automatically assign it a 26151 * unique name. 26152 * </div> 26153 * 26154 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 26155 * @param {string} value The value to which the `ngModel` expression should be set when selected. 26156 * Note that `value` only supports `string` values, i.e. the scope model needs to be a string, 26157 * too. Use `ngValue` if you need complex models (`number`, `object`, ...). 26158 * @param {string=} name Property name of the form under which the control is published. 26159 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 26160 * interaction with the input element. 26161 * @param {string} ngValue AngularJS expression to which `ngModel` will be be set when the radio 26162 * is selected. Should be used instead of the `value` attribute if you need 26163 * a non-string `ngModel` (`boolean`, `array`, ...). 26164 * 26165 * @example 26166 <example name="radio-input-directive" module="radioExample"> 26167 <file name="index.html"> 26168 <script> 26169 angular.module('radioExample', []) 26170 .controller('ExampleController', ['$scope', function($scope) { 26171 $scope.color = { 26172 name: 'blue' 26173 }; 26174 $scope.specialValue = { 26175 "id": "12345", 26176 "value": "green" 26177 }; 26178 }]); 26179 </script> 26180 <form name="myForm" ng-controller="ExampleController"> 26181 <label> 26182 <input type="radio" ng-model="color.name" value="red"> 26183 Red 26184 </label><br/> 26185 <label> 26186 <input type="radio" ng-model="color.name" ng-value="specialValue"> 26187 Green 26188 </label><br/> 26189 <label> 26190 <input type="radio" ng-model="color.name" value="blue"> 26191 Blue 26192 </label><br/> 26193 <tt>color = {{color.name | json}}</tt><br/> 26194 </form> 26195 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`. 26196 </file> 26197 <file name="protractor.js" type="protractor"> 26198 it('should change state', function() { 26199 var inputs = element.all(by.model('color.name')); 26200 var color = element(by.binding('color.name')); 26201 26202 expect(color.getText()).toContain('blue'); 26203 26204 inputs.get(0).click(); 26205 expect(color.getText()).toContain('red'); 26206 26207 inputs.get(1).click(); 26208 expect(color.getText()).toContain('green'); 26209 }); 26210 </file> 26211 </example> 26212 */ 26213 'radio': radioInputType, 26214 26215 /** 26216 * @ngdoc input 26217 * @name input[range] 26218 * 26219 * @description 26220 * Native range input with validation and transformation. 26221 * 26222 * The model for the range input must always be a `Number`. 26223 * 26224 * IE9 and other browsers that do not support the `range` type fall back 26225 * to a text input without any default values for `min`, `max` and `step`. Model binding, 26226 * validation and number parsing are nevertheless supported. 26227 * 26228 * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]` 26229 * in a way that never allows the input to hold an invalid value. That means: 26230 * - any non-numerical value is set to `(max + min) / 2`. 26231 * - any numerical value that is less than the current min val, or greater than the current max val 26232 * is set to the min / max val respectively. 26233 * - additionally, the current `step` is respected, so the nearest value that satisfies a step 26234 * is used. 26235 * 26236 * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range)) 26237 * for more info. 26238 * 26239 * This has the following consequences for AngularJS: 26240 * 26241 * Since the element value should always reflect the current model value, a range input 26242 * will set the bound ngModel expression to the value that the browser has set for the 26243 * input element. For example, in the following input `<input type="range" ng-model="model.value">`, 26244 * if the application sets `model.value = null`, the browser will set the input to `'50'`. 26245 * AngularJS will then set the model to `50`, to prevent input and model value being out of sync. 26246 * 26247 * That means the model for range will immediately be set to `50` after `ngModel` has been 26248 * initialized. It also means a range input can never have the required error. 26249 * 26250 * This does not only affect changes to the model value, but also to the values of the `min`, 26251 * `max`, and `step` attributes. When these change in a way that will cause the browser to modify 26252 * the input value, AngularJS will also update the model value. 26253 * 26254 * Automatic value adjustment also means that a range input element can never have the `required`, 26255 * `min`, or `max` errors. 26256 * 26257 * However, `step` is currently only fully implemented by Firefox. Other browsers have problems 26258 * when the step value changes dynamically - they do not adjust the element value correctly, but 26259 * instead may set the `stepMismatch` error. If that's the case, the AngularJS will set the `step` 26260 * error on the input, and set the model to `undefined`. 26261 * 26262 * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do 26263 * not set the `min` and `max` attributes, which means that the browser won't automatically adjust 26264 * the input value based on their values, and will always assume min = 0, max = 100, and step = 1. 26265 * 26266 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 26267 * @param {string=} name Property name of the form under which the control is published. 26268 * @param {string=} min Sets the `min` validation to ensure that the value entered is greater 26269 * than `min`. Can be interpolated. 26270 * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`. 26271 * Can be interpolated. 26272 * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step` 26273 * Can be interpolated. 26274 * @param {expression=} ngChange AngularJS expression to be executed when the ngModel value changes due 26275 * to user interaction with the input element. 26276 * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the 26277 * element. **Note** : `ngChecked` should not be used alongside `ngModel`. 26278 * Checkout {@link ng.directive:ngChecked ngChecked} for usage. 26279 * 26280 * @example 26281 <example name="range-input-directive" module="rangeExample"> 26282 <file name="index.html"> 26283 <script> 26284 angular.module('rangeExample', []) 26285 .controller('ExampleController', ['$scope', function($scope) { 26286 $scope.value = 75; 26287 $scope.min = 10; 26288 $scope.max = 90; 26289 }]); 26290 </script> 26291 <form name="myForm" ng-controller="ExampleController"> 26292 26293 Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}"> 26294 <hr> 26295 Model as number: <input type="number" ng-model="value"><br> 26296 Min: <input type="number" ng-model="min"><br> 26297 Max: <input type="number" ng-model="max"><br> 26298 value = <code>{{value}}</code><br/> 26299 myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/> 26300 myForm.range.$error = <code>{{myForm.range.$error}}</code> 26301 </form> 26302 </file> 26303 </example> 26304 26305 * ## Range Input with ngMin & ngMax attributes 26306 26307 * @example 26308 <example name="range-input-directive-ng" module="rangeExample"> 26309 <file name="index.html"> 26310 <script> 26311 angular.module('rangeExample', []) 26312 .controller('ExampleController', ['$scope', function($scope) { 26313 $scope.value = 75; 26314 $scope.min = 10; 26315 $scope.max = 90; 26316 }]); 26317 </script> 26318 <form name="myForm" ng-controller="ExampleController"> 26319 Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max"> 26320 <hr> 26321 Model as number: <input type="number" ng-model="value"><br> 26322 Min: <input type="number" ng-model="min"><br> 26323 Max: <input type="number" ng-model="max"><br> 26324 value = <code>{{value}}</code><br/> 26325 myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/> 26326 myForm.range.$error = <code>{{myForm.range.$error}}</code> 26327 </form> 26328 </file> 26329 </example> 26330 26331 */ 26332 'range': rangeInputType, 26333 26334 /** 26335 * @ngdoc input 26336 * @name input[checkbox] 26337 * 26338 * @description 26339 * HTML checkbox. 26340 * 26341 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 26342 * @param {string=} name Property name of the form under which the control is published. 26343 * @param {expression=} ngTrueValue The value to which the expression should be set when selected. 26344 * @param {expression=} ngFalseValue The value to which the expression should be set when not selected. 26345 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 26346 * interaction with the input element. 26347 * 26348 * @example 26349 <example name="checkbox-input-directive" module="checkboxExample"> 26350 <file name="index.html"> 26351 <script> 26352 angular.module('checkboxExample', []) 26353 .controller('ExampleController', ['$scope', function($scope) { 26354 $scope.checkboxModel = { 26355 value1 : true, 26356 value2 : 'YES' 26357 }; 26358 }]); 26359 </script> 26360 <form name="myForm" ng-controller="ExampleController"> 26361 <label>Value1: 26362 <input type="checkbox" ng-model="checkboxModel.value1"> 26363 </label><br/> 26364 <label>Value2: 26365 <input type="checkbox" ng-model="checkboxModel.value2" 26366 ng-true-value="'YES'" ng-false-value="'NO'"> 26367 </label><br/> 26368 <tt>value1 = {{checkboxModel.value1}}</tt><br/> 26369 <tt>value2 = {{checkboxModel.value2}}</tt><br/> 26370 </form> 26371 </file> 26372 <file name="protractor.js" type="protractor"> 26373 it('should change state', function() { 26374 var value1 = element(by.binding('checkboxModel.value1')); 26375 var value2 = element(by.binding('checkboxModel.value2')); 26376 26377 expect(value1.getText()).toContain('true'); 26378 expect(value2.getText()).toContain('YES'); 26379 26380 element(by.model('checkboxModel.value1')).click(); 26381 element(by.model('checkboxModel.value2')).click(); 26382 26383 expect(value1.getText()).toContain('false'); 26384 expect(value2.getText()).toContain('NO'); 26385 }); 26386 </file> 26387 </example> 26388 */ 26389 'checkbox': checkboxInputType, 26390 26391 'hidden': noop, 26392 'button': noop, 26393 'submit': noop, 26394 'reset': noop, 26395 'file': noop 26396}; 26397 26398function stringBasedInputType(ctrl) { 26399 ctrl.$formatters.push(function(value) { 26400 return ctrl.$isEmpty(value) ? value : value.toString(); 26401 }); 26402} 26403 26404function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { 26405 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 26406 stringBasedInputType(ctrl); 26407} 26408 26409function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) { 26410 var type = lowercase(element[0].type); 26411 26412 // In composition mode, users are still inputting intermediate text buffer, 26413 // hold the listener until composition is done. 26414 // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent 26415 if (!$sniffer.android) { 26416 var composing = false; 26417 26418 element.on('compositionstart', function() { 26419 composing = true; 26420 }); 26421 26422 // Support: IE9+ 26423 element.on('compositionupdate', function(ev) { 26424 // End composition when ev.data is empty string on 'compositionupdate' event. 26425 // When the input de-focusses (e.g. by clicking away), IE triggers 'compositionupdate' 26426 // instead of 'compositionend'. 26427 if (isUndefined(ev.data) || ev.data === '') { 26428 composing = false; 26429 } 26430 }); 26431 26432 element.on('compositionend', function() { 26433 composing = false; 26434 listener(); 26435 }); 26436 } 26437 26438 var timeout; 26439 26440 var listener = function(ev) { 26441 if (timeout) { 26442 $browser.defer.cancel(timeout); 26443 timeout = null; 26444 } 26445 if (composing) return; 26446 var value = element.val(), 26447 event = ev && ev.type; 26448 26449 // By default we will trim the value 26450 // If the attribute ng-trim exists we will avoid trimming 26451 // If input type is 'password', the value is never trimmed 26452 if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { 26453 value = trim(value); 26454 } 26455 26456 // If a control is suffering from bad input (due to native validators), browsers discard its 26457 // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the 26458 // control's value is the same empty value twice in a row. 26459 if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) { 26460 ctrl.$setViewValue(value, event); 26461 } 26462 }; 26463 26464 // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the 26465 // input event on backspace, delete or cut 26466 if ($sniffer.hasEvent('input')) { 26467 element.on('input', listener); 26468 } else { 26469 var deferListener = function(ev, input, origValue) { 26470 if (!timeout) { 26471 timeout = $browser.defer(function() { 26472 timeout = null; 26473 if (!input || input.value !== origValue) { 26474 listener(ev); 26475 } 26476 }); 26477 } 26478 }; 26479 26480 element.on('keydown', /** @this */ function(event) { 26481 var key = event.keyCode; 26482 26483 // ignore 26484 // command modifiers arrows 26485 if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; 26486 26487 deferListener(event, this, this.value); 26488 }); 26489 26490 // if user modifies input value using context menu in IE, we need "paste", "cut" and "drop" events to catch it 26491 if ($sniffer.hasEvent('paste')) { 26492 element.on('paste cut drop', deferListener); 26493 } 26494 } 26495 26496 // if user paste into input using mouse on older browser 26497 // or form autocomplete on newer browser, we need "change" event to catch it 26498 element.on('change', listener); 26499 26500 // Some native input types (date-family) have the ability to change validity without 26501 // firing any input/change events. 26502 // For these event types, when native validators are present and the browser supports the type, 26503 // check for validity changes on various DOM events. 26504 if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) { 26505 element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) { 26506 if (!timeout) { 26507 var validity = this[VALIDITY_STATE_PROPERTY]; 26508 var origBadInput = validity.badInput; 26509 var origTypeMismatch = validity.typeMismatch; 26510 timeout = $browser.defer(function() { 26511 timeout = null; 26512 if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) { 26513 listener(ev); 26514 } 26515 }); 26516 } 26517 }); 26518 } 26519 26520 ctrl.$render = function() { 26521 // Workaround for Firefox validation #12102. 26522 var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue; 26523 if (element.val() !== value) { 26524 element.val(value); 26525 } 26526 }; 26527} 26528 26529function weekParser(isoWeek, existingDate) { 26530 if (isDate(isoWeek)) { 26531 return isoWeek; 26532 } 26533 26534 if (isString(isoWeek)) { 26535 WEEK_REGEXP.lastIndex = 0; 26536 var parts = WEEK_REGEXP.exec(isoWeek); 26537 if (parts) { 26538 var year = +parts[1], 26539 week = +parts[2], 26540 hours = 0, 26541 minutes = 0, 26542 seconds = 0, 26543 milliseconds = 0, 26544 firstThurs = getFirstThursdayOfYear(year), 26545 addDays = (week - 1) * 7; 26546 26547 if (existingDate) { 26548 hours = existingDate.getHours(); 26549 minutes = existingDate.getMinutes(); 26550 seconds = existingDate.getSeconds(); 26551 milliseconds = existingDate.getMilliseconds(); 26552 } 26553 26554 return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds); 26555 } 26556 } 26557 26558 return NaN; 26559} 26560 26561function createDateParser(regexp, mapping) { 26562 return function(iso, previousDate) { 26563 var parts, map; 26564 26565 if (isDate(iso)) { 26566 return iso; 26567 } 26568 26569 if (isString(iso)) { 26570 // When a date is JSON'ified to wraps itself inside of an extra 26571 // set of double quotes. This makes the date parsing code unable 26572 // to match the date string and parse it as a date. 26573 if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') { 26574 iso = iso.substring(1, iso.length - 1); 26575 } 26576 if (ISO_DATE_REGEXP.test(iso)) { 26577 return new Date(iso); 26578 } 26579 regexp.lastIndex = 0; 26580 parts = regexp.exec(iso); 26581 26582 if (parts) { 26583 parts.shift(); 26584 if (previousDate) { 26585 map = { 26586 yyyy: previousDate.getFullYear(), 26587 MM: previousDate.getMonth() + 1, 26588 dd: previousDate.getDate(), 26589 HH: previousDate.getHours(), 26590 mm: previousDate.getMinutes(), 26591 ss: previousDate.getSeconds(), 26592 sss: previousDate.getMilliseconds() / 1000 26593 }; 26594 } else { 26595 map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 }; 26596 } 26597 26598 forEach(parts, function(part, index) { 26599 if (index < mapping.length) { 26600 map[mapping[index]] = +part; 26601 } 26602 }); 26603 26604 var date = new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0); 26605 if (map.yyyy < 100) { 26606 // In the constructor, 2-digit years map to 1900-1999. 26607 // Use `setFullYear()` to set the correct year. 26608 date.setFullYear(map.yyyy); 26609 } 26610 26611 return date; 26612 } 26613 } 26614 26615 return NaN; 26616 }; 26617} 26618 26619function createDateInputType(type, regexp, parseDate, format) { 26620 return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter
vendor: 10,956 bytes, lines 26620-26944
26620) { 26621 badInputChecker(scope, element, attr, ctrl, type); 26622 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 26623 26624 var isTimeType = type === 'time' || type === 'datetimelocal'; 26625 var previousDate; 26626 var previousTimezone; 26627 26628 ctrl.$parsers.push(function(value) { 26629 if (ctrl.$isEmpty(value)) return null; 26630 26631 if (regexp.test(value)) { 26632 // Note: We cannot read ctrl.$modelValue, as there might be a different 26633 // parser/formatter in the processing chain so that the model 26634 // contains some different data format! 26635 return parseDateAndConvertTimeZoneToLocal(value, previousDate); 26636 } 26637 ctrl.$$parserName = type; 26638 return undefined; 26639 }); 26640 26641 ctrl.$formatters.push(function(value) { 26642 if (value && !isDate(value)) { 26643 throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value); 26644 } 26645 if (isValidDate(value)) { 26646 previousDate = value; 26647 var timezone = ctrl.$options.getOption('timezone'); 26648 26649 if (timezone) { 26650 previousTimezone = timezone; 26651 previousDate = convertTimezoneToLocal(previousDate, timezone, true); 26652 } 26653 26654 return formatter(value, timezone); 26655 } else { 26656 previousDate = null; 26657 previousTimezone = null; 26658 return ''; 26659 } 26660 }); 26661 26662 if (isDefined(attr.min) || attr.ngMin) { 26663 var minVal; 26664 ctrl.$validators.min = function(value) { 26665 return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal; 26666 }; 26667 attr.$observe('min', function(val) { 26668 minVal = parseObservedDateValue(val); 26669 ctrl.$validate(); 26670 }); 26671 } 26672 26673 if (isDefined(attr.max) || attr.ngMax) { 26674 var maxVal; 26675 ctrl.$validators.max = function(value) { 26676 return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal; 26677 }; 26678 attr.$observe('max', function(val) { 26679 maxVal = parseObservedDateValue(val); 26680 ctrl.$validate(); 26681 }); 26682 } 26683 26684 function isValidDate(value) { 26685 // Invalid Date: getTime() returns NaN 26686 return value && !(value.getTime && value.getTime() !== value.getTime()); 26687 } 26688 26689 function parseObservedDateValue(val) { 26690 return isDefined(val) && !isDate(val) ? parseDateAndConvertTimeZoneToLocal(val) || undefined : val; 26691 } 26692 26693 function parseDateAndConvertTimeZoneToLocal(value, previousDate) { 26694 var timezone = ctrl.$options.getOption('timezone'); 26695 26696 if (previousTimezone && previousTimezone !== timezone) { 26697 // If the timezone has changed, adjust the previousDate to the default timezone 26698 // so that the new date is converted with the correct timezone offset 26699 previousDate = addDateMinutes(previousDate, timezoneToOffset(previousTimezone)); 26700 } 26701 26702 var parsedDate = parseDate(value, previousDate); 26703 26704 if (!isNaN(parsedDate) && timezone) { 26705 parsedDate = convertTimezoneToLocal(parsedDate, timezone); 26706 } 26707 return parsedDate; 26708 } 26709 26710 function formatter(value, timezone) { 26711 var targetFormat = format; 26712 26713 if (isTimeType && isString(ctrl.$options.getOption('timeSecondsFormat'))) { 26714 targetFormat = format 26715 .replace('ss.sss', ctrl.$options.getOption('timeSecondsFormat')) 26716 .replace(/:$/, ''); 26717 } 26718 26719 var formatted = $filter('date')(value, targetFormat, timezone); 26720 26721 if (isTimeType && ctrl.$options.getOption('timeStripZeroSeconds')) { 26722 formatted = formatted.replace(/(?::00)?(?:\.000)?$/, ''); 26723 } 26724 26725 return formatted; 26726 } 26727 }; 26728} 26729 26730function badInputChecker(scope, element, attr, ctrl, parserName) { 26731 var node = element[0]; 26732 var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); 26733 if (nativeValidation) { 26734 ctrl.$parsers.push(function(value) { 26735 var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; 26736 if (validity.badInput || validity.typeMismatch) { 26737 ctrl.$$parserName = parserName; 26738 return undefined; 26739 } 26740 26741 return value; 26742 }); 26743 } 26744} 26745 26746function numberFormatterParser(ctrl) { 26747 ctrl.$parsers.push(function(value) { 26748 if (ctrl.$isEmpty(value)) return null; 26749 if (NUMBER_REGEXP.test(value)) return parseFloat(value); 26750 26751 ctrl.$$parserName = 'number'; 26752 return undefined; 26753 }); 26754 26755 ctrl.$formatters.push(function(value) { 26756 if (!ctrl.$isEmpty(value)) { 26757 if (!isNumber(value)) { 26758 throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); 26759 } 26760 value = value.toString(); 26761 } 26762 return value; 26763 }); 26764} 26765 26766function parseNumberAttrVal(val) { 26767 if (isDefined(val) && !isNumber(val)) { 26768 val = parseFloat(val); 26769 } 26770 return !isNumberNaN(val) ? val : undefined; 26771} 26772 26773function isNumberInteger(num) { 26774 // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066 26775 // (minus the assumption that `num` is a number) 26776 26777 // eslint-disable-next-line no-bitwise 26778 return (num | 0) === num; 26779} 26780 26781function countDecimals(num) { 26782 var numString = num.toString(); 26783 var decimalSymbolIndex = numString.indexOf('.'); 26784 26785 if (decimalSymbolIndex === -1) { 26786 if (-1 < num && num < 1) { 26787 // It may be in the exponential notation format (`1e-X`) 26788 var match = /e-(\d+)$/.exec(numString); 26789 26790 if (match) { 26791 return Number(match[1]); 26792 } 26793 } 26794 26795 return 0; 26796 } 26797 26798 return numString.length - decimalSymbolIndex - 1; 26799} 26800 26801function isValidForStep(viewValue, stepBase, step) { 26802 // At this point `stepBase` and `step` are expected to be non-NaN values 26803 // and `viewValue` is expected to be a valid stringified number. 26804 var value = Number(viewValue); 26805 26806 var isNonIntegerValue = !isNumberInteger(value); 26807 var isNonIntegerStepBase = !isNumberInteger(stepBase); 26808 var isNonIntegerStep = !isNumberInteger(step); 26809 26810 // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or 26811 // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers. 26812 if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) { 26813 var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0; 26814 var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0; 26815 var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0; 26816 26817 var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals); 26818 var multiplier = Math.pow(10, decimalCount); 26819 26820 value = value * multiplier; 26821 stepBase = stepBase * multiplier; 26822 step = step * multiplier; 26823 26824 if (isNonIntegerValue) value = Math.round(value); 26825 if (isNonIntegerStepBase) stepBase = Math.round(stepBase); 26826 if (isNonIntegerStep) step = Math.round(step); 26827 } 26828 26829 return (value - stepBase) % step === 0; 26830} 26831 26832function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { 26833 badInputChecker(scope, element, attr, ctrl, 'number'); 26834 numberFormatterParser(ctrl); 26835 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 26836 26837 var minVal; 26838 var maxVal; 26839 26840 if (isDefined(attr.min) || attr.ngMin) { 26841 ctrl.$validators.min = function(modelValue, viewValue) { 26842 return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal; 26843 }; 26844 26845 attr.$observe('min', function(val) { 26846 minVal = parseNumberAttrVal(val); 26847 // TODO(matsko): implement validateLater to reduce number of validations 26848 ctrl.$validate(); 26849 }); 26850 } 26851 26852 if (isDefined(attr.max) || attr.ngMax) { 26853 ctrl.$validators.max = function(modelValue, viewValue) { 26854 return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal; 26855 }; 26856 26857 attr.$observe('max', function(val) { 26858 maxVal = parseNumberAttrVal(val); 26859 // TODO(matsko): implement validateLater to reduce number of validations 26860 ctrl.$validate(); 26861 }); 26862 } 26863 26864 if (isDefined(attr.step) || attr.ngStep) { 26865 var stepVal; 26866 ctrl.$validators.step = function(modelValue, viewValue) { 26867 return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || 26868 isValidForStep(viewValue, minVal || 0, stepVal); 26869 }; 26870 26871 attr.$observe('step', function(val) { 26872 stepVal = parseNumberAttrVal(val); 26873 // TODO(matsko): implement validateLater to reduce number of validations 26874 ctrl.$validate(); 26875 }); 26876 } 26877} 26878 26879function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) { 26880 badInputChecker(scope, element, attr, ctrl, 'range'); 26881 numberFormatterParser(ctrl); 26882 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 26883 26884 var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range', 26885 minVal = supportsRange ? 0 : undefined, 26886 maxVal = supportsRange ? 100 : undefined, 26887 stepVal = supportsRange ? 1 : undefined, 26888 validity = element[0].validity, 26889 hasMinAttr = isDefined(attr.min), 26890 hasMaxAttr = isDefined(attr.max), 26891 hasStepAttr = isDefined(attr.step); 26892 26893 var originalRender = ctrl.$render; 26894 26895 ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ? 26896 //Browsers that implement range will set these values automatically, but reading the adjusted values after 26897 //$render would cause the min / max validators to be applied with the wrong value 26898 function rangeRender() { 26899 originalRender(); 26900 ctrl.$setViewValue(element.val()); 26901 } : 26902 originalRender; 26903 26904 if (hasMinAttr) { 26905 ctrl.$validators.min = supportsRange ? 26906 // Since all browsers set the input to a valid value, we don't need to check validity 26907 function noopMinValidator() { return true; } : 26908 // non-support browsers validate the min val 26909 function minValidator(modelValue, viewValue) { 26910 return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal; 26911 }; 26912 26913 setInitialValueAndObserver('min', minChange); 26914 } 26915 26916 if (hasMaxAttr) { 26917 ctrl.$validators.max = supportsRange ? 26918 // Since all browsers set the input to a valid value, we don't need to check validity 26919 function noopMaxValidator() { return true; } : 26920 // non-support browsers validate the max val 26921 function maxValidator(modelValue, viewValue) { 26922 return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal; 26923 }; 26924 26925 setInitialValueAndObserver('max', maxChange); 26926 } 26927 26928 if (hasStepAttr) { 26929 ctrl.$validators.step = supportsRange ? 26930 function nativeStepValidator() { 26931 // Currently, only FF implements the spec on step change correctly (i.e. adjusting the 26932 // input element value to a valid value). It's possible that other browsers set the stepMismatch 26933 // validity error instead, so we can at least report an error in that case. 26934 return !validity.stepMismatch; 26935 } : 26936 // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would 26937 function stepValidator(modelValue, viewValue) { 26938 return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || 26939 isValidForStep(viewValue, minVal || 0, stepVal); 26940 }; 26941 26942 setInitialValueAndObserver('step', stepChange); 26943 } 26944
26945 function setInitialValueAndObserver(htmlAttrName, changeFn) { 26946 // interpolated attributes set the attribute value only after a digest, but we need the 26947 // attribute value when the input is first rendered, so that the browser can adjust the 26948 // input value based on the min/max value 26949 element.attr(htmlAttrName, attr[htmlAttrName]); 26950 attr.$observe(htmlAttrName, changeFn); 26951 } 26952 26953 function minChange(val) { 26954 minVal = parseNumberAttrVal(val); 26955 // ignore changes before model is initialized 26956 if (isNumberNaN(ctrl.$modelValue)) { 26957 return; 26958 } 26959 26960 if (supportsRange) { 26961 var elVal = element.val(); 26962 // IE11 doesn't set the el val correctly if the minVal is greater than the element value 26963 if (minVal > elVal) { 26964 elVal = minVal; 26965 element.val(elVal); 26966 } 26967 ctrl.$setViewValue(elVal); 26968 } else { 26969 // TODO(matsko): implement validateLater to reduce number of validations 26970 ctrl.$validate(); 26971 } 26972 } 26973 26974 function maxChange(val) { 26975 maxVal = parseNumberAttrVal(val); 26976 // ignore changes before model is initialized 26977 if (isNumberNaN(ctrl.$modelValue)) { 26978 return; 26979 } 26980 26981 if (supportsRange) { 26982 var elVal = element.val(); 26983 // IE11 doesn't set the el val correctly if the maxVal is less than the element value 26984 if (maxVal < elVal) { 26985 element.val(maxVal); 26986 // IE11 and Chrome don't set the value to the minVal when max < min 26987 elVal = maxVal < minVal ? minVal : maxVal; 26988 } 26989 ctrl.$setViewValue(elVal); 26990 } else { 26991 // TODO(matsko): implement validateLater to reduce number of validations 26992 ctrl.$validate(); 26993 } 26994 } 26995 26996 function stepChange(val) { 26997 stepVal = parseNumberAttrVal(val); 26998 // ignore changes before model is initialized 26999 if (isNumberNaN(ctrl.$modelValue)) { 27000 return; 27001 } 27002 27003 // Some browsers don't adjust the input value correctly, but set the stepMismatch error 27004 if (supportsRange && ctrl.$viewValue !== element.val()) { 27005 ctrl.$setViewValue(element.val()); 27006 } else { 27007 // TODO(matsko): implement validateLater to reduce number of validations 27008 ctrl.$validate(
vendor: 30,864 bytes, lines 27008-27820
27008); 27009 } 27010 } 27011} 27012 27013function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { 27014 // Note: no badInputChecker here by purpose as `url` is only a validation 27015 // in browsers, i.e. we can always read out input.value even if it is not valid! 27016 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 27017 stringBasedInputType(ctrl); 27018 27019 ctrl.$validators.url = function(modelValue, viewValue) { 27020 var value = modelValue || viewValue; 27021 return ctrl.$isEmpty(value) || URL_REGEXP.test(value); 27022 }; 27023} 27024 27025function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { 27026 // Note: no badInputChecker here by purpose as `url` is only a validation 27027 // in browsers, i.e. we can always read out input.value even if it is not valid! 27028 baseInputType(scope, element, attr, ctrl, $sniffer, $browser); 27029 stringBasedInputType(ctrl); 27030 27031 ctrl.$validators.email = function(modelValue, viewValue) { 27032 var value = modelValue || viewValue; 27033 return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); 27034 }; 27035} 27036 27037function radioInputType(scope, element, attr, ctrl) { 27038 var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false'; 27039 // make the name unique, if not defined 27040 if (isUndefined(attr.name)) { 27041 element.attr('name', nextUid()); 27042 } 27043 27044 var listener = function(ev) { 27045 var value; 27046 if (element[0].checked) { 27047 value = attr.value; 27048 if (doTrim) { 27049 value = trim(value); 27050 } 27051 ctrl.$setViewValue(value, ev && ev.type); 27052 } 27053 }; 27054 27055 element.on('change', listener); 27056 27057 ctrl.$render = function() { 27058 var value = attr.value; 27059 if (doTrim) { 27060 value = trim(value); 27061 } 27062 element[0].checked = (value === ctrl.$viewValue); 27063 }; 27064 27065 attr.$observe('value', ctrl.$render); 27066} 27067 27068function parseConstantExpr($parse, context, name, expression, fallback) { 27069 var parseFn; 27070 if (isDefined(expression)) { 27071 parseFn = $parse(expression); 27072 if (!parseFn.constant) { 27073 throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' + 27074 '`{1}`.', name, expression); 27075 } 27076 return parseFn(context); 27077 } 27078 return fallback; 27079} 27080 27081function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { 27082 var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true); 27083 var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false); 27084 27085 var listener = function(ev) { 27086 ctrl.$setViewValue(element[0].checked, ev && ev.type); 27087 }; 27088 27089 element.on('change', listener); 27090 27091 ctrl.$render = function() { 27092 element[0].checked = ctrl.$viewValue; 27093 }; 27094 27095 // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false` 27096 // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert 27097 // it to a boolean. 27098 ctrl.$isEmpty = function(value) { 27099 return value === false; 27100 }; 27101 27102 ctrl.$formatters.push(function(value) { 27103 return equals(value, trueValue); 27104 }); 27105 27106 ctrl.$parsers.push(function(value) { 27107 return value ? trueValue : falseValue; 27108 }); 27109} 27110 27111 27112/** 27113 * @ngdoc directive 27114 * @name textarea 27115 * @restrict E 27116 * 27117 * @description 27118 * HTML textarea element control with AngularJS data-binding. The data-binding and validation 27119 * properties of this element are exactly the same as those of the 27120 * {@link ng.directive:input input element}. 27121 * 27122 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 27123 * @param {string=} name Property name of the form under which the control is published. 27124 * @param {string=} required Sets `required` validation error key if the value is not entered. 27125 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 27126 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 27127 * `required` when you want to data-bind to the `required` attribute. 27128 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 27129 * minlength. 27130 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 27131 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any 27132 * length. 27133 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 27134 * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. 27135 * If the expression evaluates to a RegExp object, then this is used directly. 27136 * If the expression evaluates to a string, then it will be converted to a RegExp 27137 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 27138 * `new RegExp('^abc$')`.<br /> 27139 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 27140 * start at the index of the last search's match, thus not taking the whole input value into 27141 * account. 27142 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 27143 * interaction with the input element. 27144 * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input. 27145 * 27146 * @knownIssue 27147 * 27148 * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily 27149 * insert the placeholder value as the textarea's content. If the placeholder value contains 27150 * interpolation (`{{ ... }}`), an error will be logged in the console when AngularJS tries to update 27151 * the value of the by-then-removed text node. This doesn't affect the functionality of the 27152 * textarea, but can be undesirable. 27153 * 27154 * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of 27155 * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can 27156 * find more details on `ngAttr` in the 27157 * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the 27158 * Developer Guide. 27159 */ 27160 27161 27162/** 27163 * @ngdoc directive 27164 * @name input 27165 * @restrict E 27166 * 27167 * @description 27168 * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding, 27169 * input state control, and validation. 27170 * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers. 27171 * 27172 * <div class="alert alert-warning"> 27173 * **Note:** Not every feature offered is available for all input types. 27174 * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`. 27175 * </div> 27176 * 27177 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 27178 * @param {string=} name Property name of the form under which the control is published. 27179 * @param {string=} required Sets `required` validation error key if the value is not entered. 27180 * @param {boolean=} ngRequired Sets `required` attribute if set to true 27181 * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than 27182 * minlength. 27183 * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than 27184 * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any 27185 * length. 27186 * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} 27187 * value does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. 27188 * If the expression evaluates to a RegExp object, then this is used directly. 27189 * If the expression evaluates to a string, then it will be converted to a RegExp 27190 * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to 27191 * `new RegExp('^abc$')`.<br /> 27192 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 27193 * start at the index of the last search's match, thus not taking the whole input value into 27194 * account. 27195 * @param {string=} ngChange AngularJS expression to be executed when input changes due to user 27196 * interaction with the input element. 27197 * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input. 27198 * This parameter is ignored for input[type=password] controls, which will never trim the 27199 * input. 27200 * 27201 * @example 27202 <example name="input-directive" module="inputExample"> 27203 <file name="index.html"> 27204 <script> 27205 angular.module('inputExample', []) 27206 .controller('ExampleController', ['$scope', function($scope) { 27207 $scope.user = {name: 'guest', last: 'visitor'}; 27208 }]); 27209 </script> 27210 <div ng-controller="ExampleController"> 27211 <form name="myForm"> 27212 <label> 27213 User name: 27214 <input type="text" name="userName" ng-model="user.name" required> 27215 </label> 27216 <div role="alert"> 27217 <span class="error" ng-show="myForm.userName.$error.required"> 27218 Required!</span> 27219 </div> 27220 <label> 27221 Last name: 27222 <input type="text" name="lastName" ng-model="user.last" 27223 ng-minlength="3" ng-maxlength="10"> 27224 </label> 27225 <div role="alert"> 27226 <span class="error" ng-show="myForm.lastName.$error.minlength"> 27227 Too short!</span> 27228 <span class="error" ng-show="myForm.lastName.$error.maxlength"> 27229 Too long!</span> 27230 </div> 27231 </form> 27232 <hr> 27233 <tt>user = {{user}}</tt><br/> 27234 <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/> 27235 <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/> 27236 <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/> 27237 <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/> 27238 <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 27239 <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 27240 <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/> 27241 <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/> 27242 </div> 27243 </file> 27244 <file name="protractor.js" type="protractor"> 27245 var user = element(by.exactBinding('user')); 27246 var userNameValid = element(by.binding('myForm.userName.$valid')); 27247 var lastNameValid = element(by.binding('myForm.lastName.$valid')); 27248 var lastNameError = element(by.binding('myForm.lastName.$error')); 27249 var formValid = element(by.binding('myForm.$valid')); 27250 var userNameInput = element(by.model('user.name')); 27251 var userLastInput = element(by.model('user.last')); 27252 27253 it('should initialize to model', function() { 27254 expect(user.getText()).toContain('{"name":"guest","last":"visitor"}'); 27255 expect(userNameValid.getText()).toContain('true'); 27256 expect(formValid.getText()).toContain('true'); 27257 }); 27258 27259 it('should be invalid if empty when required', function() { 27260 userNameInput.clear(); 27261 userNameInput.sendKeys(''); 27262 27263 expect(user.getText()).toContain('{"last":"visitor"}'); 27264 expect(userNameValid.getText()).toContain('false'); 27265 expect(formValid.getText()).toContain('false'); 27266 }); 27267 27268 it('should be valid if empty when min length is set', function() { 27269 userLastInput.clear(); 27270 userLastInput.sendKeys(''); 27271 27272 expect(user.getText()).toContain('{"name":"guest","last":""}'); 27273 expect(lastNameValid.getText()).toContain('true'); 27274 expect(formValid.getText()).toContain('true'); 27275 }); 27276 27277 it('should be invalid if less than required min length', function() { 27278 userLastInput.clear(); 27279 userLastInput.sendKeys('xx'); 27280 27281 expect(user.getText()).toContain('{"name":"guest"}'); 27282 expect(lastNameValid.getText()).toContain('false'); 27283 expect(lastNameError.getText()).toContain('minlength'); 27284 expect(formValid.getText()).toContain('false'); 27285 }); 27286 27287 it('should be invalid if longer than max length', function() { 27288 userLastInput.clear(); 27289 userLastInput.sendKeys('some ridiculously long name'); 27290 27291 expect(user.getText()).toContain('{"name":"guest"}'); 27292 expect(lastNameValid.getText()).toContain('false'); 27293 expect(lastNameError.getText()).toContain('maxlength'); 27294 expect(formValid.getText()).toContain('false'); 27295 }); 27296 </file> 27297 </example> 27298 */ 27299var inputDirective = ['$browser', '$sniffer', '$filter', '$parse', 27300 function($browser, $sniffer, $filter, $parse) { 27301 return { 27302 restrict: 'E', 27303 require: ['?ngModel'], 27304 link: { 27305 pre: function(scope, element, attr, ctrls) { 27306 if (ctrls[0]) { 27307 (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer, 27308 $browser, $filter, $parse); 27309 } 27310 } 27311 } 27312 }; 27313}]; 27314 27315 27316 27317var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; 27318/** 27319 * @ngdoc directive 27320 * @name ngValue 27321 * @restrict A 27322 * @priority 100 27323 * 27324 * @description 27325 * Binds the given expression to the value of the element. 27326 * 27327 * It is mainly used on {@link input[radio] `input[radio]`} and option elements, 27328 * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its 27329 * {@link select `select`} parent element) is set to the bound value. It is especially useful 27330 * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below. 27331 * 27332 * It can also be used to achieve one-way binding of a given expression to an input element 27333 * such as an `input[text]` or a `textarea`, when that element does not use ngModel. 27334 * 27335 * @element ANY 27336 * @param {string=} ngValue AngularJS expression, whose value will be bound to the `value` attribute 27337 * and `value` property of the element. 27338 * 27339 * @example 27340 <example name="ngValue-directive" module="valueExample"> 27341 <file name="index.html"> 27342 <script> 27343 angular.module('valueExample', []) 27344 .controller('ExampleController', ['$scope', function($scope) { 27345 $scope.names = ['pizza', 'unicorns', 'robots']; 27346 $scope.my = { favorite: 'unicorns' }; 27347 }]); 27348 </script> 27349 <form ng-controller="ExampleController"> 27350 <h2>Which is your favorite?</h2> 27351 <label ng-repeat="name in names" for="{{name}}"> 27352 {{name}} 27353 <input type="radio" 27354 ng-model="my.favorite" 27355 ng-value="name" 27356 id="{{name}}" 27357 name="favorite"> 27358 </label> 27359 <div>You chose {{my.favorite}}</div> 27360 </form> 27361 </file> 27362 <file name="protractor.js" type="protractor"> 27363 var favorite = element(by.binding('my.favorite')); 27364 27365 it('should initialize to model', function() { 27366 expect(favorite.getText()).toContain('unicorns'); 27367 }); 27368 it('should bind the values to the inputs', function() { 27369 element.all(by.model('my.favorite')).get(0).click(); 27370 expect(favorite.getText()).toContain('pizza'); 27371 }); 27372 </file> 27373 </example> 27374 */ 27375var ngValueDirective = function() { 27376 /** 27377 * inputs use the value attribute as their default value if the value property is not set. 27378 * Once the value property has been set (by adding input), it will not react to changes to 27379 * the value attribute anymore. Setting both attribute and property fixes this behavior, and 27380 * makes it possible to use ngValue as a sort of one-way bind. 27381 */ 27382 function updateElementValue(element, attr, value) { 27383 // Support: IE9 only 27384 // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`). 27385 var propValue = isDefined(value) ? value : (msie === 9) ? '' : null; 27386 element.prop('value', propValue); 27387 attr.$set('value', value); 27388 } 27389 27390 return { 27391 restrict: 'A', 27392 priority: 100, 27393 compile: function(tpl, tplAttr) { 27394 if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { 27395 return function ngValueConstantLink(scope, elm, attr) { 27396 var value = scope.$eval(attr.ngValue); 27397 updateElementValue(elm, attr, value); 27398 }; 27399 } else { 27400 return function ngValueLink(scope, elm, attr) { 27401 scope.$watch(attr.ngValue, function valueWatchAction(value) { 27402 updateElementValue(elm, attr, value); 27403 }); 27404 }; 27405 } 27406 } 27407 }; 27408}; 27409 27410/** 27411 * @ngdoc directive 27412 * @name ngBind 27413 * @restrict AC 27414 * 27415 * @description 27416 * The `ngBind` attribute tells AngularJS to replace the text content of the specified HTML element 27417 * with the value of a given expression, and to update the text content when the value of that 27418 * expression changes. 27419 * 27420 * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like 27421 * `{{ expression }}` which is similar but less verbose. 27422 * 27423 * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily 27424 * displayed by the browser in its raw state before AngularJS compiles it. Since `ngBind` is an 27425 * element attribute, it makes the bindings invisible to the user while the page is loading. 27426 * 27427 * An alternative solution to this problem would be using the 27428 * {@link ng.directive:ngCloak ngCloak} directive. 27429 * 27430 * 27431 * @element ANY 27432 * @param {expression} ngBind {@link guide/expression Expression} to evaluate. 27433 * 27434 * @example 27435 * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. 27436 <example module="bindExample" name="ng-bind"> 27437 <file name="index.html"> 27438 <script> 27439 angular.module('bindExample', []) 27440 .controller('ExampleController', ['$scope', function($scope) { 27441 $scope.name = 'Whirled'; 27442 }]); 27443 </script> 27444 <div ng-controller="ExampleController"> 27445 <label>Enter name: <input type="text" ng-model="name"></label><br> 27446 Hello <span ng-bind="name"></span>! 27447 </div> 27448 </file> 27449 <file name="protractor.js" type="protractor"> 27450 it('should check ng-bind', function() { 27451 var nameInput = element(by.model('name')); 27452 27453 expect(element(by.binding('name')).getText()).toBe('Whirled'); 27454 nameInput.clear(); 27455 nameInput.sendKeys('world'); 27456 expect(element(by.binding('name')).getText()).toBe('world'); 27457 }); 27458 </file> 27459 </example> 27460 */ 27461var ngBindDirective = ['$compile', function($compile) { 27462 return { 27463 restrict: 'AC', 27464 compile: function ngBindCompile(templateElement) { 27465 $compile.$$addBindingClass(templateElement); 27466 return function ngBindLink(scope, element, attr) { 27467 $compile.$$addBindingInfo(element, attr.ngBind); 27468 element = element[0]; 27469 scope.$watch(attr.ngBind, function ngBindWatchAction(value) { 27470 element.textContent = stringify(value); 27471 }); 27472 }; 27473 } 27474 }; 27475}]; 27476 27477 27478/** 27479 * @ngdoc directive 27480 * @name ngBindTemplate 27481 * 27482 * @description 27483 * The `ngBindTemplate` directive specifies that the element 27484 * text content should be replaced with the interpolation of the template 27485 * in the `ngBindTemplate` attribute. 27486 * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` 27487 * expressions. This directive is needed since some HTML elements 27488 * (such as TITLE and OPTION) cannot contain SPAN elements. 27489 * 27490 * @element ANY 27491 * @param {string} ngBindTemplate template of form 27492 * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. 27493 * 27494 * @example 27495 * Try it here: enter text in text box and watch the greeting change. 27496 <example module="bindExample" name="ng-bind-template"> 27497 <file name="index.html"> 27498 <script> 27499 angular.module('bindExample', []) 27500 .controller('ExampleController', ['$scope', function($scope) { 27501 $scope.salutation = 'Hello'; 27502 $scope.name = 'World'; 27503 }]); 27504 </script> 27505 <div ng-controller="ExampleController"> 27506 <label>Salutation: <input type="text" ng-model="salutation"></label><br> 27507 <label>Name: <input type="text" ng-model="name"></label><br> 27508 <pre ng-bind-template="{{salutation}} {{name}}!"></pre> 27509 </div> 27510 </file> 27511 <file name="protractor.js" type="protractor"> 27512 it('should check ng-bind', function() { 27513 var salutationElem = element(by.binding('salutation')); 27514 var salutationInput = element(by.model('salutation')); 27515 var nameInput = element(by.model('name')); 27516 27517 expect(salutationElem.getText()).toBe('Hello World!'); 27518 27519 salutationInput.clear(); 27520 salutationInput.sendKeys('Greetings'); 27521 nameInput.clear(); 27522 nameInput.sendKeys('user'); 27523 27524 expect(salutationElem.getText()).toBe('Greetings user!'); 27525 }); 27526 </file> 27527 </example> 27528 */ 27529var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) { 27530 return { 27531 compile: function ngBindTemplateCompile(templateElement) { 27532 $compile.$$addBindingClass(templateElement); 27533 return function ngBindTemplateLink(scope, element, attr) { 27534 var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); 27535 $compile.$$addBindingInfo(element, interpolateFn.expressions); 27536 element = element[0]; 27537 attr.$observe('ngBindTemplate', function(value) { 27538 element.textContent = isUndefined(value) ? '' : value; 27539 }); 27540 }; 27541 } 27542 }; 27543}]; 27544 27545 27546/** 27547 * @ngdoc directive 27548 * @name ngBindHtml 27549 * 27550 * @description 27551 * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, 27552 * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service. 27553 * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link 27554 * ngSanitize} in your module's dependencies (not in core AngularJS). In order to use {@link ngSanitize} 27555 * in your module's dependencies, you need to include "angular-sanitize.js" in your application. 27556 * 27557 * You may also bypass sanitization for values you know are safe. To do so, bind to 27558 * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example 27559 * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}. 27560 * 27561 * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you 27562 * will have an exception (instead of an exploit.) 27563 * 27564 * @element ANY 27565 * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. 27566 * 27567 * @example 27568 27569 <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html"> 27570 <file name="index.html"> 27571 <div ng-controller="ExampleController"> 27572 <p ng-bind-html="myHTML"></p> 27573 </div> 27574 </file> 27575 27576 <file name="script.js"> 27577 angular.module('bindHtmlExample', ['ngSanitize']) 27578 .controller('ExampleController', ['$scope', function($scope) { 27579 $scope.myHTML = 27580 'I am an <code>HTML</code>string with ' + 27581 '<a href="#">links!</a> and other <em>stuff</em>'; 27582 }]); 27583 </file> 27584 27585 <file name="protractor.js" type="protractor"> 27586 it('should check ng-bind-html', function() { 27587 expect(element(by.binding('myHTML')).getText()).toBe( 27588 'I am an HTMLstring with links! and other stuff'); 27589 }); 27590 </file> 27591 </example> 27592 */ 27593var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) { 27594 return { 27595 restrict: 'A', 27596 compile: function ngBindHtmlCompile(tElement, tAttrs) { 27597 var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); 27598 var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) { 27599 // Unwrap the value to compare the actual inner safe value, not the wrapper object. 27600 return $sce.valueOf(val); 27601 }); 27602 $compile.$$addBindingClass(tElement); 27603 27604 return function ngBindHtmlLink(scope, element, attr) { 27605 $compile.$$addBindingInfo(element, attr.ngBindHtml); 27606 27607 scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { 27608 // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter. 27609 var value = ngBindHtmlGetter(scope); 27610 element.html($sce.getTrustedHtml(value) || ''); 27611 }); 27612 }; 27613 } 27614 }; 27615}]; 27616 27617/** 27618 * @ngdoc directive 27619 * @name ngChange 27620 * @restrict A 27621 * 27622 * @description 27623 * Evaluate the given expression when the user changes the input. 27624 * The expression is evaluated immediately, unlike the JavaScript onchange event 27625 * which only triggers at the end of a change (usually, when the user leaves the 27626 * form element or presses the return key). 27627 * 27628 * The `ngChange` expression is only evaluated when a change in the input value causes 27629 * a new value to be committed to the model. 27630 * 27631 * It will not be evaluated: 27632 * * if the value returned from the `$parsers` transformation pipeline has not changed 27633 * * if the input has continued to be invalid since the model will stay `null` 27634 * * if the model is changed programmatically and not by a change to the input value 27635 * 27636 * 27637 * Note, this directive requires `ngModel` to be present. 27638 * 27639 * @element ANY 27640 * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change 27641 * in input value. 27642 * 27643 * @example 27644 * <example name="ngChange-directive" module="changeExample"> 27645 * <file name="index.html"> 27646 * <script> 27647 * angular.module('changeExample', []) 27648 * .controller('ExampleController', ['$scope', function($scope) { 27649 * $scope.counter = 0; 27650 * $scope.change = function() { 27651 * $scope.counter++; 27652 * }; 27653 * }]); 27654 * </script> 27655 * <div ng-controller="ExampleController"> 27656 * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> 27657 * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> 27658 * <label for="ng-change-example2">Confirmed</label><br /> 27659 * <tt>debug = {{confirmed}}</tt><br/> 27660 * <tt>counter = {{counter}}</tt><br/> 27661 * </div> 27662 * </file> 27663 * <file name="protractor.js" type="protractor"> 27664 * var counter = element(by.binding('counter')); 27665 * var debug = element(by.binding('confirmed')); 27666 * 27667 * it('should evaluate the expression if changing from view', function() { 27668 * expect(counter.getText()).toContain('0'); 27669 * 27670 * element(by.id('ng-change-example1')).click(); 27671 * 27672 * expect(counter.getText()).toContain('1'); 27673 * expect(debug.getText()).toContain('true'); 27674 * }); 27675 * 27676 * it('should not evaluate the expression if changing from model', function() { 27677 * element(by.id('ng-change-example2')).click(); 27678 27679 * expect(counter.getText()).toContain('0'); 27680 * expect(debug.getText()).toContain('true'); 27681 * }); 27682 * </file> 27683 * </example> 27684 */ 27685var ngChangeDirective = valueFn({ 27686 restrict: 'A', 27687 require: 'ngModel', 27688 link: function(scope, element, attr, ctrl) { 27689 ctrl.$viewChangeListeners.push(function() { 27690 scope.$eval(attr.ngChange); 27691 }); 27692 } 27693}); 27694 27695/* exported 27696 ngClassDirective, 27697 ngClassEvenDirective, 27698 ngClassOddDirective 27699*/ 27700 27701function classDirective(name, selector) { 27702 name = 'ngClass' + name; 27703 var indexWatchExpression; 27704 27705 return ['$parse', function($parse) { 27706 return { 27707 restrict: 'AC', 27708 link: function(scope, element, attr) { 27709 var classCounts = element.data('$classCounts'); 27710 var oldModulo = true; 27711 var oldClassString; 27712 27713 if (!classCounts) { 27714 // Use createMap() to prevent class assumptions involving property 27715 // names in Object.prototype 27716 classCounts = createMap(); 27717 element.data('$classCounts', classCounts); 27718 } 27719 27720 if (name !== 'ngClass') { 27721 if (!indexWatchExpression) { 27722 indexWatchExpression = $parse('$index', function moduloTwo($index) { 27723 // eslint-disable-next-line no-bitwise 27724 return $index & 1; 27725 }); 27726 } 27727 27728 scope.$watch(indexWatchExpression, ngClassIndexWatchAction); 27729 } 27730 27731 scope.$watch($parse(attr[name], toClassString), ngClassWatchAction); 27732 27733 function addClasses(classString) { 27734 classString = digestClassCounts(split(classString), 1); 27735 attr.$addClass(classString); 27736 } 27737 27738 function removeClasses(classString) { 27739 classString = digestClassCounts(split(classString), -1); 27740 attr.$removeClass(classString); 27741 } 27742 27743 function updateClasses(oldClassString, newClassString) { 27744 var oldClassArray = split(oldClassString); 27745 var newClassArray = split(newClassString); 27746 27747 var toRemoveArray = arrayDifference(oldClassArray, newClassArray); 27748 var toAddArray = arrayDifference(newClassArray, oldClassArray); 27749 27750 var toRemoveString = digestClassCounts(toRemoveArray, -1); 27751 var toAddString = digestClassCounts(toAddArray, 1); 27752 27753 attr.$addClass(toAddString); 27754 attr.$removeClass(toRemoveString); 27755 } 27756 27757 function digestClassCounts(classArray, count) { 27758 var classesToUpdate = []; 27759 27760 forEach(classArray, function(className) { 27761 if (count > 0 || classCounts[className]) { 27762 classCounts[className] = (classCounts[className] || 0) + count; 27763 if (classCounts[className] === +(count > 0)) { 27764 classesToUpdate.push(className); 27765 } 27766 } 27767 }); 27768 27769 return classesToUpdate.join(' '); 27770 } 27771 27772 function ngClassIndexWatchAction(newModulo) { 27773 // This watch-action should run before the `ngClassWatchAction()`, thus it 27774 // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the 27775 // `ngClassWatchAction()` will update the classes. 27776 if (newModulo === selector) { 27777 addClasses(oldClassString); 27778 } else { 27779 removeClasses(oldClassString); 27780 } 27781 27782 oldModulo = newModulo; 27783 } 27784 27785 function ngClassWatchAction(newClassString) { 27786 if (oldModulo === selector) { 27787 updateClasses(oldClassString, newClassString); 27788 } 27789 27790 oldClassString = newClassString; 27791 } 27792 } 27793 }; 27794 }]; 27795 27796 // Helpers 27797 function arrayDifference(tokens1, tokens2) { 27798 if (!tokens1 || !tokens1.length) return []; 27799 if (!tokens2 || !tokens2.length) return tokens1; 27800 27801 var values = []; 27802 27803 outer: 27804 for (var i = 0; i < tokens1.length; i++) { 27805 var token = tokens1[i]; 27806 for (var j = 0; j < tokens2.length; j++) { 27807 if (token === tokens2[j]) continue outer; 27808 } 27809 values.push(token); 27810 } 27811 27812 return values; 27813 } 27814 27815 function split(classString) { 27816 return classString && classString.split(' '); 27817 } 27818 27819 function toClassString(classValue) { 27820
27820var classString = classValue; 27821 27822 if (isArray(classValue)) { 27823 classString = classValue.map(toClassString).join(' '); 27824 } else if (isObject(classValue)) { 27825 classString = Object.keys(classValue). 27826 filter(function(key) { return classValue[key]; }). 27827 join(' ')
vendor: 54,910 bytes, lines 27827-29393
27827; 27828 } 27829 27830 return classString; 27831 } 27832} 27833 27834/** 27835 * @ngdoc directive 27836 * @name ngClass 27837 * @restrict AC 27838 * @element ANY 27839 * 27840 * @description 27841 * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding 27842 * an expression that represents all classes to be added. 27843 * 27844 * The directive operates in three different ways, depending on which of three types the expression 27845 * evaluates to: 27846 * 27847 * 1. If the expression evaluates to a string, the string should be one or more space-delimited class 27848 * names. 27849 * 27850 * 2. If the expression evaluates to an object, then for each key-value pair of the 27851 * object with a truthy value the corresponding key is used as a class name. 27852 * 27853 * 3. If the expression evaluates to an array, each element of the array should either be a string as in 27854 * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array 27855 * to give you more control over what CSS classes appear. See the code below for an example of this. 27856 * 27857 * 27858 * The directive won't add duplicate classes if a particular class was already set. 27859 * 27860 * When the expression changes, the previously added classes are removed and only then are the 27861 * new classes added. 27862 * 27863 * @knownIssue 27864 * You should not use {@link guide/interpolation interpolation} in the value of the `class` 27865 * attribute, when using the `ngClass` directive on the same element. 27866 * See {@link guide/interpolation#known-issues here} for more info. 27867 * 27868 * @animations 27869 * | Animation | Occurs | 27870 * |----------------------------------|-------------------------------------| 27871 * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element | 27872 * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element | 27873 * | {@link ng.$animate#setClass setClass} | just before classes are added and classes are removed from the element at the same time | 27874 * 27875 * ### ngClass and pre-existing CSS3 Transitions/Animations 27876 The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. 27877 Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder 27878 any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure 27879 to view the step by step details of {@link $animate#addClass $animate.addClass} and 27880 {@link $animate#removeClass $animate.removeClass}. 27881 * 27882 * @param {expression} ngClass {@link guide/expression Expression} to eval. The result 27883 * of the evaluation can be a string representing space delimited class 27884 * names, an array, or a map of class names to boolean values. In the case of a map, the 27885 * names of the properties whose values are truthy will be added as css classes to the 27886 * element. 27887 * 27888 * @example 27889 * ### Basic 27890 <example name="ng-class"> 27891 <file name="index.html"> 27892 <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p> 27893 <label> 27894 <input type="checkbox" ng-model="deleted"> 27895 deleted (apply "strike" class) 27896 </label><br> 27897 <label> 27898 <input type="checkbox" ng-model="important"> 27899 important (apply "bold" class) 27900 </label><br> 27901 <label> 27902 <input type="checkbox" ng-model="error"> 27903 error (apply "has-error" class) 27904 </label> 27905 <hr> 27906 <p ng-class="style">Using String Syntax</p> 27907 <input type="text" ng-model="style" 27908 placeholder="Type: bold strike red" aria-label="Type: bold strike red"> 27909 <hr> 27910 <p ng-class="[style1, style2, style3]">Using Array Syntax</p> 27911 <input ng-model="style1" 27912 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br> 27913 <input ng-model="style2" 27914 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br> 27915 <input ng-model="style3" 27916 placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br> 27917 <hr> 27918 <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p> 27919 <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br> 27920 <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label> 27921 </file> 27922 <file name="style.css"> 27923 .strike { 27924 text-decoration: line-through; 27925 } 27926 .bold { 27927 font-weight: bold; 27928 } 27929 .red { 27930 color: red; 27931 } 27932 .has-error { 27933 color: red; 27934 background-color: yellow; 27935 } 27936 .orange { 27937 color: orange; 27938 } 27939 </file> 27940 <file name="protractor.js" type="protractor"> 27941 var ps = element.all(by.css('p')); 27942 27943 it('should let you toggle the class', function() { 27944 27945 expect(ps.first().getAttribute('class')).not.toMatch(/bold/); 27946 expect(ps.first().getAttribute('class')).not.toMatch(/has-error/); 27947 27948 element(by.model('important')).click(); 27949 expect(ps.first().getAttribute('class')).toMatch(/bold/); 27950 27951 element(by.model('error')).click(); 27952 expect(ps.first().getAttribute('class')).toMatch(/has-error/); 27953 }); 27954 27955 it('should let you toggle string example', function() { 27956 expect(ps.get(1).getAttribute('class')).toBe(''); 27957 element(by.model('style')).clear(); 27958 element(by.model('style')).sendKeys('red'); 27959 expect(ps.get(1).getAttribute('class')).toBe('red'); 27960 }); 27961 27962 it('array example should have 3 classes', function() { 27963 expect(ps.get(2).getAttribute('class')).toBe(''); 27964 element(by.model('style1')).sendKeys('bold'); 27965 element(by.model('style2')).sendKeys('strike'); 27966 element(by.model('style3')).sendKeys('red'); 27967 expect(ps.get(2).getAttribute('class')).toBe('bold strike red'); 27968 }); 27969 27970 it('array with map example should have 2 classes', function() { 27971 expect(ps.last().getAttribute('class')).toBe(''); 27972 element(by.model('style4')).sendKeys('bold'); 27973 element(by.model('warning')).click(); 27974 expect(ps.last().getAttribute('class')).toBe('bold orange'); 27975 }); 27976 </file> 27977 </example> 27978 27979 @example 27980 ### Animations 27981 27982 The example below demonstrates how to perform animations using ngClass. 27983 27984 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class"> 27985 <file name="index.html"> 27986 <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'"> 27987 <input id="clearbtn" type="button" value="clear" ng-click="myVar=''"> 27988 <br> 27989 <span class="base-class" ng-class="myVar">Sample Text</span> 27990 </file> 27991 <file name="style.css"> 27992 .base-class { 27993 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; 27994 } 27995 27996 .base-class.my-class { 27997 color: red; 27998 font-size:3em; 27999 } 28000 </file> 28001 <file name="protractor.js" type="protractor"> 28002 it('should check ng-class', function() { 28003 expect(element(by.css('.base-class')).getAttribute('class')).not. 28004 toMatch(/my-class/); 28005 28006 element(by.id('setbtn')).click(); 28007 28008 expect(element(by.css('.base-class')).getAttribute('class')). 28009 toMatch(/my-class/); 28010 28011 element(by.id('clearbtn')).click(); 28012 28013 expect(element(by.css('.base-class')).getAttribute('class')).not. 28014 toMatch(/my-class/); 28015 }); 28016 </file> 28017 </example> 28018 */ 28019var ngClassDirective = classDirective('', true); 28020 28021/** 28022 * @ngdoc directive 28023 * @name ngClassOdd 28024 * @restrict AC 28025 * 28026 * @description 28027 * The `ngClassOdd` and `ngClassEven` directives work exactly as 28028 * {@link ng.directive:ngClass ngClass}, except they work in 28029 * conjunction with `ngRepeat` and take effect only on odd (even) rows. 28030 * 28031 * This directive can be applied only within the scope of an 28032 * {@link ng.directive:ngRepeat ngRepeat}. 28033 * 28034 * @animations 28035 * | Animation | Occurs | 28036 * |----------------------------------|-------------------------------------| 28037 * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element | 28038 * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element | 28039 * 28040 * @element ANY 28041 * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result 28042 * of the evaluation can be a string representing space delimited class names or an array. 28043 * 28044 * @example 28045 <example name="ng-class-odd"> 28046 <file name="index.html"> 28047 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> 28048 <li ng-repeat="name in names"> 28049 <span ng-class-odd="'odd'" ng-class-even="'even'"> 28050 {{name}} 28051 </span> 28052 </li> 28053 </ol> 28054 </file> 28055 <file name="style.css"> 28056 .odd { 28057 color: red; 28058 } 28059 .even { 28060 color: blue; 28061 } 28062 </file> 28063 <file name="protractor.js" type="protractor"> 28064 it('should check ng-class-odd and ng-class-even', function() { 28065 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). 28066 toMatch(/odd/); 28067 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). 28068 toMatch(/even/); 28069 }); 28070 </file> 28071 </example> 28072 * 28073 * <hr /> 28074 * @example 28075 * An example on how to implement animations using `ngClassOdd`: 28076 * 28077 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class-odd-animate"> 28078 <file name="index.html"> 28079 <div ng-init="items=['Item 3', 'Item 2', 'Item 1', 'Item 0']"> 28080 <button ng-click="items.unshift('Item ' + items.length)">Add item</button> 28081 <hr /> 28082 <table> 28083 <tr ng-repeat="item in items" ng-class-odd="'odd'"> 28084 <td>{{ item }}</td> 28085 </tr> 28086 </table> 28087 </div> 28088 </file> 28089 <file name="style.css"> 28090 .odd { 28091 background: rgba(255, 255, 0, 0.25); 28092 } 28093 28094 .odd-add, .odd-remove { 28095 transition: 1.5s; 28096 } 28097 </file> 28098 <file name="protractor.js" type="protractor"> 28099 it('should add new entries to the beginning of the list', function() { 28100 var button = element(by.buttonText('Add item')); 28101 var rows = element.all(by.repeater('item in items')); 28102 28103 expect(rows.count()).toBe(4); 28104 expect(rows.get(0).getText()).toBe('Item 3'); 28105 expect(rows.get(1).getText()).toBe('Item 2'); 28106 28107 button.click(); 28108 28109 expect(rows.count()).toBe(5); 28110 expect(rows.get(0).getText()).toBe('Item 4'); 28111 expect(rows.get(1).getText()).toBe('Item 3'); 28112 }); 28113 28114 it('should add odd class to odd entries', function() { 28115 var button = element(by.buttonText('Add item')); 28116 var rows = element.all(by.repeater('item in items')); 28117 28118 expect(rows.get(0).getAttribute('class')).toMatch(/odd/); 28119 expect(rows.get(1).getAttribute('class')).not.toMatch(/odd/); 28120 28121 button.click(); 28122 28123 expect(rows.get(0).getAttribute('class')).toMatch(/odd/); 28124 expect(rows.get(1).getAttribute('class')).not.toMatch(/odd/); 28125 }); 28126 </file> 28127 </example> 28128 */ 28129var ngClassOddDirective = classDirective('Odd', 0); 28130 28131/** 28132 * @ngdoc directive 28133 * @name ngClassEven 28134 * @restrict AC 28135 * 28136 * @description 28137 * The `ngClassOdd` and `ngClassEven` directives work exactly as 28138 * {@link ng.directive:ngClass ngClass}, except they work in 28139 * conjunction with `ngRepeat` and take effect only on odd (even) rows. 28140 * 28141 * This directive can be applied only within the scope of an 28142 * {@link ng.directive:ngRepeat ngRepeat}. 28143 * 28144 * @animations 28145 * | Animation | Occurs | 28146 * |----------------------------------|-------------------------------------| 28147 * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element | 28148 * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element | 28149 * 28150 * @element ANY 28151 * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The 28152 * result of the evaluation can be a string representing space delimited class names or an array. 28153 * 28154 * @example 28155 <example name="ng-class-even"> 28156 <file name="index.html"> 28157 <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> 28158 <li ng-repeat="name in names"> 28159 <span ng-class-odd="'odd'" ng-class-even="'even'"> 28160 {{name}} 28161 </span> 28162 </li> 28163 </ol> 28164 </file> 28165 <file name="style.css"> 28166 .odd { 28167 color: red; 28168 } 28169 .even { 28170 color: blue; 28171 } 28172 </file> 28173 <file name="protractor.js" type="protractor"> 28174 it('should check ng-class-odd and ng-class-even', function() { 28175 expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). 28176 toMatch(/odd/); 28177 expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). 28178 toMatch(/even/); 28179 }); 28180 </file> 28181 </example> 28182 * 28183 * <hr /> 28184 * @example 28185 * An example on how to implement animations using `ngClassEven`: 28186 * 28187 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class-even-animate"> 28188 <file name="index.html"> 28189 <div ng-init="items=['Item 3', 'Item 2', 'Item 1', 'Item 0']"> 28190 <button ng-click="items.unshift('Item ' + items.length)">Add item</button> 28191 <hr /> 28192 <table> 28193 <tr ng-repeat="item in items" ng-class-even="'even'"> 28194 <td>{{ item }}</td> 28195 </tr> 28196 </table> 28197 </div> 28198 </file> 28199 <file name="style.css"> 28200 .even { 28201 background: rgba(255, 255, 0, 0.25); 28202 } 28203 28204 .even-add, .even-remove { 28205 transition: 1.5s; 28206 } 28207 </file> 28208 <file name="protractor.js" type="protractor"> 28209 it('should add new entries to the beginning of the list', function() { 28210 var button = element(by.buttonText('Add item')); 28211 var rows = element.all(by.repeater('item in items')); 28212 28213 expect(rows.count()).toBe(4); 28214 expect(rows.get(0).getText()).toBe('Item 3'); 28215 expect(rows.get(1).getText()).toBe('Item 2'); 28216 28217 button.click(); 28218 28219 expect(rows.count()).toBe(5); 28220 expect(rows.get(0).getText()).toBe('Item 4'); 28221 expect(rows.get(1).getText()).toBe('Item 3'); 28222 }); 28223 28224 it('should add even class to even entries', function() { 28225 var button = element(by.buttonText('Add item')); 28226 var rows = element.all(by.repeater('item in items')); 28227 28228 expect(rows.get(0).getAttribute('class')).not.toMatch(/even/); 28229 expect(rows.get(1).getAttribute('class')).toMatch(/even/); 28230 28231 button.click(); 28232 28233 expect(rows.get(0).getAttribute('class')).not.toMatch(/even/); 28234 expect(rows.get(1).getAttribute('class')).toMatch(/even/); 28235 }); 28236 </file> 28237 </example> 28238 */ 28239var ngClassEvenDirective = classDirective('Even', 1); 28240 28241/** 28242 * @ngdoc directive 28243 * @name ngCloak 28244 * @restrict AC 28245 * 28246 * @description 28247 * The `ngCloak` directive is used to prevent the AngularJS html template from being briefly 28248 * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this 28249 * directive to avoid the undesirable flicker effect caused by the html template display. 28250 * 28251 * The directive can be applied to the `<body>` element, but the preferred usage is to apply 28252 * multiple `ngCloak` directives to small portions of the page to permit progressive rendering 28253 * of the browser view. 28254 * 28255 * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and 28256 * `angular.min.js`. 28257 * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). 28258 * 28259 * ```css 28260 * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { 28261 * display: none !important; 28262 * } 28263 * ``` 28264 * 28265 * When this css rule is loaded by the browser, all html elements (including their children) that 28266 * are tagged with the `ngCloak` directive are hidden. When AngularJS encounters this directive 28267 * during the compilation of the template it deletes the `ngCloak` element attribute, making 28268 * the compiled element visible. 28269 * 28270 * For the best result, the `angular.js` script must be loaded in the head section of the html 28271 * document; alternatively, the css rule above must be included in the external stylesheet of the 28272 * application. 28273 * 28274 * @element ANY 28275 * 28276 * @example 28277 <example name="ng-cloak"> 28278 <file name="index.html"> 28279 <div id="template1" ng-cloak>{{ 'hello' }}</div> 28280 <div id="template2" class="ng-cloak">{{ 'world' }}</div> 28281 </file> 28282 <file name="protractor.js" type="protractor"> 28283 it('should remove the template directive and css class', function() { 28284 expect($('#template1').getAttribute('ng-cloak')). 28285 toBeNull(); 28286 expect($('#template2').getAttribute('ng-cloak')). 28287 toBeNull(); 28288 }); 28289 </file> 28290 </example> 28291 * 28292 */ 28293var ngCloakDirective = ngDirective({ 28294 compile: function(element, attr) { 28295 attr.$set('ngCloak', undefined); 28296 element.removeClass('ng-cloak'); 28297 } 28298}); 28299 28300/** 28301 * @ngdoc directive 28302 * @name ngController 28303 * 28304 * @description 28305 * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular 28306 * supports the principles behind the Model-View-Controller design pattern. 28307 * 28308 * MVC components in angular: 28309 * 28310 * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties 28311 * are accessed through bindings. 28312 * * View — The template (HTML with data bindings) that is rendered into the View. 28313 * * Controller — The `ngController` directive specifies a Controller class; the class contains business 28314 * logic behind the application to decorate the scope with functions and values 28315 * 28316 * Note that you can also attach controllers to the DOM by declaring it in a route definition 28317 * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller 28318 * again using `ng-controller` in the template itself. This will cause the controller to be attached 28319 * and executed twice. 28320 * 28321 * @element ANY 28322 * @scope 28323 * @priority 500 28324 * @param {expression} ngController Name of a constructor function registered with the current 28325 * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression} 28326 * that on the current scope evaluates to a constructor function. 28327 * 28328 * The controller instance can be published into a scope property by specifying 28329 * `ng-controller="as propertyName"`. 28330 * 28331 * @example 28332 * Here is a simple form for editing user contact information. Adding, removing, clearing, and 28333 * greeting are methods declared on the controller (see source tab). These methods can 28334 * easily be called from the AngularJS markup. Any changes to the data are automatically reflected 28335 * in the View without the need for a manual update. 28336 * 28337 * Two different declaration styles are included below: 28338 * 28339 * * one binds methods and properties directly onto the controller using `this`: 28340 * `ng-controller="SettingsController1 as settings"` 28341 * * one injects `$scope` into the controller: 28342 * `ng-controller="SettingsController2"` 28343 * 28344 * The second option is more common in the AngularJS community, and is generally used in boilerplates 28345 * and in this guide. However, there are advantages to binding properties directly to the controller 28346 * and avoiding scope. 28347 * 28348 * * Using `controller as` makes it obvious which controller you are accessing in the template when 28349 * multiple controllers apply to an element. 28350 * * If you are writing your controllers as classes you have easier access to the properties and 28351 * methods, which will appear on the scope, from inside the controller code. 28352 * * Since there is always a `.` in the bindings, you don't have to worry about prototypal 28353 * inheritance masking primitives. 28354 * 28355 * This example demonstrates the `controller as` syntax. 28356 * 28357 * <example name="ngControllerAs" module="controllerAsExample"> 28358 * <file name="index.html"> 28359 * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings"> 28360 * <label>Name: <input type="text" ng-model="settings.name"/></label> 28361 * <button ng-click="settings.greet()">greet</button><br/> 28362 * Contact: 28363 * <ul> 28364 * <li ng-repeat="contact in settings.contacts"> 28365 * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}"> 28366 * <option>phone</option> 28367 * <option>email</option> 28368 * </select> 28369 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" /> 28370 * <button ng-click="settings.clearContact(contact)">clear</button> 28371 * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button> 28372 * </li> 28373 * <li><button ng-click="settings.addContact()">add</button></li> 28374 * </ul> 28375 * </div> 28376 * </file> 28377 * <file name="app.js"> 28378 * angular.module('controllerAsExample', []) 28379 * .controller('SettingsController1', SettingsController1); 28380 * 28381 * function SettingsController1() { 28382 * this.name = 'John Smith'; 28383 * this.contacts = [ 28384 * {type: 'phone', value: '408 555 1212'}, 28385 * {type: 'email', value: '[email protected]'} 28386 * ]; 28387 * } 28388 * 28389 * SettingsController1.prototype.greet = function() { 28390 * alert(this.name); 28391 * }; 28392 * 28393 * SettingsController1.prototype.addContact = function() { 28394 * this.contacts.push({type: 'email', value: '[email protected]'}); 28395 * }; 28396 * 28397 * SettingsController1.prototype.removeContact = function(contactToRemove) { 28398 * var index = this.contacts.indexOf(contactToRemove); 28399 * this.contacts.splice(index, 1); 28400 * }; 28401 * 28402 * SettingsController1.prototype.clearContact = function(contact) { 28403 * contact.type = 'phone'; 28404 * contact.value = ''; 28405 * }; 28406 * </file> 28407 * <file name="protractor.js" type="protractor"> 28408 * it('should check controller as', function() { 28409 * var container = element(by.id('ctrl-as-exmpl')); 28410 * expect(container.element(by.model('settings.name')) 28411 * .getAttribute('value')).toBe('John Smith'); 28412 * 28413 * var firstRepeat = 28414 * container.element(by.repeater('contact in settings.contacts').row(0)); 28415 * var secondRepeat = 28416 * container.element(by.repeater('contact in settings.contacts').row(1)); 28417 * 28418 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) 28419 * .toBe('408 555 1212'); 28420 * 28421 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) 28422 * .toBe('[email protected]'); 28423 * 28424 * firstRepeat.element(by.buttonText('clear')).click(); 28425 * 28426 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) 28427 * .toBe(''); 28428 * 28429 * container.element(by.buttonText('add')).click(); 28430 * 28431 * expect(container.element(by.repeater('contact in settings.contacts').row(2)) 28432 * .element(by.model('contact.value')) 28433 * .getAttribute('value')) 28434 * .toBe('[email protected]'); 28435 * }); 28436 * </file> 28437 * </example> 28438 * 28439 * This example demonstrates the "attach to `$scope`" style of controller. 28440 * 28441 * <example name="ngController" module="controllerExample"> 28442 * <file name="index.html"> 28443 * <div id="ctrl-exmpl" ng-controller="SettingsController2"> 28444 * <label>Name: <input type="text" ng-model="name"/></label> 28445 * <button ng-click="greet()">greet</button><br/> 28446 * Contact: 28447 * <ul> 28448 * <li ng-repeat="contact in contacts"> 28449 * <select ng-model="contact.type" id="select_{{$index}}"> 28450 * <option>phone</option> 28451 * <option>email</option> 28452 * </select> 28453 * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" /> 28454 * <button ng-click="clearContact(contact)">clear</button> 28455 * <button ng-click="removeContact(contact)">X</button> 28456 * </li> 28457 * <li>[ <button ng-click="addContact()">add</button> ]</li> 28458 * </ul> 28459 * </div> 28460 * </file> 28461 * <file name="app.js"> 28462 * angular.module('controllerExample', []) 28463 * .controller('SettingsController2', ['$scope', SettingsController2]); 28464 * 28465 * function SettingsController2($scope) { 28466 * $scope.name = 'John Smith'; 28467 * $scope.contacts = [ 28468 * {type:'phone', value:'408 555 1212'}, 28469 * {type:'email', value:'[email protected]'} 28470 * ]; 28471 * 28472 * $scope.greet = function() { 28473 * alert($scope.name); 28474 * }; 28475 * 28476 * $scope.addContact = function() { 28477 * $scope.contacts.push({type:'email', value:'[email protected]'}); 28478 * }; 28479 * 28480 * $scope.removeContact = function(contactToRemove) { 28481 * var index = $scope.contacts.indexOf(contactToRemove); 28482 * $scope.contacts.splice(index, 1); 28483 * }; 28484 * 28485 * $scope.clearContact = function(contact) { 28486 * contact.type = 'phone'; 28487 * contact.value = ''; 28488 * }; 28489 * } 28490 * </file> 28491 * <file name="protractor.js" type="protractor"> 28492 * it('should check controller', function() { 28493 * var container = element(by.id('ctrl-exmpl')); 28494 * 28495 * expect(container.element(by.model('name')) 28496 * .getAttribute('value')).toBe('John Smith'); 28497 * 28498 * var firstRepeat = 28499 * container.element(by.repeater('contact in contacts').row(0)); 28500 * var secondRepeat = 28501 * container.element(by.repeater('contact in contacts').row(1)); 28502 * 28503 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) 28504 * .toBe('408 555 1212'); 28505 * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) 28506 * .toBe('[email protected]'); 28507 * 28508 * firstRepeat.element(by.buttonText('clear')).click(); 28509 * 28510 * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) 28511 * .toBe(''); 28512 * 28513 * container.element(by.buttonText('add')).click(); 28514 * 28515 * expect(container.element(by.repeater('contact in contacts').row(2)) 28516 * .element(by.model('contact.value')) 28517 * .getAttribute('value')) 28518 * .toBe('[email protected]'); 28519 * }); 28520 * </file> 28521 *</example> 28522 28523 */ 28524var ngControllerDirective = [function() { 28525 return { 28526 restrict: 'A', 28527 scope: true, 28528 controller: '@', 28529 priority: 500 28530 }; 28531}]; 28532 28533/** 28534 * @ngdoc directive 28535 * @name ngCsp 28536 * 28537 * @restrict A 28538 * @element ANY 28539 * @description 28540 * 28541 * AngularJS has some features that can conflict with certain restrictions that are applied when using 28542 * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules. 28543 * 28544 * If you intend to implement CSP with these rules then you must tell AngularJS not to use these 28545 * features. 28546 * 28547 * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps. 28548 * 28549 * 28550 * The following default rules in CSP affect AngularJS: 28551 * 28552 * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute 28553 * code from strings is forbidden. AngularJS makes use of this in the {@link $parse} service to 28554 * provide a 30% increase in the speed of evaluating AngularJS expressions. (This CSP rule can be 28555 * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would 28556 * weaken the protections offered by CSP.) 28557 * 28558 * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden. 28559 * This prevents apps from injecting custom styles directly into the document. AngularJS makes use of 28560 * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these 28561 * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css` 28562 * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but 28563 * it is generally not recommended as it would weaken the protections offered by CSP.) 28564 * 28565 * If you do not provide `ngCsp` then AngularJS tries to autodetect if CSP is blocking dynamic code 28566 * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically 28567 * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a 28568 * CSP error to be logged in the console: 28569 * 28570 * ``` 28571 * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of 28572 * script in the following Content Security Policy directive: "default-src 'self'". Note that 28573 * 'script-src' was not explicitly set, so 'default-src' is used as a fallback. 28574 * ``` 28575 * 28576 * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp` 28577 * directive on an element of the HTML document that appears before the `<script>` tag that loads 28578 * the `angular.js` file. 28579 * 28580 * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* 28581 * 28582 * You can specify which of the CSP related AngularJS features should be deactivated by providing 28583 * a value for the `ng-csp` attribute. The options are as follows: 28584 * 28585 * * no-inline-style: this stops AngularJS from injecting CSS styles into the DOM 28586 * 28587 * * no-unsafe-eval: this stops AngularJS from optimizing $parse with unsafe eval of strings 28588 * 28589 * You can use these values in the following combinations: 28590 * 28591 * 28592 * * No declaration means that AngularJS will assume that you can do inline styles, but it will do 28593 * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous 28594 * versions of AngularJS. 28595 * 28596 * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell AngularJS to deactivate both inline 28597 * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous 28598 * versions of AngularJS. 28599 * 28600 * * Specifying only `no-unsafe-eval` tells AngularJS that we must not use eval, but that we can 28601 * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`. 28602 * 28603 * * Specifying only `no-inline-style` tells AngularJS that we must not inject styles, but that we can 28604 * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">` 28605 * 28606 * * Specifying both `no-unsafe-eval` and `no-inline-style` tells AngularJS that we must not inject 28607 * styles nor use eval, which is the same as an empty: ng-csp. 28608 * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">` 28609 * 28610 * @example 28611 * 28612 * This example shows how to apply the `ngCsp` directive to the `html` tag. 28613 ```html 28614 <!doctype html> 28615 <html ng-app ng-csp> 28616 ... 28617 ... 28618 </html> 28619 ``` 28620 28621 <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! --> 28622 <example name="example.csp" module="cspExample" ng-csp="true"> 28623 <file name="index.html"> 28624 <div ng-controller="MainController as ctrl"> 28625 <div> 28626 <button ng-click="ctrl.inc()" id="inc">Increment</button> 28627 <span id="counter"> 28628 {{ctrl.counter}} 28629 </span> 28630 </div> 28631 28632 <div> 28633 <button ng-click="ctrl.evil()" id="evil">Evil</button> 28634 <span id="evilError"> 28635 {{ctrl.evilError}} 28636 </span> 28637 </div> 28638 </div> 28639 </file> 28640 <file name="script.js"> 28641 angular.module('cspExample', []) 28642 .controller('MainController', function MainController() { 28643 this.counter = 0; 28644 this.inc = function() { 28645 this.counter++; 28646 }; 28647 this.evil = function() { 28648 try { 28649 eval('1+2'); // eslint-disable-line no-eval 28650 } catch (e) { 28651 this.evilError = e.message; 28652 } 28653 }; 28654 }); 28655 </file> 28656 <file name="protractor.js" type="protractor"> 28657 var util, webdriver; 28658 28659 var incBtn = element(by.id('inc')); 28660 var counter = element(by.id('counter')); 28661 var evilBtn = element(by.id('evil')); 28662 var evilError = element(by.id('evilError')); 28663 28664 function getAndClearSevereErrors() { 28665 return browser.manage().logs().get('browser').then(function(browserLog) { 28666 return browserLog.filter(function(logEntry) { 28667 return logEntry.level.value > webdriver.logging.Level.WARNING.value; 28668 }); 28669 }); 28670 } 28671 28672 function clearErrors() { 28673 getAndClearSevereErrors(); 28674 } 28675 28676 function expectNoErrors() { 28677 getAndClearSevereErrors().then(function(filteredLog) { 28678 expect(filteredLog.length).toEqual(0); 28679 if (filteredLog.length) { 28680 console.log('browser console errors: ' + util.inspect(filteredLog)); 28681 } 28682 }); 28683 } 28684 28685 function expectError(regex) { 28686 getAndClearSevereErrors().then(function(filteredLog) { 28687 var found = false; 28688 filteredLog.forEach(function(log) { 28689 if (log.message.match(regex)) { 28690 found = true; 28691 } 28692 }); 28693 if (!found) { 28694 throw new Error('expected an error that matches ' + regex); 28695 } 28696 }); 28697 } 28698 28699 beforeEach(function() { 28700 util = require('util'); 28701 webdriver = require('selenium-webdriver'); 28702 }); 28703 28704 // For now, we only test on Chrome, 28705 // as Safari does not load the page with Protractor's injected scripts, 28706 // and Firefox webdriver always disables content security policy (#6358) 28707 if (browser.params.browser !== 'chrome') { 28708 return; 28709 } 28710 28711 it('should not report errors when the page is loaded', function() { 28712 // clear errors so we are not dependent on previous tests 28713 clearErrors(); 28714 // Need to reload the page as the page is already loaded when 28715 // we come here 28716 browser.driver.getCurrentUrl().then(function(url) { 28717 browser.get(url); 28718 }); 28719 expectNoErrors(); 28720 }); 28721 28722 it('should evaluate expressions', function() { 28723 expect(counter.getText()).toEqual('0'); 28724 incBtn.click(); 28725 expect(counter.getText()).toEqual('1'); 28726 expectNoErrors(); 28727 }); 28728 28729 it('should throw and report an error when using "eval"', function() { 28730 evilBtn.click(); 28731 expect(evilError.getText()).toMatch(/Content Security Policy/); 28732 expectError(/Content Security Policy/); 28733 }); 28734 </file> 28735 </example> 28736 */ 28737 28738// `ngCsp` is not implemented as a proper directive any more, because we need it be processed while 28739// we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()` 28740// fn that looks for the `ng-csp` attribute anywhere in the current doc. 28741 28742/** 28743 * @ngdoc directive 28744 * @name ngClick 28745 * @restrict A 28746 * @element ANY 28747 * @priority 0 28748 * 28749 * @description 28750 * The ngClick directive allows you to specify custom behavior when 28751 * an element is clicked. 28752 * 28753 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon 28754 * click. ({@link guide/expression#-event- Event object is available as `$event`}) 28755 * 28756 * @example 28757 <example name="ng-click"> 28758 <file name="index.html"> 28759 <button ng-click="count = count + 1" ng-init="count=0"> 28760 Increment 28761 </button> 28762 <span> 28763 count: {{count}} 28764 </span> 28765 </file> 28766 <file name="protractor.js" type="protractor"> 28767 it('should check ng-click', function() { 28768 expect(element(by.binding('count')).getText()).toMatch('0'); 28769 element(by.css('button')).click(); 28770 expect(element(by.binding('count')).getText()).toMatch('1'); 28771 }); 28772 </file> 28773 </example> 28774 */ 28775/* 28776 * A collection of directives that allows creation of custom event handlers that are defined as 28777 * AngularJS expressions and are compiled and executed within the current scope. 28778 */ 28779var ngEventDirectives = {}; 28780 28781// For events that might fire synchronously during DOM manipulation 28782// we need to execute their event handlers asynchronously using $evalAsync, 28783// so that they are not executed in an inconsistent state. 28784var forceAsyncEvents = { 28785 'blur': true, 28786 'focus': true 28787}; 28788forEach( 28789 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), 28790 function(eventName) { 28791 var directiveName = directiveNormalize('ng-' + eventName); 28792 ngEventDirectives[directiveName] = ['$parse', '$rootScope', '$exceptionHandler', function($parse, $rootScope, $exceptionHandler) { 28793 return createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsyncEvents[eventName]); 28794 }]; 28795 } 28796); 28797 28798function createEventDirective($parse, $rootScope, $exceptionHandler, directiveName, eventName, forceAsync) { 28799 return { 28800 restrict: 'A', 28801 compile: function($element, attr) { 28802 // NOTE: 28803 // We expose the powerful `$event` object on the scope that provides access to the Window, 28804 // etc. This is OK, because expressions are not sandboxed any more (and the expression 28805 // sandbox was never meant to be a security feature anyway). 28806 var fn = $parse(attr[directiveName]); 28807 return function ngEventHandler(scope, element) { 28808 element.on(eventName, function(event) { 28809 var callback = function() { 28810 fn(scope, {$event: event}); 28811 }; 28812 28813 if (!$rootScope.$$phase) { 28814 scope.$apply(callback); 28815 } else if (forceAsync) { 28816 scope.$evalAsync(callback); 28817 } else { 28818 try { 28819 callback(); 28820 } catch (error) { 28821 $exceptionHandler(error); 28822 } 28823 } 28824 }); 28825 }; 28826 } 28827 }; 28828} 28829 28830/** 28831 * @ngdoc directive 28832 * @name ngDblclick 28833 * @restrict A 28834 * @element ANY 28835 * @priority 0 28836 * 28837 * @description 28838 * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. 28839 * 28840 * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon 28841 * a dblclick. (The Event object is available as `$event`) 28842 * 28843 * @example 28844 <example name="ng-dblclick"> 28845 <file name="index.html"> 28846 <button ng-dblclick="count = count + 1" ng-init="count=0"> 28847 Increment (on double click) 28848 </button> 28849 count: {{count}} 28850 </file> 28851 </example> 28852 */ 28853 28854 28855/** 28856 * @ngdoc directive 28857 * @name ngMousedown 28858 * @restrict A 28859 * @element ANY 28860 * @priority 0 28861 * 28862 * @description 28863 * The ngMousedown directive allows you to specify custom behavior on mousedown event. 28864 * 28865 * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon 28866 * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) 28867 * 28868 * @example 28869 <example name="ng-mousedown"> 28870 <file name="index.html"> 28871 <button ng-mousedown="count = count + 1" ng-init="count=0"> 28872 Increment (on mouse down) 28873 </button> 28874 count: {{count}} 28875 </file> 28876 </example> 28877 */ 28878 28879 28880/** 28881 * @ngdoc directive 28882 * @name ngMouseup 28883 * @restrict A 28884 * @element ANY 28885 * @priority 0 28886 * 28887 * @description 28888 * Specify custom behavior on mouseup event. 28889 * 28890 * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon 28891 * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) 28892 * 28893 * @example 28894 <example name="ng-mouseup"> 28895 <file name="index.html"> 28896 <button ng-mouseup="count = count + 1" ng-init="count=0"> 28897 Increment (on mouse up) 28898 </button> 28899 count: {{count}} 28900 </file> 28901 </example> 28902 */ 28903 28904/** 28905 * @ngdoc directive 28906 * @name ngMouseover 28907 * @restrict A 28908 * @element ANY 28909 * @priority 0 28910 * 28911 * @description 28912 * Specify custom behavior on mouseover event. 28913 * 28914 * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon 28915 * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) 28916 * 28917 * @example 28918 <example name="ng-mouseover"> 28919 <file name="index.html"> 28920 <button ng-mouseover="count = count + 1" ng-init="count=0"> 28921 Increment (when mouse is over) 28922 </button> 28923 count: {{count}} 28924 </file> 28925 </example> 28926 */ 28927 28928 28929/** 28930 * @ngdoc directive 28931 * @name ngMouseenter 28932 * @restrict A 28933 * @element ANY 28934 * @priority 0 28935 * 28936 * @description 28937 * Specify custom behavior on mouseenter event. 28938 * 28939 * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon 28940 * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) 28941 * 28942 * @example 28943 <example name="ng-mouseenter"> 28944 <file name="index.html"> 28945 <button ng-mouseenter="count = count + 1" ng-init="count=0"> 28946 Increment (when mouse enters) 28947 </button> 28948 count: {{count}} 28949 </file> 28950 </example> 28951 */ 28952 28953 28954/** 28955 * @ngdoc directive 28956 * @name ngMouseleave 28957 * @restrict A 28958 * @element ANY 28959 * @priority 0 28960 * 28961 * @description 28962 * Specify custom behavior on mouseleave event. 28963 * 28964 * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon 28965 * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) 28966 * 28967 * @example 28968 <example name="ng-mouseleave"> 28969 <file name="index.html"> 28970 <button ng-mouseleave="count = count + 1" ng-init="count=0"> 28971 Increment (when mouse leaves) 28972 </button> 28973 count: {{count}} 28974 </file> 28975 </example> 28976 */ 28977 28978 28979/** 28980 * @ngdoc directive 28981 * @name ngMousemove 28982 * @restrict A 28983 * @element ANY 28984 * @priority 0 28985 * 28986 * @description 28987 * Specify custom behavior on mousemove event. 28988 * 28989 * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon 28990 * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) 28991 * 28992 * @example 28993 <example name="ng-mousemove"> 28994 <file name="index.html"> 28995 <button ng-mousemove="count = count + 1" ng-init="count=0"> 28996 Increment (when mouse moves) 28997 </button> 28998 count: {{count}} 28999 </file> 29000 </example> 29001 */ 29002 29003 29004/** 29005 * @ngdoc directive 29006 * @name ngKeydown 29007 * @restrict A 29008 * @element ANY 29009 * @priority 0 29010 * 29011 * @description 29012 * Specify custom behavior on keydown event. 29013 * 29014 * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon 29015 * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) 29016 * 29017 * @example 29018 <example name="ng-keydown"> 29019 <file name="index.html"> 29020 <input ng-keydown="count = count + 1" ng-init="count=0"> 29021 key down count: {{count}} 29022 </file> 29023 </example> 29024 */ 29025 29026 29027/** 29028 * @ngdoc directive 29029 * @name ngKeyup 29030 * @restrict A 29031 * @element ANY 29032 * @priority 0 29033 * 29034 * @description 29035 * Specify custom behavior on keyup event. 29036 * 29037 * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon 29038 * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) 29039 * 29040 * @example 29041 <example name="ng-keyup"> 29042 <file name="index.html"> 29043 <p>Typing in the input box below updates the key count</p> 29044 <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}} 29045 29046 <p>Typing in the input box below updates the keycode</p> 29047 <input ng-keyup="event=$event"> 29048 <p>event keyCode: {{ event.keyCode }}</p> 29049 <p>event altKey: {{ event.altKey }}</p> 29050 </file> 29051 </example> 29052 */ 29053 29054 29055/** 29056 * @ngdoc directive 29057 * @name ngKeypress 29058 * @restrict A 29059 * @element ANY 29060 * 29061 * @description 29062 * Specify custom behavior on keypress event. 29063 * 29064 * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon 29065 * keypress. ({@link guide/expression#-event- Event object is available as `$event`} 29066 * and can be interrogated for keyCode, altKey, etc.) 29067 * 29068 * @example 29069 <example name="ng-keypress"> 29070 <file name="index.html"> 29071 <input ng-keypress="count = count + 1" ng-init="count=0"> 29072 key press count: {{count}} 29073 </file> 29074 </example> 29075 */ 29076 29077 29078/** 29079 * @ngdoc directive 29080 * @name ngSubmit 29081 * @restrict A 29082 * @element form 29083 * @priority 0 29084 * 29085 * @description 29086 * Enables binding AngularJS expressions to onsubmit events. 29087 * 29088 * Additionally it prevents the default action (which for form means sending the request to the 29089 * server and reloading the current page), but only if the form does not contain `action`, 29090 * `data-action`, or `x-action` attributes. 29091 * 29092 * <div class="alert alert-warning"> 29093 * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and 29094 * `ngSubmit` handlers together. See the 29095 * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} 29096 * for a detailed discussion of when `ngSubmit` may be triggered. 29097 * </div> 29098 * 29099 * @param {expression} ngSubmit {@link guide/expression Expression} to eval. 29100 * ({@link guide/expression#-event- Event object is available as `$event`}) 29101 * 29102 * @example 29103 <example module="submitExample" name="ng-submit"> 29104 <file name="index.html"> 29105 <script> 29106 angular.module('submitExample', []) 29107 .controller('ExampleController', ['$scope', function($scope) { 29108 $scope.list = []; 29109 $scope.text = 'hello'; 29110 $scope.submit = function() { 29111 if ($scope.text) { 29112 $scope.list.push(this.text); 29113 $scope.text = ''; 29114 } 29115 }; 29116 }]); 29117 </script> 29118 <form ng-submit="submit()" ng-controller="ExampleController"> 29119 Enter text and hit enter: 29120 <input type="text" ng-model="text" name="text" /> 29121 <input type="submit" id="submit" value="Submit" /> 29122 <pre>list={{list}}</pre> 29123 </form> 29124 </file> 29125 <file name="protractor.js" type="protractor"> 29126 it('should check ng-submit', function() { 29127 expect(element(by.binding('list')).getText()).toBe('list=[]'); 29128 element(by.css('#submit')).click(); 29129 expect(element(by.binding('list')).getText()).toContain('hello'); 29130 expect(element(by.model('text')).getAttribute('value')).toBe(''); 29131 }); 29132 it('should ignore empty strings', function() { 29133 expect(element(by.binding('list')).getText()).toBe('list=[]'); 29134 element(by.css('#submit')).click(); 29135 element(by.css('#submit')).click(); 29136 expect(element(by.binding('list')).getText()).toContain('hello'); 29137 }); 29138 </file> 29139 </example> 29140 */ 29141 29142/** 29143 * @ngdoc directive 29144 * @name ngFocus 29145 * @restrict A 29146 * @element window, input, select, textarea, a 29147 * @priority 0 29148 * 29149 * @description 29150 * Specify custom behavior on focus event. 29151 * 29152 * Note: As the `focus` event is executed synchronously when calling `input.focus()` 29153 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired 29154 * during an `$apply` to ensure a consistent state. 29155 * 29156 * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon 29157 * focus. ({@link guide/expression#-event- Event object is available as `$event`}) 29158 * 29159 * @example 29160 * See {@link ng.directive:ngClick ngClick} 29161 */ 29162 29163/** 29164 * @ngdoc directive 29165 * @name ngBlur 29166 * @restrict A 29167 * @element window, input, select, textarea, a 29168 * @priority 0 29169 * 29170 * @description 29171 * Specify custom behavior on blur event. 29172 * 29173 * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when 29174 * an element has lost focus. 29175 * 29176 * Note: As the `blur` event is executed synchronously also during DOM manipulations 29177 * (e.g. removing a focussed input), 29178 * AngularJS executes the expression using `scope.$evalAsync` if the event is fired 29179 * during an `$apply` to ensure a consistent state. 29180 * 29181 * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon 29182 * blur. ({@link guide/expression#-event- Event object is available as `$event`}) 29183 * 29184 * @example 29185 * See {@link ng.directive:ngClick ngClick} 29186 */ 29187 29188/** 29189 * @ngdoc directive 29190 * @name ngCopy 29191 * @restrict A 29192 * @element window, input, select, textarea, a 29193 * @priority 0 29194 * 29195 * @description 29196 * Specify custom behavior on copy event. 29197 * 29198 * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon 29199 * copy. ({@link guide/expression#-event- Event object is available as `$event`}) 29200 * 29201 * @example 29202 <example name="ng-copy"> 29203 <file name="index.html"> 29204 <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value"> 29205 copied: {{copied}} 29206 </file> 29207 </example> 29208 */ 29209 29210/** 29211 * @ngdoc directive 29212 * @name ngCut 29213 * @restrict A 29214 * @element window, input, select, textarea, a 29215 * @priority 0 29216 * 29217 * @description 29218 * Specify custom behavior on cut event. 29219 * 29220 * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon 29221 * cut. ({@link guide/expression#-event- Event object is available as `$event`}) 29222 * 29223 * @example 29224 <example name="ng-cut"> 29225 <file name="index.html"> 29226 <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value"> 29227 cut: {{cut}} 29228 </file> 29229 </example> 29230 */ 29231 29232/** 29233 * @ngdoc directive 29234 * @name ngPaste 29235 * @restrict A 29236 * @element window, input, select, textarea, a 29237 * @priority 0 29238 * 29239 * @description 29240 * Specify custom behavior on paste event. 29241 * 29242 * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon 29243 * paste. ({@link guide/expression#-event- Event object is available as `$event`}) 29244 * 29245 * @example 29246 <example name="ng-paste"> 29247 <file name="index.html"> 29248 <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'> 29249 pasted: {{paste}} 29250 </file> 29251 </example> 29252 */ 29253 29254/** 29255 * @ngdoc directive 29256 * @name ngIf 29257 * @restrict A 29258 * @multiElement 29259 * 29260 * @description 29261 * The `ngIf` directive removes or recreates a portion of the DOM tree based on an 29262 * {expression}. If the expression assigned to `ngIf` evaluates to a false 29263 * value then the element is removed from the DOM, otherwise a clone of the 29264 * element is reinserted into the DOM. 29265 * 29266 * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the 29267 * element in the DOM rather than changing its visibility via the `display` css property. A common 29268 * case when this difference is significant is when using css selectors that rely on an element's 29269 * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. 29270 * 29271 * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope 29272 * is created when the element is restored. The scope created within `ngIf` inherits from 29273 * its parent scope using 29274 * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). 29275 * An important implication of this is if `ngModel` is used within `ngIf` to bind to 29276 * a javascript primitive defined in the parent scope. In this case any modifications made to the 29277 * variable within the child scope will override (hide) the value in the parent scope. 29278 * 29279 * Also, `ngIf` recreates elements using their compiled state. An example of this behavior 29280 * is if an element's class attribute is directly modified after it's compiled, using something like 29281 * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element 29282 * the added class will be lost because the original compiled state is used to regenerate the element. 29283 * 29284 * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` 29285 * and `leave` effects. 29286 * 29287 * @animations 29288 * | Animation | Occurs | 29289 * |----------------------------------|-------------------------------------| 29290 * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container | 29291 * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM | 29292 * 29293 * @element ANY 29294 * @scope 29295 * @priority 600 29296 * @param {expression} ngIf If the {@link guide/expression expression} is falsy then 29297 * the element is removed from the DOM tree. If it is truthy a copy of the compiled 29298 * element is added to the DOM tree. 29299 * 29300 * @example 29301 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if"> 29302 <file name="index.html"> 29303 <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/> 29304 Show when checked: 29305 <span ng-if="checked" class="animate-if"> 29306 This is removed when the checkbox is unchecked. 29307 </span> 29308 </file> 29309 <file name="animations.css"> 29310 .animate-if { 29311 background:white; 29312 border:1px solid black; 29313 padding:10px; 29314 } 29315 29316 .animate-if.ng-enter, .animate-if.ng-leave { 29317 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; 29318 } 29319 29320 .animate-if.ng-enter, 29321 .animate-if.ng-leave.ng-leave-active { 29322 opacity:0; 29323 } 29324 29325 .animate-if.ng-leave, 29326 .animate-if.ng-enter.ng-enter-active { 29327 opacity:1; 29328 } 29329 </file> 29330 </example> 29331 */ 29332var ngIfDirective = ['$animate', '$compile', function($animate, $compile) { 29333 return { 29334 multiElement: true, 29335 transclude: 'element', 29336 priority: 600, 29337 terminal: true, 29338 restrict: 'A', 29339 $$tlb: true, 29340 link: function($scope, $element, $attr, ctrl, $transclude) { 29341 var block, childScope, previousElements; 29342 $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { 29343 29344 if (value) { 29345 if (!childScope) { 29346 $transclude(function(clone, newScope) { 29347 childScope = newScope; 29348 clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf); 29349 // Note: We only need the first/last node of the cloned nodes. 29350 // However, we need to keep the reference to the jqlite wrapper as it might be changed later 29351 // by a directive with templateUrl when its template arrives. 29352 block = { 29353 clone: clone 29354 }; 29355 $animate.enter(clone, $element.parent(), $element); 29356 }); 29357 } 29358 } else { 29359 if (previousElements) { 29360 previousElements.remove(); 29361 previousElements = null; 29362 } 29363 if (childScope) { 29364 childScope.$destroy(); 29365 childScope = null; 29366 } 29367 if (block) { 29368 previousElements = getBlockNodes(block.clone); 29369 $animate.leave(previousElements).done(function(response) { 29370 if (response !== false) previousElements = null; 29371 }); 29372 block = null; 29373 } 29374 } 29375 }); 29376 } 29377 }; 29378}]; 29379 29380/** 29381 * @ngdoc directive 29382 * @name ngInclude 29383 * @restrict ECA 29384 * @scope 29385 * @priority -400 29386 * 29387 * @description 29388 * Fetches, compiles and includes an external HTML fragment. 29389 * 29390 * By default, the template URL is restricted to the same domain and protocol as the 29391 * application document. This is done by calling {@link $sce#getTrustedResourceUrl 29392 * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols 29393 * you may either
29393{@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or 29394 * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to AngularJS's {@link 29395 *
vendor: 163,852 bytes, lines 29395-33464
29395 ng.$sce Strict Contextual Escaping}. 29396 * 29397 * In addition, the browser's 29398 * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) 29399 * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) 29400 * policy may further restrict whether the template is successfully loaded. 29401 * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` 29402 * access on some browsers. 29403 * 29404 * @animations 29405 * | Animation | Occurs | 29406 * |----------------------------------|-------------------------------------| 29407 * | {@link ng.$animate#enter enter} | when the expression changes, on the new include | 29408 * | {@link ng.$animate#leave leave} | when the expression changes, on the old include | 29409 * 29410 * The enter and leave animation occur concurrently. 29411 * 29412 * @param {string} ngInclude|src AngularJS expression evaluating to URL. If the source is a string constant, 29413 * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. 29414 * @param {string=} onload Expression to evaluate when a new partial is loaded. 29415 * <div class="alert alert-warning"> 29416 * **Note:** When using onload on SVG elements in IE11, the browser will try to call 29417 * a function with the name on the window element, which will usually throw a 29418 * "function is undefined" error. To fix this, you can instead use `data-onload` or a 29419 * different form that {@link guide/directive#normalization matches} `onload`. 29420 * </div> 29421 * 29422 * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll 29423 * $anchorScroll} to scroll the viewport after the content is loaded. 29424 * 29425 * - If the attribute is not set, disable scrolling. 29426 * - If the attribute is set without value, enable scrolling. 29427 * - Otherwise enable scrolling only if the expression evaluates to truthy value. 29428 * 29429 * @example 29430 <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include"> 29431 <file name="index.html"> 29432 <div ng-controller="ExampleController"> 29433 <select ng-model="template" ng-options="t.name for t in templates"> 29434 <option value="">(blank)</option> 29435 </select> 29436 url of the template: <code>{{template.url}}</code> 29437 <hr/> 29438 <div class="slide-animate-container"> 29439 <div class="slide-animate" ng-include="template.url"></div> 29440 </div> 29441 </div> 29442 </file> 29443 <file name="script.js"> 29444 angular.module('includeExample', ['ngAnimate']) 29445 .controller('ExampleController', ['$scope', function($scope) { 29446 $scope.templates = 29447 [{ name: 'template1.html', url: 'template1.html'}, 29448 { name: 'template2.html', url: 'template2.html'}]; 29449 $scope.template = $scope.templates[0]; 29450 }]); 29451 </file> 29452 <file name="template1.html"> 29453 Content of template1.html 29454 </file> 29455 <file name="template2.html"> 29456 Content of template2.html 29457 </file> 29458 <file name="animations.css"> 29459 .slide-animate-container { 29460 position:relative; 29461 background:white; 29462 border:1px solid black; 29463 height:40px; 29464 overflow:hidden; 29465 } 29466 29467 .slide-animate { 29468 padding:10px; 29469 } 29470 29471 .slide-animate.ng-enter, .slide-animate.ng-leave { 29472 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; 29473 29474 position:absolute; 29475 top:0; 29476 left:0; 29477 right:0; 29478 bottom:0; 29479 display:block; 29480 padding:10px; 29481 } 29482 29483 .slide-animate.ng-enter { 29484 top:-50px; 29485 } 29486 .slide-animate.ng-enter.ng-enter-active { 29487 top:0; 29488 } 29489 29490 .slide-animate.ng-leave { 29491 top:0; 29492 } 29493 .slide-animate.ng-leave.ng-leave-active { 29494 top:50px; 29495 } 29496 </file> 29497 <file name="protractor.js" type="protractor"> 29498 var templateSelect = element(by.model('template')); 29499 var includeElem = element(by.css('[ng-include]')); 29500 29501 it('should load template1.html', function() { 29502 expect(includeElem.getText()).toMatch(/Content of template1.html/); 29503 }); 29504 29505 it('should load template2.html', function() { 29506 if (browser.params.browser === 'firefox') { 29507 // Firefox can't handle using selects 29508 // See https://github.com/angular/protractor/issues/480 29509 return; 29510 } 29511 templateSelect.click(); 29512 templateSelect.all(by.css('option')).get(2).click(); 29513 expect(includeElem.getText()).toMatch(/Content of template2.html/); 29514 }); 29515 29516 it('should change to blank', function() { 29517 if (browser.params.browser === 'firefox') { 29518 // Firefox can't handle using selects 29519 return; 29520 } 29521 templateSelect.click(); 29522 templateSelect.all(by.css('option')).get(0).click(); 29523 expect(includeElem.isPresent()).toBe(false); 29524 }); 29525 </file> 29526 </example> 29527 */ 29528 29529 29530/** 29531 * @ngdoc event 29532 * @name ngInclude#$includeContentRequested 29533 * @eventType emit on the scope ngInclude was declared in 29534 * @description 29535 * Emitted every time the ngInclude content is requested. 29536 * 29537 * @param {Object} angularEvent Synthetic event object. 29538 * @param {String} src URL of content to load. 29539 */ 29540 29541 29542/** 29543 * @ngdoc event 29544 * @name ngInclude#$includeContentLoaded 29545 * @eventType emit on the current ngInclude scope 29546 * @description 29547 * Emitted every time the ngInclude content is reloaded. 29548 * 29549 * @param {Object} angularEvent Synthetic event object. 29550 * @param {String} src URL of content to load. 29551 */ 29552 29553 29554/** 29555 * @ngdoc event 29556 * @name ngInclude#$includeContentError 29557 * @eventType emit on the scope ngInclude was declared in 29558 * @description 29559 * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299) 29560 * 29561 * @param {Object} angularEvent Synthetic event object. 29562 * @param {String} src URL of content to load. 29563 */ 29564var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', 29565 function($templateRequest, $anchorScroll, $animate) { 29566 return { 29567 restrict: 'ECA', 29568 priority: 400, 29569 terminal: true, 29570 transclude: 'element', 29571 controller: angular.noop, 29572 compile: function(element, attr) { 29573 var srcExp = attr.ngInclude || attr.src, 29574 onloadExp = attr.onload || '', 29575 autoScrollExp = attr.autoscroll; 29576 29577 return function(scope, $element, $attr, ctrl, $transclude) { 29578 var changeCounter = 0, 29579 currentScope, 29580 previousElement, 29581 currentElement; 29582 29583 var cleanupLastIncludeContent = function() { 29584 if (previousElement) { 29585 previousElement.remove(); 29586 previousElement = null; 29587 } 29588 if (currentScope) { 29589 currentScope.$destroy(); 29590 currentScope = null; 29591 } 29592 if (currentElement) { 29593 $animate.leave(currentElement).done(function(response) { 29594 if (response !== false) previousElement = null; 29595 }); 29596 previousElement = currentElement; 29597 currentElement = null; 29598 } 29599 }; 29600 29601 scope.$watch(srcExp, function ngIncludeWatchAction(src) { 29602 var afterAnimation = function(response) { 29603 if (response !== false && isDefined(autoScrollExp) && 29604 (!autoScrollExp || scope.$eval(autoScrollExp))) { 29605 $anchorScroll(); 29606 } 29607 }; 29608 var thisChangeId = ++changeCounter; 29609 29610 if (src) { 29611 //set the 2nd param to true to ignore the template request error so that the inner 29612 //contents and scope can be cleaned up. 29613 $templateRequest(src, true).then(function(response) { 29614 if (scope.$$destroyed) return; 29615 29616 if (thisChangeId !== changeCounter) return; 29617 var newScope = scope.$new(); 29618 ctrl.template = response; 29619 29620 // Note: This will also link all children of ng-include that were contained in the original 29621 // html. If that content contains controllers, ... they could pollute/change the scope. 29622 // However, using ng-include on an element with additional content does not make sense... 29623 // Note: We can't remove them in the cloneAttchFn of $transclude as that 29624 // function is called before linking the content, which would apply child 29625 // directives to non existing elements. 29626 var clone = $transclude(newScope, function(clone) { 29627 cleanupLastIncludeContent(); 29628 $animate.enter(clone, null, $element).done(afterAnimation); 29629 }); 29630 29631 currentScope = newScope; 29632 currentElement = clone; 29633 29634 currentScope.$emit('$includeContentLoaded', src); 29635 scope.$eval(onloadExp); 29636 }, function() { 29637 if (scope.$$destroyed) return; 29638 29639 if (thisChangeId === changeCounter) { 29640 cleanupLastIncludeContent(); 29641 scope.$emit('$includeContentError', src); 29642 } 29643 }); 29644 scope.$emit('$includeContentRequested', src); 29645 } else { 29646 cleanupLastIncludeContent(); 29647 ctrl.template = null; 29648 } 29649 }); 29650 }; 29651 } 29652 }; 29653}]; 29654 29655// This directive is called during the $transclude call of the first `ngInclude` directive. 29656// It will replace and compile the content of the element with the loaded template. 29657// We need this directive so that the element content is already filled when 29658// the link function of another directive on the same element as ngInclude 29659// is called. 29660var ngIncludeFillContentDirective = ['$compile', 29661 function($compile) { 29662 return { 29663 restrict: 'ECA', 29664 priority: -400, 29665 require: 'ngInclude', 29666 link: function(scope, $element, $attr, ctrl) { 29667 if (toString.call($element[0]).match(/SVG/)) { 29668 // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not 29669 // support innerHTML, so detect this here and try to generate the contents 29670 // specially. 29671 $element.empty(); 29672 $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope, 29673 function namespaceAdaptedClone(clone) { 29674 $element.append(clone); 29675 }, {futureParentElement: $element}); 29676 return; 29677 } 29678 29679 $element.html(ctrl.template); 29680 $compile($element.contents())(scope); 29681 } 29682 }; 29683 }]; 29684 29685/** 29686 * @ngdoc directive 29687 * @name ngInit 29688 * @restrict AC 29689 * @priority 450 29690 * @element ANY 29691 * 29692 * @param {expression} ngInit {@link guide/expression Expression} to eval. 29693 * 29694 * @description 29695 * The `ngInit` directive allows you to evaluate an expression in the 29696 * current scope. 29697 * 29698 * <div class="alert alert-danger"> 29699 * This directive can be abused to add unnecessary amounts of logic into your templates. 29700 * There are only a few appropriate uses of `ngInit`: 29701 * <ul> 29702 * <li>aliasing special properties of {@link ng.directive:ngRepeat `ngRepeat`}, 29703 * as seen in the demo below.</li> 29704 * <li>initializing data during development, or for examples, as seen throughout these docs.</li> 29705 * <li>injecting data via server side scripting.</li> 29706 * </ul> 29707 * 29708 * Besides these few cases, you should use {@link guide/component Components} or 29709 * {@link guide/controller Controllers} rather than `ngInit` to initialize values on a scope. 29710 * </div> 29711 * 29712 * <div class="alert alert-warning"> 29713 * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make 29714 * sure you have parentheses to ensure correct operator precedence: 29715 * <pre class="prettyprint"> 29716 * `<div ng-init="test1 = ($index | toString)"></div>` 29717 * </pre> 29718 * </div> 29719 * 29720 * @example 29721 <example module="initExample" name="ng-init"> 29722 <file name="index.html"> 29723 <script> 29724 angular.module('initExample', []) 29725 .controller('ExampleController', ['$scope', function($scope) { 29726 $scope.list = [['a', 'b'], ['c', 'd']]; 29727 }]); 29728 </script> 29729 <div ng-controller="ExampleController"> 29730 <div ng-repeat="innerList in list" ng-init="outerIndex = $index"> 29731 <div ng-repeat="value in innerList" ng-init="innerIndex = $index"> 29732 <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span> 29733 </div> 29734 </div> 29735 </div> 29736 </file> 29737 <file name="protractor.js" type="protractor"> 29738 it('should alias index positions', function() { 29739 var elements = element.all(by.css('.example-init')); 29740 expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); 29741 expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); 29742 expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); 29743 expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); 29744 }); 29745 </file> 29746 </example> 29747 */ 29748var ngInitDirective = ngDirective({ 29749 priority: 450, 29750 compile: function() { 29751 return { 29752 pre: function(scope, element, attrs) { 29753 scope.$eval(attrs.ngInit); 29754 } 29755 }; 29756 } 29757}); 29758 29759/** 29760 * @ngdoc directive 29761 * @name ngList 29762 * @restrict A 29763 * @priority 100 29764 * 29765 * @param {string=} ngList optional delimiter that should be used to split the value. 29766 * 29767 * @description 29768 * Text input that converts between a delimited string and an array of strings. The default 29769 * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom 29770 * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`. 29771 * 29772 * The behaviour of the directive is affected by the use of the `ngTrim` attribute. 29773 * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each 29774 * list item is respected. This implies that the user of the directive is responsible for 29775 * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a 29776 * tab or newline character. 29777 * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected 29778 * when joining the list items back together) and whitespace around each list item is stripped 29779 * before it is added to the model. 29780 * 29781 * @example 29782 * ### Validation 29783 * 29784 * <example name="ngList-directive" module="listExample"> 29785 * <file name="app.js"> 29786 * angular.module('listExample', []) 29787 * .controller('ExampleController', ['$scope', function($scope) { 29788 * $scope.names = ['morpheus', 'neo', 'trinity']; 29789 * }]); 29790 * </file> 29791 * <file name="index.html"> 29792 * <form name="myForm" ng-controller="ExampleController"> 29793 * <label>List: <input name="namesInput" ng-model="names" ng-list required></label> 29794 * <span role="alert"> 29795 * <span class="error" ng-show="myForm.namesInput.$error.required"> 29796 * Required!</span> 29797 * </span> 29798 * <br> 29799 * <tt>names = {{names}}</tt><br/> 29800 * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> 29801 * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> 29802 * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> 29803 * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> 29804 * </form> 29805 * </file> 29806 * <file name="protractor.js" type="protractor"> 29807 * var listInput = element(by.model('names')); 29808 * var names = element(by.exactBinding('names')); 29809 * var valid = element(by.binding('myForm.namesInput.$valid')); 29810 * var error = element(by.css('span.error')); 29811 * 29812 * it('should initialize to model', function() { 29813 * expect(names.getText()).toContain('["morpheus","neo","trinity"]'); 29814 * expect(valid.getText()).toContain('true'); 29815 * expect(error.getCssValue('display')).toBe('none'); 29816 * }); 29817 * 29818 * it('should be invalid if empty', function() { 29819 * listInput.clear(); 29820 * listInput.sendKeys(''); 29821 * 29822 * expect(names.getText()).toContain(''); 29823 * expect(valid.getText()).toContain('false'); 29824 * expect(error.getCssValue('display')).not.toBe('none'); 29825 * }); 29826 * </file> 29827 * </example> 29828 * 29829 * @example 29830 * ### Splitting on newline 29831 * 29832 * <example name="ngList-directive-newlines"> 29833 * <file name="index.html"> 29834 * <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea> 29835 * <pre>{{ list | json }}</pre> 29836 * </file> 29837 * <file name="protractor.js" type="protractor"> 29838 * it("should split the text by newlines", function() { 29839 * var listInput = element(by.model('list')); 29840 * var output = element(by.binding('list | json')); 29841 * listInput.sendKeys('abc\ndef\nghi'); 29842 * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]'); 29843 * }); 29844 * </file> 29845 * </example> 29846 * 29847 */ 29848var ngListDirective = function() { 29849 return { 29850 restrict: 'A', 29851 priority: 100, 29852 require: 'ngModel', 29853 link: function(scope, element, attr, ctrl) { 29854 var ngList = attr.ngList || ', '; 29855 var trimValues = attr.ngTrim !== 'false'; 29856 var separator = trimValues ? trim(ngList) : ngList; 29857 29858 var parse = function(viewValue) { 29859 // If the viewValue is invalid (say required but empty) it will be `undefined` 29860 if (isUndefined(viewValue)) return; 29861 29862 var list = []; 29863 29864 if (viewValue) { 29865 forEach(viewValue.split(separator), function(value) { 29866 if (value) list.push(trimValues ? trim(value) : value); 29867 }); 29868 } 29869 29870 return list; 29871 }; 29872 29873 ctrl.$parsers.push(parse); 29874 ctrl.$formatters.push(function(value) { 29875 if (isArray(value)) { 29876 return value.join(ngList); 29877 } 29878 29879 return undefined; 29880 }); 29881 29882 // Override the standard $isEmpty because an empty array means the input is empty. 29883 ctrl.$isEmpty = function(value) { 29884 return !value || !value.length; 29885 }; 29886 } 29887 }; 29888}; 29889 29890/* global VALID_CLASS: true, 29891 INVALID_CLASS: true, 29892 PRISTINE_CLASS: true, 29893 DIRTY_CLASS: true, 29894 UNTOUCHED_CLASS: true, 29895 TOUCHED_CLASS: true, 29896 PENDING_CLASS: true, 29897 addSetValidityMethod: true, 29898 setupValidity: true, 29899 defaultModelOptions: false 29900*/ 29901 29902 29903var VALID_CLASS = 'ng-valid', 29904 INVALID_CLASS = 'ng-invalid', 29905 PRISTINE_CLASS = 'ng-pristine', 29906 DIRTY_CLASS = 'ng-dirty', 29907 UNTOUCHED_CLASS = 'ng-untouched', 29908 TOUCHED_CLASS = 'ng-touched', 29909 EMPTY_CLASS = 'ng-empty', 29910 NOT_EMPTY_CLASS = 'ng-not-empty'; 29911 29912var ngModelMinErr = minErr('ngModel'); 29913 29914/** 29915 * @ngdoc type 29916 * @name ngModel.NgModelController 29917 * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a 29918 * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue 29919 * is set. 29920 * 29921 * @property {*} $modelValue The value in the model that the control is bound to. 29922 * 29923 * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever 29924 * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue 29925 `$viewValue`} from the DOM, usually via user input. 29926 See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation. 29927 Note that the `$parsers` are not called when the bound ngModel expression changes programmatically. 29928 29929 The functions are called in array order, each passing 29930 its return value through to the next. The last return value is forwarded to the 29931 {@link ngModel.NgModelController#$validators `$validators`} collection. 29932 29933 Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue 29934 `$viewValue`}. 29935 29936 Returning `undefined` from a parser means a parse error occurred. In that case, 29937 no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel` 29938 will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`} 29939 is set to `true`. The parse error is stored in `ngModel.$error.parse`. 29940 29941 This simple example shows a parser that would convert text input value to lowercase: 29942 * ```js 29943 * function parse(value) { 29944 * if (value) { 29945 * return value.toLowerCase(); 29946 * } 29947 * } 29948 * ngModelController.$parsers.push(parse); 29949 * ``` 29950 29951 * 29952 * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever 29953 the bound ngModel expression changes programmatically. The `$formatters` are not called when the 29954 value of the control is changed by user interaction. 29955 29956 Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue 29957 `$modelValue`} for display in the control. 29958 29959 The functions are called in reverse array order, each passing the value through to the 29960 next. The last return value is used as the actual DOM value. 29961 29962 This simple example shows a formatter that would convert the model value to uppercase: 29963 29964 * ```js 29965 * function format(value) { 29966 * if (value) { 29967 * return value.toUpperCase(); 29968 * } 29969 * } 29970 * ngModel.$formatters.push(format); 29971 * ``` 29972 * 29973 * @property {Object.<string, function>} $validators A collection of validators that are applied 29974 * whenever the model value changes. The key value within the object refers to the name of the 29975 * validator while the function refers to the validation operation. The validation operation is 29976 * provided with the model value as an argument and must return a true or false value depending 29977 * on the response of that validation. 29978 * 29979 * ```js 29980 * ngModel.$validators.validCharacters = function(modelValue, viewValue) { 29981 * var value = modelValue || viewValue; 29982 * return /[0-9]+/.test(value) && 29983 * /[a-z]+/.test(value) && 29984 * /[A-Z]+/.test(value) && 29985 * /\W+/.test(value); 29986 * }; 29987 * ``` 29988 * 29989 * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to 29990 * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided 29991 * is expected to return a promise when it is run during the model validation process. Once the promise 29992 * is delivered then the validation status will be set to true when fulfilled and false when rejected. 29993 * When the asynchronous validators are triggered, each of the validators will run in parallel and the model 29994 * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator 29995 * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators 29996 * will only run once all synchronous validators have passed. 29997 * 29998 * Please note that if $http is used then it is important that the server returns a success HTTP response code 29999 * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. 30000 * 30001 * ```js 30002 * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { 30003 * var value = modelValue || viewValue; 30004 * 30005 * // Lookup user by username 30006 * return $http.get('/api/users/' + value). 30007 * then(function resolved() { 30008 * //username exists, this means validation fails 30009 * return $q.reject('exists'); 30010 * }, function rejected() { 30011 * //username does not exist, therefore this validation passes 30012 * return true; 30013 * }); 30014 * }; 30015 * ``` 30016 * 30017 * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever 30018 * a change to {@link ngModel.NgModelController#$viewValue `$viewValue`} has caused a change 30019 * to {@link ngModel.NgModelController#$modelValue `$modelValue`}. 30020 * It is called with no arguments, and its return value is ignored. 30021 * This can be used in place of additional $watches against the model value. 30022 * 30023 * @property {Object} $error An object hash with all failing validator ids as keys. 30024 * @property {Object} $pending An object hash with all pending validator ids as keys. 30025 * 30026 * @property {boolean} $untouched True if control has not lost focus yet. 30027 * @property {boolean} $touched True if control has lost focus. 30028 * @property {boolean} $pristine True if user has not interacted with the control yet. 30029 * @property {boolean} $dirty True if user has already interacted with the control. 30030 * @property {boolean} $valid True if there is no error. 30031 * @property {boolean} $invalid True if at least one error on the control. 30032 * @property {string} $name The name attribute of the control. 30033 * 30034 * @description 30035 * 30036 * `NgModelController` provides API for the {@link ngModel `ngModel`} directive. 30037 * The controller contains services for data-binding, validation, CSS updates, and value formatting 30038 * and parsing. It purposefully does not contain any logic which deals with DOM rendering or 30039 * listening to DOM events. 30040 * Such DOM related logic should be provided by other directives which make use of 30041 * `NgModelController` for data-binding to control elements. 30042 * AngularJS provides this DOM logic for most {@link input `input`} elements. 30043 * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example 30044 * custom control example} that uses `ngModelController` to bind to `contenteditable` elements. 30045 * 30046 * @example 30047 * ### Custom Control Example 30048 * This example shows how to use `NgModelController` with a custom control to achieve 30049 * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) 30050 * collaborate together to achieve the desired result. 30051 * 30052 * `contenteditable` is an HTML5 attribute, which tells the browser to let the element 30053 * contents be edited in place by the user. 30054 * 30055 * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} 30056 * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`). 30057 * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks 30058 * that content using the `$sce` service. 30059 * 30060 * <example name="NgModelController" module="customControl" deps="angular-sanitize.js"> 30061 <file name="style.css"> 30062 [contenteditable] { 30063 border: 1px solid black; 30064 background-color: white; 30065 min-height: 20px; 30066 } 30067 30068 .ng-invalid { 30069 border: 1px solid red; 30070 } 30071 30072 </file> 30073 <file name="script.js"> 30074 angular.module('customControl', ['ngSanitize']). 30075 directive('contenteditable', ['$sce', function($sce) { 30076 return { 30077 restrict: 'A', // only activate on element attribute 30078 require: '?ngModel', // get a hold of NgModelController 30079 link: function(scope, element, attrs, ngModel) { 30080 if (!ngModel) return; // do nothing if no ng-model 30081 30082 // Specify how UI should be updated 30083 ngModel.$render = function() { 30084 element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); 30085 }; 30086 30087 // Listen for change events to enable binding 30088 element.on('blur keyup change', function() { 30089 scope.$evalAsync(read); 30090 }); 30091 read(); // initialize 30092 30093 // Write data to the model 30094 function read() { 30095 var html = element.html(); 30096 // When we clear the content editable the browser leaves a <br> behind 30097 // If strip-br attribute is provided then we strip this out 30098 if (attrs.stripBr && html === '<br>') { 30099 html = ''; 30100 } 30101 ngModel.$setViewValue(html); 30102 } 30103 } 30104 }; 30105 }]); 30106 </file> 30107 <file name="index.html"> 30108 <form name="myForm"> 30109 <div contenteditable 30110 name="myWidget" ng-model="userContent" 30111 strip-br="true" 30112 required>Change me!</div> 30113 <span ng-show="myForm.myWidget.$error.required">Required!</span> 30114 <hr> 30115 <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea> 30116 </form> 30117 </file> 30118 <file name="protractor.js" type="protractor"> 30119 it('should data-bind and become invalid', function() { 30120 if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') { 30121 // SafariDriver can't handle contenteditable 30122 // and Firefox driver can't clear contenteditables very well 30123 return; 30124 } 30125 var contentEditable = element(by.css('[contenteditable]')); 30126 var content = 'Change me!'; 30127 30128 expect(contentEditable.getText()).toEqual(content); 30129 30130 contentEditable.clear(); 30131 contentEditable.sendKeys(protractor.Key.BACK_SPACE); 30132 expect(contentEditable.getText()).toEqual(''); 30133 expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); 30134 }); 30135 </file> 30136 * </example> 30137 * 30138 * 30139 */ 30140NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate']; 30141function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) { 30142 this.$viewValue = Number.NaN; 30143 this.$modelValue = Number.NaN; 30144 this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity. 30145 this.$validators = {}; 30146 this.$asyncValidators = {}; 30147 this.$parsers = []; 30148 this.$formatters = []; 30149 this.$viewChangeListeners = []; 30150 this.$untouched = true; 30151 this.$touched = false; 30152 this.$pristine = true; 30153 this.$dirty = false; 30154 this.$valid = true; 30155 this.$invalid = false; 30156 this.$error = {}; // keep invalid keys here 30157 this.$$success = {}; // keep valid keys here 30158 this.$pending = undefined; // keep pending keys here 30159 this.$name = $interpolate($attr.name || '', false)($scope); 30160 this.$$parentForm = nullFormCtrl; 30161 this.$options = defaultModelOptions; 30162 this.$$updateEvents = ''; 30163 // Attach the correct context to the event handler function for updateOn 30164 this.$$updateEventHandler = this.$$updateEventHandler.bind(this); 30165 30166 this.$$parsedNgModel = $parse($attr.ngModel); 30167 this.$$parsedNgModelAssign = this.$$parsedNgModel.assign; 30168 this.$$ngModelGet = this.$$parsedNgModel; 30169 this.$$ngModelSet = this.$$parsedNgModelAssign; 30170 this.$$pendingDebounce = null; 30171 this.$$parserValid = undefined; 30172 this.$$parserName = 'parse'; 30173 30174 this.$$currentValidationRunId = 0; 30175 30176 this.$$scope = $scope; 30177 this.$$rootScope = $scope.$root; 30178 this.$$attr = $attr; 30179 this.$$element = $element; 30180 this.$$animate = $animate; 30181 this.$$timeout = $timeout; 30182 this.$$parse = $parse; 30183 this.$$q = $q; 30184 this.$$exceptionHandler = $exceptionHandler; 30185 30186 setupValidity(this); 30187 setupModelWatcher(this); 30188} 30189 30190NgModelController.prototype = { 30191 $$initGetterSetters: function() { 30192 if (this.$options.getOption('getterSetter')) { 30193 var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'), 30194 invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)'); 30195 30196 this.$$ngModelGet = function($scope) { 30197 var modelValue = this.$$parsedNgModel($scope); 30198 if (isFunction(modelValue)) { 30199 modelValue = invokeModelGetter($scope); 30200 } 30201 return modelValue; 30202 }; 30203 this.$$ngModelSet = function($scope, newValue) { 30204 if (isFunction(this.$$parsedNgModel($scope))) { 30205 invokeModelSetter($scope, {$$$p: newValue}); 30206 } else { 30207 this.$$parsedNgModelAssign($scope, newValue); 30208 } 30209 }; 30210 } else if (!this.$$parsedNgModel.assign) { 30211 throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}', 30212 this.$$attr.ngModel, startingTag(this.$$element)); 30213 } 30214 }, 30215 30216 30217 /** 30218 * @ngdoc method 30219 * @name ngModel.NgModelController#$render 30220 * 30221 * @description 30222 * Called when the view needs to be updated. It is expected that the user of the ng-model 30223 * directive will implement this method. 30224 * 30225 * The `$render()` method is invoked in the following situations: 30226 * 30227 * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last 30228 * committed value then `$render()` is called to update the input control. 30229 * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and 30230 * the `$viewValue` are different from last time. 30231 * 30232 * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of 30233 * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue` 30234 * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be 30235 * invoked if you only change a property on the objects. 30236 */ 30237 $render: noop, 30238 30239 /** 30240 * @ngdoc method 30241 * @name ngModel.NgModelController#$isEmpty 30242 * 30243 * @description 30244 * This is called when we need to determine if the value of an input is empty. 30245 * 30246 * For instance, the required directive does this to work out if the input has data or not. 30247 * 30248 * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. 30249 * 30250 * You can override this for input directives whose concept of being empty is different from the 30251 * default. The `checkboxInputType` directive does this because in its case a value of `false` 30252 * implies empty. 30253 * 30254 * @param {*} value The value of the input to check for emptiness. 30255 * @returns {boolean} True if `value` is "empty". 30256 */ 30257 $isEmpty: function(value) { 30258 // eslint-disable-next-line no-self-compare 30259 return isUndefined(value) || value === '' || value === null || value !== value; 30260 }, 30261 30262 $$updateEmptyClasses: function(value) { 30263 if (this.$isEmpty(value)) { 30264 this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS); 30265 this.$$animate.addClass(this.$$element, EMPTY_CLASS); 30266 } else { 30267 this.$$animate.removeClass(this.$$element, EMPTY_CLASS); 30268 this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS); 30269 } 30270 }, 30271 30272 /** 30273 * @ngdoc method 30274 * @name ngModel.NgModelController#$setPristine 30275 * 30276 * @description 30277 * Sets the control to its pristine state. 30278 * 30279 * This method can be called to remove the `ng-dirty` class and set the control to its pristine 30280 * state (`ng-pristine` class). A model is considered to be pristine when the control 30281 * has not been changed from when first compiled. 30282 */ 30283 $setPristine: function() { 30284 this.$dirty = false; 30285 this.$pristine = true; 30286 this.$$animate.removeClass(this.$$element, DIRTY_CLASS); 30287 this.$$animate.addClass(this.$$element, PRISTINE_CLASS); 30288 }, 30289 30290 /** 30291 * @ngdoc method 30292 * @name ngModel.NgModelController#$setDirty 30293 * 30294 * @description 30295 * Sets the control to its dirty state. 30296 * 30297 * This method can be called to remove the `ng-pristine` class and set the control to its dirty 30298 * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed 30299 * from when first compiled. 30300 */ 30301 $setDirty: function() { 30302 this.$dirty = true; 30303 this.$pristine = false; 30304 this.$$animate.removeClass(this.$$element, PRISTINE_CLASS); 30305 this.$$animate.addClass(this.$$element, DIRTY_CLASS); 30306 this.$$parentForm.$setDirty(); 30307 }, 30308 30309 /** 30310 * @ngdoc method 30311 * @name ngModel.NgModelController#$setUntouched 30312 * 30313 * @description 30314 * Sets the control to its untouched state. 30315 * 30316 * This method can be called to remove the `ng-touched` class and set the control to its 30317 * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched 30318 * by default, however this function can be used to restore that state if the model has 30319 * already been touched by the user. 30320 */ 30321 $setUntouched: function() { 30322 this.$touched = false; 30323 this.$untouched = true; 30324 this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS); 30325 }, 30326 30327 /** 30328 * @ngdoc method 30329 * @name ngModel.NgModelController#$setTouched 30330 * 30331 * @description 30332 * Sets the control to its touched state. 30333 * 30334 * This method can be called to remove the `ng-untouched` class and set the control to its 30335 * touched state (`ng-touched` class). A model is considered to be touched when the user has 30336 * first focused the control element and then shifted focus away from the control (blur event). 30337 */ 30338 $setTouched: function() { 30339 this.$touched = true; 30340 this.$untouched = false; 30341 this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS); 30342 }, 30343 30344 /** 30345 * @ngdoc method 30346 * @name ngModel.NgModelController#$rollbackViewValue 30347 * 30348 * @description 30349 * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, 30350 * which may be caused by a pending debounced event or because the input is waiting for some 30351 * future event. 30352 * 30353 * If you have an input that uses `ng-model-options` to set up debounced updates or updates that 30354 * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of 30355 * sync with the ngModel's `$modelValue`. 30356 * 30357 * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update 30358 * and reset the input to the last committed view value. 30359 * 30360 * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue` 30361 * programmatically before these debounced/future events have resolved/occurred, because AngularJS's 30362 * dirty checking mechanism is not able to tell whether the model has actually changed or not. 30363 * 30364 * The `$rollbackViewValue()` method should be called before programmatically changing the model of an 30365 * input which may have such events pending. This is important in order to make sure that the 30366 * input field will be updated with the new model value and any pending operations are cancelled. 30367 * 30368 * @example 30369 * <example name="ng-model-cancel-update" module="cancel-update-example"> 30370 * <file name="app.js"> 30371 * angular.module('cancel-update-example', []) 30372 * 30373 * .controller('CancelUpdateController', ['$scope', function($scope) { 30374 * $scope.model = {value1: '', value2: ''}; 30375 * 30376 * $scope.setEmpty = function(e, value, rollback) { 30377 * if (e.keyCode === 27) { 30378 * e.preventDefault(); 30379 * if (rollback) { 30380 * $scope.myForm[value].$rollbackViewValue(); 30381 * } 30382 * $scope.model[value] = ''; 30383 * } 30384 * }; 30385 * }]); 30386 * </file> 30387 * <file name="index.html"> 30388 * <div ng-controller="CancelUpdateController"> 30389 * <p>Both of these inputs are only updated if they are blurred. Hitting escape should 30390 * empty them. Follow these steps and observe the difference:</p> 30391 * <ol> 30392 * <li>Type something in the input. You will see that the model is not yet updated</li> 30393 * <li>Press the Escape key. 30394 * <ol> 30395 * <li> In the first example, nothing happens, because the model is already '', and no 30396 * update is detected. If you blur the input, the model will be set to the current view. 30397 * </li> 30398 * <li> In the second example, the pending update is cancelled, and the input is set back 30399 * to the last committed view value (''). Blurring the input does nothing. 30400 * </li> 30401 * </ol> 30402 * </li> 30403 * </ol> 30404 * 30405 * <form name="myForm" ng-model-options="{ updateOn: 'blur' }"> 30406 * <div> 30407 * <p id="inputDescription1">Without $rollbackViewValue():</p> 30408 * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1" 30409 * ng-keydown="setEmpty($event, 'value1')"> 30410 * value1: "{{ model.value1 }}" 30411 * </div> 30412 * 30413 * <div> 30414 * <p id="inputDescription2">With $rollbackViewValue():</p> 30415 * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2" 30416 * ng-keydown="setEmpty($event, 'value2', true)"> 30417 * value2: "{{ model.value2 }}" 30418 * </div> 30419 * </form> 30420 * </div> 30421 * </file> 30422 <file name="style.css"> 30423 div { 30424 display: table-cell; 30425 } 30426 div:nth-child(1) { 30427 padding-right: 30px; 30428 } 30429 30430 </file> 30431 * </example> 30432 */ 30433 $rollbackViewValue: function() { 30434 this.$$timeout.cancel(this.$$pendingDebounce); 30435 this.$viewValue = this.$$lastCommittedViewValue; 30436 this.$render(); 30437 }, 30438 30439 /** 30440 * @ngdoc method 30441 * @name ngModel.NgModelController#$validate 30442 * 30443 * @description 30444 * Runs each of the registered validators (first synchronous validators and then 30445 * asynchronous validators). 30446 * If the validity changes to invalid, the model will be set to `undefined`, 30447 * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`. 30448 * If the validity changes to valid, it will set the model to the last available valid 30449 * `$modelValue`, i.e. either the last parsed value or the last value set from the scope. 30450 */ 30451 $validate: function() { 30452 // ignore $validate before model is initialized 30453 if (isNumberNaN(this.$modelValue)) { 30454 return; 30455 } 30456 30457 var viewValue = this.$$lastCommittedViewValue; 30458 // Note: we use the $$rawModelValue as $modelValue might have been 30459 // set to undefined during a view -> model update that found validation 30460 // errors. We can't parse the view here, since that could change 30461 // the model although neither viewValue nor the model on the scope changed 30462 var modelValue = this.$$rawModelValue; 30463 30464 var prevValid = this.$valid; 30465 var prevModelValue = this.$modelValue; 30466 30467 var allowInvalid = this.$options.getOption('allowInvalid'); 30468 30469 var that = this; 30470 this.$$runValidators(modelValue, viewValue, function(allValid) { 30471 // If there was no change in validity, don't update the model 30472 // This prevents changing an invalid modelValue to undefined 30473 if (!allowInvalid && prevValid !== allValid) { 30474 // Note: Don't check this.$valid here, as we could have 30475 // external validators (e.g. calculated on the server), 30476 // that just call $setValidity and need the model value 30477 // to calculate their validity. 30478 that.$modelValue = allValid ? modelValue : undefined; 30479 30480 if (that.$modelValue !== prevModelValue) { 30481 that.$$writeModelToScope(); 30482 } 30483 } 30484 }); 30485 }, 30486 30487 $$runValidators: function(modelValue, viewValue, doneCallback) { 30488 this.$$currentValidationRunId++; 30489 var localValidationRunId = this.$$currentValidationRunId; 30490 var that = this; 30491 30492 // check parser error 30493 if (!processParseErrors()) { 30494 validationDone(false); 30495 return; 30496 } 30497 if (!processSyncValidators()) { 30498 validationDone(false); 30499 return; 30500 } 30501 processAsyncValidators(); 30502 30503 function processParseErrors() { 30504 var errorKey = that.$$parserName; 30505 30506 if (isUndefined(that.$$parserValid)) { 30507 setValidity(errorKey, null); 30508 } else { 30509 if (!that.$$parserValid) { 30510 forEach(that.$validators, function(v, name) { 30511 setValidity(name, null); 30512 }); 30513 forEach(that.$asyncValidators, function(v, name) { 30514 setValidity(name, null); 30515 }); 30516 } 30517 30518 // Set the parse error last, to prevent unsetting it, should a $validators key == parserName 30519 setValidity(errorKey, that.$$parserValid); 30520 return that.$$parserValid; 30521 } 30522 return true; 30523 } 30524 30525 function processSyncValidators() { 30526 var syncValidatorsValid = true; 30527 forEach(that.$validators, function(validator, name) { 30528 var result = Boolean(validator(modelValue, viewValue)); 30529 syncValidatorsValid = syncValidatorsValid && result; 30530 setValidity(name, result); 30531 }); 30532 if (!syncValidatorsValid) { 30533 forEach(that.$asyncValidators, function(v, name) { 30534 setValidity(name, null); 30535 }); 30536 return false; 30537 } 30538 return true; 30539 } 30540 30541 function processAsyncValidators() { 30542 var validatorPromises = []; 30543 var allValid = true; 30544 forEach(that.$asyncValidators, function(validator, name) { 30545 var promise = validator(modelValue, viewValue); 30546 if (!isPromiseLike(promise)) { 30547 throw ngModelMinErr('nopromise', 30548 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise); 30549 } 30550 setValidity(name, undefined); 30551 validatorPromises.push(promise.then(function() { 30552 setValidity(name, true); 30553 }, function() { 30554 allValid = false; 30555 setValidity(name, false); 30556 })); 30557 }); 30558 if (!validatorPromises.length) { 30559 validationDone(true); 30560 } else { 30561 that.$$q.all(validatorPromises).then(function() { 30562 validationDone(allValid); 30563 }, noop); 30564 } 30565 } 30566 30567 function setValidity(name, isValid) { 30568 if (localValidationRunId === that.$$currentValidationRunId) { 30569 that.$setValidity(name, isValid); 30570 } 30571 } 30572 30573 function validationDone(allValid) { 30574 if (localValidationRunId === that.$$currentValidationRunId) { 30575 30576 doneCallback(allValid); 30577 } 30578 } 30579 }, 30580 30581 /** 30582 * @ngdoc method 30583 * @name ngModel.NgModelController#$commitViewValue 30584 * 30585 * @description 30586 * Commit a pending update to the `$modelValue`. 30587 * 30588 * Updates may be pending by a debounced event or because the input is waiting for a some future 30589 * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` 30590 * usually handles calling this in response to input events. 30591 */ 30592 $commitViewValue: function() { 30593 var viewValue = this.$viewValue; 30594 30595 this.$$timeout.cancel(this.$$pendingDebounce); 30596 30597 // If the view value has not changed then we should just exit, except in the case where there is 30598 // a native validator on the element. In this case the validation state may have changed even though 30599 // the viewValue has stayed empty. 30600 if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) { 30601 return; 30602 } 30603 this.$$updateEmptyClasses(viewValue); 30604 this.$$lastCommittedViewValue = viewValue; 30605 30606 // change to dirty 30607 if (this.$pristine) { 30608 this.$setDirty(); 30609 } 30610 this.$$parseAndValidate(); 30611 }, 30612 30613 $$parseAndValidate: function() { 30614 var viewValue = this.$$lastCommittedViewValue; 30615 var modelValue = viewValue; 30616 var that = this; 30617 30618 this.$$parserValid = isUndefined(modelValue) ? undefined : true; 30619 30620 // Reset any previous parse error 30621 this.$setValidity(this.$$parserName, null); 30622 this.$$parserName = 'parse'; 30623 30624 if (this.$$parserValid) { 30625 for (var i = 0; i < this.$parsers.length; i++) { 30626 modelValue = this.$parsers[i](modelValue); 30627 if (isUndefined(modelValue)) { 30628 this.$$parserValid = false; 30629 break; 30630 } 30631 } 30632 } 30633 if (isNumberNaN(this.$modelValue)) { 30634 // this.$modelValue has not been touched yet... 30635 this.$modelValue = this.$$ngModelGet(this.$$scope); 30636 } 30637 var prevModelValue = this.$modelValue; 30638 var allowInvalid = this.$options.getOption('allowInvalid'); 30639 this.$$rawModelValue = modelValue; 30640 30641 if (allowInvalid) { 30642 this.$modelValue = modelValue; 30643 writeToModelIfNeeded(); 30644 } 30645 30646 // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date. 30647 // This can happen if e.g. $setViewValue is called from inside a parser 30648 this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) { 30649 if (!allowInvalid) { 30650 // Note: Don't check this.$valid here, as we could have 30651 // external validators (e.g. calculated on the server), 30652 // that just call $setValidity and need the model value 30653 // to calculate their validity. 30654 that.$modelValue = allValid ? modelValue : undefined; 30655 writeToModelIfNeeded(); 30656 } 30657 }); 30658 30659 function writeToModelIfNeeded() { 30660 if (that.$modelValue !== prevModelValue) { 30661 that.$$writeModelToScope(); 30662 } 30663 } 30664 }, 30665 30666 $$writeModelToScope: function() { 30667 this.$$ngModelSet(this.$$scope, this.$modelValue); 30668 forEach(this.$viewChangeListeners, function(listener) { 30669 try { 30670 listener(); 30671 } catch (e) { 30672 // eslint-disable-next-line no-invalid-this 30673 this.$$exceptionHandler(e); 30674 } 30675 }, this); 30676 }, 30677 30678 /** 30679 * @ngdoc method 30680 * @name ngModel.NgModelController#$setViewValue 30681 * 30682 * @description 30683 * Update the view value. 30684 * 30685 * This method should be called when a control wants to change the view value; typically, 30686 * this is done from within a DOM event handler. For example, the {@link ng.directive:input input} 30687 * directive calls it when the value of the input changes and {@link ng.directive:select select} 30688 * calls it when an option is selected. 30689 * 30690 * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers` 30691 * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged 30692 * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and 30693 * `$asyncValidators` are called and the value is applied to `$modelValue`. 30694 * Finally, the value is set to the **expression** specified in the `ng-model` attribute and 30695 * all the registered change listeners, in the `$viewChangeListeners` list are called. 30696 * 30697 * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` 30698 * and the `default` trigger is not listed, all those actions will remain pending until one of the 30699 * `updateOn` events is triggered on the DOM element. 30700 * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} 30701 * directive is used with a custom debounce for this particular event. 30702 * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce` 30703 * is specified, once the timer runs out. 30704 * 30705 * When used with standard inputs, the view value will always be a string (which is in some cases 30706 * parsed into another type, such as a `Date` object for `input[date]`.) 30707 * However, custom controls might also pass objects to this method. In this case, we should make 30708 * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not 30709 * perform a deep watch of objects, it only looks for a change of identity. If you only change 30710 * the property of the object then ngModel will not realize that the object has changed and 30711 * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should 30712 * not change properties of the copy once it has been passed to `$setViewValue`. 30713 * Otherwise you may cause the model value on the scope to change incorrectly. 30714 * 30715 * <div class="alert alert-info"> 30716 * In any case, the value passed to the method should always reflect the current value 30717 * of the control. For example, if you are calling `$setViewValue` for an input element, 30718 * you should pass the input DOM value. Otherwise, the control and the scope model become 30719 * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change 30720 * the control's DOM value in any way. If we want to change the control's DOM value 30721 * programmatically, we should update the `ngModel` scope expression. Its new value will be 30722 * picked up by the model controller, which will run it through the `$formatters`, `$render` it 30723 * to update the DOM, and finally call `$validate` on it. 30724 * </div> 30725 * 30726 * @param {*} value value from the view. 30727 * @param {string} trigger Event that triggered the update. 30728 */ 30729 $setViewValue: function(value, trigger) { 30730 this.$viewValue = value; 30731 if (this.$options.getOption('updateOnDefault')) { 30732 this.$$debounceViewValueCommit(trigger); 30733 } 30734 }, 30735 30736 $$debounceViewValueCommit: function(trigger) { 30737 var debounceDelay = this.$options.getOption('debounce'); 30738 30739 if (isNumber(debounceDelay[trigger])) { 30740 debounceDelay = debounceDelay[trigger]; 30741 } else if (isNumber(debounceDelay['default']) && 30742 this.$options.getOption('updateOn').indexOf(trigger) === -1 30743 ) { 30744 debounceDelay = debounceDelay['default']; 30745 } else if (isNumber(debounceDelay['*'])) { 30746 debounceDelay = debounceDelay['*']; 30747 } 30748 30749 this.$$timeout.cancel(this.$$pendingDebounce); 30750 var that = this; 30751 if (debounceDelay > 0) { // this fails if debounceDelay is an object 30752 this.$$pendingDebounce = this.$$timeout(function() { 30753 that.$commitViewValue(); 30754 }, debounceDelay); 30755 } else if (this.$$rootScope.$$phase) { 30756 this.$commitViewValue(); 30757 } else { 30758 this.$$scope.$apply(function() { 30759 that.$commitViewValue(); 30760 }); 30761 } 30762 }, 30763 30764 /** 30765 * @ngdoc method 30766 * 30767 * @name ngModel.NgModelController#$overrideModelOptions 30768 * 30769 * @description 30770 * 30771 * Override the current model options settings programmatically. 30772 * 30773 * The previous `ModelOptions` value will not be modified. Instead, a 30774 * new `ModelOptions` object will inherit from the previous one overriding 30775 * or inheriting settings that are defined in the given parameter. 30776 * 30777 * See {@link ngModelOptions} for information about what options can be specified 30778 * and how model option inheritance works. 30779 * 30780 * <div class="alert alert-warning"> 30781 * **Note:** this function only affects the options set on the `ngModelController`, 30782 * and not the options on the {@link ngModelOptions} directive from which they might have been 30783 * obtained initially. 30784 * </div> 30785 * 30786 * <div class="alert alert-danger"> 30787 * **Note:** it is not possible to override the `getterSetter` option. 30788 * </div> 30789 * 30790 * @param {Object} options a hash of settings to override the previous options 30791 * 30792 */ 30793 $overrideModelOptions: function(options) { 30794 this.$options = this.$options.createChild(options); 30795 this.$$setUpdateOnEvents(); 30796 }, 30797 30798 /** 30799 * @ngdoc method 30800 * 30801 * @name ngModel.NgModelController#$processModelValue 30802 30803 * @description 30804 * 30805 * Runs the model -> view pipeline on the current 30806 * {@link ngModel.NgModelController#$modelValue $modelValue}. 30807 * 30808 * The following actions are performed by this method: 30809 * 30810 * - the `$modelValue` is run through the {@link ngModel.NgModelController#$formatters $formatters} 30811 * and the result is set to the {@link ngModel.NgModelController#$viewValue $viewValue} 30812 * - the `ng-empty` or `ng-not-empty` class is set on the element 30813 * - if the `$viewValue` has changed: 30814 * - {@link ngModel.NgModelController#$render $render} is called on the control 30815 * - the {@link ngModel.NgModelController#$validators $validators} are run and 30816 * the validation status is set. 30817 * 30818 * This method is called by ngModel internally when the bound scope value changes. 30819 * Application developers usually do not have to call this function themselves. 30820 * 30821 * This function can be used when the `$viewValue` or the rendered DOM value are not correctly 30822 * formatted and the `$modelValue` must be run through the `$formatters` again. 30823 * 30824 * @example 30825 * Consider a text input with an autocomplete list (for fruit), where the items are 30826 * objects with a name and an id. 30827 * A user enters `ap` and then selects `Apricot` from the list. 30828 * Based on this, the autocomplete widget will call `$setViewValue({name: 'Apricot', id: 443})`, 30829 * but the rendered value will still be `ap`. 30830 * The widget can then call `ctrl.$processModelValue()` to run the model -> view 30831 * pipeline again, which formats the object to the string `Apricot`, 30832 * then updates the `$viewValue`, and finally renders it in the DOM. 30833 * 30834 * <example module="inputExample" name="ng-model-process"> 30835 <file name="index.html"> 30836 <div ng-controller="inputController" style="display: flex;"> 30837 <div style="margin-right: 30px;"> 30838 Search Fruit: 30839 <basic-autocomplete items="items" on-select="selectedFruit = item"></basic-autocomplete> 30840 </div> 30841 <div> 30842 Model:<br> 30843 <pre>{{selectedFruit | json}}</pre> 30844 </div> 30845 </div> 30846 </file> 30847 <file name="app.js"> 30848 angular.module('inputExample', []) 30849 .controller('inputController', function($scope) { 30850 $scope.items = [ 30851 {name: 'Apricot', id: 443}, 30852 {name: 'Clementine', id: 972}, 30853 {name: 'Durian', id: 169}, 30854 {name: 'Jackfruit', id: 982}, 30855 {name: 'Strawberry', id: 863} 30856 ]; 30857 }) 30858 .component('basicAutocomplete', { 30859 bindings: { 30860 items: '<', 30861 onSelect: '&' 30862 }, 30863 templateUrl: 'autocomplete.html', 30864 controller: function($element, $scope) { 30865 var that = this; 30866 var ngModel; 30867 30868 that.$postLink = function() { 30869 ngModel = $element.find('input').controller('ngModel'); 30870 30871 ngModel.$formatters.push(function(value) { 30872 return (value && value.name) || value; 30873 }); 30874 30875 ngModel.$parsers.push(function(value) { 30876 var match = value; 30877 for (var i = 0; i < that.items.length; i++) { 30878 if (that.items[i].name === value) { 30879 match = that.items[i]; 30880 break; 30881 } 30882 } 30883 30884 return match; 30885 }); 30886 }; 30887 30888 that.selectItem = function(item) { 30889 ngModel.$setViewValue(item); 30890 ngModel.$processModelValue(); 30891 that.onSelect({item: item}); 30892 }; 30893 } 30894 }); 30895 </file> 30896 <file name="autocomplete.html"> 30897 <div> 30898 <input type="search" ng-model="$ctrl.searchTerm" /> 30899 <ul> 30900 <li ng-repeat="item in $ctrl.items | filter:$ctrl.searchTerm"> 30901 <button ng-click="$ctrl.selectItem(item)">{{ item.name }}</button> 30902 </li> 30903 </ul> 30904 </div> 30905 </file> 30906 * </example> 30907 * 30908 */ 30909 $processModelValue: function() { 30910 var viewValue = this.$$format(); 30911 30912 if (this.$viewValue !== viewValue) { 30913 this.$$updateEmptyClasses(viewValue); 30914 this.$viewValue = this.$$lastCommittedViewValue = viewValue; 30915 this.$render(); 30916 // It is possible that model and view value have been updated during render 30917 this.$$runValidators(this.$modelValue, this.$viewValue, noop); 30918 } 30919 }, 30920 30921 /** 30922 * This method is called internally to run the $formatters on the $modelValue 30923 */ 30924 $$format: function() { 30925 var formatters = this.$formatters, 30926 idx = formatters.length; 30927 30928 var viewValue = this.$modelValue; 30929 while (idx--) { 30930 viewValue = formatters[idx](viewValue); 30931 } 30932 30933 return viewValue; 30934 }, 30935 30936 /** 30937 * This method is called internally when the bound scope value changes. 30938 */ 30939 $$setModelValue: function(modelValue) { 30940 this.$modelValue = this.$$rawModelValue = modelValue; 30941 this.$$parserValid = undefined; 30942 this.$processModelValue(); 30943 }, 30944 30945 $$setUpdateOnEvents: function() { 30946 if (this.$$updateEvents) { 30947 this.$$element.off(this.$$updateEvents, this.$$updateEventHandler); 30948 } 30949 30950 this.$$updateEvents = this.$options.getOption('updateOn'); 30951 if (this.$$updateEvents) { 30952 this.$$element.on(this.$$updateEvents, this.$$updateEventHandler); 30953 } 30954 }, 30955 30956 $$updateEventHandler: function(ev) { 30957 this.$$debounceViewValueCommit(ev && ev.type); 30958 } 30959}; 30960 30961function setupModelWatcher(ctrl) { 30962 // model -> value 30963 // Note: we cannot use a normal scope.$watch as we want to detect the following: 30964 // 1. scope value is 'a' 30965 // 2. user enters 'b' 30966 // 3. ng-change kicks in and reverts scope value to 'a' 30967 // -> scope value did not change since the last digest as 30968 // ng-change executes in apply phase 30969 // 4. view should be changed back to 'a' 30970 ctrl.$$scope.$watch(function ngModelWatch(scope) { 30971 var modelValue = ctrl.$$ngModelGet(scope); 30972 30973 // if scope model value and ngModel value are out of sync 30974 // This cannot be moved to the action function, because it would not catch the 30975 // case where the model is changed in the ngChange function or the model setter 30976 if (modelValue !== ctrl.$modelValue && 30977 // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator 30978 // eslint-disable-next-line no-self-compare 30979 (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue) 30980 ) { 30981 ctrl.$$setModelValue(modelValue); 30982 } 30983 30984 return modelValue; 30985 }); 30986} 30987 30988/** 30989 * @ngdoc method 30990 * @name ngModel.NgModelController#$setValidity 30991 * 30992 * @description 30993 * Change the validity state, and notify the form. 30994 * 30995 * This method can be called within $parsers/$formatters or a custom validation implementation. 30996 * However, in most cases it should be sufficient to use the `ngModel.$validators` and 30997 * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically. 30998 * 30999 * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned 31000 * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` 31001 * (for unfulfilled `$asyncValidators`), so that it is available for data-binding. 31002 * The `validationErrorKey` should be in camelCase and will get converted into dash-case 31003 * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` 31004 * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`. 31005 * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), 31006 * or skipped (null). Pending is used for unfulfilled `$asyncValidators`. 31007 * Skipped is used by AngularJS when validators do not run because of parse errors and 31008 * when `$asyncValidators` do not run because any of the `$validators` failed. 31009 */ 31010addSetValidityMethod({ 31011 clazz: NgModelController, 31012 set: function(object, property) { 31013 object[property] = true; 31014 }, 31015 unset: function(object, property) { 31016 delete object[property]; 31017 } 31018}); 31019 31020 31021/** 31022 * @ngdoc directive 31023 * @name ngModel 31024 * @restrict A 31025 * @priority 1 31026 * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to. 31027 * 31028 * @description 31029 * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a 31030 * property on the scope using {@link ngModel.NgModelController NgModelController}, 31031 * which is created and exposed by this directive. 31032 * 31033 * `ngModel` is responsible for: 31034 * 31035 * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` 31036 * require. 31037 * - Providing validation behavior (i.e. required, number, email, url). 31038 * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). 31039 * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, 31040 * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations. 31041 * - Registering the control with its parent {@link ng.directive:form form}. 31042 * 31043 * Note: `ngModel` will try to bind to the property given by evaluating the expression on the 31044 * current scope. If the property doesn't already exist on this scope, it will be created 31045 * implicitly and added to the scope. 31046 * 31047 * For best practices on using `ngModel`, see: 31048 * 31049 * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes) 31050 * 31051 * For basic examples, how to use `ngModel`, see: 31052 * 31053 * - {@link ng.directive:input input} 31054 * - {@link input[text] text} 31055 * - {@link input[checkbox] checkbox} 31056 * - {@link input[radio] radio} 31057 * - {@link input[number] number} 31058 * - {@link input[email] email} 31059 * - {@link input[url] url} 31060 * - {@link input[date] date} 31061 * - {@link input[datetime-local] datetime-local} 31062 * - {@link input[time] time} 31063 * - {@link input[month] month} 31064 * - {@link input[week] week} 31065 * - {@link ng.directive:select select} 31066 * - {@link ng.directive:textarea textarea} 31067 * 31068 * ## Complex Models (objects or collections) 31069 * 31070 * By default, `ngModel` watches the model by reference, not value. This is important to know when 31071 * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the 31072 * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered. 31073 * 31074 * The model must be assigned an entirely new object or collection before a re-rendering will occur. 31075 * 31076 * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression 31077 * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or 31078 * if the select is given the `multiple` attribute. 31079 * 31080 * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the 31081 * first level of the object (or only changing the properties of an item in the collection if it's an array) will still 31082 * not trigger a re-rendering of the model. 31083 * 31084 * ## CSS classes 31085 * The following CSS classes are added and removed on the associated input/select/textarea element 31086 * depending on the validity of the model. 31087 * 31088 * - `ng-valid`: the model is valid 31089 * - `ng-invalid`: the model is invalid 31090 * - `ng-valid-[key]`: for each valid key added by `$setValidity` 31091 * - `ng-invalid-[key]`: for each invalid key added by `$setValidity` 31092 * - `ng-pristine`: the control hasn't been interacted with yet 31093 * - `ng-dirty`: the control has been interacted with 31094 * - `ng-touched`: the control has been blurred 31095 * - `ng-untouched`: the control hasn't been blurred 31096 * - `ng-pending`: any `$asyncValidators` are unfulfilled 31097 * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined 31098 * by the {@link ngModel.NgModelController#$isEmpty} method 31099 * - `ng-not-empty`: the view contains a non-empty value 31100 * 31101 * Keep in mind that ngAnimate can detect each of these classes when added and removed. 31102 * 31103 * @animations 31104 * Animations within models are triggered when any of the associated CSS classes are added and removed 31105 * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`, 31106 * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. 31107 * The animations that are triggered within ngModel are similar to how they work in ngClass and 31108 * animations can be hooked into using CSS transitions, keyframes as well as JS animations. 31109 * 31110 * The following example shows a simple way to utilize CSS transitions to style an input element 31111 * that has been rendered as invalid after it has been validated: 31112 * 31113 * <pre> 31114 * //be sure to include ngAnimate as a module to hook into more 31115 * //advanced animations 31116 * .my-input { 31117 * transition:0.5s linear all; 31118 * background: white; 31119 * } 31120 * .my-input.ng-invalid { 31121 * background: red; 31122 * color:white; 31123 * } 31124 * </pre> 31125 * 31126 * @example 31127 * ### Basic Usage 31128 * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model"> 31129 <file name="index.html"> 31130 <script> 31131 angular.module('inputExample', []) 31132 .controller('ExampleController', ['$scope', function($scope) { 31133 $scope.val = '1'; 31134 }]); 31135 </script> 31136 <style> 31137 .my-input { 31138 transition:all linear 0.5s; 31139 background: transparent; 31140 } 31141 .my-input.ng-invalid { 31142 color:white; 31143 background: red; 31144 } 31145 </style> 31146 <p id="inputDescription"> 31147 Update input to see transitions when valid/invalid. 31148 Integer is a valid value. 31149 </p> 31150 <form name="testForm" ng-controller="ExampleController"> 31151 <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" 31152 aria-describedby="inputDescription" /> 31153 </form> 31154 </file> 31155 * </example> 31156 * 31157 * @example 31158 * ### Binding to a getter/setter 31159 * 31160 * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a 31161 * function that returns a representation of the model when called with zero arguments, and sets 31162 * the internal state of a model when called with an argument. It's sometimes useful to use this 31163 * for models that have an internal representation that's different from what the model exposes 31164 * to the view. 31165 * 31166 * <div class="alert alert-success"> 31167 * **Best Practice:** It's best to keep getters fast because AngularJS is likely to call them more 31168 * frequently than other parts of your code. 31169 * </div> 31170 * 31171 * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that 31172 * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to 31173 * a `<form>`, which will enable this behavior for all `<input>`s within it. See 31174 * {@link ng.directive:ngModelOptions `ngModelOptions`} for more. 31175 * 31176 * The following example shows how to use `ngModel` with a getter/setter: 31177 * 31178 * @example 31179 * <example name="ngModel-getter-setter" module="getterSetterExample"> 31180 <file name="index.html"> 31181 <div ng-controller="ExampleController"> 31182 <form name="userForm"> 31183 <label>Name: 31184 <input type="text" name="userName" 31185 ng-model="user.name" 31186 ng-model-options="{ getterSetter: true }" /> 31187 </label> 31188 </form> 31189 <pre>user.name = <span ng-bind="user.name()"></span></pre> 31190 </div> 31191 </file> 31192 <file name="app.js"> 31193 angular.module('getterSetterExample', []) 31194 .controller('ExampleController', ['$scope', function($scope) { 31195 var _name = 'Brian'; 31196 $scope.user = { 31197 name: function(newName) { 31198 // Note that newName can be undefined for two reasons: 31199 // 1. Because it is called as a getter and thus called with no arguments 31200 // 2. Because the property should actually be set to undefined. This happens e.g. if the 31201 // input is invalid 31202 return arguments.length ? (_name = newName) : _name; 31203 } 31204 }; 31205 }]); 31206 </file> 31207 * </example> 31208 */ 31209var ngModelDirective = ['$rootScope', function($rootScope) { 31210 return { 31211 restrict: 'A', 31212 require: ['ngModel', '^?form', '^?ngModelOptions'], 31213 controller: NgModelController, 31214 // Prelink needs to run before any input directive 31215 // so that we can set the NgModelOptions in NgModelController 31216 // before anyone else uses it. 31217 priority: 1, 31218 compile: function ngModelCompile(element) { 31219 // Setup initial state of the control 31220 element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); 31221 31222 return { 31223 pre: function ngModelPreLink(scope, element, attr, ctrls) { 31224 var modelCtrl = ctrls[0], 31225 formCtrl = ctrls[1] || modelCtrl.$$parentForm, 31226 optionsCtrl = ctrls[2]; 31227 31228 if (optionsCtrl) { 31229 modelCtrl.$options = optionsCtrl.$options; 31230 } 31231 31232 modelCtrl.$$initGetterSetters(); 31233 31234 // notify others, especially parent forms 31235 formCtrl.$addControl(modelCtrl); 31236 31237 attr.$observe('name', function(newValue) { 31238 if (modelCtrl.$name !== newValue) { 31239 modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue); 31240 } 31241 }); 31242 31243 scope.$on('$destroy', function() { 31244 modelCtrl.$$parentForm.$removeControl(modelCtrl); 31245 }); 31246 }, 31247 post: function ngModelPostLink(scope, element, attr, ctrls) { 31248 var modelCtrl = ctrls[0]; 31249 modelCtrl.$$setUpdateOnEvents(); 31250 31251 function setTouched() { 31252 modelCtrl.$setTouched(); 31253 } 31254 31255 element.on('blur', function() { 31256 if (modelCtrl.$touched) return; 31257 31258 if ($rootScope.$$phase) { 31259 scope.$evalAsync(setTouched); 31260 } else { 31261 scope.$apply(setTouched); 31262 } 31263 }); 31264 } 31265 }; 31266 } 31267 }; 31268}]; 31269 31270/* exported defaultModelOptions */ 31271var defaultModelOptions; 31272var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; 31273 31274/** 31275 * @ngdoc type 31276 * @name ModelOptions 31277 * @description 31278 * A container for the options set by the {@link ngModelOptions} directive 31279 */ 31280function ModelOptions(options) { 31281 this.$$options = options; 31282} 31283 31284ModelOptions.prototype = { 31285 31286 /** 31287 * @ngdoc method 31288 * @name ModelOptions#getOption 31289 * @param {string} name the name of the option to retrieve 31290 * @returns {*} the value of the option 31291 * @description 31292 * Returns the value of the given option 31293 */ 31294 getOption: function(name) { 31295 return this.$$options[name]; 31296 }, 31297 31298 /** 31299 * @ngdoc method 31300 * @name ModelOptions#createChild 31301 * @param {Object} options a hash of options for the new child that will override the parent's options 31302 * @return {ModelOptions} a new `ModelOptions` object initialized with the given options. 31303 */ 31304 createChild: function(options) { 31305 var inheritAll = false; 31306 31307 // make a shallow copy 31308 options = extend({}, options); 31309 31310 // Inherit options from the parent if specified by the value `"$inherit"` 31311 forEach(options, /** @this */ function(option, key) { 31312 if (option === '$inherit') { 31313 if (key === '*') { 31314 inheritAll = true; 31315 } else { 31316 options[key] = this.$$options[key]; 31317 // `updateOn` is special so we must also inherit the `updateOnDefault` option 31318 if (key === 'updateOn') { 31319 options.updateOnDefault = this.$$options.updateOnDefault; 31320 } 31321 } 31322 } else { 31323 if (key === 'updateOn') { 31324 // If the `updateOn` property contains the `default` event then we have to remove 31325 // it from the event list and set the `updateOnDefault` flag. 31326 options.updateOnDefault = false; 31327 options[key] = trim(option.replace(DEFAULT_REGEXP, function() { 31328 options.updateOnDefault = true; 31329 return ' '; 31330 })); 31331 } 31332 } 31333 }, this); 31334 31335 if (inheritAll) { 31336 // We have a property of the form: `"*": "$inherit"` 31337 delete options['*']; 31338 defaults(options, this.$$options); 31339 } 31340 31341 // Finally add in any missing defaults 31342 defaults(options, defaultModelOptions.$$options); 31343 31344 return new ModelOptions(options); 31345 } 31346}; 31347 31348 31349defaultModelOptions = new ModelOptions({ 31350 updateOn: '', 31351 updateOnDefault: true, 31352 debounce: 0, 31353 getterSetter: false, 31354 allowInvalid: false, 31355 timezone: null 31356}); 31357 31358 31359/** 31360 * @ngdoc directive 31361 * @name ngModelOptions 31362 * @restrict A 31363 * @priority 10 31364 * 31365 * @description 31366 * This directive allows you to modify the behaviour of {@link ngModel} directives within your 31367 * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel} 31368 * directives will use the options of their nearest `ngModelOptions` ancestor. 31369 * 31370 * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as 31371 * an AngularJS expression. This expression should evaluate to an object, whose properties contain 31372 * the settings. For example: `<div ng-model-options="{ debounce: 100 }"`. 31373 * 31374 * ## Inheriting Options 31375 * 31376 * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions` 31377 * directive by giving it the value of `"$inherit"`. 31378 * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the 31379 * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings 31380 * will be used. 31381 * 31382 * For example given the following fragment of HTML 31383 * 31384 * 31385 * ```html 31386 * <div ng-model-options="{ allowInvalid: true, debounce: 200 }"> 31387 * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }"> 31388 * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" /> 31389 * </form> 31390 * </div> 31391 * ``` 31392 * 31393 * the `input` element will have the following settings 31394 * 31395 * ```js 31396 * { allowInvalid: true, updateOn: 'default', debounce: 0 } 31397 * ``` 31398 * 31399 * Notice that the `debounce` setting was not inherited and used the default value instead. 31400 * 31401 * You can specify that all undefined settings are automatically inherited from an ancestor by 31402 * including a property with key of `"*"` and value of `"$inherit"`. 31403 * 31404 * For example given the following fragment of HTML 31405 * 31406 * 31407 * ```html 31408 * <div ng-model-options="{ allowInvalid: true, debounce: 200 }"> 31409 * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }"> 31410 * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" /> 31411 * </form> 31412 * </div> 31413 * ``` 31414 * 31415 * the `input` element will have the following settings 31416 * 31417 * ```js 31418 * { allowInvalid: true, updateOn: 'default', debounce: 200 } 31419 * ``` 31420 * 31421 * Notice that the `debounce` setting now inherits the value from the outer `<div>` element. 31422 * 31423 * If you are creating a reusable component then you should be careful when using `"*": "$inherit"` 31424 * since you may inadvertently inherit a setting in the future that changes the behavior of your component. 31425 * 31426 * 31427 * ## Triggering and debouncing model updates 31428 * 31429 * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will 31430 * trigger a model update and/or a debouncing delay so that the actual update only takes place when 31431 * a timer expires; this timer will be reset after another change takes place. 31432 * 31433 * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might 31434 * be different from the value in the actual model. This means that if you update the model you 31435 * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in 31436 * order to make sure it is synchronized with the model and that any debounced action is canceled. 31437 * 31438 * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue} 31439 * method is by making sure the input is placed inside a form that has a `name` attribute. This is 31440 * important because `form` controllers are published to the related scope under the name in their 31441 * `name` attribute. 31442 * 31443 * Any pending changes will take place immediately when an enclosing form is submitted via the 31444 * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` 31445 * to have access to the updated model. 31446 * 31447 * ### Overriding immediate updates 31448 * 31449 * The following example shows how to override immediate updates. Changes on the inputs within the 31450 * form will update the model only when the control loses focus (blur event). If `escape` key is 31451 * pressed while the input field is focused, the value is reset to the value in the current model. 31452 * 31453 * <example name="ngModelOptions-directive-blur" module="optionsExample"> 31454 * <file name="index.html"> 31455 * <div ng-controller="ExampleController"> 31456 * <form name="userForm"> 31457 * <label> 31458 * Name: 31459 * <input type="text" name="userName" 31460 * ng-model="user.name" 31461 * ng-model-options="{ updateOn: 'blur' }" 31462 * ng-keyup="cancel($event)" /> 31463 * </label><br /> 31464 * <label> 31465 * Other data: 31466 * <input type="text" ng-model="user.data" /> 31467 * </label><br /> 31468 * </form> 31469 * <pre>user.name = <span ng-bind="user.name"></span></pre> 31470 * </div> 31471 * </file> 31472 * <file name="app.js"> 31473 * angular.module('optionsExample', []) 31474 * .controller('ExampleController', ['$scope', function($scope) { 31475 * $scope.user = { name: 'say', data: '' }; 31476 * 31477 * $scope.cancel = function(e) { 31478 * if (e.keyCode === 27) { 31479 * $scope.userForm.userName.$rollbackViewValue(); 31480 * } 31481 * }; 31482 * }]); 31483 * </file> 31484 * <file name="protractor.js" type="protractor"> 31485 * var model = element(by.binding('user.name')); 31486 * var input = element(by.model('user.name')); 31487 * var other = element(by.model('user.data')); 31488 * 31489 * it('should allow custom events', function() { 31490 * input.sendKeys(' hello'); 31491 * input.click(); 31492 * expect(model.getText()).toEqual('say'); 31493 * other.click(); 31494 * expect(model.getText()).toEqual('say hello'); 31495 * }); 31496 * 31497 * it('should $rollbackViewValue when model changes', function() { 31498 * input.sendKeys(' hello'); 31499 * expect(input.getAttribute('value')).toEqual('say hello'); 31500 * input.sendKeys(protractor.Key.ESCAPE); 31501 * expect(input.getAttribute('value')).toEqual('say'); 31502 * other.click(); 31503 * expect(model.getText()).toEqual('say'); 31504 * }); 31505 * </file> 31506 * </example> 31507 * 31508 * ### Debouncing updates 31509 * 31510 * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change. 31511 * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. 31512 * 31513 * <example name="ngModelOptions-directive-debounce" module="optionsExample"> 31514 * <file name="index.html"> 31515 * <div ng-controller="ExampleController"> 31516 * <form name="userForm"> 31517 * Name: 31518 * <input type="text" name="userName" 31519 * ng-model="user.name" 31520 * ng-model-options="{ debounce: 1000 }" /> 31521 * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br /> 31522 * </form> 31523 * <pre>user.name = <span ng-bind="user.name"></span></pre> 31524 * </div> 31525 * </file> 31526 * <file name="app.js"> 31527 * angular.module('optionsExample', []) 31528 * .controller('ExampleController', ['$scope', function($scope) { 31529 * $scope.user = { name: 'say' }; 31530 * }]); 31531 * </file> 31532 * </example> 31533 * 31534 * ### Default events, extra triggers, and catch-all debounce values 31535 * 31536 * This example shows the relationship between "default" update events and 31537 * additional `updateOn` triggers. 31538 * 31539 * `default` events are those that are bound to the control, and when fired, update the `$viewValue` 31540 * via {@link ngModel.NgModelController#$setViewValue $setViewValue}. Every event that is not listed 31541 * in `updateOn` is considered a "default" event, since different control types have different 31542 * default events. 31543 * 31544 * The control in this example updates by "default", "click", and "blur", with different `debounce` 31545 * values. You can see that "click" doesn't have an individual `debounce` value - 31546 * therefore it uses the `*` debounce value. 31547 * 31548 * There is also a button that calls {@link ngModel.NgModelController#$setViewValue $setViewValue} 31549 * directly with a "custom" event. Since "custom" is not defined in the `updateOn` list, 31550 * it is considered a "default" event and will update the 31551 * control if "default" is defined in `updateOn`, and will receive the "default" debounce value. 31552 * Note that this is just to illustrate how custom controls would possibly call `$setViewValue`. 31553 * 31554 * You can change the `updateOn` and `debounce` configuration to test different scenarios. This 31555 * is done with {@link ngModel.NgModelController#$overrideModelOptions $overrideModelOptions}. 31556 * 31557 <example name="ngModelOptions-advanced" module="optionsExample"> 31558 <file name="index.html"> 31559 <model-update-demo></model-update-demo> 31560 </file> 31561 <file name="app.js"> 31562 angular.module('optionsExample', []) 31563 .component('modelUpdateDemo', { 31564 templateUrl: 'template.html', 31565 controller: function() { 31566 this.name = 'Chinua'; 31567 31568 this.options = { 31569 updateOn: 'default blur click', 31570 debounce: { 31571 default: 2000, 31572 blur: 0, 31573 '*': 1000 31574 } 31575 }; 31576 31577 this.updateEvents = function() { 31578 var eventList = this.options.updateOn.split(' '); 31579 eventList.push('*'); 31580 var events = {}; 31581 31582 for (var i = 0; i < eventList.length; i++) { 31583 events[eventList[i]] = this.options.debounce[eventList[i]]; 31584 } 31585 31586 this.events = events; 31587 }; 31588 31589 this.updateOptions = function() { 31590 var options = angular.extend(this.options, { 31591 updateOn: Object.keys(this.events).join(' ').replace('*', ''), 31592 debounce: this.events 31593 }); 31594 31595 this.form.input.$overrideModelOptions(options); 31596 }; 31597 31598 // Initialize the event form 31599 this.updateEvents(); 31600 } 31601 }); 31602 </file> 31603 <file name="template.html"> 31604 <form name="$ctrl.form"> 31605 Input: <input type="text" name="input" ng-model="$ctrl.name" ng-model-options="$ctrl.options" /> 31606 </form> 31607 Model: <tt>{{$ctrl.name}}</tt> 31608 <hr> 31609 <button ng-click="$ctrl.form.input.$setViewValue('some value', 'custom')">Trigger setViewValue with 'some value' and 'custom' event</button> 31610 31611 <hr> 31612 <form ng-submit="$ctrl.updateOptions()"> 31613 <b>updateOn</b><br> 31614 <input type="text" ng-model="$ctrl.options.updateOn" ng-change="$ctrl.updateEvents()" ng-model-options="{debounce: 500}"> 31615 31616 <table> 31617 <tr> 31618 <th>Option</th> 31619 <th>Debounce value</th> 31620 </tr> 31621 <tr ng-repeat="(key, value) in $ctrl.events"> 31622 <td>{{key}}</td> 31623 <td><input type="number" ng-model="$ctrl.events[key]" /></td> 31624 </tr> 31625 </table> 31626 31627 <br> 31628 <input type="submit" value="Update options"> 31629 </form> 31630 </file> 31631 </example> 31632 * 31633 * 31634 * ## Model updates and validation 31635 * 31636 * The default behaviour in `ngModel` is that the model value is set to `undefined` when the 31637 * validation determines that the value is invalid. By setting the `allowInvalid` property to true, 31638 * the model will still be updated even if the value is invalid. 31639 * 31640 * 31641 * ## Connecting to the scope 31642 * 31643 * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression 31644 * on the scope refers to a "getter/setter" function rather than the value itself. 31645 * 31646 * The following example shows how to bind to getter/setters: 31647 * 31648 * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample"> 31649 * <file name="index.html"> 31650 * <div ng-controller="ExampleController"> 31651 * <form name="userForm"> 31652 * <label> 31653 * Name: 31654 * <input type="text" name="userName" 31655 * ng-model="user.name" 31656 * ng-model-options="{ getterSetter: true }" /> 31657 * </label> 31658 * </form> 31659 * <pre>user.name = <span ng-bind="user.name()"></span></pre> 31660 * </div> 31661 * </file> 31662 * <file name="app.js"> 31663 * angular.module('getterSetterExample', []) 31664 * .controller('ExampleController', ['$scope', function($scope) { 31665 * var _name = 'Brian'; 31666 * $scope.user = { 31667 * name: function(newName) { 31668 * return angular.isDefined(newName) ? (_name = newName) : _name; 31669 * } 31670 * }; 31671 * }]); 31672 * </file> 31673 * </example> 31674 * 31675 * 31676 * ## Programmatically changing options 31677 * 31678 * The `ngModelOptions` expression is only evaluated once when the directive is linked; it is not 31679 * watched for changes. However, it is possible to override the options on a single 31680 * {@link ngModel.NgModelController} instance with 31681 * {@link ngModel.NgModelController#$overrideModelOptions `NgModelController#$overrideModelOptions()`}. 31682 * See also the example for 31683 * {@link ngModelOptions#default-events-extra-triggers-and-catch-all-debounce-values 31684 * Default events, extra triggers, and catch-all debounce values}. 31685 * 31686 * 31687 * ## Specifying timezones 31688 * 31689 * You can specify the timezone that date/time input directives expect by providing its name in the 31690 * `timezone` property. 31691 * 31692 * 31693 * ## Formatting the value of `time` and `datetime-local` 31694 * 31695 * With the options `timeSecondsFormat` and `timeStripZeroSeconds` it is possible to adjust the value 31696 * that is displayed in the control. Note that browsers may apply their own formatting 31697 * in the user interface. 31698 * 31699 <example name="ngModelOptions-time-format" module="timeExample"> 31700 <file name="index.html"> 31701 <time-example></time-example> 31702 </file> 31703 <file name="script.js"> 31704 angular.module('timeExample', []) 31705 .component('timeExample', { 31706 templateUrl: 'timeExample.html', 31707 controller: function() { 31708 this.time = new Date(1970, 0, 1, 14, 57, 0); 31709 31710 this.options = { 31711 timeSecondsFormat: 'ss', 31712 timeStripZeroSeconds: true 31713 }; 31714 31715 this.optionChange = function() { 31716 this.timeForm.timeFormatted.$overrideModelOptions(this.options); 31717 this.time = new Date(this.time); 31718 }; 31719 } 31720 }); 31721 </file> 31722 <file name="timeExample.html"> 31723 <form name="$ctrl.timeForm"> 31724 <strong>Default</strong>: 31725 <input type="time" ng-model="$ctrl.time" step="any" /><br> 31726 <strong>With options</strong>: 31727 <input type="time" name="timeFormatted" ng-model="$ctrl.time" step="any" ng-model-options="$ctrl.options" /> 31728 <br> 31729 31730 Options:<br> 31731 <code>timeSecondsFormat</code>: 31732 <input 31733 type="text" 31734 ng-model="$ctrl.options.timeSecondsFormat" 31735 ng-change="$ctrl.optionChange()"> 31736 <br> 31737 <code>timeStripZeroSeconds</code>: 31738 <input 31739 type="checkbox" 31740 ng-model="$ctrl.options.timeStripZeroSeconds" 31741 ng-change="$ctrl.optionChange()"> 31742 </form> 31743 </file> 31744 * </example> 31745 * 31746 * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and 31747 * and its descendents. 31748 * 31749 * **General options**: 31750 * 31751 * - `updateOn`: string specifying which event should the input be bound to. You can set several 31752 * events using an space delimited list. There is a special event called `default` that 31753 * matches the default events belonging to the control. These are the events that are bound to 31754 * the control, and when fired, update the `$viewValue` via `$setViewValue`. 31755 * 31756 * `ngModelOptions` considers every event that is not listed in `updateOn` a "default" event, 31757 * since different control types use different default events. 31758 * 31759 * See also the section {@link ngModelOptions#triggering-and-debouncing-model-updates 31760 * Triggering and debouncing model updates}. 31761 * 31762 * - `debounce`: integer value which contains the debounce model update value in milliseconds. A 31763 * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a 31764 * custom value for each event. For example: 31765 * ``` 31766 * ng-model-options="{ 31767 * updateOn: 'default blur', 31768 * debounce: { 'default': 500, 'blur': 0 } 31769 * }" 31770 * ``` 31771 * You can use the `*` key to specify a debounce value that applies to all events that are not 31772 * specifically listed. In the following example, `mouseup` would have a debounce delay of 1000: 31773 * ``` 31774 * ng-model-options="{ 31775 * updateOn: 'default blur mouseup', 31776 * debounce: { 'default': 500, 'blur': 0, '*': 1000 } 31777 * }" 31778 * ``` 31779 * - `allowInvalid`: boolean value which indicates that the model can be set with values that did 31780 * not validate correctly instead of the default behavior of setting the model to undefined. 31781 * - `getterSetter`: boolean value which determines whether or not to treat functions bound to 31782 * `ngModel` as getters/setters. 31783 * 31784 * 31785 * **Input-type specific options**: 31786 * 31787 * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for 31788 * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the 31789 * continental US time zone abbreviations, but for general use, use a time zone offset, for 31790 * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian) 31791 * If not specified, the timezone of the browser will be used. 31792 * Note that changing the timezone will have no effect on the current date, and is only applied after 31793 * the next input / model change. 31794 * 31795 * - `timeSecondsFormat`: Defines if the `time` and `datetime-local` types should show seconds and 31796 * milliseconds. The option follows the format string of {@link date date filter}. 31797 * By default, the options is `undefined` which is equal to `'ss.sss'` (seconds and milliseconds). 31798 * The other options are `'ss'` (strips milliseconds), and `''` (empty string), which strips both 31799 * seconds and milliseconds. 31800 * Note that browsers that support `time` and `datetime-local` require the hour and minutes 31801 * part of the time string, and may show the value differently in the user interface. 31802 * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}. 31803 * 31804 * - `timeStripZeroSeconds`: Defines if the `time` and `datetime-local` types should strip the 31805 * seconds and milliseconds from the formatted value if they are zero. This option is applied 31806 * after `timeSecondsFormat`. 31807 * This option can be used to make the formatting consistent over different browsers, as some 31808 * browsers with support for `time` will natively hide the milliseconds and 31809 * seconds if they are zero, but others won't, and browsers that don't implement these input 31810 * types will always show the full string. 31811 * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}. 31812 * 31813 */ 31814var ngModelOptionsDirective = function() { 31815 NgModelOptionsController.$inject = ['$attrs', '$scope']; 31816 function NgModelOptionsController($attrs, $scope) { 31817 this.$$attrs = $attrs; 31818 this.$$scope = $scope; 31819 } 31820 NgModelOptionsController.prototype = { 31821 $onInit: function() { 31822 var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions; 31823 var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions); 31824 31825 this.$options = parentOptions.createChild(modelOptionsDefinition); 31826 } 31827 }; 31828 31829 return { 31830 restrict: 'A', 31831 // ngModelOptions needs to run before ngModel and input directives 31832 priority: 10, 31833 require: {parentCtrl: '?^^ngModelOptions'}, 31834 bindToController: true, 31835 controller: NgModelOptionsController 31836 }; 31837}; 31838 31839 31840// shallow copy over values from `src` that are not already specified on `dst` 31841function defaults(dst, src) { 31842 forEach(src, function(value, key) { 31843 if (!isDefined(dst[key])) { 31844 dst[key] = value; 31845 } 31846 }); 31847} 31848 31849/** 31850 * @ngdoc directive 31851 * @name ngNonBindable 31852 * @restrict AC 31853 * @priority 1000 31854 * @element ANY 31855 * 31856 * @description 31857 * The `ngNonBindable` directive tells AngularJS not to compile or bind the contents of the current 31858 * DOM element, including directives on the element itself that have a lower priority than 31859 * `ngNonBindable`. This is useful if the element contains what appears to be AngularJS directives 31860 * and bindings but which should be ignored by AngularJS. This could be the case if you have a site 31861 * that displays snippets of code, for instance. 31862 * 31863 * @example 31864 * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, 31865 * but the one wrapped in `ngNonBindable` is left alone. 31866 * 31867 <example name="ng-non-bindable"> 31868 <file name="index.html"> 31869 <div>Normal: {{1 + 2}}</div> 31870 <div ng-non-bindable>Ignored: {{1 + 2}}</div> 31871 </file> 31872 <file name="protractor.js" type="protractor"> 31873 it('should check ng-non-bindable', function() { 31874 expect(element(by.binding('1 + 2')).getText()).toContain('3'); 31875 expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); 31876 }); 31877 </file> 31878 </example> 31879 */ 31880var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); 31881 31882/* exported ngOptionsDirective */ 31883 31884/* global jqLiteRemove */ 31885 31886var ngOptionsMinErr = minErr('ngOptions'); 31887 31888/** 31889 * @ngdoc directive 31890 * @name ngOptions 31891 * @restrict A 31892 * 31893 * @description 31894 * 31895 * The `ngOptions` attribute can be used to dynamically generate a list of `<option>` 31896 * elements for the `<select>` element using the array or object obtained by evaluating the 31897 * `ngOptions` comprehension expression. 31898 * 31899 * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of 31900 * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits: 31901 * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the 31902 * comprehension expression 31903 * - reduced memory consumption by not creating a new scope for each repeated instance 31904 * - increased render speed by creating the options in a documentFragment instead of individually 31905 * 31906 * When an item in the `<select>` menu is selected, the array element or object property 31907 * represented by the selected option will be bound to the model identified by the `ngModel` 31908 * directive. 31909 * 31910 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can 31911 * be nested into the `<select>` element. This element will then represent the `null` or "not selected" 31912 * option. See example below for demonstration. 31913 * 31914 * ## Complex Models (objects or collections) 31915 * 31916 * By default, `ngModel` watches the model by reference, not value. This is important to know when 31917 * binding the select to a model that is an object or a collection. 31918 * 31919 * One issue occurs if you want to preselect an option. For example, if you set 31920 * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection, 31921 * because the objects are not identical. So by default, you should always reference the item in your collection 31922 * for preselections, e.g.: `$scope.selected = $scope.collection[3]`. 31923 * 31924 * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity 31925 * of the item not by reference, but by the result of the `track by` expression. For example, if your 31926 * collection items have an id property, you would `track by item.id`. 31927 * 31928 * A different issue with objects or collections is that ngModel won't detect if an object property or 31929 * a collection item changes. For that reason, `ngOptions` additionally watches the model using 31930 * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute. 31931 * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection 31932 * has not changed identity, but only a property on the object or an item in the collection changes. 31933 * 31934 * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection 31935 * if the model is an array). This means that changing a property deeper than the first level inside the 31936 * object/collection will not trigger a re-rendering. 31937 * 31938 * ## `select` **`as`** 31939 * 31940 * Using `select` **`as`** will bind the result of the `select` expression to the model, but 31941 * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources) 31942 * or property name (for object data sources) of the value within the collection. If a **`track by`** expression 31943 * is used, the result of that expression will be set as the value of the `option` and `select` elements. 31944 * 31945 * 31946 * ### `select` **`as`** and **`track by`** 31947 * 31948 * <div class="alert alert-warning"> 31949 * Be careful when using `select` **`as`** and **`track by`** in the same expression. 31950 * </div> 31951 * 31952 * Given this array of items on the $scope: 31953 * 31954 * ```js 31955 * $scope.items = [{ 31956 * id: 1, 31957 * label: 'aLabel', 31958 * subItem: { name: 'aSubItem' } 31959 * }, { 31960 * id: 2, 31961 * label: 'bLabel', 31962 * subItem: { name: 'bSubItem' } 31963 * }]; 31964 * ``` 31965 * 31966 * This will work: 31967 * 31968 * ```html 31969 * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select> 31970 * ``` 31971 * ```js 31972 * $scope.selected = $scope.items[0]; 31973 * ``` 31974 * 31975 * but this will not work: 31976 * 31977 * ```html 31978 * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select> 31979 * ``` 31980 * ```js 31981 * $scope.selected = $scope.items[0].subItem; 31982 * ``` 31983 * 31984 * In both examples, the **`track by`** expression is applied successfully to each `item` in the 31985 * `items` array. Because the selected option has been set programmatically in the controller, the 31986 * **`track by`** expression is also applied to the `ngModel` value. In the first example, the 31987 * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with 31988 * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`** 31989 * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value 31990 * is not matched against any `<option>` and the `<select>` appears as having no selected value. 31991 * 31992 * 31993 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 31994 * @param {comprehension_expression} ngOptions in one of the following forms: 31995 * 31996 * * for array data sources: 31997 * * `label` **`for`** `value` **`in`** `array` 31998 * * `select` **`as`** `label` **`for`** `value` **`in`** `array` 31999 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` 32000 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` 32001 * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` 32002 * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` 32003 * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr` 32004 * (for including a filter with `track by`) 32005 * * for object data sources: 32006 * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` 32007 * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` 32008 * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` 32009 * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object` 32010 * * `select` **`as`** `label` **`group by`** `group` 32011 * **`for` `(`**`key`**`,`** `value`**`) in`** `object` 32012 * * `select` **`as`** `label` **`disable when`** `disable` 32013 * **`for` `(`**`key`**`,`** `value`**`) in`** `object` 32014 * 32015 * Where: 32016 * 32017 * * `array` / `object`: an expression which evaluates to an array / object to iterate over. 32018 * * `value`: local variable which will refer to each item in the `array` or each property value 32019 * of `object` during iteration. 32020 * * `key`: local variable which will refer to a property name in `object` during iteration. 32021 * * `label`: The result of this expression will be the label for `<option>` element. The 32022 * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). 32023 * * `select`: The result of this expression will be bound to the model of the parent `<select>` 32024 * element. If not specified, `select` expression will default to `value`. 32025 * * `group`: The result of this expression will be used to group options using the `<optgroup>` 32026 * DOM element. 32027 * * `disable`: The result of this expression will be used to disable the rendered `<option>` 32028 * element. Return `true` to disable. 32029 * * `trackexpr`: Used when working with an array of objects. The result of this expression will be 32030 * used to identify the objects in the array. The `trackexpr` will most likely refer to the 32031 * `value` variable (e.g. `value.propertyName`). With this the selection is preserved 32032 * even when the options are recreated (e.g. reloaded from the server). 32033 * @param {string=} name Property name of the form under which the control is published. 32034 * @param {string=} required The control is considered valid only if value is entered. 32035 * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to 32036 * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of 32037 * `required` when you want to data-bind to the `required` attribute. 32038 * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the 32039 * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive. 32040 * 32041 * @example 32042 <example module="selectExample" name="select"> 32043 <file name="index.html"> 32044 <script> 32045 angular.module('selectExample', []) 32046 .controller('ExampleController', ['$scope', function($scope) { 32047 $scope.colors = [ 32048 {name:'black', shade:'dark'}, 32049 {name:'white', shade:'light', notAnOption: true}, 32050 {name:'red', shade:'dark'}, 32051 {name:'blue', shade:'dark', notAnOption: true}, 32052 {name:'yellow', shade:'light', notAnOption: false} 32053 ]; 32054 $scope.myColor = $scope.colors[2]; // red 32055 }]); 32056 </script> 32057 <div ng-controller="ExampleController"> 32058 <ul> 32059 <li ng-repeat="color in colors"> 32060 <label>Name: <input ng-model="color.name"></label> 32061 <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label> 32062 <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button> 32063 </li> 32064 <li> 32065 <button ng-click="colors.push({})">add</button> 32066 </li> 32067 </ul> 32068 <hr/> 32069 <label>Color (null not allowed): 32070 <select ng-model="myColor" ng-options="color.name for color in colors"></select> 32071 </label><br/> 32072 <label>Color (null allowed): 32073 <span class="nullable"> 32074 <select ng-model="myColor" ng-options="color.name for color in colors"> 32075 <option value="">-- choose color --</option> 32076 </select> 32077 </span></label><br/> 32078 32079 <label>Color grouped by shade: 32080 <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors"> 32081 </select> 32082 </label><br/> 32083 32084 <label>Color grouped by shade, with some disabled: 32085 <select ng-model="myColor" 32086 ng-options="color.name group by color.shade disable when color.notAnOption for color in colors"> 32087 </select> 32088 </label><br/> 32089 32090 32091 32092 Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>. 32093 <br/> 32094 <hr/> 32095 Currently selected: {{ {selected_color:myColor} }} 32096 <div style="border:solid 1px black; height:20px" 32097 ng-style="{'background-color':myColor.name}"> 32098 </div> 32099 </div> 32100 </file> 32101 <file name="protractor.js" type="protractor"> 32102 it('should check ng-options', function() { 32103 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); 32104 element.all(by.model('myColor')).first().click(); 32105 element.all(by.css('select[ng-model="myColor"] option')).first().click(); 32106 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); 32107 element(by.css('.nullable select[ng-model="myColor"]')).click(); 32108 element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); 32109 expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); 32110 }); 32111 </file> 32112 </example> 32113 */ 32114 32115/* eslint-disable max-len */ 32116// //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999 32117var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([$\w][$\w]*)|(?:\(\s*([$\w][$\w]*)\s*,\s*([$\w][$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/; 32118 // 1: value expression (valueFn) 32119 // 2: label expression (displayFn) 32120 // 3: group by expression (groupByFn) 32121 // 4: disable when expression (disableWhenFn) 32122 // 5: array item variable name 32123 // 6: object item key variable name 32124 // 7: object item value variable name 32125 // 8: collection expression 32126 // 9: track by expression 32127/* eslint-enable */ 32128 32129 32130var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) { 32131 32132 function parseOptionsExpression(optionsExp, selectElement, scope) { 32133 32134 var match = optionsExp.match(NG_OPTIONS_REGEXP); 32135 if (!(match)) { 32136 throw ngOptionsMinErr('iexp', 32137 'Expected expression in form of ' + 32138 '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' + 32139 ' but got \'{0}\'. Element: {1}', 32140 optionsExp, startingTag(selectElement)); 32141 } 32142 32143 // Extract the parts from the ngOptions expression 32144 32145 // The variable name for the value of the item in the collection 32146 var valueName = match[5] || match[7]; 32147 // The variable name for the key of the item in the collection 32148 var keyName = match[6]; 32149 32150 // An expression that generates the viewValue for an option if there is a label expression 32151 var selectAs = / as /.test(match[0]) && match[1]; 32152 // An expression that is used to track the id of each object in the options collection 32153 var trackBy = match[9]; 32154 // An expression that generates the viewValue for an option if there is no label expression 32155 var valueFn = $parse(match[2] ? match[1] : valueName); 32156 var selectAsFn = selectAs && $parse(selectAs); 32157 var viewValueFn = selectAsFn || valueFn; 32158 var trackByFn = trackBy && $parse(trackBy); 32159 32160 // Get the value by which we are going to track the option 32161 // if we have a trackFn then use that (passing scope and locals) 32162 // otherwise just hash the given viewValue 32163 var getTrackByValueFn = trackBy ? 32164 function(value, locals) { return trackByFn(scope, locals); } : 32165 function getHashOfValue(value) { return hashKey(value); }; 32166 var getTrackByValue = function(value, key) { 32167 return getTrackByValueFn(value, getLocals(value, key)); 32168 }; 32169 32170 var displayFn = $parse(match[2] || match[1]); 32171 var groupByFn = $parse(match[3] || ''); 32172 var disableWhenFn = $parse(match[4] || ''); 32173 var valuesFn = $parse(match[8]); 32174 32175 var locals = {}; 32176 var getLocals = keyName ? function(value, key) { 32177 locals[keyName] = key; 32178 locals[valueName] = value; 32179 return locals; 32180 } : function(value) { 32181 locals[valueName] = value; 32182 return locals; 32183 }; 32184 32185 32186 function Option(selectValue, viewValue, label, group, disabled) { 32187 this.selectValue = selectValue; 32188 this.viewValue = viewValue; 32189 this.label = label; 32190 this.group = group; 32191 this.disabled = disabled; 32192 } 32193 32194 function getOptionValuesKeys(optionValues) { 32195 var optionValuesKeys; 32196 32197 if (!keyName && isArrayLike(optionValues)) { 32198 optionValuesKeys = optionValues; 32199 } else { 32200 // if object, extract keys, in enumeration order, unsorted 32201 optionValuesKeys = []; 32202 for (var itemKey in optionValues) { 32203 if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') { 32204 optionValuesKeys.push(itemKey); 32205 } 32206 } 32207 } 32208 return optionValuesKeys; 32209 } 32210 32211 return { 32212 trackBy: trackBy, 32213 getTrackByValue: getTrackByValue, 32214 getWatchables: $parse(valuesFn, function(optionValues) { 32215 // Create a collection of things that we would like to watch (watchedArray) 32216 // so that they can all be watched using a single $watchCollection 32217 // that only runs the handler once if anything changes 32218 var watchedArray = []; 32219 optionValues = optionValues || []; 32220 32221 var optionValuesKeys = getOptionValuesKeys(optionValues); 32222 var optionValuesLength = optionValuesKeys.length; 32223 for (var index = 0; index < optionValuesLength; index++) { 32224 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index]; 32225 var value = optionValues[key]; 32226 32227 var locals = getLocals(value, key); 32228 var selectValue = getTrackByValueFn(value, locals); 32229 watchedArray.push(selectValue); 32230 32231 // Only need to watch the displayFn if there is a specific label expression 32232 if (match[2] || match[1]) { 32233 var label = displayFn(scope, locals); 32234 watchedArray.push(label); 32235 } 32236 32237 // Only need to watch the disableWhenFn if there is a specific disable expression 32238 if (match[4]) { 32239 var disableWhen = disableWhenFn(scope, locals); 32240 watchedArray.push(disableWhen); 32241 } 32242 } 32243 return watchedArray; 32244 }), 32245 32246 getOptions: function() { 32247 32248 var optionItems = []; 32249 var selectValueMap = {}; 32250 32251 // The option values were already computed in the `getWatchables` fn, 32252 // which must have been called to trigger `getOptions` 32253 var optionValues = valuesFn(scope) || []; 32254 var optionValuesKeys = getOptionValuesKeys(optionValues); 32255 var optionValuesLength = optionValuesKeys.length; 32256 32257 for (var index = 0; index < optionValuesLength; index++) { 32258 var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index]; 32259 var value = optionValues[key]; 32260 var locals = getLocals(value, key); 32261 var viewValue = viewValueFn(scope, locals); 32262 var selectValue = getTrackByValueFn(viewValue, locals); 32263 var label = displayFn(scope, locals); 32264 var group = groupByFn(scope, locals); 32265 var disabled = disableWhenFn(scope, locals); 32266 var optionItem = new Option(selectValue, viewValue, label, group, disabled); 32267 32268 optionItems.push(optionItem); 32269 selectValueMap[selectValue] = optionItem; 32270 } 32271 32272 return { 32273 items: optionItems, 32274 selectValueMap: selectValueMap, 32275 getOptionFromViewValue: function(value) { 32276 return selectValueMap[getTrackByValue(value)]; 32277 }, 32278 getViewValueFromOption: function(option) { 32279 // If the viewValue could be an object that may be mutated by the application, 32280 // we need to make a copy and not return the reference to the value on the option. 32281 return trackBy ? copy(option.viewValue) : option.viewValue; 32282 } 32283 }; 32284 } 32285 }; 32286 } 32287 32288 32289 // Support: IE 9 only 32290 // We can't just jqLite('<option>') since jqLite is not smart enough 32291 // to create it in <select> and IE barfs otherwise. 32292 var optionTemplate = window.document.createElement('option'), 32293 optGroupTemplate = window.document.createElement('optgroup'); 32294 32295 function ngOptionsPostLink(scope, selectElement, attr, ctrls) { 32296 32297 var selectCtrl = ctrls[0]; 32298 var ngModelCtrl = ctrls[1]; 32299 var multiple = attr.multiple; 32300 32301 // The emptyOption allows the application developer to provide their own custom "empty" 32302 // option when the viewValue does not match any of the option values. 32303 for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) { 32304 if (children[i].value === '') { 32305 selectCtrl.hasEmptyOption = true; 32306 selectCtrl.emptyOption = children.eq(i); 32307 break; 32308 } 32309 } 32310 32311 // The empty option will be compiled and rendered before we first generate the options 32312 selectElement.empty(); 32313 32314 var providedEmptyOption = !!selectCtrl.emptyOption; 32315 32316 var unknownOption = jqLite(optionTemplate.cloneNode(false)); 32317 unknownOption.val('?'); 32318 32319 var options; 32320 var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope); 32321 // This stores the newly created options before they are appended to the select. 32322 // Since the contents are removed from the fragment when it is appended, 32323 // we only need to create it once. 32324 var listFragment = $document[0].createDocumentFragment(); 32325 32326 // Overwrite the implementation. ngOptions doesn't use hashes 32327 selectCtrl.generateUnknownOptionValue = function(val) { 32328 return '?'; 32329 }; 32330 32331 // Update the controller methods for multiple selectable options 32332 if (!multiple) { 32333 32334 selectCtrl.writeValue = function writeNgOptionsValue(value) { 32335 // The options might not be defined yet when ngModel tries to render 32336 if (!options) return; 32337 32338 var selectedOption = selectElement[0].options[selectElement[0].selectedIndex]; 32339 var option = options.getOptionFromViewValue(value); 32340 32341 // Make sure to remove the selected attribute from the previously selected option 32342 // Otherwise, screen readers might get confused 32343 if (selectedOption) selectedOption.removeAttribute('selected'); 32344 32345 if (option) { 32346 // Don't update the option when it is already selected. 32347 // For example, the browser will select the first option by default. In that case, 32348 // most properties are set automatically - except the `selected` attribute, which we 32349 // set always 32350 32351 if (selectElement[0].value !== option.selectValue) { 32352 selectCtrl.removeUnknownOption(); 32353 32354 selectElement[0].value = option.selectValue; 32355 option.element.selected = true; 32356 } 32357 32358 option.element.setAttribute('selected', 'selected'); 32359 } else { 32360 selectCtrl.selectUnknownOrEmptyOption(value); 32361 } 32362 }; 32363 32364 selectCtrl.readValue = function readNgOptionsValue() { 32365 32366 var selectedOption = options.selectValueMap[selectElement.val()]; 32367 32368 if (selectedOption && !selectedOption.disabled) { 32369 selectCtrl.unselectEmptyOption(); 32370 selectCtrl.removeUnknownOption(); 32371 return options.getViewValueFromOption(selectedOption); 32372 } 32373 return null; 32374 }; 32375 32376 // If we are using `track by` then we must watch the tracked value on the model 32377 // since ngModel only watches for object identity change 32378 // FIXME: When a user selects an option, this watch will fire needlessly 32379 if (ngOptions.trackBy) { 32380 scope.$watch( 32381 function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); }, 32382 function() { ngModelCtrl.$render(); } 32383 ); 32384 } 32385 32386 } else { 32387 32388 selectCtrl.writeValue = function writeNgOptionsMultiple(values) { 32389 // The options might not be defined yet when ngModel tries to render 32390 if (!options) return; 32391 32392 // Only set `<option>.selected` if necessary, in order to prevent some browsers from 32393 // scrolling to `<option>` elements that are outside the `<select>` element's viewport. 32394 var selectedOptions = values && values.map(getAndUpdateSelectedOption) || []; 32395 32396 options.items.forEach(function(option) { 32397 if (option.element.selected && !includes(selectedOptions, option)) { 32398 option.element.selected = false; 32399 } 32400 }); 32401 }; 32402 32403 32404 selectCtrl.readValue = function readNgOptionsMultiple() { 32405 var selectedValues = selectElement.val() || [], 32406 selections = []; 32407 32408 forEach(selectedValues, function(value) { 32409 var option = options.selectValueMap[value]; 32410 if (option && !option.disabled) selections.push(options.getViewValueFromOption(option)); 32411 }); 32412 32413 return selections; 32414 }; 32415 32416 // If we are using `track by` then we must watch these tracked values on the model 32417 // since ngModel only watches for object identity change 32418 if (ngOptions.trackBy) { 32419 32420 scope.$watchCollection(function() { 32421 if (isArray(ngModelCtrl.$viewValue)) { 32422 return ngModelCtrl.$viewValue.map(function(value) { 32423 return ngOptions.getTrackByValue(value); 32424 }); 32425 } 32426 }, function() { 32427 ngModelCtrl.$render(); 32428 }); 32429 32430 } 32431 } 32432 32433 if (providedEmptyOption) { 32434 32435 // compile the element since there might be bindings in it 32436 $compile(selectCtrl.emptyOption)(scope); 32437 32438 selectElement.prepend(selectCtrl.emptyOption); 32439 32440 if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) { 32441 // This means the empty option has currently no actual DOM node, probably because 32442 // it has been modified by a transclusion directive. 32443 selectCtrl.hasEmptyOption = false; 32444 32445 // Redefine the registerOption function, which will catch 32446 // options that are added by ngIf etc. (rendering of the node is async because of 32447 // lazy transclusion) 32448 selectCtrl.registerOption = function(optionScope, optionEl) { 32449 if (optionEl.val() === '') { 32450 selectCtrl.hasEmptyOption = true; 32451 selectCtrl.emptyOption = optionEl; 32452 selectCtrl.emptyOption.removeClass('ng-scope'); 32453 // This ensures the new empty option is selected if previously no option was selected 32454 ngModelCtrl.$render(); 32455 32456 optionEl.on('$destroy', function() { 32457 var needsRerender = selectCtrl.$isEmptyOptionSelected(); 32458 32459 selectCtrl.hasEmptyOption = false; 32460 selectCtrl.emptyOption = undefined; 32461 32462 if (needsRerender) ngModelCtrl.$render(); 32463 }); 32464 } 32465 }; 32466 32467 } else { 32468 // remove the class, which is added automatically because we recompile the element and it 32469 // becomes the compilation root 32470 selectCtrl.emptyOption.removeClass('ng-scope'); 32471 } 32472 32473 } 32474 32475 // We will re-render the option elements if the option values or labels change 32476 scope.$watchCollection(ngOptions.getWatchables, updateOptions); 32477 32478 // ------------------------------------------------------------------ // 32479 32480 function addOptionElement(option, parent) { 32481 var optionElement = optionTemplate.cloneNode(false); 32482 parent.appendChild(optionElement); 32483 updateOptionElement(option, optionElement); 32484 } 32485 32486 function getAndUpdateSelectedOption(viewValue) { 32487 var option = options.getOptionFromViewValue(viewValue); 32488 var element = option && option.element; 32489 32490 if (element && !element.selected) element.selected = true; 32491 32492 return option; 32493 } 32494 32495 function updateOptionElement(option, element) { 32496 option.element = element; 32497 element.disabled = option.disabled; 32498 // Support: IE 11 only, Edge 12-13 only 32499 // NOTE: The label must be set before the value, otherwise IE 11 & Edge create unresponsive 32500 // selects in certain circumstances when multiple selects are next to each other and display 32501 // the option list in listbox style, i.e. the select is [multiple], or specifies a [size]. 32502 // See https://github.com/angular/angular.js/issues/11314 for more info. 32503 // This is unfortunately untestable with unit / e2e tests 32504 if (option.label !== element.label) { 32505 element.label = option.label; 32506 element.textContent = option.label; 32507 } 32508 element.value = option.selectValue; 32509 } 32510 32511 function updateOptions() { 32512 var previousValue = options && selectCtrl.readValue(); 32513 32514 // We must remove all current options, but cannot simply set innerHTML = null 32515 // since the providedEmptyOption might have an ngIf on it that inserts comments which we 32516 // must preserve. 32517 // Instead, iterate over the current option elements and remove them or their optgroup 32518 // parents 32519 if (options) { 32520 32521 for (var i = options.items.length - 1; i >= 0; i--) { 32522 var option = options.items[i]; 32523 if (isDefined(option.group)) { 32524 jqLiteRemove(option.element.parentNode); 32525 } else { 32526 jqLiteRemove(option.element); 32527 } 32528 } 32529 } 32530 32531 options = ngOptions.getOptions(); 32532 32533 var groupElementMap = {}; 32534 32535 options.items.forEach(function addOption(option) { 32536 var groupElement; 32537 32538 if (isDefined(option.group)) { 32539 32540 // This option is to live in a group 32541 // See if we have already created this group 32542 groupElement = groupElementMap[option.group]; 32543 32544 if (!groupElement) { 32545 32546 groupElement = optGroupTemplate.cloneNode(false); 32547 listFragment.appendChild(groupElement); 32548 32549 // Update the label on the group element 32550 // "null" is special cased because of Safari 32551 groupElement.label = option.group === null ? 'null' : option.group; 32552 32553 // Store it for use later 32554 groupElementMap[option.group] = groupElement; 32555 } 32556 32557 addOptionElement(option, groupElement); 32558 32559 } else { 32560 32561 // This option is not in a group 32562 addOptionElement(option, listFragment); 32563 } 32564 }); 32565 32566 selectElement[0].appendChild(listFragment); 32567 32568 ngModelCtrl.$render(); 32569 32570 // Check to see if the value has changed due to the update to the options 32571 if (!ngModelCtrl.$isEmpty(previousValue)) { 32572 var nextValue = selectCtrl.readValue(); 32573 var isNotPrimitive = ngOptions.trackBy || multiple; 32574 if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) { 32575 ngModelCtrl.$setViewValue(nextValue); 32576 ngModelCtrl.$render(); 32577 } 32578 } 32579 } 32580 } 32581 32582 return { 32583 restrict: 'A', 32584 terminal: true, 32585 require: ['select', 'ngModel'], 32586 link: { 32587 pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) { 32588 // Deactivate the SelectController.register method to prevent 32589 // option directives from accidentally registering themselves 32590 // (and unwanted $destroy handlers etc.) 32591 ctrls[0].registerOption = noop; 32592 }, 32593 post: ngOptionsPostLink 32594 } 32595 }; 32596}]; 32597 32598/** 32599 * @ngdoc directive 32600 * @name ngPluralize 32601 * @restrict EA 32602 * 32603 * @description 32604 * `ngPluralize` is a directive that displays messages according to en-US localization rules. 32605 * These rules are bundled with angular.js, but can be overridden 32606 * (see {@link guide/i18n AngularJS i18n} dev guide). You configure ngPluralize directive 32607 * by specifying the mappings between 32608 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) 32609 * and the strings to be displayed. 32610 * 32611 * ## Plural categories and explicit number rules 32612 * There are two 32613 * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) 32614 * in AngularJS's default en-US locale: "one" and "other". 32615 * 32616 * While a plural category may match many numbers (for example, in en-US locale, "other" can match 32617 * any number that is not 1), an explicit number rule can only match one number. For example, the 32618 * explicit number rule for "3" matches the number 3. There are examples of plural categories 32619 * and explicit number rules throughout the rest of this documentation. 32620 * 32621 * ## Configuring ngPluralize 32622 * You configure ngPluralize by providing 2 attributes: `count` and `when`. 32623 * You can also provide an optional attribute, `offset`. 32624 * 32625 * The value of the `count` attribute can be either a string or an {@link guide/expression 32626 * AngularJS expression}; these are evaluated on the current scope for its bound value. 32627 * 32628 * The `when` attribute specifies the mappings between plural categories and the actual 32629 * string to be displayed. The value of the attribute should be a JSON object. 32630 * 32631 * The following example shows how to configure ngPluralize: 32632 * 32633 * ```html 32634 * <ng-pluralize count="personCount" 32635 when="{'0': 'Nobody is viewing.', 32636 * 'one': '1 person is viewing.', 32637 * 'other': '{} people are viewing.'}"> 32638 * </ng-pluralize> 32639 *``` 32640 * 32641 * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not 32642 * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" 32643 * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for 32644 * other numbers, for example 12, so that instead of showing "12 people are viewing", you can 32645 * show "a dozen people are viewing". 32646 * 32647 * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted 32648 * into pluralized strings. In the previous example, AngularJS will replace `{}` with 32649 * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder 32650 * for <span ng-non-bindable>{{numberExpression}}</span>. 32651 * 32652 * If no rule is defined for a category, then an empty string is displayed and a warning is generated. 32653 * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`. 32654 * 32655 * ## Configuring ngPluralize with offset 32656 * The `offset` attribute allows further customization of pluralized text, which can result in 32657 * a better user experience. For example, instead of the message "4 people are viewing this document", 32658 * you might display "John, Kate and 2 others are viewing this document". 32659 * The offset attribute allows you to offset a number by any desired value. 32660 * Let's take a look at an example: 32661 * 32662 * ```html 32663 * <ng-pluralize count="personCount" offset=2 32664 * when="{'0': 'Nobody is viewing.', 32665 * '1': '{{person1}} is viewing.', 32666 * '2': '{{person1}} and {{person2}} are viewing.', 32667 * 'one': '{{person1}}, {{person2}} and one other person are viewing.', 32668 * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> 32669 * </ng-pluralize> 32670 * ``` 32671 * 32672 * Notice that we are still using two plural categories(one, other), but we added 32673 * three explicit number rules 0, 1 and 2. 32674 * When one person, perhaps John, views the document, "John is viewing" will be shown. 32675 * When three people view the document, no explicit number rule is found, so 32676 * an offset of 2 is taken off 3, and AngularJS uses 1 to decide the plural category. 32677 * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing" 32678 * is shown. 32679 * 32680 * Note that when you specify offsets, you must provide explicit number rules for 32681 * numbers from 0 up to and including the offset. If you use an offset of 3, for example, 32682 * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for 32683 * plural categories "one" and "other". 32684 * 32685 * @param {string|expression} count The variable to be bound to. 32686 * @param {string} when The mapping between plural category to its corresponding strings. 32687 * @param {number=} offset Offset to deduct from the total number. 32688 * 32689 * @example 32690 <example module="pluralizeExample" name="ng-pluralize"> 32691 <file name="index.html"> 32692 <script> 32693 angular.module('pluralizeExample', []) 32694 .controller('ExampleController', ['$scope', function($scope) { 32695 $scope.person1 = 'Igor'; 32696 $scope.person2 = 'Misko'; 32697 $scope.personCount = 1; 32698 }]); 32699 </script> 32700 <div ng-controller="ExampleController"> 32701 <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/> 32702 <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/> 32703 <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/> 32704 32705 <!--- Example with simple pluralization rules for en locale ---> 32706 Without Offset: 32707 <ng-pluralize count="personCount" 32708 when="{'0': 'Nobody is viewing.', 32709 'one': '1 person is viewing.', 32710 'other': '{} people are viewing.'}"> 32711 </ng-pluralize><br> 32712 32713 <!--- Example with offset ---> 32714 With Offset(2): 32715 <ng-pluralize count="personCount" offset=2 32716 when="{'0': 'Nobody is viewing.', 32717 '1': '{{person1}} is viewing.', 32718 '2': '{{person1}} and {{person2}} are viewing.', 32719 'one': '{{person1}}, {{person2}} and one other person are viewing.', 32720 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> 32721 </ng-pluralize> 32722 </div> 32723 </file> 32724 <file name="protractor.js" type="protractor"> 32725 it('should show correct pluralized string', function() { 32726 var withoutOffset = element.all(by.css('ng-pluralize')).get(0); 32727 var withOffset = element.all(by.css('ng-pluralize')).get(1); 32728 var countInput = element(by.model('personCount')); 32729 32730 expect(withoutOffset.getText()).toEqual('1 person is viewing.'); 32731 expect(withOffset.getText()).toEqual('Igor is viewing.'); 32732 32733 countInput.clear(); 32734 countInput.sendKeys('0'); 32735 32736 expect(withoutOffset.getText()).toEqual('Nobody is viewing.'); 32737 expect(withOffset.getText()).toEqual('Nobody is viewing.'); 32738 32739 countInput.clear(); 32740 countInput.sendKeys('2'); 32741 32742 expect(withoutOffset.getText()).toEqual('2 people are viewing.'); 32743 expect(withOffset.getText()).toEqual('Igor and Misko are viewing.'); 32744 32745 countInput.clear(); 32746 countInput.sendKeys('3'); 32747 32748 expect(withoutOffset.getText()).toEqual('3 people are viewing.'); 32749 expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.'); 32750 32751 countInput.clear(); 32752 countInput.sendKeys('4'); 32753 32754 expect(withoutOffset.getText()).toEqual('4 people are viewing.'); 32755 expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.'); 32756 }); 32757 it('should show data-bound names', function() { 32758 var withOffset = element.all(by.css('ng-pluralize')).get(1); 32759 var personCount = element(by.model('personCount')); 32760 var person1 = element(by.model('person1')); 32761 var person2 = element(by.model('person2')); 32762 personCount.clear(); 32763 personCount.sendKeys('4'); 32764 person1.clear(); 32765 person1.sendKeys('Di'); 32766 person2.clear(); 32767 person2.sendKeys('Vojta'); 32768 expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.'); 32769 }); 32770 </file> 32771 </example> 32772 */ 32773var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) { 32774 var BRACE = /{}/g, 32775 IS_WHEN = /^when(Minus)?(.+)$/; 32776 32777 return { 32778 link: function(scope, element, attr) { 32779 var numberExp = attr.count, 32780 whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs 32781 offset = attr.offset || 0, 32782 whens = scope.$eval(whenExp) || {}, 32783 whensExpFns = {}, 32784 startSymbol = $interpolate.startSymbol(), 32785 endSymbol = $interpolate.endSymbol(), 32786 braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol, 32787 watchRemover = angular.noop, 32788 lastCount; 32789 32790 forEach(attr, function(expression, attributeName) { 32791 var tmpMatch = IS_WHEN.exec(attributeName); 32792 if (tmpMatch) { 32793 var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]); 32794 whens[whenKey] = element.attr(attr.$attr[attributeName]); 32795 } 32796 }); 32797 forEach(whens, function(expression, key) { 32798 whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement)); 32799 32800 }); 32801 32802 scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) { 32803 var count = parseFloat(newVal); 32804 var countIsNaN = isNumberNaN(count); 32805 32806 if (!countIsNaN && !(count in whens)) { 32807 // If an explicit number rule such as 1, 2, 3... is defined, just use it. 32808 // Otherwise, check it against pluralization rules in $locale service. 32809 count = $locale.pluralCat(count - offset); 32810 } 32811 32812 // If both `count` and `lastCount` are NaN, we don't need to re-register a watch. 32813 // In JS `NaN !== NaN`, so we have to explicitly check. 32814 if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) { 32815 watchRemover(); 32816 var whenExpFn = whensExpFns[count]; 32817 if (isUndefined(whenExpFn)) { 32818 if (newVal != null) { 32819 $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp); 32820 } 32821 watchRemover = noop; 32822 updateElementText(); 32823 } else { 32824 watchRemover = scope.$watch(whenExpFn, updateElementText); 32825 } 32826 lastCount = count; 32827 } 32828 }); 32829 32830 function updateElementText(newText) { 32831 element.text(newText || ''); 32832 } 32833 } 32834 }; 32835}]; 32836 32837/** 32838 * @ngdoc directive 32839 * @name ngRef 32840 * @restrict A 32841 * 32842 * @description 32843 * The `ngRef` attribute tells AngularJS to assign the controller of a component (or a directive) 32844 * to the given property in the current scope. It is also possible to add the jqlite-wrapped DOM 32845 * element to the scope. 32846 * 32847 * If the element with `ngRef` is destroyed `null` is assigned to the property. 32848 * 32849 * Note that if you want to assign from a child into the parent scope, you must initialize the 32850 * target property on the parent scope, otherwise `ngRef` will assign on the child scope. 32851 * This commonly happens when assigning elements or components wrapped in {@link ngIf} or 32852 * {@link ngRepeat}. See the second example below. 32853 * 32854 * 32855 * @element ANY 32856 * @param {string} ngRef property name - A valid AngularJS expression identifier to which the 32857 * controller or jqlite-wrapped DOM element will be bound. 32858 * @param {string=} ngRefRead read value - The name of a directive (or component) on this element, 32859 * or the special string `$element`. If a name is provided, `ngRef` will 32860 * assign the matching controller. If `$element` is provided, the element 32861 * itself is assigned (even if a controller is available). 32862 * 32863 * 32864 * @example 32865 * ### Simple toggle 32866 * This example shows how the controller of the component toggle 32867 * is reused in the template through the scope to use its logic. 32868 * <example name="ng-ref-component" module="myApp"> 32869 * <file name="index.html"> 32870 * <my-toggle ng-ref="myToggle"></my-toggle> 32871 * <button ng-click="myToggle.toggle()">Toggle</button> 32872 * <div ng-show="myToggle.isOpen()"> 32873 * You are using a component in the same template to show it. 32874 * </div> 32875 * </file> 32876 * <file name="index.js"> 32877 * angular.module('myApp', []) 32878 * .component('myToggle', { 32879 * controller: function ToggleController() { 32880 * var opened = false; 32881 * this.isOpen = function() { return opened; }; 32882 * this.toggle = function() { opened = !opened; }; 32883 * } 32884 * }); 32885 * </file> 32886 * <file name="protractor.js" type="protractor"> 32887 * it('should publish the toggle into the scope', function() { 32888 * var toggle = element(by.buttonText('Toggle')); 32889 * expect(toggle.evaluate('myToggle.isOpen()')).toEqual(false); 32890 * toggle.click(); 32891 * expect(toggle.evaluate('myToggle.isOpen()')).toEqual(true); 32892 * }); 32893 * </file> 32894 * </example> 32895 * 32896 * @example 32897 * ### ngRef inside scopes 32898 * This example shows how `ngRef` works with child scopes. The `ngRepeat`-ed `myWrapper` components 32899 * are assigned to the scope of `myRoot`, because the `toggles` property has been initialized. 32900 * The repeated `myToggle` components are published to the child scopes created by `ngRepeat`. 32901 * `ngIf` behaves similarly - the assignment of `myToggle` happens in the `ngIf` child scope, 32902 * because the target property has not been initialized on the `myRoot` component controller. 32903 * 32904 * <example name="ng-ref-scopes" module="myApp"> 32905 * <file name="index.html"> 32906 * <my-root></my-root> 32907 * </file> 32908 * <file name="index.js"> 32909 * angular.module('myApp', []) 32910 * .component('myRoot', { 32911 * templateUrl: 'root.html', 32912 * controller: function() { 32913 * this.wrappers = []; // initialize the array so that the wrappers are assigned into the parent scope 32914 * } 32915 * }) 32916 * .component('myToggle', { 32917 * template: '<strong>myToggle</strong><button ng-click="$ctrl.toggle()" ng-transclude></button>', 32918 * transclude: true, 32919 * controller: function ToggleController() { 32920 * var opened = false; 32921 * this.isOpen = function() { return opened; }; 32922 * this.toggle = function() { opened = !opened; }; 32923 * } 32924 * }) 32925 * .component('myWrapper', { 32926 * transclude: true, 32927 * template: '<strong>myWrapper</strong>' + 32928 * '<div>ngRepeatToggle.isOpen(): {{$ctrl.ngRepeatToggle.isOpen() | json}}</div>' + 32929 * '<my-toggle ng-ref="$ctrl.ngRepeatToggle"><ng-transclude></ng-transclude></my-toggle>' 32930 * }); 32931 * </file> 32932 * <file name="root.html"> 32933 * <strong>myRoot</strong> 32934 * <my-toggle ng-ref="$ctrl.outerToggle">Outer Toggle</my-toggle> 32935 * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div> 32936 * <div><em>wrappers assigned to root</em><br> 32937 * <div ng-repeat="wrapper in $ctrl.wrappers"> 32938 * wrapper.ngRepeatToggle.isOpen(): {{wrapper.ngRepeatToggle.isOpen() | json}} 32939 * </div> 32940 * 32941 * <ul> 32942 * <li ng-repeat="(index, value) in [1,2,3]"> 32943 * <strong>ngRepeat</strong> 32944 * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div> 32945 * <my-wrapper ng-ref="$ctrl.wrappers[index]">ngRepeat Toggle {{$index + 1}}</my-wrapper> 32946 * </li> 32947 * </ul> 32948 * 32949 * <div>ngIfToggle.isOpen(): {{ngIfToggle.isOpen()}} // This is always undefined because it's 32950 * assigned to the child scope created by ngIf. 32951 * </div> 32952 * <div ng-if="true"> 32953 <strong>ngIf</strong> 32954 * <my-toggle ng-ref="ngIfToggle">ngIf Toggle</my-toggle> 32955 * <div>ngIfToggle.isOpen(): {{ngIfToggle.isOpen() | json}}</div> 32956 * <div>outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}</div> 32957 * </div> 32958 * </file> 32959 * <file name="styles.css"> 32960 * ul { 32961 * list-style: none; 32962 * padding-left: 0; 32963 * } 32964 * 32965 * li[ng-repeat] { 32966 * background: lightgreen; 32967 * padding: 8px; 32968 * margin: 8px; 32969 * } 32970 * 32971 * [ng-if] { 32972 * background: lightgrey; 32973 * padding: 8px; 32974 * } 32975 * 32976 * my-root { 32977 * background: lightgoldenrodyellow; 32978 * padding: 8px; 32979 * display: block; 32980 * } 32981 * 32982 * my-wrapper { 32983 * background: lightsalmon; 32984 * padding: 8px; 32985 * display: block; 32986 * } 32987 * 32988 * my-toggle { 32989 * background: lightblue; 32990 * padding: 8px; 32991 * display: block; 32992 * } 32993 * </file> 32994 * <file name="protractor.js" type="protractor"> 32995 * var OuterToggle = function() { 32996 * this.toggle = function() { 32997 * element(by.buttonText('Outer Toggle')).click(); 32998 * }; 32999 * this.isOpen = function() { 33000 * return element.all(by.binding('outerToggle.isOpen()')).first().getText(); 33001 * }; 33002 * }; 33003 * var NgRepeatToggle = function(i) { 33004 * var parent = element.all(by.repeater('(index, value) in [1,2,3]')).get(i - 1); 33005 * this.toggle = function() { 33006 * element(by.buttonText('ngRepeat Toggle ' + i)).click(); 33007 * }; 33008 * this.isOpen = function() { 33009 * return parent.element(by.binding('ngRepeatToggle.isOpen() | json')).getText(); 33010 * }; 33011 * this.isOuterOpen = function() { 33012 * return parent.element(by.binding('outerToggle.isOpen() | json')).getText(); 33013 * }; 33014 * }; 33015 * var NgRepeatToggles = function() { 33016 * var toggles = [1,2,3].map(function(i) { return new NgRepeatToggle(i); }); 33017 * this.forEach = function(fn) { 33018 * toggles.forEach(fn); 33019 * }; 33020 * this.isOuterOpen = function(i) { 33021 * return toggles[i - 1].isOuterOpen(); 33022 * }; 33023 * }; 33024 * var NgIfToggle = function() { 33025 * var parent = element(by.css('[ng-if]')); 33026 * this.toggle = function() { 33027 * element(by.buttonText('ngIf Toggle')).click(); 33028 * }; 33029 * this.isOpen = function() { 33030 * return by.binding('ngIfToggle.isOpen() | json').getText(); 33031 * }; 33032 * this.isOuterOpen = function() { 33033 * return parent.element(by.binding('outerToggle.isOpen() | json')).getText(); 33034 * }; 33035 * }; 33036 * 33037 * it('should toggle the outer toggle', function() { 33038 * var outerToggle = new OuterToggle(); 33039 * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false'); 33040 * outerToggle.toggle(); 33041 * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true'); 33042 * }); 33043 * 33044 * it('should toggle all outer toggles', function() { 33045 * var outerToggle = new OuterToggle(); 33046 * var repeatToggles = new NgRepeatToggles(); 33047 * var ifToggle = new NgIfToggle(); 33048 * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false'); 33049 * expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): false'); 33050 * expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): false'); 33051 * expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): false'); 33052 * expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false'); 33053 * outerToggle.toggle(); 33054 * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true'); 33055 * expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): true'); 33056 * expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): true'); 33057 * expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): true'); 33058 * expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): true'); 33059 * }); 33060 * 33061 * it('should toggle each repeat iteration separately', function() { 33062 * var repeatToggles = new NgRepeatToggles(); 33063 * 33064 * repeatToggles.forEach(function(repeatToggle) { 33065 * expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): false'); 33066 * expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false'); 33067 * repeatToggle.toggle(); 33068 * expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): true'); 33069 * expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false'); 33070 * }); 33071 * }); 33072 * </file> 33073 * </example> 33074 * 33075 */ 33076 33077var ngRefMinErr = minErr('ngRef'); 33078 33079var ngRefDirective = ['$parse', function($parse) { 33080 return { 33081 priority: -1, // Needed for compatibility with element transclusion on the same element 33082 restrict: 'A', 33083 compile: function(tElement, tAttrs) { 33084 // Get the expected controller name, converts <data-some-thing> into "someThing" 33085 var controllerName = directiveNormalize(nodeName_(tElement)); 33086 33087 // Get the expression for value binding 33088 var getter = $parse(tAttrs.ngRef); 33089 var setter = getter.assign || function() { 33090 throw ngRefMinErr('nonassign', 'Expression in ngRef="{0}" is non-assignable!', tAttrs.ngRef); 33091 }; 33092 33093 return function(scope, element, attrs) { 33094 var refValue; 33095 33096 if (attrs.hasOwnProperty('ngRefRead')) { 33097 if (attrs.ngRefRead === '$element') { 33098 refValue = element; 33099 } else { 33100 refValue = element.data('$' + attrs.ngRefRead + 'Controller'); 33101 33102 if (!refValue) { 33103 throw ngRefMinErr( 33104 'noctrl', 33105 'The controller for ngRefRead="{0}" could not be found on ngRef="{1}"', 33106 attrs.ngRefRead, 33107 tAttrs.ngRef 33108 ); 33109 } 33110 } 33111 } else { 33112 refValue = element.data('$' + controllerName + 'Controller'); 33113 } 33114 33115 refValue = refValue || element; 33116 33117 setter(scope, refValue); 33118 33119 // when the element is removed, remove it (nullify it) 33120 element.on('$destroy', function() { 33121 // only remove it if value has not changed, 33122 // because animations (and other procedures) may duplicate elements 33123 if (getter(scope) === refValue) { 33124 setter(scope, null); 33125 } 33126 }); 33127 }; 33128 } 33129 }; 33130}]; 33131 33132/* exported ngRepeatDirective */ 33133 33134/** 33135 * @ngdoc directive 33136 * @name ngRepeat 33137 * @multiElement 33138 * @restrict A 33139 * 33140 * @description 33141 * The `ngRepeat` directive instantiates a template once per item from a collection. Each template 33142 * instance gets its own scope, where the given loop variable is set to the current collection item, 33143 * and `$index` is set to the item index or key. 33144 * 33145 * Special properties are exposed on the local scope of each template instance, including: 33146 * 33147 * | Variable | Type | Details | 33148 * |-----------|-----------------|-----------------------------------------------------------------------------| 33149 * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) | 33150 * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. | 33151 * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. | 33152 * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. | 33153 * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | 33154 * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | 33155 * 33156 * <div class="alert alert-info"> 33157 * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. 33158 * This may be useful when, for instance, nesting ngRepeats. 33159 * </div> 33160 * 33161 * 33162 * ## Iterating over object properties 33163 * 33164 * It is possible to get `ngRepeat` to iterate over the properties of an object using the following 33165 * syntax: 33166 * 33167 * ```js 33168 * <div ng-repeat="(key, value) in myObj"> ... </div> 33169 * ``` 33170 * 33171 * However, there are a few limitations compared to array iteration: 33172 * 33173 * - The JavaScript specification does not define the order of keys 33174 * returned for an object, so AngularJS relies on the order returned by the browser 33175 * when running `for key in myObj`. Browsers generally follow the strategy of providing 33176 * keys in the order in which they were defined, although there are exceptions when keys are deleted 33177 * and reinstated. See the 33178 * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes). 33179 * 33180 * - `ngRepeat` will silently *ignore* object keys starting with `$`, because 33181 * it's a prefix used by AngularJS for public (`$`) and private (`$$`) properties. 33182 * 33183 * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with 33184 * objects, and will throw an error if used with one. 33185 * 33186 * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array 33187 * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could 33188 * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter) 33189 * or implement a `$watch` on the object yourself. 33190 * 33191 * 33192 * ## Tracking and Duplicates 33193 * 33194 * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in 33195 * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM: 33196 * 33197 * * When an item is added, a new instance of the template is added to the DOM. 33198 * * When an item is removed, its template instance is removed from the DOM. 33199 * * When items are reordered, their respective templates are reordered in the DOM. 33200 * 33201 * To minimize creation of DOM elements, `ngRepeat` uses a function 33202 * to "keep track" of all items in the collection and their corresponding DOM elements. 33203 * For example, if an item is added to the collection, `ngRepeat` will know that all other items 33204 * already have DOM elements, and will not re-render them. 33205 * 33206 * All different types of tracking functions, their syntax, and and their support for duplicate 33207 * items in collections can be found in the 33208 * {@link ngRepeat#ngRepeat-arguments ngRepeat expression description}. 33209 * 33210 * <div class="alert alert-success"> 33211 * **Best Practice:** If you are working with objects that have a unique identifier property, you 33212 * should track by this identifier instead of the object instance, 33213 * e.g. `item in items track by item.id`. 33214 * Should you reload your data later, `ngRepeat` will not have to rebuild the DOM elements for items 33215 * it has already rendered, even if the JavaScript objects in the collection have been substituted 33216 * for new ones. For large collections, this significantly improves rendering performance. 33217 * </div> 33218 * 33219 * ### Effects of DOM Element re-use 33220 * 33221 * When DOM elements are re-used, ngRepeat updates the scope for the element, which will 33222 * automatically update any active bindings on the template. However, other 33223 * functionality will not be updated, because the element is not re-created: 33224 * 33225 * - Directives are not re-compiled 33226 * - {@link guide/expression#one-time-binding one-time expressions} on the repeated template are not 33227 * updated if they have stabilized. 33228 * 33229 * The above affects all kinds of element re-use due to tracking, but may be especially visible 33230 * when tracking by `$index` due to the way ngRepeat re-uses elements. 33231 * 33232 * The following example shows the effects of different actions with tracking: 33233 33234 <example module="ngRepeat" name="ngRepeat-tracking" deps="angular-animate.js" animations="true"> 33235 <file name="script.js"> 33236 angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) { 33237 var friends = [ 33238 {name:'John', age:25}, 33239 {name:'Mary', age:40}, 33240 {name:'Peter', age:85} 33241 ]; 33242 33243 $scope.removeFirst = function() { 33244 $scope.friends.shift(); 33245 }; 33246 33247 $scope.updateAge = function() { 33248 $scope.friends.forEach(function(el) { 33249 el.age = el.age + 5; 33250 }); 33251 }; 33252 33253 $scope.copy = function() { 33254 $scope.friends = angular.copy($scope.friends); 33255 }; 33256 33257 $scope.reset = function() { 33258 $scope.friends = angular.copy(friends); 33259 }; 33260 33261 $scope.reset(); 33262 }); 33263 </file> 33264 <file name="index.html"> 33265 <div ng-controller="repeatController"> 33266 <ol> 33267 <li>When you click "Update Age", only the first list updates the age, because all others have 33268 a one-time binding on the age property. If you then click "Copy", the current friend list 33269 is copied, and now the second list updates the age, because the identity of the collection items 33270 has changed and the list must be re-rendered. The 3rd and 4th list stay the same, because all the 33271 items are already known according to their tracking functions. 33272 </li> 33273 <li>When you click "Remove First", the 4th list has the wrong age on both remaining items. This is 33274 due to tracking by $index: when the first collection item is removed, ngRepeat reuses the first 33275 DOM element for the new first collection item, and so on. Since the age property is one-time 33276 bound, the value remains from the collection item which was previously at this index. 33277 </li> 33278 </ol> 33279 33280 <button ng-click="removeFirst()">Remove First</button> 33281 <button ng-click="updateAge()">Update Age</button> 33282 <button ng-click="copy()">Copy</button> 33283 <br><button ng-click="reset()">Reset List</button> 33284 <br> 33285 <code>track by $id(friend)</code> (default): 33286 <ul class="example-animate-container"> 33287 <li class="animate-repeat" ng-repeat="friend in friends"> 33288 {{friend.name}} is {{friend.age}} years old. 33289 </li> 33290 </ul> 33291 <code>track by $id(friend)</code> (default), with age one-time binding: 33292 <ul class="example-animate-container"> 33293 <li class="animate-repeat" ng-repeat="friend in friends"> 33294 {{friend.name}} is {{::friend.age}} years old. 33295 </li> 33296 </ul> 33297 <code>track by friend.name</code>, with age one-time binding: 33298 <ul class="example-animate-container"> 33299 <li class="animate-repeat" ng-repeat="friend in friends track by friend.name"> 33300 {{friend.name}} is {{::friend.age}} years old. 33301 </li> 33302 </ul> 33303 <code>track by $index</code>, with age one-time binding: 33304 <ul class="example-animate-container"> 33305 <li class="animate-repeat" ng-repeat="friend in friends track by $index"> 33306 {{friend.name}} is {{::friend.age}} years old. 33307 </li> 33308 </ul> 33309 </div> 33310 </file> 33311 <file name="animations.css"> 33312 .example-animate-container { 33313 background:white; 33314 border:1px solid black; 33315 list-style:none; 33316 margin:0; 33317 padding:0 10px; 33318 } 33319 33320 .animate-repeat { 33321 line-height:30px; 33322 list-style:none; 33323 box-sizing:border-box; 33324 } 33325 33326 .animate-repeat.ng-move, 33327 .animate-repeat.ng-enter, 33328 .animate-repeat.ng-leave { 33329 transition:all linear 0.5s; 33330 } 33331 33332 .animate-repeat.ng-leave.ng-leave-active, 33333 .animate-repeat.ng-move, 33334 .animate-repeat.ng-enter { 33335 opacity:0; 33336 max-height:0; 33337 } 33338 33339 .animate-repeat.ng-leave, 33340 .animate-repeat.ng-move.ng-move-active, 33341 .animate-repeat.ng-enter.ng-enter-active { 33342 opacity:1; 33343 max-height:30px; 33344 } 33345 </file> 33346 </example> 33347 33348 * 33349 * ## Special repeat start and end points 33350 * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending 33351 * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. 33352 * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) 33353 * up to and including the ending HTML tag where **ng-repeat-end** is placed. 33354 * 33355 * The example below makes use of this feature: 33356 * ```html 33357 * <header ng-repeat-start="item in items"> 33358 * Header {{ item }} 33359 * </header> 33360 * <div class="body"> 33361 * Body {{ item }} 33362 * </div> 33363 * <footer ng-repeat-end> 33364 * Footer {{ item }} 33365 * </footer> 33366 * ``` 33367 * 33368 * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to: 33369 * ```html 33370 * <header> 33371 * Header A 33372 * </header> 33373 * <div class="body"> 33374 * Body A 33375 * </div> 33376 * <footer> 33377 * Footer A 33378 * </footer> 33379 * <header> 33380 * Header B 33381 * </header> 33382 * <div class="body"> 33383 * Body B 33384 * </div> 33385 * <footer> 33386 * Footer B 33387 * </footer> 33388 * ``` 33389 * 33390 * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such 33391 * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). 33392 * 33393 * @animations 33394 * | Animation | Occurs | 33395 * |----------------------------------|-------------------------------------| 33396 * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter | 33397 * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out | 33398 * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered | 33399 * 33400 * See the example below for defining CSS animations with ngRepeat. 33401 * 33402 * @element ANY 33403 * @scope 33404 * @priority 1000 33405 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These 33406 * formats are currently supported: 33407 * 33408 * * `variable in expression` – where variable is the user defined loop variable and `expression` 33409 * is a scope expression giving the collection to enumerate. 33410 * 33411 * For example: `album in artist.albums`. 33412 * 33413 * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, 33414 * and `expression` is the scope expression giving the collection to enumerate. 33415 * 33416 * For example: `(name, age) in {'adam':10, 'amalie':12}`. 33417 * 33418 * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression 33419 * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression 33420 * is specified, ng-repeat associates elements by identity. It is an error to have 33421 * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are 33422 * mapped to the same DOM element, which is not possible.) 33423 * 33424 * *Default tracking: $id()*: `item in items` is equivalent to `item in items track by $id(item)`. 33425 * This implies that the DOM elements will be associated by item identity in the collection. 33426 * 33427 * The built-in `$id()` function can be used to assign a unique 33428 * `$$hashKey` property to each item in the collection. This property is then used as a key to associated DOM elements 33429 * with the corresponding item in the collection by identity. Moving the same object would move 33430 * the DOM element in the same way in the DOM. 33431 * Note that the default id function does not support duplicate primitive values (`number`, `string`), 33432 * but supports duplictae non-primitive values (`object`) that are *equal* in shape. 33433 * 33434 * *Custom Expression*: It is possible to use any AngularJS expression to compute the tracking 33435 * id, for example with a function, or using a property on the collection items. 33436 * `item in items track by item.id` is a typical pattern when the items have a unique identifier, 33437 * e.g. database id. In this case the object identity does not matter. Two objects are considered 33438 * equivalent as long as their `id` property is same. 33439 * Tracking by unique identifier is the most performant way and should be used whenever possible. 33440 * 33441 * *$index*: This special property tracks the collection items by their index, and 33442 * re-uses the DOM elements that match that index, e.g. `item in items track by $index`. This can 33443 * be used for a performance improvement if no unique identfier is available and the identity of 33444 * the collection items cannot be easily computed. It also allows duplicates. 33445 * 33446 * <div class="alert alert-warning"> 33447 * <strong>Note:</strong> Re-using DOM elements can have unforeseen effects. Read the 33448 * {@link ngRepeat#tracking-and-duplicates section on tracking and duplicates} for 33449 * more info. 33450 * </div> 33451 * 33452 * <div class="alert alert-warning"> 33453 * <strong>Note:</strong> the `track by` expression must come last - after any filters, and the alias expression: 33454 * `item in items | filter:searchText as results track by item.id` 33455 * </div> 33456 * 33457 * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the 33458 * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message 33459 * when a filter is active on the repeater, but the filtered result set is empty. 33460 * 33461 * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after 33462 * the items have been processed through the filter. 33463 * 33464 * Please note that `as [variable name]
33464 is not an operator but rather a part of ngRepeat 33465 * micro-syntax so it can be used only after all filters (and not as operator, inside an expression). 33466 * 33467 * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results track by item.id` . 33468 * 33469 * @example 33470 * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed 33471 * results by name or by age. New (entering) and removed (leaving) items are animated. 33472 <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true"> 33473 <file name="index.html"> 33474 <div ng-controller="repeatController"> 33475 I have {{friends.length}} friends. They are: 33476 <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" /> 33477 <ul class="example-animate-container"> 33478 <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results track by friend.name"> 33479 [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. 33480 </li> 33481 <li class="animate-repeat" ng-if="results.length === 0"> 33482 <strong>No results found...</strong> 33483 </li> 33484 </ul> 33485 </div> 33486 </file> 33487 <file name="script.js"> 33488 angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) { 33489 $scope.friends = [ 33490 {name:'John', age:25, gender:'boy'}, 33491 {name:'Jessie', age:30, gender:'girl'}, 33492 {name:'Johanna', age:28, gender:'girl'}, 33493 {name:'Joy', age:15, gender:'girl'}, 33494 {name:'Mary', age:28, gender:'girl'}, 33495 {name:'Peter', age:95, gender:'boy'}, 33496 {name:'Sebastian', age:50, gender:'boy'}, 33497 {name:'Erika', age:27, gender:'girl'}, 33498 {name:'Patrick', age:40, gender:'boy'}, 33499 {name:'Samantha', age:60, gender:'girl'} 33500 ]; 33501 }); 33502 </file> 33503 <file name="animations.css"> 33504 .example-animate-container { 33505 background:white; 33506 border:1px solid black; 33507 list-style:none; 33508 margin:0; 33509 padding:0 10px; 33510 } 33511 33512 .animate-repeat { 33513 line-height:30px; 33514 list-style:none; 33515 box-sizing:border-box; 33516 } 33517 33518 .animate-repeat.ng-move, 33519 .animate-repeat.ng-enter, 33520 .animate-repeat.ng-leave { 33521 transition:all linear 0.5s; 33522 } 33523 33524 .animate-repeat.ng-leave.ng-leave-active, 33525 .animate-repeat.ng-move, 33526 .animate-repeat.ng-enter { 33527 opacity:0; 33528 max-height:0; 33529 } 33530 33531 .animate-repeat.ng-leave, 33532 .animate-repeat.ng-move.ng-move-active, 33533 .animate-repeat.ng-enter.ng-enter-active { 33534 opacity:1; 33535 max-height:30px; 33536 } 33537 </file> 33538 <file name="protractor.js" type="protractor"> 33539 var friends = element.all(by.repeater('friend in friends')); 33540 33541 it('should render initial data set', function() { 33542 expect(friends.count()).toBe(10); 33543 expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.'); 33544 expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.'); 33545 expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.'); 33546 expect(element(by.binding('friends.length')).getText()) 33547 .toMatch("I have 10 friends. They are:"); 33548 }); 33549 33550 it('should update repeater when filter predicate changes', function() { 33551 expect(friends.count()).toBe(10); 33552
33553 element(by.model('q')).sendKeys('ma'); 33554 33555 expect(friends.count()).toBe(2); 33556 expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.'); 33557 expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.'); 33558 }); 33559 </file> 33560 </example> 33561 */ 33562var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) { 33563 var NG_REMOVED = '$$NG_REMOVED'; 33564 var ngRepeatMinErr = minErr('ngRepeat'); 33565 33566 var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) { 33567 // TODO(perf): generate setters to shave off ~40ms or 1-1.5% 33568 scope[valueIdentifier] = value; 33569 if (keyIdentifier) scope[keyIdentifier] = key; 33570 scope.$index = index; 33571 scope.$first = (index === 0); 33572 scope.$last = (index === (arrayLength - 1)); 33573 scope.$middle = !(scope.$first || scope.$last); 33574 // eslint-disable-next-line no-bitwise 33575 scope.$odd = !(scope.$even = (index & 1) === 0); 33576 }; 33577 33578 var getBlockStart = function(block) { 33579 return block.clone[0]; 33580 }; 33581 33582 var getBlockEnd = function(block) { 33583 return block.clone[block.clone.length - 1]; 33584 }; 33585 33586 33587 return { 33588 restrict: 'A', 33589 multiElement: true, 33590 transclude: 'element', 33591 priority: 1000, 33592 terminal: true, 33593 $$tlb: true, 33594 compile: function ngRepeatCompile($element, $attr) { 33595 var expression = $attr.ngRepeat; 33596 var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression); 33597 33598 var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); 33599 33600 if (!match) { 33601 throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.', 33602 expression); 33603 } 33604 33605 var lhs = match[1]; 33606 var rhs = match[2]; 33607 var aliasAs = match[3]; 33608 var trackByExp = match[4]; 33609 33610 match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/); 33611 33612 if (!match) { 33613 throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.', 33614 lhs); 33615 } 33616 var valueIdentifier = match[3] || match[1]; 33617 var keyIdentifier = match[2]; 33618 33619 if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) || 33620 /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) { 33621 throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.', 33622 aliasAs); 33623 } 33624 33625 var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn; 33626 var hashFnLocals = {$id: hashKey}; 33627 33628 if (trackByExp) { 33629 trackByExpGetter = $parse(trackByExp); 33630 } else { 33631 trackByIdArrayFn = function(key, value) { 33632 return hashKey(value); 33633 }; 33634 trackByIdObjFn = function(key) { 33635 return key; 33636 }; 33637 } 33638 33639 return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) { 33640 33641 if (trackByExpGetter) { 33642 trackByIdExpFn = function(key, value, index) { 33643 // assign key, value, and $index to the locals so that they can be used in hash functions 33644 if (keyIdentifier) hashFnLocals[keyIdentifier] = key; 33645 hashFnLocals[valueIdentifier] = value; 33646 hashFnLocals.$index = index; 33647 return trackByExpGetter($scope, hashFnLocals); 33648 }; 33649 } 33650 33651 // Store a list of elements from previous run. This is a hash where key is the item from the 33652 // iterator, and the value is objects with following properties. 33653 // - scope: bound scope 33654 // - clone: previous element. 33655 // - index: position 33656 // 33657 // We are using no-proto object so that we don't need to guard against inherited props via 33658 // hasOwnProperty. 33659 var lastBlockMap = createMap(); 33660 33661 //watch props 33662 $scope.$watchCollection(rhs, function ngRepeatAction(collection) { 33663 var index, length, 33664 previousNode = $element[0], // node that cloned
vendor: 2,676 bytes, lines 33664-33723
33664nodes should be inserted after 33665 // initialized to the comment node anchor 33666 nextNode, 33667 // Same as lastBlockMap but it has the current state. It will become the 33668 // lastBlockMap on the next iteration. 33669 nextBlockMap = createMap(), 33670 collectionLength, 33671 key, value, // key/value of iteration 33672 trackById, 33673 trackByIdFn, 33674 collectionKeys, 33675 block, // last object information {scope, element, id} 33676 nextBlockOrder, 33677 elementsToRemove; 33678 33679 if (aliasAs) { 33680 $scope[aliasAs] = collection; 33681 } 33682 33683 if (isArrayLike(collection)) { 33684 collectionKeys = collection; 33685 trackByIdFn = trackByIdExpFn || trackByIdArrayFn; 33686 } else { 33687 trackByIdFn = trackByIdExpFn || trackByIdObjFn; 33688 // if object, extract keys, in enumeration order, unsorted 33689 collectionKeys = []; 33690 for (var itemKey in collection) { 33691 if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') { 33692 collectionKeys.push(itemKey); 33693 } 33694 } 33695 } 33696 33697 collectionLength = collectionKeys.length; 33698 nextBlockOrder = new Array(collectionLength); 33699 33700 // locate existing items 33701 for (index = 0; index < collectionLength; index++) { 33702 key = (collection === collectionKeys) ? index : collectionKeys[index]; 33703 value = collection[key]; 33704 trackById = trackByIdFn(key, value, index); 33705 if (lastBlockMap[trackById]) { 33706 // found previously seen block 33707 block = lastBlockMap[trackById]; 33708 delete lastBlockMap[trackById]; 33709 nextBlockMap[trackById] = block; 33710 nextBlockOrder[index] = block; 33711 } else if (nextBlockMap[trackById]) { 33712 // if collision detected. restore lastBlockMap and throw an error 33713 forEach(nextBlockOrder, function(block) { 33714 if (block && block.scope) lastBlockMap[block.id] = block; 33715 }); 33716 throw ngRepeatMinErr('dupes', 33717 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}', 33718 expression, trackById, value); 33719 } else { 33720 // new never before seen block 33721 nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined}; 33722 nextBlockMap[trackById] = true; 33723 }
vendor: 21,929 bytes, lines 33723-34269
33723 33724 } 33725 33726 // remove leftover items 33727 for (var blockKey in lastBlockMap) { 33728 block = lastBlockMap[blockKey]; 33729 elementsToRemove = getBlockNodes(block.clone); 33730 $animate.leave(elementsToRemove); 33731 if (elementsToRemove[0].parentNode) { 33732 // if the element was not removed yet because of pending animation, mark it as deleted 33733 // so that we can ignore it later 33734 for (index = 0, length = elementsToRemove.length; index < length; index++) { 33735 elementsToRemove[index][NG_REMOVED] = true; 33736 } 33737 } 33738 block.scope.$destroy(); 33739 } 33740 33741 // we are not using forEach for perf reasons (trying to avoid #call) 33742 for (index = 0; index < collectionLength; index++) { 33743 key = (collection === collectionKeys) ? index : collectionKeys[index]; 33744 value = collection[key]; 33745 block = nextBlockOrder[index]; 33746 33747 if (block.scope) { 33748 // if we have already seen this object, then we need to reuse the 33749 // associated scope/element 33750 33751 nextNode = previousNode; 33752 33753 // skip nodes that are already pending removal via leave animation 33754 do { 33755 nextNode = nextNode.nextSibling; 33756 } while (nextNode && nextNode[NG_REMOVED]); 33757 33758 if (getBlockStart(block) !== nextNode) { 33759 // existing item which got moved 33760 $animate.move(getBlockNodes(block.clone), null, previousNode); 33761 } 33762 previousNode = getBlockEnd(block); 33763 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); 33764 } else { 33765 // new item which we don't know about 33766 $transclude(function ngRepeatTransclude(clone, scope) { 33767 block.scope = scope; 33768 // http://jsperf.com/clone-vs-createcomment 33769 var endNode = ngRepeatEndComment.cloneNode(false); 33770 clone[clone.length++] = endNode; 33771 33772 $animate.enter(clone, null, previousNode); 33773 previousNode = endNode; 33774 // Note: We only need the first/last node of the cloned nodes. 33775 // However, we need to keep the reference to the jqlite wrapper as it might be changed later 33776 // by a directive with templateUrl when its template arrives. 33777 block.clone = clone; 33778 nextBlockMap[block.id] = block; 33779 updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); 33780 }); 33781 } 33782 } 33783 lastBlockMap = nextBlockMap; 33784 }); 33785 }; 33786 } 33787 }; 33788}]; 33789 33790var NG_HIDE_CLASS = 'ng-hide'; 33791var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; 33792/** 33793 * @ngdoc directive 33794 * @name ngShow 33795 * @multiElement 33796 * 33797 * @description 33798 * The `ngShow` directive shows or hides the given HTML element based on the expression provided to 33799 * the `ngShow` attribute. 33800 * 33801 * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element. 33802 * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an 33803 * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see 33804 * {@link ng.directive:ngCsp ngCsp}). 33805 * 33806 * ```html 33807 * <!-- when $scope.myValue is truthy (element is visible) --> 33808 * <div ng-show="myValue"></div> 33809 * 33810 * <!-- when $scope.myValue is falsy (element is hidden) --> 33811 * <div ng-show="myValue" class="ng-hide"></div> 33812 * ``` 33813 * 33814 * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added 33815 * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide` 33816 * CSS class is removed from the element causing the element not to appear hidden. 33817 * 33818 * ## Why is `!important` used? 33819 * 33820 * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the 33821 * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as 33822 * simple as changing the display style on a HTML list item would make hidden elements appear 33823 * visible. This also becomes a bigger issue when dealing with CSS frameworks. 33824 * 33825 * By using `!important`, the show and hide behavior will work as expected despite any clash between 33826 * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a 33827 * developer chooses to override the styling to change how to hide an element then it is just a 33828 * matter of using `!important` in their own CSS code. 33829 * 33830 * ### Overriding `.ng-hide` 33831 * 33832 * By default, the `.ng-hide` class will style the element with `display: none !important`. If you 33833 * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for 33834 * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually 33835 * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added. 33836 * 33837 * ```css 33838 * .ng-hide:not(.ng-hide-animate) { 33839 * /* These are just alternative ways of hiding an element */ 33840 * display: block!important; 33841 * position: absolute; 33842 * top: -9999px; 33843 * left: -9999px; 33844 * } 33845 * ``` 33846 * 33847 * By default you don't need to override anything in CSS and the animations will work around the 33848 * display style. 33849 * 33850 * @animations 33851 * | Animation | Occurs | 33852 * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------| 33853 * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden. | 33854 * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. | 33855 * 33856 * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the 33857 * directive expression is true and false. This system works like the animation system present with 33858 * `ngClass` except that you must also include the `!important` flag to override the display 33859 * property so that the elements are not actually hidden during the animation. 33860 * 33861 * ```css 33862 * /* A working example can be found at the bottom of this page. */ 33863 * .my-element.ng-hide-add, .my-element.ng-hide-remove { 33864 * transition: all 0.5s linear; 33865 * } 33866 * 33867 * .my-element.ng-hide-add { ... } 33868 * .my-element.ng-hide-add.ng-hide-add-active { ... } 33869 * .my-element.ng-hide-remove { ... } 33870 * .my-element.ng-hide-remove.ng-hide-remove-active { ... } 33871 * ``` 33872 * 33873 * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property 33874 * to block during animation states - ngAnimate will automatically handle the style toggling for you. 33875 * 33876 * @element ANY 33877 * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the 33878 * element is shown/hidden respectively. 33879 * 33880 * @example 33881 * A simple example, animating the element's opacity: 33882 * 33883 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple"> 33884 <file name="index.html"> 33885 Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br /> 33886 <div class="check-element animate-show-hide" ng-show="checked"> 33887 I show up when your checkbox is checked. 33888 </div> 33889 </file> 33890 <file name="animations.css"> 33891 .animate-show-hide.ng-hide { 33892 opacity: 0; 33893 } 33894 33895 .animate-show-hide.ng-hide-add, 33896 .animate-show-hide.ng-hide-remove { 33897 transition: all linear 0.5s; 33898 } 33899 33900 .check-element { 33901 border: 1px solid black; 33902 opacity: 1; 33903 padding: 10px; 33904 } 33905 </file> 33906 <file name="protractor.js" type="protractor"> 33907 it('should check ngShow', function() { 33908 var checkbox = element(by.model('checked')); 33909 var checkElem = element(by.css('.check-element')); 33910 33911 expect(checkElem.isDisplayed()).toBe(false); 33912 checkbox.click(); 33913 expect(checkElem.isDisplayed()).toBe(true); 33914 }); 33915 </file> 33916 </example> 33917 * 33918 * <hr /> 33919 * @example 33920 * A more complex example, featuring different show/hide animations: 33921 * 33922 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex"> 33923 <file name="index.html"> 33924 Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br /> 33925 <div class="check-element funky-show-hide" ng-show="checked"> 33926 I show up when your checkbox is checked. 33927 </div> 33928 </file> 33929 <file name="animations.css"> 33930 body { 33931 overflow: hidden; 33932 perspective: 1000px; 33933 } 33934 33935 .funky-show-hide.ng-hide-add { 33936 transform: rotateZ(0); 33937 transform-origin: right; 33938 transition: all 0.5s ease-in-out; 33939 } 33940 33941 .funky-show-hide.ng-hide-add.ng-hide-add-active { 33942 transform: rotateZ(-135deg); 33943 } 33944 33945 .funky-show-hide.ng-hide-remove { 33946 transform: rotateY(90deg); 33947 transform-origin: left; 33948 transition: all 0.5s ease; 33949 } 33950 33951 .funky-show-hide.ng-hide-remove.ng-hide-remove-active { 33952 transform: rotateY(0); 33953 } 33954 33955 .check-element { 33956 border: 1px solid black; 33957 opacity: 1; 33958 padding: 10px; 33959 } 33960 </file> 33961 <file name="protractor.js" type="protractor"> 33962 it('should check ngShow', function() { 33963 var checkbox = element(by.model('checked')); 33964 var checkElem = element(by.css('.check-element')); 33965 33966 expect(checkElem.isDisplayed()).toBe(false); 33967 checkbox.click(); 33968 expect(checkElem.isDisplayed()).toBe(true); 33969 }); 33970 </file> 33971 </example> 33972 * 33973 * @knownIssue 33974 * 33975 * ### Flickering when using ngShow to toggle between elements 33976 * 33977 * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can 33978 * happen that both the element to show and the element to hide are visible for a very short time. 33979 * 33980 * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations 33981 * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than 33982 * other browsers. 33983 * 33984 * There are several way to mitigate this problem: 33985 * 33986 * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}. 33987 * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}. 33988 * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements. 33989 * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}. 33990 * - Define an animation on the affected elements. 33991 */ 33992var ngShowDirective = ['$animate', function($animate) { 33993 return { 33994 restrict: 'A', 33995 multiElement: true, 33996 link: function(scope, element, attr) { 33997 scope.$watch(attr.ngShow, function ngShowWatchAction(value) { 33998 // we're adding a temporary, animation-specific class for ng-hide since this way 33999 // we can control when the element is actually displayed on screen without having 34000 // to have a global/greedy CSS selector that breaks when other animations are run. 34001 // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845 34002 $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, { 34003 tempClasses: NG_HIDE_IN_PROGRESS_CLASS 34004 }); 34005 }); 34006 } 34007 }; 34008}]; 34009 34010 34011/** 34012 * @ngdoc directive 34013 * @name ngHide 34014 * @multiElement 34015 * 34016 * @description 34017 * The `ngHide` directive shows or hides the given HTML element based on the expression provided to 34018 * the `ngHide` attribute. 34019 * 34020 * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element. 34021 * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an 34022 * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see 34023 * {@link ng.directive:ngCsp ngCsp}). 34024 * 34025 * ```html 34026 * <!-- when $scope.myValue is truthy (element is hidden) --> 34027 * <div ng-hide="myValue" class="ng-hide"></div> 34028 * 34029 * <!-- when $scope.myValue is falsy (element is visible) --> 34030 * <div ng-hide="myValue"></div> 34031 * ``` 34032 * 34033 * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added 34034 * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide` 34035 * CSS class is removed from the element causing the element not to appear hidden. 34036 * 34037 * ## Why is `!important` used? 34038 * 34039 * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the 34040 * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as 34041 * simple as changing the display style on a HTML list item would make hidden elements appear 34042 * visible. This also becomes a bigger issue when dealing with CSS frameworks. 34043 * 34044 * By using `!important`, the show and hide behavior will work as expected despite any clash between 34045 * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a 34046 * developer chooses to override the styling to change how to hide an element then it is just a 34047 * matter of using `!important` in their own CSS code. 34048 * 34049 * ### Overriding `.ng-hide` 34050 * 34051 * By default, the `.ng-hide` class will style the element with `display: none !important`. If you 34052 * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for 34053 * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually 34054 * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added. 34055 * 34056 * ```css 34057 * .ng-hide:not(.ng-hide-animate) { 34058 * /* These are just alternative ways of hiding an element */ 34059 * display: block!important; 34060 * position: absolute; 34061 * top: -9999px; 34062 * left: -9999px; 34063 * } 34064 * ``` 34065 * 34066 * By default you don't need to override in CSS anything and the animations will work around the 34067 * display style. 34068 * 34069 * @animations 34070 * | Animation | Occurs | 34071 * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------| 34072 * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. | 34073 * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. | 34074 * 34075 * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the 34076 * directive expression is true and false. This system works like the animation system present with 34077 * `ngClass` except that you must also include the `!important` flag to override the display 34078 * property so that the elements are not actually hidden during the animation. 34079 * 34080 * ```css 34081 * /* A working example can be found at the bottom of this page. */ 34082 * .my-element.ng-hide-add, .my-element.ng-hide-remove { 34083 * transition: all 0.5s linear; 34084 * } 34085 * 34086 * .my-element.ng-hide-add { ... } 34087 * .my-element.ng-hide-add.ng-hide-add-active { ... } 34088 * .my-element.ng-hide-remove { ... } 34089 * .my-element.ng-hide-remove.ng-hide-remove-active { ... } 34090 * ``` 34091 * 34092 * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property 34093 * to block during animation states - ngAnimate will automatically handle the style toggling for you. 34094 * 34095 * @element ANY 34096 * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the 34097 * element is hidden/shown respectively. 34098 * 34099 * @example 34100 * A simple example, animating the element's opacity: 34101 * 34102 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple"> 34103 <file name="index.html"> 34104 Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br /> 34105 <div class="check-element animate-show-hide" ng-hide="checked"> 34106 I hide when your checkbox is checked. 34107 </div> 34108 </file> 34109 <file name="animations.css"> 34110 .animate-show-hide.ng-hide { 34111 opacity: 0; 34112 } 34113 34114 .animate-show-hide.ng-hide-add, 34115 .animate-show-hide.ng-hide-remove { 34116 transition: all linear 0.5s; 34117 } 34118 34119 .check-element { 34120 border: 1px solid black; 34121 opacity: 1; 34122 padding: 10px; 34123 } 34124 </file> 34125 <file name="protractor.js" type="protractor"> 34126 it('should check ngHide', function() { 34127 var checkbox = element(by.model('checked')); 34128 var checkElem = element(by.css('.check-element')); 34129 34130 expect(checkElem.isDisplayed()).toBe(true); 34131 checkbox.click(); 34132 expect(checkElem.isDisplayed()).toBe(false); 34133 }); 34134 </file> 34135 </example> 34136 * 34137 * <hr /> 34138 * @example 34139 * A more complex example, featuring different show/hide animations: 34140 * 34141 <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex"> 34142 <file name="index.html"> 34143 Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br /> 34144 <div class="check-element funky-show-hide" ng-hide="checked"> 34145 I hide when your checkbox is checked. 34146 </div> 34147 </file> 34148 <file name="animations.css"> 34149 body { 34150 overflow: hidden; 34151 perspective: 1000px; 34152 } 34153 34154 .funky-show-hide.ng-hide-add { 34155 transform: rotateZ(0); 34156 transform-origin: right; 34157 transition: all 0.5s ease-in-out; 34158 } 34159 34160 .funky-show-hide.ng-hide-add.ng-hide-add-active { 34161 transform: rotateZ(-135deg); 34162 } 34163 34164 .funky-show-hide.ng-hide-remove { 34165 transform: rotateY(90deg); 34166 transform-origin: left; 34167 transition: all 0.5s ease; 34168 } 34169 34170 .funky-show-hide.ng-hide-remove.ng-hide-remove-active { 34171 transform: rotateY(0); 34172 } 34173 34174 .check-element { 34175 border: 1px solid black; 34176 opacity: 1; 34177 padding: 10px; 34178 } 34179 </file> 34180 <file name="protractor.js" type="protractor"> 34181 it('should check ngHide', function() { 34182 var checkbox = element(by.model('checked')); 34183 var checkElem = element(by.css('.check-element')); 34184 34185 expect(checkElem.isDisplayed()).toBe(true); 34186 checkbox.click(); 34187 expect(checkElem.isDisplayed()).toBe(false); 34188 }); 34189 </file> 34190 </example> 34191 * 34192 * @knownIssue 34193 * 34194 * ### Flickering when using ngHide to toggle between elements 34195 * 34196 * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can 34197 * happen that both the element to show and the element to hide are visible for a very short time. 34198 * 34199 * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations 34200 * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than 34201 * other browsers. 34202 * 34203 * There are several way to mitigate this problem: 34204 * 34205 * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}. 34206 * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}. 34207 * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements. 34208 * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}. 34209 * - Define an animation on the affected elements. 34210 */ 34211var ngHideDirective = ['$animate', function($animate) { 34212 return { 34213 restrict: 'A', 34214 multiElement: true, 34215 link: function(scope, element, attr) { 34216 scope.$watch(attr.ngHide, function ngHideWatchAction(value) { 34217 // The comment inside of the ngShowDirective explains why we add and 34218 // remove a temporary class for the show/hide animation 34219 $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, { 34220 tempClasses: NG_HIDE_IN_PROGRESS_CLASS 34221 }); 34222 }); 34223 } 34224 }; 34225}]; 34226 34227/** 34228 * @ngdoc directive 34229 * @name ngStyle 34230 * @restrict AC 34231 * 34232 * @description 34233 * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. 34234 * 34235 * @knownIssue 34236 * You should not use {@link guide/interpolation interpolation} in the value of the `style` 34237 * attribute, when using the `ngStyle` directive on the same element. 34238 * See {@link guide/interpolation#known-issues here} for more info. 34239 * 34240 * @element ANY 34241 * @param {expression} ngStyle 34242 * 34243 * {@link guide/expression Expression} which evals to an 34244 * object whose keys are CSS style names and values are corresponding values for those CSS 34245 * keys. 34246 * 34247 * Since some CSS style names are not valid keys for an object, they must be quoted. 34248 * See the 'background-color' style in the example below. 34249 * 34250 * @example 34251 <example name="ng-style"> 34252 <file name="index.html"> 34253 <input type="button" value="set color" ng-click="myStyle={color:'red'}"> 34254 <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}"> 34255 <input type="button" value="clear" ng-click="myStyle={}"> 34256 <br/> 34257 <span ng-style="myStyle">Sample Text</span> 34258 <pre>myStyle={{myStyle}}</pre> 34259 </file> 34260 <file name="style.css"> 34261 span { 34262 color: black; 34263 } 34264 </file> 34265 <file name="protractor.js" type="protractor"> 34266 var colorSpan = element(by.css('span')); 34267 34268 it('should check ng-style', function() { 34269 expect(colorSpan.getCssValue('color')).to
34269Be('rgba(0, 0, 0, 1)'); 34270 element(by.css('input[value=\'set color\']')).click(); 34271 expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); 34272 element(by.css('input[value=clear]')).click(); 34273 expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); 34274 }); 34275 </file> 34276 </example> 34277 */ 34278var ngStyleDirective = ngDirective(function(scope, element, attr) { 34279 scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { 34280 if (oldStyles && (newStyles !== oldStyles)) { 34281 forEach(oldStyles, function(val, style) { element.css(style, '');
vendor: 32,433 bytes, lines 34281-35167
34281}); 34282 } 34283 if (newStyles) element.css(newStyles); 34284 }); 34285}); 34286 34287/** 34288 * @ngdoc directive 34289 * @name ngSwitch 34290 * @restrict EA 34291 * 34292 * @description 34293 * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression. 34294 * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location 34295 * as specified in the template. 34296 * 34297 * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it 34298 * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element 34299 * matches the value obtained from the evaluated expression. In other words, you define a container element 34300 * (where you place the directive), place an expression on the **`on="..."` attribute** 34301 * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place 34302 * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on 34303 * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default 34304 * attribute is displayed. 34305 * 34306 * <div class="alert alert-info"> 34307 * Be aware that the attribute values to match against cannot be expressions. They are interpreted 34308 * as literal string values to match against. 34309 * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the 34310 * value of the expression `$scope.someVal`. 34311 * </div> 34312 34313 * @animations 34314 * | Animation | Occurs | 34315 * |----------------------------------|-------------------------------------| 34316 * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container | 34317 * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM | 34318 * 34319 * @usage 34320 * 34321 * ``` 34322 * <ANY ng-switch="expression"> 34323 * <ANY ng-switch-when="matchValue1">...</ANY> 34324 * <ANY ng-switch-when="matchValue2">...</ANY> 34325 * <ANY ng-switch-default>...</ANY> 34326 * </ANY> 34327 * ``` 34328 * 34329 * 34330 * @scope 34331 * @priority 1200 34332 * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>. 34333 * On child elements add: 34334 * 34335 * * `ngSwitchWhen`: the case statement to match against. If match then this 34336 * case will be displayed. If the same match appears multiple times, all the 34337 * elements will be displayed. It is possible to associate multiple values to 34338 * the same `ngSwitchWhen` by defining the optional attribute 34339 * `ngSwitchWhenSeparator`. The separator will be used to split the value of 34340 * the `ngSwitchWhen` attribute into multiple tokens, and the element will show 34341 * if any of the `ngSwitch` evaluates to any of these tokens. 34342 * * `ngSwitchDefault`: the default case when no other case match. If there 34343 * are multiple default cases, all of them will be displayed when no other 34344 * case match. 34345 * 34346 * 34347 * @example 34348 <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch"> 34349 <file name="index.html"> 34350 <div ng-controller="ExampleController"> 34351 <select ng-model="selection" ng-options="item for item in items"> 34352 </select> 34353 <code>selection={{selection}}</code> 34354 <hr/> 34355 <div class="animate-switch-container" 34356 ng-switch on="selection"> 34357 <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div> 34358 <div class="animate-switch" ng-switch-when="home">Home Span</div> 34359 <div class="animate-switch" ng-switch-default>default</div> 34360 </div> 34361 </div> 34362 </file> 34363 <file name="script.js"> 34364 angular.module('switchExample', ['ngAnimate']) 34365 .controller('ExampleController', ['$scope', function($scope) { 34366 $scope.items = ['settings', 'home', 'options', 'other']; 34367 $scope.selection = $scope.items[0]; 34368 }]); 34369 </file> 34370 <file name="animations.css"> 34371 .animate-switch-container { 34372 position:relative; 34373 background:white; 34374 border:1px solid black; 34375 height:40px; 34376 overflow:hidden; 34377 } 34378 34379 .animate-switch { 34380 padding:10px; 34381 } 34382 34383 .animate-switch.ng-animate { 34384 transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; 34385 34386 position:absolute; 34387 top:0; 34388 left:0; 34389 right:0; 34390 bottom:0; 34391 } 34392 34393 .animate-switch.ng-leave.ng-leave-active, 34394 .animate-switch.ng-enter { 34395 top:-50px; 34396 } 34397 .animate-switch.ng-leave, 34398 .animate-switch.ng-enter.ng-enter-active { 34399 top:0; 34400 } 34401 </file> 34402 <file name="protractor.js" type="protractor"> 34403 var switchElem = element(by.css('[ng-switch]')); 34404 var select = element(by.model('selection')); 34405 34406 it('should start in settings', function() { 34407 expect(switchElem.getText()).toMatch(/Settings Div/); 34408 }); 34409 it('should change to home', function() { 34410 select.all(by.css('option')).get(1).click(); 34411 expect(switchElem.getText()).toMatch(/Home Span/); 34412 }); 34413 it('should change to settings via "options"', function() { 34414 select.all(by.css('option')).get(2).click(); 34415 expect(switchElem.getText()).toMatch(/Settings Div/); 34416 }); 34417 it('should select default', function() { 34418 select.all(by.css('option')).get(3).click(); 34419 expect(switchElem.getText()).toMatch(/default/); 34420 }); 34421 </file> 34422 </example> 34423 */ 34424var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) { 34425 return { 34426 require: 'ngSwitch', 34427 34428 // asks for $scope to fool the BC controller module 34429 controller: ['$scope', function NgSwitchController() { 34430 this.cases = {}; 34431 }], 34432 link: function(scope, element, attr, ngSwitchController) { 34433 var watchExpr = attr.ngSwitch || attr.on, 34434 selectedTranscludes = [], 34435 selectedElements = [], 34436 previousLeaveAnimations = [], 34437 selectedScopes = []; 34438 34439 var spliceFactory = function(array, index) { 34440 return function(response) { 34441 if (response !== false) array.splice(index, 1); 34442 }; 34443 }; 34444 34445 scope.$watch(watchExpr, function ngSwitchWatchAction(value) { 34446 var i, ii; 34447 34448 // Start with the last, in case the array is modified during the loop 34449 while (previousLeaveAnimations.length) { 34450 $animate.cancel(previousLeaveAnimations.pop()); 34451 } 34452 34453 for (i = 0, ii = selectedScopes.length; i < ii; ++i) { 34454 var selected = getBlockNodes(selectedElements[i].clone); 34455 selectedScopes[i].$destroy(); 34456 var runner = previousLeaveAnimations[i] = $animate.leave(selected); 34457 runner.done(spliceFactory(previousLeaveAnimations, i)); 34458 } 34459 34460 selectedElements.length = 0; 34461 selectedScopes.length = 0; 34462 34463 if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { 34464 forEach(selectedTranscludes, function(selectedTransclude) { 34465 selectedTransclude.transclude(function(caseElement, selectedScope) { 34466 selectedScopes.push(selectedScope); 34467 var anchor = selectedTransclude.element; 34468 caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen'); 34469 var block = { clone: caseElement }; 34470 34471 selectedElements.push(block); 34472 $animate.enter(caseElement, anchor.parent(), anchor); 34473 }); 34474 }); 34475 } 34476 }); 34477 } 34478 }; 34479}]; 34480 34481var ngSwitchWhenDirective = ngDirective({ 34482 transclude: 'element', 34483 priority: 1200, 34484 require: '^ngSwitch', 34485 multiElement: true, 34486 link: function(scope, element, attrs, ctrl, $transclude) { 34487 34488 var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter( 34489 // Filter duplicate cases 34490 function(element, index, array) { return array[index - 1] !== element; } 34491 ); 34492 34493 forEach(cases, function(whenCase) { 34494 ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []); 34495 ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element }); 34496 }); 34497 } 34498}); 34499 34500var ngSwitchDefaultDirective = ngDirective({ 34501 transclude: 'element', 34502 priority: 1200, 34503 require: '^ngSwitch', 34504 multiElement: true, 34505 link: function(scope, element, attr, ctrl, $transclude) { 34506 ctrl.cases['?'] = (ctrl.cases['?'] || []); 34507 ctrl.cases['?'].push({ transclude: $transclude, element: element }); 34508 } 34509}); 34510 34511/** 34512 * @ngdoc directive 34513 * @name ngTransclude 34514 * @restrict EAC 34515 * 34516 * @description 34517 * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. 34518 * 34519 * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name 34520 * as the value of the `ng-transclude` or `ng-transclude-slot` attribute. 34521 * 34522 * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing 34523 * content of this element will be removed before the transcluded content is inserted. 34524 * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback 34525 * content in the case that no transcluded content is provided. 34526 * 34527 * @element ANY 34528 * 34529 * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty 34530 * or its value is the same as the name of the attribute then the default slot is used. 34531 * 34532 * @example 34533 * ### Basic transclusion 34534 * This example demonstrates basic transclusion of content into a component directive. 34535 * <example name="simpleTranscludeExample" module="transcludeExample"> 34536 * <file name="index.html"> 34537 * <script> 34538 * angular.module('transcludeExample', []) 34539 * .directive('pane', function(){ 34540 * return { 34541 * restrict: 'E', 34542 * transclude: true, 34543 * scope: { title:'@' }, 34544 * template: '<div style="border: 1px solid black;">' + 34545 * '<div style="background-color: gray">{{title}}</div>' + 34546 * '<ng-transclude></ng-transclude>' + 34547 * '</div>' 34548 * }; 34549 * }) 34550 * .controller('ExampleController', ['$scope', function($scope) { 34551 * $scope.title = 'Lorem Ipsum'; 34552 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; 34553 * }]); 34554 * </script> 34555 * <div ng-controller="ExampleController"> 34556 * <input ng-model="title" aria-label="title"> <br/> 34557 * <textarea ng-model="text" aria-label="text"></textarea> <br/> 34558 * <pane title="{{title}}"><span>{{text}}</span></pane> 34559 * </div> 34560 * </file> 34561 * <file name="protractor.js" type="protractor"> 34562 * it('should have transcluded', function() { 34563 * var titleElement = element(by.model('title')); 34564 * titleElement.clear(); 34565 * titleElement.sendKeys('TITLE'); 34566 * var textElement = element(by.model('text')); 34567 * textElement.clear(); 34568 * textElement.sendKeys('TEXT'); 34569 * expect(element(by.binding('title')).getText()).toEqual('TITLE'); 34570 * expect(element(by.binding('text')).getText()).toEqual('TEXT'); 34571 * }); 34572 * </file> 34573 * </example> 34574 * 34575 * @example 34576 * ### Transclude fallback content 34577 * This example shows how to use `NgTransclude` with fallback content, that 34578 * is displayed if no transcluded content is provided. 34579 * 34580 * <example module="transcludeFallbackContentExample" name="ng-transclude"> 34581 * <file name="index.html"> 34582 * <script> 34583 * angular.module('transcludeFallbackContentExample', []) 34584 * .directive('myButton', function(){ 34585 * return { 34586 * restrict: 'E', 34587 * transclude: true, 34588 * scope: true, 34589 * template: '<button style="cursor: pointer;">' + 34590 * '<ng-transclude>' + 34591 * '<b style="color: red;">Button1</b>' + 34592 * '</ng-transclude>' + 34593 * '</button>' 34594 * }; 34595 * }); 34596 * </script> 34597 * <!-- fallback button content --> 34598 * <my-button id="fallback"></my-button> 34599 * <!-- modified button content --> 34600 * <my-button id="modified"> 34601 * <i style="color: green;">Button2</i> 34602 * </my-button> 34603 * </file> 34604 * <file name="protractor.js" type="protractor"> 34605 * it('should have different transclude element content', function() { 34606 * expect(element(by.id('fallback')).getText()).toBe('Button1'); 34607 * expect(element(by.id('modified')).getText()).toBe('Button2'); 34608 * }); 34609 * </file> 34610 * </example> 34611 * 34612 * @example 34613 * ### Multi-slot transclusion 34614 * This example demonstrates using multi-slot transclusion in a component directive. 34615 * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample"> 34616 * <file name="index.html"> 34617 * <style> 34618 * .title, .footer { 34619 * background-color: gray 34620 * } 34621 * </style> 34622 * <div ng-controller="ExampleController"> 34623 * <input ng-model="title" aria-label="title"> <br/> 34624 * <textarea ng-model="text" aria-label="text"></textarea> <br/> 34625 * <pane> 34626 * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title> 34627 * <pane-body><p>{{text}}</p></pane-body> 34628 * </pane> 34629 * </div> 34630 * </file> 34631 * <file name="app.js"> 34632 * angular.module('multiSlotTranscludeExample', []) 34633 * .directive('pane', function() { 34634 * return { 34635 * restrict: 'E', 34636 * transclude: { 34637 * 'title': '?paneTitle', 34638 * 'body': 'paneBody', 34639 * 'footer': '?paneFooter' 34640 * }, 34641 * template: '<div style="border: 1px solid black;">' + 34642 * '<div class="title" ng-transclude="title">Fallback Title</div>' + 34643 * '<div ng-transclude="body"></div>' + 34644 * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' + 34645 * '</div>' 34646 * }; 34647 * }) 34648 * .controller('ExampleController', ['$scope', function($scope) { 34649 * $scope.title = 'Lorem Ipsum'; 34650 * $scope.link = 'https://google.com'; 34651 * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; 34652 * }]); 34653 * </file> 34654 * <file name="protractor.js" type="protractor"> 34655 * it('should have transcluded the title and the body', function() { 34656 * var titleElement = element(by.model('title')); 34657 * titleElement.clear(); 34658 * titleElement.sendKeys('TITLE'); 34659 * var textElement = element(by.model('text')); 34660 * textElement.clear(); 34661 * textElement.sendKeys('TEXT'); 34662 * expect(element(by.css('.title')).getText()).toEqual('TITLE'); 34663 * expect(element(by.binding('text')).getText()).toEqual('TEXT'); 34664 * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer'); 34665 * }); 34666 * </file> 34667 * </example> 34668 */ 34669var ngTranscludeMinErr = minErr('ngTransclude'); 34670var ngTranscludeDirective = ['$compile', function($compile) { 34671 return { 34672 restrict: 'EAC', 34673 compile: function ngTranscludeCompile(tElement) { 34674 34675 // Remove and cache any original content to act as a fallback 34676 var fallbackLinkFn = $compile(tElement.contents()); 34677 tElement.empty(); 34678 34679 return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) { 34680 34681 if (!$transclude) { 34682 throw ngTranscludeMinErr('orphan', 34683 'Illegal use of ngTransclude directive in the template! ' + 34684 'No parent directive that requires a transclusion found. ' + 34685 'Element: {0}', 34686 startingTag($element)); 34687 } 34688 34689 34690 // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default 34691 if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) { 34692 $attrs.ngTransclude = ''; 34693 } 34694 var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot; 34695 34696 // If the slot is required and no transclusion content is provided then this call will throw an error 34697 $transclude(ngTranscludeCloneAttachFn, null, slotName); 34698 34699 // If the slot is optional and no transclusion content is provided then use the fallback content 34700 if (slotName && !$transclude.isSlotFilled(slotName)) { 34701 useFallbackContent(); 34702 } 34703 34704 function ngTranscludeCloneAttachFn(clone, transcludedScope) { 34705 if (clone.length && notWhitespace(clone)) { 34706 $element.append(clone); 34707 } else { 34708 useFallbackContent(); 34709 // There is nothing linked against the transcluded scope since no content was available, 34710 // so it should be safe to clean up the generated scope. 34711 transcludedScope.$destroy(); 34712 } 34713 } 34714 34715 function useFallbackContent() { 34716 // Since this is the fallback content rather than the transcluded content, 34717 // we link against the scope of this directive rather than the transcluded scope 34718 fallbackLinkFn($scope, function(clone) { 34719 $element.append(clone); 34720 }); 34721 } 34722 34723 function notWhitespace(nodes) { 34724 for (var i = 0, ii = nodes.length; i < ii; i++) { 34725 var node = nodes[i]; 34726 if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) { 34727 return true; 34728 } 34729 } 34730 } 34731 }; 34732 } 34733 }; 34734}]; 34735 34736/** 34737 * @ngdoc directive 34738 * @name script 34739 * @restrict E 34740 * 34741 * @description 34742 * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the 34743 * template can be used by {@link ng.directive:ngInclude `ngInclude`}, 34744 * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the 34745 * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be 34746 * assigned through the element's `id`, which can then be used as a directive's `templateUrl`. 34747 * 34748 * @param {string} type Must be set to `'text/ng-template'`. 34749 * @param {string} id Cache name of the template. 34750 * 34751 * @example 34752 <example name="script-tag"> 34753 <file name="index.html"> 34754 <script type="text/ng-template" id="/tpl.html"> 34755 Content of the template. 34756 </script> 34757 34758 <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> 34759 <div id="tpl-content" ng-include src="currentTpl"></div> 34760 </file> 34761 <file name="protractor.js" type="protractor"> 34762 it('should load template defined inside script tag', function() { 34763 element(by.css('#tpl-link')).click(); 34764 expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/); 34765 }); 34766 </file> 34767 </example> 34768 */ 34769var scriptDirective = ['$templateCache', function($templateCache) { 34770 return { 34771 restrict: 'E', 34772 terminal: true, 34773 compile: function(element, attr) { 34774 if (attr.type === 'text/ng-template') { 34775 var templateUrl = attr.id, 34776 text = element[0].text; 34777 34778 $templateCache.put(templateUrl, text); 34779 } 34780 } 34781 }; 34782}]; 34783 34784/* exported selectDirective, optionDirective */ 34785 34786var noopNgModelController = { $setViewValue: noop, $render: noop }; 34787 34788function setOptionSelectedStatus(optionEl, value) { 34789 optionEl.prop('selected', value); 34790 /** 34791 * When unselecting an option, setting the property to null / false should be enough 34792 * However, screenreaders might react to the selected attribute instead, see 34793 * https://github.com/angular/angular.js/issues/14419 34794 * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false 34795 * or null 34796 */ 34797 optionEl.attr('selected', value); 34798} 34799 34800/** 34801 * @ngdoc type 34802 * @name select.SelectController 34803 * 34804 * @description 34805 * The controller for the {@link ng.select select} directive. The controller exposes 34806 * a few utility methods that can be used to augment the behavior of a regular or an 34807 * {@link ng.ngOptions ngOptions} select element. 34808 * 34809 * @example 34810 * ### Set a custom error when the unknown option is selected 34811 * 34812 * This example sets a custom error "unknownValue" on the ngModelController 34813 * when the select element's unknown option is selected, i.e. when the model is set to a value 34814 * that is not matched by any option. 34815 * 34816 * <example name="select-unknown-value-error" module="staticSelect"> 34817 * <file name="index.html"> 34818 * <div ng-controller="ExampleController"> 34819 * <form name="myForm"> 34820 * <label for="testSelect"> Single select: </label><br> 34821 * <select name="testSelect" ng-model="selected" unknown-value-error> 34822 * <option value="option-1">Option 1</option> 34823 * <option value="option-2">Option 2</option> 34824 * </select><br> 34825 * <span class="error" ng-if="myForm.testSelect.$error.unknownValue"> 34826 * Error: The current model doesn't match any option</span><br> 34827 * 34828 * <button ng-click="forceUnknownOption()">Force unknown option</button><br> 34829 * </form> 34830 * </div> 34831 * </file> 34832 * <file name="app.js"> 34833 * angular.module('staticSelect', []) 34834 * .controller('ExampleController', ['$scope', function($scope) { 34835 * $scope.selected = null; 34836 * 34837 * $scope.forceUnknownOption = function() { 34838 * $scope.selected = 'nonsense'; 34839 * }; 34840 * }]) 34841 * .directive('unknownValueError', function() { 34842 * return { 34843 * require: ['ngModel', 'select'], 34844 * link: function(scope, element, attrs, ctrls) { 34845 * var ngModelCtrl = ctrls[0]; 34846 * var selectCtrl = ctrls[1]; 34847 * 34848 * ngModelCtrl.$validators.unknownValue = function(modelValue, viewValue) { 34849 * if (selectCtrl.$isUnknownOptionSelected()) { 34850 * return false; 34851 * } 34852 * 34853 * return true; 34854 * }; 34855 * } 34856 * 34857 * }; 34858 * }); 34859 * </file> 34860 *</example> 34861 * 34862 * 34863 * @example 34864 * ### Set the "required" error when the unknown option is selected. 34865 * 34866 * By default, the "required" error on the ngModelController is only set on a required select 34867 * when the empty option is selected. This example adds a custom directive that also sets the 34868 * error when the unknown option is selected. 34869 * 34870 * <example name="select-unknown-value-required" module="staticSelect"> 34871 * <file name="index.html"> 34872 * <div ng-controller="ExampleController"> 34873 * <form name="myForm"> 34874 * <label for="testSelect"> Select: </label><br> 34875 * <select name="testSelect" ng-model="selected" required unknown-value-required> 34876 * <option value="option-1">Option 1</option> 34877 * <option value="option-2">Option 2</option> 34878 * </select><br> 34879 * <span class="error" ng-if="myForm.testSelect.$error.required">Error: Please select a value</span><br> 34880 * 34881 * <button ng-click="forceUnknownOption()">Force unknown option</button><br> 34882 * </form> 34883 * </div> 34884 * </file> 34885 * <file name="app.js"> 34886 * angular.module('staticSelect', []) 34887 * .controller('ExampleController', ['$scope', function($scope) { 34888 * $scope.selected = null; 34889 * 34890 * $scope.forceUnknownOption = function() { 34891 * $scope.selected = 'nonsense'; 34892 * }; 34893 * }]) 34894 * .directive('unknownValueRequired', function() { 34895 * return { 34896 * priority: 1, // This directive must run after the required directive has added its validator 34897 * require: ['ngModel', 'select'], 34898 * link: function(scope, element, attrs, ctrls) { 34899 * var ngModelCtrl = ctrls[0]; 34900 * var selectCtrl = ctrls[1]; 34901 * 34902 * var originalRequiredValidator = ngModelCtrl.$validators.required; 34903 * 34904 * ngModelCtrl.$validators.required = function() { 34905 * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) { 34906 * return false; 34907 * } 34908 * 34909 * return originalRequiredValidator.apply(this, arguments); 34910 * }; 34911 * } 34912 * }; 34913 * }); 34914 * </file> 34915 * <file name="protractor.js" type="protractor"> 34916 * it('should show the error message when the unknown option is selected', function() { 34917 34918 var error = element(by.className('error')); 34919 34920 expect(error.getText()).toBe('Error: Please select a value'); 34921 34922 element(by.cssContainingText('option', 'Option 1')).click(); 34923 34924 expect(error.isPresent()).toBe(false); 34925 34926 element(by.tagName('button')).click(); 34927 34928 expect(error.getText()).toBe('Error: Please select a value'); 34929 }); 34930 * </file> 34931 *</example> 34932 * 34933 * 34934 */ 34935var SelectController = 34936 ['$element', '$scope', /** @this */ function($element, $scope) { 34937 34938 var self = this, 34939 optionsMap = new NgMap(); 34940 34941 self.selectValueMap = {}; // Keys are the hashed values, values the original values 34942 34943 // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors 34944 self.ngModelCtrl = noopNgModelController; 34945 self.multiple = false; 34946 34947 // The "unknown" option is one that is prepended to the list if the viewValue 34948 // does not match any of the options. When it is rendered the value of the unknown 34949 // option is '? XXX ?' where XXX is the hashKey of the value that is not known. 34950 // 34951 // Support: IE 9 only 34952 // We can't just jqLite('<option>') since jqLite is not smart enough 34953 // to create it in <select> and IE barfs otherwise. 34954 self.unknownOption = jqLite(window.document.createElement('option')); 34955 34956 // The empty option is an option with the value '' that the application developer can 34957 // provide inside the select. It is always selectable and indicates that a "null" selection has 34958 // been made by the user. 34959 // If the select has an empty option, and the model of the select is set to "undefined" or "null", 34960 // the empty option is selected. 34961 // If the model is set to a different unmatched value, the unknown option is rendered and 34962 // selected, i.e both are present, because a "null" selection and an unknown value are different. 34963 self.hasEmptyOption = false; 34964 self.emptyOption = undefined; 34965 34966 self.renderUnknownOption = function(val) { 34967 var unknownVal = self.generateUnknownOptionValue(val); 34968 self.unknownOption.val(unknownVal); 34969 $element.prepend(self.unknownOption); 34970 setOptionSelectedStatus(self.unknownOption, true); 34971 $element.val(unknownVal); 34972 }; 34973 34974 self.updateUnknownOption = function(val) { 34975 var unknownVal = self.generateUnknownOptionValue(val); 34976 self.unknownOption.val(unknownVal); 34977 setOptionSelectedStatus(self.unknownOption, true); 34978 $element.val(unknownVal); 34979 }; 34980 34981 self.generateUnknownOptionValue = function(val) { 34982 return '? ' + hashKey(val) + ' ?'; 34983 }; 34984 34985 self.removeUnknownOption = function() { 34986 if (self.unknownOption.parent()) self.unknownOption.remove(); 34987 }; 34988 34989 self.selectEmptyOption = function() { 34990 if (self.emptyOption) { 34991 $element.val(''); 34992 setOptionSelectedStatus(self.emptyOption, true); 34993 } 34994 }; 34995 34996 self.unselectEmptyOption = function() { 34997 if (self.hasEmptyOption) { 34998 setOptionSelectedStatus(self.emptyOption, false); 34999 } 35000 }; 35001 35002 $scope.$on('$destroy', function() { 35003 // disable unknown option so that we don't do work when the whole select is being destroyed 35004 self.renderUnknownOption = noop; 35005 }); 35006 35007 // Read the value of the select control, the implementation of this changes depending 35008 // upon whether the select can have multiple values and whether ngOptions is at work. 35009 self.readValue = function readSingleValue() { 35010 var val = $element.val(); 35011 // ngValue added option values are stored in the selectValueMap, normal interpolations are not 35012 var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val; 35013 35014 if (self.hasOption(realVal)) { 35015 return realVal; 35016 } 35017 35018 return null; 35019 }; 35020 35021 35022 // Write the value to the select control, the implementation of this changes depending 35023 // upon whether the select can have multiple values and whether ngOptions is at work. 35024 self.writeValue = function writeSingleValue(value) { 35025 // Make sure to remove the selected attribute from the previously selected option 35026 // Otherwise, screen readers might get confused 35027 var currentlySelectedOption = $element[0].options[$element[0].selectedIndex]; 35028 if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false); 35029 35030 if (self.hasOption(value)) { 35031 self.removeUnknownOption(); 35032 35033 var hashedVal = hashKey(value); 35034 $element.val(hashedVal in self.selectValueMap ? hashedVal : value); 35035 35036 // Set selected attribute and property on selected option for screen readers 35037 var selectedOption = $element[0].options[$element[0].selectedIndex]; 35038 setOptionSelectedStatus(jqLite(selectedOption), true); 35039 } else { 35040 self.selectUnknownOrEmptyOption(value); 35041 } 35042 }; 35043 35044 35045 // Tell the select control that an option, with the given value, has been added 35046 self.addOption = function(value, element) { 35047 // Skip comment nodes, as they only pollute the `optionsMap` 35048 if (element[0].nodeType === NODE_TYPE_COMMENT) return; 35049 35050 assertNotHasOwnProperty(value, '"option value"'); 35051 if (value === '') { 35052 self.hasEmptyOption = true; 35053 self.emptyOption = element; 35054 } 35055 var count = optionsMap.get(value) || 0; 35056 optionsMap.set(value, count + 1); 35057 // Only render at the end of a digest. This improves render performance when many options 35058 // are added during a digest and ensures all relevant options are correctly marked as selected 35059 scheduleRender(); 35060 }; 35061 35062 // Tell the select control that an option, with the given value, has been removed 35063 self.removeOption = function(value) { 35064 var count = optionsMap.get(value); 35065 if (count) { 35066 if (count === 1) { 35067 optionsMap.delete(value); 35068 if (value === '') { 35069 self.hasEmptyOption = false; 35070 self.emptyOption = undefined; 35071 } 35072 } else { 35073 optionsMap.set(value, count - 1); 35074 } 35075 } 35076 }; 35077 35078 // Check whether the select control has an option matching the given value 35079 self.hasOption = function(value) { 35080 return !!optionsMap.get(value); 35081 }; 35082 35083 /** 35084 * @ngdoc method 35085 * @name select.SelectController#$hasEmptyOption 35086 * 35087 * @description 35088 * 35089 * Returns `true` if the select element currently has an empty option 35090 * element, i.e. an option that signifies that the select is empty / the selection is null. 35091 * 35092 */ 35093 self.$hasEmptyOption = function() { 35094 return self.hasEmptyOption; 35095 }; 35096 35097 /** 35098 * @ngdoc method 35099 * @name select.SelectController#$isUnknownOptionSelected 35100 * 35101 * @description 35102 * 35103 * Returns `true` if the select element's unknown option is selected. The unknown option is added 35104 * and automatically selected whenever the select model doesn't match any option. 35105 * 35106 */ 35107 self.$isUnknownOptionSelected = function() { 35108 // Presence of the unknown option means it is selected 35109 return $element[0].options[0] === self.unknownOption[0]; 35110 }; 35111 35112 /** 35113 * @ngdoc method 35114 * @name select.SelectController#$isEmptyOptionSelected 35115 * 35116 * @description 35117 * 35118 * Returns `true` if the select element has an empty option and this empty option is currently 35119 * selected. Returns `false` if the select element has no empty option or it is not selected. 35120 * 35121 */ 35122 self.$isEmptyOptionSelected = function() { 35123 return self.hasEmptyOption && $element[0].options[$element[0].selectedIndex] === self.emptyOption[0]; 35124 }; 35125 35126 self.selectUnknownOrEmptyOption = function(value) { 35127 if (value == null && self.emptyOption) { 35128 self.removeUnknownOption(); 35129 self.selectEmptyOption(); 35130 } else if (self.unknownOption.parent().length) { 35131 self.updateUnknownOption(value); 35132 } else { 35133 self.renderUnknownOption(value); 35134 } 35135 }; 35136 35137 var renderScheduled = false; 35138 function scheduleRender() { 35139 if (renderScheduled) return; 35140 renderScheduled = true; 35141 $scope.$$postDigest(function() { 35142 renderScheduled = false; 35143 self.ngModelCtrl.$render(); 35144 }); 35145 } 35146 35147 var updateScheduled = false; 35148 function scheduleViewValueUpdate(renderAfter) { 35149 if (updateScheduled) return; 35150 35151 updateScheduled = true; 35152 35153 $scope.$$postDigest(function() { 35154 if ($scope.$$destroyed) return; 35155 35156 updateScheduled = false; 35157 self.ngModelCtrl.$setViewValue(self.readValue()); 35158 if (renderAfter) self.ngModelCtrl.$render(); 35159 }); 35160 } 35161 35162 35163 self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) { 35164 35165 if (optionAttrs.$attr.ngValue) { 35166 // The value attribute is set by ngValue 35167 var oldVal, hashedVal
vendor: 3,872 bytes, lines 35167-35280
35167 = NaN; 35168 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) { 35169 35170 var removal; 35171 var previouslySelected = optionElement.prop('selected'); 35172 35173 if (isDefined(hashedVal)) { 35174 self.removeOption(oldVal); 35175 delete self.selectValueMap[hashedVal]; 35176 removal = true; 35177 } 35178 35179 hashedVal = hashKey(newVal); 35180 oldVal = newVal; 35181 self.selectValueMap[hashedVal] = newVal; 35182 self.addOption(newVal, optionElement); 35183 // Set the attribute directly instead of using optionAttrs.$set - this stops the observer 35184 // from firing a second time. Other $observers on value will also get the result of the 35185 // ngValue expression, not the hashed value 35186 optionElement.attr('value', hashedVal); 35187 35188 if (removal && previouslySelected) { 35189 scheduleViewValueUpdate(); 35190 } 35191 35192 }); 35193 } else if (interpolateValueFn) { 35194 // The value attribute is interpolated 35195 optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) { 35196 // This method is overwritten in ngOptions and has side-effects! 35197 self.readValue(); 35198 35199 var removal; 35200 var previouslySelected = optionElement.prop('selected'); 35201 35202 if (isDefined(oldVal)) { 35203 self.removeOption(oldVal); 35204 removal = true; 35205 } 35206 oldVal = newVal; 35207 self.addOption(newVal, optionElement); 35208 35209 if (removal && previouslySelected) { 35210 scheduleViewValueUpdate(); 35211 } 35212 }); 35213 } else if (interpolateTextFn) { 35214 // The text content is interpolated 35215 optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) { 35216 optionAttrs.$set('value', newVal); 35217 var previouslySelected = optionElement.prop('selected'); 35218 if (oldVal !== newVal) { 35219 self.removeOption(oldVal); 35220 } 35221 self.addOption(newVal, optionElement); 35222 35223 if (oldVal && previouslySelected) { 35224 scheduleViewValueUpdate(); 35225 } 35226 }); 35227 } else { 35228 // The value attribute is static 35229 self.addOption(optionAttrs.value, optionElement); 35230 } 35231 35232 35233 optionAttrs.$observe('disabled', function(newVal) { 35234 35235 // Since model updates will also select disabled options (like ngOptions), 35236 // we only have to handle options becoming disabled, not enabled 35237 35238 if (newVal === 'true' || newVal && optionElement.prop('selected')) { 35239 if (self.multiple) { 35240 scheduleViewValueUpdate(true); 35241 } else { 35242 self.ngModelCtrl.$setViewValue(null); 35243 self.ngModelCtrl.$render(); 35244 } 35245 } 35246 }); 35247 35248 optionElement.on('$destroy', function() { 35249 var currentValue = self.readValue(); 35250 var removeValue = optionAttrs.value; 35251 35252 self.removeOption(removeValue); 35253 scheduleRender(); 35254 35255 if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 || 35256 currentValue === removeValue 35257 ) { 35258 // When multiple (selected) options are destroyed at the same time, we don't want 35259 // to run a model update for each of them. Instead, run a single update in the $$postDigest 35260 scheduleViewValueUpdate(true); 35261 } 35262 }); 35263 }; 35264}]; 35265 35266/** 35267 * @ngdoc directive 35268 * @name select 35269 * @restrict E 35270 * 35271 * @description 35272 * HTML `select` element with AngularJS data-binding. 35273 * 35274 * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding 35275 * between the scope and the `<select>` control (including setting default values). 35276 * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or 35277 * {@link ngOptions `ngOptions`} directives. 35278 * 35279 * When an item in the `<select>` menu is selected, the value of the selected option will be bound 35280 * to the model identified by the `ngModel` directive. With static or repeated o
35280ptions, this is 35281 * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing. 35282 * Value and textContent can be interpolated. 35283 * 35284 * The {@link select.SelectController select controller} exposes utility functions that can be used 35285 * to manipulate the select's behavior. 35286 * 35287 * ## Matching model and option values 35288 * 35289 * In general, the match between the model and an option is evaluated by strictly comparing the model 35290 * value against the value of the available options. 35291 * 35292 * If you are setting the option value with the option's `value` attribute, or textContent, the 35293 * value will always be a `string` which means that the model value must also be a string. 35294 * Otherwise the `select` directive cannot match them correctly. 35295 * 35296 * To bind the model to a non-string value, you can use one of the following strategies: 35297 * - the {@link ng.ngOptions `ngOptions`} directive 35298 * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value}) 35299 * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be 35300 * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example}) 35301 * - model $parsers / $formatters to convert the string value 35302 * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example}) 35303 * 35304 * If the viewValue of `ngModel` does not match any of the options, then the control 35305 * will automatically add an "unknown" option, which it then removes when the mismatch is resolved. 35306 * 35307 * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can 35308 * be nested into the `<select>` element. This element will then represent the `null` or "not selected" 35309 * option. See example below for demonstration. 35310 * 35311 * ## Choosing between `ngRepeat` and `ngOptions` 35312 * 35313 * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions 35314 * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits: 35315 * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the 35316 * comprehension expression 35317 * - reduced memory consumption by not creating a new scope for each repeated instance 35318 * - increased render speed by creating the options in a documentFragment instead of individually 35319 * 35320 * Specifically, select with repeated options slows down significantly starting at 2000 options in 35321 * Chrome and Internet Explorer / Edge. 35322 * 35323 * 35324 * @param {string} ngModel Assignable AngularJS expression to data-bind to. 35325 * @param {string=} name Property name of the form under which the control is published. 35326 * @param {string=} multiple Allows multiple options to be selected. The selected values will be 35327 * bound to the model as an array. 35328 * @param {string=} required Sets `required` validation error key if the value is not entered. 35329 * @param {string=} ngRequired Adds required attribute and required validation constraint to 35330 * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required 35331 * when you want to data-bind to the required attribute. 35332 * @param {string=} ngChange AngularJS expression to be executed when selected option(s) changes due to user 35333 * interaction with the select element. 35334 * @param {string=} ngOptions sets the options that the select is populated with and defines what is 35335 * set on the model on selection. See {@link ngOptions `ngOptions`}. 35336 * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the 35337 * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive. 35338 * 35339 * 35340 * @knownIssue 35341 * 35342 * In Firefox, the select model is only updated when the select element is blurred. For example, 35343 * when switching between options with the keyboard, the select model is only set to the 35344 * currently selected option when the select is blurred, e.g via tab key or clicking the mouse 35345 * outside the select. 35346 * 35347 * This is due to an ambiguity in the select element specification. See the 35348 * [issue on the Firefox bug tracker](https://bugzilla.mozilla.org/show_bug.cgi?id=126379) 35349 * for more information, and this 35350 * [Github comment for a workaround](https://github.com/angular/angular.js/issues/9134#issuecomment-130800488)
vendor: 15,509 bytes, lines 35350-35755
35350 35351 * 35352 * @example 35353 * ### Simple `select` elements with static options 35354 * 35355 * <example name="static-select" module="staticSelect"> 35356 * <file name="index.html"> 35357 * <div ng-controller="ExampleController"> 35358 * <form name="myForm"> 35359 * <label for="singleSelect"> Single select: </label><br> 35360 * <select name="singleSelect" ng-model="data.singleSelect"> 35361 * <option value="option-1">Option 1</option> 35362 * <option value="option-2">Option 2</option> 35363 * </select><br> 35364 * 35365 * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br> 35366 * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect"> 35367 * <option value="">---Please select---</option> <!-- not selected / blank option --> 35368 * <option value="{{data.option1}}">Option 1</option> <!-- interpolation --> 35369 * <option value="option-2">Option 2</option> 35370 * </select><br> 35371 * <button ng-click="forceUnknownOption()">Force unknown option</button><br> 35372 * <tt>singleSelect = {{data.singleSelect}}</tt> 35373 * 35374 * <hr> 35375 * <label for="multipleSelect"> Multiple select: </label><br> 35376 * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple> 35377 * <option value="option-1">Option 1</option> 35378 * <option value="option-2">Option 2</option> 35379 * <option value="option-3">Option 3</option> 35380 * </select><br> 35381 * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/> 35382 * </form> 35383 * </div> 35384 * </file> 35385 * <file name="app.js"> 35386 * angular.module('staticSelect', []) 35387 * .controller('ExampleController', ['$scope', function($scope) { 35388 * $scope.data = { 35389 * singleSelect: null, 35390 * multipleSelect: [], 35391 * option1: 'option-1' 35392 * }; 35393 * 35394 * $scope.forceUnknownOption = function() { 35395 * $scope.data.singleSelect = 'nonsense'; 35396 * }; 35397 * }]); 35398 * </file> 35399 *</example> 35400 * 35401 * @example 35402 * ### Using `ngRepeat` to generate `select` options 35403 * <example name="select-ngrepeat" module="ngrepeatSelect"> 35404 * <file name="index.html"> 35405 * <div ng-controller="ExampleController"> 35406 * <form name="myForm"> 35407 * <label for="repeatSelect"> Repeat select: </label> 35408 * <select name="repeatSelect" id="repeatSelect" ng-model="data.model"> 35409 * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option> 35410 * </select> 35411 * </form> 35412 * <hr> 35413 * <tt>model = {{data.model}}</tt><br/> 35414 * </div> 35415 * </file> 35416 * <file name="app.js"> 35417 * angular.module('ngrepeatSelect', []) 35418 * .controller('ExampleController', ['$scope', function($scope) { 35419 * $scope.data = { 35420 * model: null, 35421 * availableOptions: [ 35422 * {id: '1', name: 'Option A'}, 35423 * {id: '2', name: 'Option B'}, 35424 * {id: '3', name: 'Option C'} 35425 * ] 35426 * }; 35427 * }]); 35428 * </file> 35429 *</example> 35430 * 35431 * @example 35432 * ### Using `ngValue` to bind the model to an array of objects 35433 * <example name="select-ngvalue" module="ngvalueSelect"> 35434 * <file name="index.html"> 35435 * <div ng-controller="ExampleController"> 35436 * <form name="myForm"> 35437 * <label for="ngvalueselect"> ngvalue select: </label> 35438 * <select size="6" name="ngvalueselect" ng-model="data.model" multiple> 35439 * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option> 35440 * </select> 35441 * </form> 35442 * <hr> 35443 * <pre>model = {{data.model | json}}</pre><br/> 35444 * </div> 35445 * </file> 35446 * <file name="app.js"> 35447 * angular.module('ngvalueSelect', []) 35448 * .controller('ExampleController', ['$scope', function($scope) { 35449 * $scope.data = { 35450 * model: null, 35451 * availableOptions: [ 35452 {value: 'myString', name: 'string'}, 35453 {value: 1, name: 'integer'}, 35454 {value: true, name: 'boolean'}, 35455 {value: null, name: 'null'}, 35456 {value: {prop: 'value'}, name: 'object'}, 35457 {value: ['a'], name: 'array'} 35458 * ] 35459 * }; 35460 * }]); 35461 * </file> 35462 *</example> 35463 * 35464 * @example 35465 * ### Using `select` with `ngOptions` and setting a default value 35466 * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples. 35467 * 35468 * <example name="select-with-default-values" module="defaultValueSelect"> 35469 * <file name="index.html"> 35470 * <div ng-controller="ExampleController"> 35471 * <form name="myForm"> 35472 * <label for="mySelect">Make a choice:</label> 35473 * <select name="mySelect" id="mySelect" 35474 * ng-options="option.name for option in data.availableOptions track by option.id" 35475 * ng-model="data.selectedOption"></select> 35476 * </form> 35477 * <hr> 35478 * <tt>option = {{data.selectedOption}}</tt><br/> 35479 * </div> 35480 * </file> 35481 * <file name="app.js"> 35482 * angular.module('defaultValueSelect', []) 35483 * .controller('ExampleController', ['$scope', function($scope) { 35484 * $scope.data = { 35485 * availableOptions: [ 35486 * {id: '1', name: 'Option A'}, 35487 * {id: '2', name: 'Option B'}, 35488 * {id: '3', name: 'Option C'} 35489 * ], 35490 * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui 35491 * }; 35492 * }]); 35493 * </file> 35494 *</example> 35495 * 35496 * @example 35497 * ### Binding `select` to a non-string value via `ngModel` parsing / formatting 35498 * 35499 * <example name="select-with-non-string-options" module="nonStringSelect"> 35500 * <file name="index.html"> 35501 * <select ng-model="model.id" convert-to-number> 35502 * <option value="0">Zero</option> 35503 * <option value="1">One</option> 35504 * <option value="2">Two</option> 35505 * </select> 35506 * {{ model }} 35507 * </file> 35508 * <file name="app.js"> 35509 * angular.module('nonStringSelect', []) 35510 * .run(function($rootScope) { 35511 * $rootScope.model = { id: 2 }; 35512 * }) 35513 * .directive('convertToNumber', function() { 35514 * return { 35515 * require: 'ngModel', 35516 * link: function(scope, element, attrs, ngModel) { 35517 * ngModel.$parsers.push(function(val) { 35518 * return parseInt(val, 10); 35519 * }); 35520 * ngModel.$formatters.push(function(val) { 35521 * return '' + val; 35522 * }); 35523 * } 35524 * }; 35525 * }); 35526 * </file> 35527 * <file name="protractor.js" type="protractor"> 35528 * it('should initialize to model', function() { 35529 * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two'); 35530 * }); 35531 * </file> 35532 * </example> 35533 * 35534 */ 35535var selectDirective = function() { 35536 35537 return { 35538 restrict: 'E', 35539 require: ['select', '?ngModel'], 35540 controller: SelectController, 35541 priority: 1, 35542 link: { 35543 pre: selectPreLink, 35544 post: selectPostLink 35545 } 35546 }; 35547 35548 function selectPreLink(scope, element, attr, ctrls) { 35549 35550 var selectCtrl = ctrls[0]; 35551 var ngModelCtrl = ctrls[1]; 35552 35553 // if ngModel is not defined, we don't need to do anything but set the registerOption 35554 // function to noop, so options don't get added internally 35555 if (!ngModelCtrl) { 35556 selectCtrl.registerOption = noop; 35557 return; 35558 } 35559 35560 35561 selectCtrl.ngModelCtrl = ngModelCtrl; 35562 35563 // When the selected item(s) changes we delegate getting the value of the select control 35564 // to the `readValue` method, which can be changed if the select can have multiple 35565 // selected values or if the options are being generated by `ngOptions` 35566 element.on('change', function() { 35567 selectCtrl.removeUnknownOption(); 35568 scope.$apply(function() { 35569 ngModelCtrl.$setViewValue(selectCtrl.readValue()); 35570 }); 35571 }); 35572 35573 // If the select allows multiple values then we need to modify how we read and write 35574 // values from and to the control; also what it means for the value to be empty and 35575 // we have to add an extra watch since ngModel doesn't work well with arrays - it 35576 // doesn't trigger rendering if only an item in the array changes. 35577 if (attr.multiple) { 35578 selectCtrl.multiple = true; 35579 35580 // Read value now needs to check each option to see if it is selected 35581 selectCtrl.readValue = function readMultipleValue() { 35582 var array = []; 35583 forEach(element.find('option'), function(option) { 35584 if (option.selected && !option.disabled) { 35585 var val = option.value; 35586 array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val); 35587 } 35588 }); 35589 return array; 35590 }; 35591 35592 // Write value now needs to set the selected property of each matching option 35593 selectCtrl.writeValue = function writeMultipleValue(value) { 35594 forEach(element.find('option'), function(option) { 35595 var shouldBeSelected = !!value && (includes(value, option.value) || 35596 includes(value, selectCtrl.selectValueMap[option.value])); 35597 var currentlySelected = option.selected; 35598 35599 // Support: IE 9-11 only, Edge 12-15+ 35600 // In IE and Edge adding options to the selection via shift+click/UP/DOWN 35601 // will de-select already selected options if "selected" on those options was set 35602 // more than once (i.e. when the options were already selected) 35603 // So we only modify the selected property if necessary. 35604 // Note: this behavior cannot be replicated via unit tests because it only shows in the 35605 // actual user interface. 35606 if (shouldBeSelected !== currentlySelected) { 35607 setOptionSelectedStatus(jqLite(option), shouldBeSelected); 35608 } 35609 35610 }); 35611 }; 35612 35613 // we have to do it on each watch since ngModel watches reference, but 35614 // we need to work of an array, so we need to see if anything was inserted/removed 35615 var lastView, lastViewRef = NaN; 35616 scope.$watch(function selectMultipleWatch() { 35617 if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) { 35618 lastView = shallowCopy(ngModelCtrl.$viewValue); 35619 ngModelCtrl.$render(); 35620 } 35621 lastViewRef = ngModelCtrl.$viewValue; 35622 }); 35623 35624 // If we are a multiple select then value is now a collection 35625 // so the meaning of $isEmpty changes 35626 ngModelCtrl.$isEmpty = function(value) { 35627 return !value || value.length === 0; 35628 }; 35629 35630 } 35631 } 35632 35633 function selectPostLink(scope, element, attrs, ctrls) { 35634 // if ngModel is not defined, we don't need to do anything 35635 var ngModelCtrl = ctrls[1]; 35636 if (!ngModelCtrl) return; 35637 35638 var selectCtrl = ctrls[0]; 35639 35640 // We delegate rendering to the `writeValue` method, which can be changed 35641 // if the select can have multiple selected values or if the options are being 35642 // generated by `ngOptions`. 35643 // This must be done in the postLink fn to prevent $render to be called before 35644 // all nodes have been linked correctly. 35645 ngModelCtrl.$render = function() { 35646 selectCtrl.writeValue(ngModelCtrl.$viewValue); 35647 }; 35648 } 35649}; 35650 35651 35652// The option directive is purely designed to communicate the existence (or lack of) 35653// of dynamically created (and destroyed) option elements to their containing select 35654// directive via its controller. 35655var optionDirective = ['$interpolate', function($interpolate) { 35656 return { 35657 restrict: 'E', 35658 priority: 100, 35659 compile: function(element, attr) { 35660 var interpolateValueFn, interpolateTextFn; 35661 35662 if (isDefined(attr.ngValue)) { 35663 // Will be handled by registerOption 35664 } else if (isDefined(attr.value)) { 35665 // If the value attribute is defined, check if it contains an interpolation 35666 interpolateValueFn = $interpolate(attr.value, true); 35667 } else { 35668 // If the value attribute is not defined then we fall back to the 35669 // text content of the option element, which may be interpolated 35670 interpolateTextFn = $interpolate(element.text(), true); 35671 if (!interpolateTextFn) { 35672 attr.$set('value', element.text()); 35673 } 35674 } 35675 35676 return function(scope, element, attr) { 35677 // This is an optimization over using ^^ since we don't want to have to search 35678 // all the way to the root of the DOM for every single option element 35679 var selectCtrlName = '$selectController', 35680 parent = element.parent(), 35681 selectCtrl = parent.data(selectCtrlName) || 35682 parent.parent().data(selectCtrlName); // in case we are in optgroup 35683 35684 if (selectCtrl) { 35685 selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn); 35686 } 35687 }; 35688 } 35689 }; 35690}]; 35691 35692/** 35693 * @ngdoc directive 35694 * @name ngRequired 35695 * @restrict A 35696 * 35697 * @param {expression} ngRequired AngularJS expression. If it evaluates to `true`, it sets the 35698 * `required` attribute to the element and adds the `required` 35699 * {@link ngModel.NgModelController#$validators `validator`}. 35700 * 35701 * @description 35702 * 35703 * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. 35704 * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be 35705 * applied to custom controls. 35706 * 35707 * The directive sets the `required` attribute on the element if the AngularJS expression inside 35708 * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we 35709 * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide} 35710 * for more info. 35711 * 35712 * The validator will set the `required` error key to true if the `required` attribute is set and 35713 * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the 35714 * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the 35715 * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing 35716 * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based. 35717 * 35718 * @example 35719 * <example name="ngRequiredDirective" module="ngRequiredExample"> 35720 * <file name="index.html"> 35721 * <script> 35722 * angular.module('ngRequiredExample', []) 35723 * .controller('ExampleController', ['$scope', function($scope) { 35724 * $scope.required = true; 35725 * }]); 35726 * </script> 35727 * <div ng-controller="ExampleController"> 35728 * <form name="form"> 35729 * <label for="required">Toggle required: </label> 35730 * <input type="checkbox" ng-model="required" id="required" /> 35731 * <br> 35732 * <label for="input">This input must be filled if `required` is true: </label> 35733 * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br> 35734 * <hr> 35735 * required error set? = <code>{{form.input.$error.required}}</code><br> 35736 * model = <code>{{model}}</code> 35737 * </form> 35738 * </div> 35739 * </file> 35740 * <file name="protractor.js" type="protractor"> 35741 var required = element(by.binding('form.input.$error.required')); 35742 var model = element(by.binding('model')); 35743 var input = element(by.id('input')); 35744 35745 it('should set the required error', function() { 35746 expect(required.getText()).toContain('true'); 35747 35748 input.sendKeys('123'); 35749 expect(required.getText()).not.toContain('true'); 35750 expect(model.getText()).toContain('123'); 35751 }); 35752 * </file> 35753 * </example> 35754 */ 35755var requiredDirective =
35755function() { 35756 return { 35757 restrict: 'A', 35758 require: '?ngModel', 35759 link: function(scope, elm, attr, ctrl) { 35760 if (!ctrl) return; 35761 attr.required = true; // force truthy in case we are on non input element 35762 35763 ctrl.$validators.required = function(modelValue, viewValue) { 35764 return !attr.required || !ctrl.$isEmpty(viewValue); 35765 }; 35766 35767 attr.$observe('required', function() { 35768 ctrl.$validate(); 35769 }); 35770 } 35771 }; 35772}; 35773 35774/** 35775 * @ngdoc directive 35776 * @name ngPattern 35777 * @restrict A 35778 * 35779 * @param {expression|RegExp} ngPattern AngularJS expression that must evaluate to a `RegExp` or a `String` 35780 * parsable into a `RegExp`, or a `RegExp` literal. See above for 35781 * more details. 35782 * 35783 * @description 35784 * 35785 * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. 35786 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. 35787 * 35788 * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} 35789 * does not match a RegExp which is obtained from the `ngPattern` attribute value: 35790 * - the value is an AngularJS expression: 35791 * - If the expression evaluates to a RegExp object, then this is used directly. 35792 * - If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it 35793 * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`. 35794 * - If the value is a RegExp literal, e.g. `ngPattern="/^\d+$/"`, it is used directly. 35795 * 35796 * <div class="alert alert-info"> 35797 * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to 35798 * start at the index of the last search's match, thus not taking the whole input value into 35799 * account. 35800 * </div> 35801 * 35802 * <div class="alert alert-info"> 35803 * **Note:** This directive is also added when the plain `pattern` attribute is used, with two 35804 * differences: 35805 * <ol> 35806 * <li> 35807 * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is 35808 * not available. 35809 * </li> 35810 * <li> 35811 * The `ngPattern` attribute must be an expression, while the `pattern` value must be 35812 * interpolated. 35813 * </li> 35814 * </ol> 35815 * </div> 35816 * 35817 * @example 35818 * <example name="ngPatternDirective" module="ngPatternExample"> 35819 * <file name="index.html"> 35820 * <script> 35821 * angular.module('ngPatternExample', []) 35822 * .controller('ExampleController', ['$scope', function($scope) { 35823 * $scope.regex = '\\d+'; 35824 * }]); 35825 * </script>
35826 * <div ng-controller="ExampleController"> 35827 * <form name="form"> 35828 * <label for="regex">Set a pattern (regex string): </label> 35829 * <input type="text" ng-model="regex" id="regex" /> 35830 * <br> 35831 * <label for="input">This input is restricted by the current pattern: </label> 35832 * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br> 35833 * <hr> 35834 * input valid? = <code>{{form.input.$valid}}</code><br> 35835 * model = <code>{{model}}</code> 35836 * </form> 35837 * </div> 35838 * </file> 35839 * <file name="protractor.js" type="protractor"> 35840 var model = element(by.binding('model')); 35841 var input = element(by.id('input')); 35842 35843 it('should validate the input with the default pattern', function() { 35844 input.sendKeys('aaa'); 35845 expect(model.getText()).not.toContain('aaa'); 35846 35847 input.clear().then(function() { 35848 input.sendKeys('123'); 35849 expect(model.getText()).toContain('123'); 35850 }); 35851 }); 35852 * </file> 35853 * </example> 35854 */ 35855var patternDirective = function() { 35856 return { 35857 restrict: 'A', 35858 require: '?ngModel', 35859 link: function(scope, elm, attr, ctrl) { 35860 if (!ctrl) return; 35861 35862 var regexp, patternExp = attr.ngPattern || attr.pattern; 35863 attr.$observe('pattern', function(regex) { 35864 if (isString(regex) && regex.length > 0) { 35865 regex = new RegExp('^' + regex + '$'); 35866 } 35867 35868 if (regex && !regex.test) { 35869 throw minErr('ngPattern')('noregexp', 35870 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, 35871 regex, startingTag(elm)); 35872 } 35873 35874 regexp = regex || undefined; 35875 ctrl.$validate(); 35876 }); 35877 35878 ctrl.$validators.pattern = function(modelValue, viewValue) { 35879 // HTML5 pattern constraint validates the input value, so we validate the viewValue 35880 return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue); 35881 }; 35882 } 35883 }; 35884}; 35885 35886/** 35887 * @ngdoc directive 35888 * @name ngMaxlength 35889 * @restrict A 35890 * 35891 * @param {expression} ngMaxlength AngularJS expression that must evaluate to a `Number` or `String` 35892 * parsable into a `Number`. Used as value for the `maxlength` 35893 * {@link ngModel.NgModelController#$validators validator}. 35894 * 35895 * @description 35896 * 35897 * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. 35898 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. 35899 * 35900 * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} 35901 * is longer than the integer obtained by evaluating the AngularJS expression given in the 35902 * `ngMaxlength` attribute value. 35903 * 35904 * <div class="alert alert-info"> 35905 * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two 35906 * differences: 35907 * <ol> 35908 * <li> 35909 * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint 35910 * validation is not available. 35911 * </li> 35912 * <li> 35913 * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be 35914 * interpolated. 35915 * </li> 35916 * </ol> 35917 * </div> 35918 * 35919 * @example 35920 * <example name="ngMaxlengthDirective" module="ngMaxlengthExample"> 35921 * <file name="index.html"> 35922 * <script> 35923 * angular.module('ngMaxlengthExample', []) 35924 * .controller('ExampleController', ['$scope', function($scope) { 35925 * $scope.maxlength = 5; 35926 * }]); 35927 * </script>
35928 * <div ng-controller="ExampleController"> 35929 * <form name="form"> 35930 * <label for="maxlength">Set a maxlength: </label> 35931 * <input type="number" ng-model="maxlength" id="maxlength" /> 35932 * <br> 35933 * <label for="input">This input is restricted by the current maxlength: </label> 35934 * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br> 35935 * <hr> 35936 * input valid? = <code>{{form.input.$valid}}</code><br> 35937 * model = <code>{{model}}</code> 35938 * </form> 35939 * </div> 35940 * </file> 35941 * <file name="protractor.js" type="protractor"> 35942 var model = element(by.binding('model')); 35943 var input = element(by.id('input')); 35944 35945 it('should validate the input with the default maxlength', function() { 35946 input.sendKeys('abcdef'); 35947 expect(model.getText()).not.toContain('abcdef'); 35948 35949 input.clear().then(function() { 35950 input.sendKeys('abcde'); 35951 expect(model.getText()).toContain('abcde'); 35952 }); 35953 }); 35954 * </file> 35955 * </example> 35956 */ 35957var maxlengthDirective = function() { 35958 return { 35959 restrict: 'A', 35960 require: '?ngModel', 35961 link: function(scope, elm, attr, ctrl) { 35962 if (!ctrl) return; 35963 35964 var maxlength = -1; 35965 attr.$observe('maxlength', function(value) { 35966 var intVal = toInt(value); 35967 maxlength = isNumberNaN(intVal) ? -1 : intVal; 35968 ctrl.$validate(); 35969 }); 35970 ctrl.$validators.maxlength = function(modelValue, viewValue) { 35971 return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength); 35972 }; 35973 } 35974 }; 35975}; 35976 35977/** 35978 * @ngdoc directive 35979 * @name ngMinlength 35980 * @restrict A 35981 * 35982 * @param {expression} ngMinlength AngularJS expression that must evaluate to a `Number` or `String` 35983 * parsable into a `Number`. Used as value for the `minlength` 35984 * {@link ngModel.NgModelController#$validators validator}. 35985 * 35986 * @description 35987 * 35988 * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. 35989 * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. 35990 * 35991 * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} 35992 * is shorter than the integer obtained by evaluating the AngularJS expression given in the 35993 * `ngMinlength` attribute value. 35994 * 35995 * <div class="alert alert-info"> 35996 * **Note:** This directive is also added when the plain `minlength` attribute is used, with two 35997 * differences: 35998 * <ol> 35999 * <li> 36000 * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint 36001 * validation is not available. 36002 * </li> 36003 * <li> 36004 * The `ngMinlength` value must be an expression, while the `minlength` value must be 36005 * interpolated. 36006 * </li> 36007 * </ol> 36008 * </div> 36009 * 36010 * @example 36011 * <example name="ngMinlengthDirective" module="ngMinlengthExample"> 36012 * <file name="index.html"> 36013 * <script> 36014 * angular.module('ngMinlengthExample', []) 36015 * .controller('ExampleController', ['$scope', function($scope) { 36016 * $scope.minlength = 3; 36017 * }]); 36018 * </script>
36019 * <div ng-controller="ExampleController"> 36020 * <form name="form"> 36021 * <label for="minlength">Set a minlength: </label> 36022 * <input type="number" ng-model="minlength" id="minlength" /> 36023 * <br> 36024 * <label for="input">This input is restricted by the current minlength: </label> 36025 * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br> 36026 * <hr> 36027 * input valid? = <code>{{form.input.$valid}}</code><br> 36028 * model = <code>{{model}}</code> 36029 * </form> 36030 * </div> 36031 * </file> 36032 * <file name="protractor.js" type="protractor"> 36033 var model = element(by.binding('model')); 36034 var input = element(by.id('input')); 36035 36036 it('should validate the input with the default minlength', function() { 36037 input.sendKeys('ab'); 36038 expect(model.getText()).not.toContain('ab'); 36039 36040 input.sendKeys('abc'); 36041 expect(model.getText()).toContain('abc'); 36042 }); 36043 * </file> 36044 * </example> 36045 */ 36046var minlengthDirective = function() { 36047 return { 36048 restrict: 'A', 36049 require: '?ngModel', 36050 link: function(scope, elm, attr, ctrl) { 36051 if (!ctrl) return; 36052 36053 var minlength = 0; 36054 attr.$observe('minlength', function(value) { 36055 minlength = toInt(value) || 0; 36056 ctrl.$validate(); 36057 }); 36058 ctrl.$validators.minlength = function(modelValue, viewValue) { 36059 return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength; 36060 }; 36061 } 36062 }; 36063}; 36064 36065if (window.angular.bootstrap) { 36066 // AngularJS is already loaded, so we can return here... 36067 if (window.console) { 36068 console.log('WARNING: Tried to load AngularJS more than once.'); 36069 } 36070 return; 36071} 36072 36073// try to bind to jquery now so that one can write jqLite(fn) 36074// but we will rebind on bootstrap again. 36075bindJQuery(); 36076 36077publishExternalAPI(angular); 36078 36079angular.module("ngLocale", [], ["$provide", function($provide) { 36080var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; 36081function getDecimals(n) { 36082 n = n + ''; 36083 var i = n.indexOf('.'); 36084 return (i == -1) ? 0 : n.length - i - 1; 36085} 36086 36087function getVF(n, opt_precision) { 36088 var v = opt_precision; 36089 36090 if (undefined === v) { 36091 v = Math.min(getDecimals(n), 3); 36092 } 36093 36094 var base = Math.pow(10, v); 36095 var f = ((n * base) | 0) % base; 36096 return {v: v, f: f}; 36097} 36098 36099$provide.value("$locale", { 36100 "DATETIME_FORMATS": { 36101 "AMPMS": [ 36102 "AM", 36103 "PM" 36104 ], 36105 "DAY": [ 36106 "Sunday", 36107 "Monday", 36108 "Tuesday", 36109 "Wednesday", 36110 "Thursday", 36111 "Friday", 36112 "Saturday" 36113 ], 36114 "ERANAMES": [ 36115 "Before Christ", 36116 "Anno Domini" 36117 ], 36118 "ERAS": [ 36119 "BC", 36120 "AD" 36121 ], 36122 "FIRSTDAYOFWEEK": 6, 36123 "MONTH": [ 36124 "January", 36125 "February", 36126 "March", 36127 "April", 36128 "May", 36129 "June", 36130 "July", 36131 "August", 36132 "September", 36133 "October", 36134 "November", 36135 "December" 36136 ], 36137 "SHORTDAY": [ 36138 "Sun", 36139 "Mon", 36140 "Tue", 36141 "Wed", 36142 "Thu", 36143 "Fri", 36144 "Sat" 36145 ], 36146 "SHORTMONTH": [ 36147 "Jan", 36148 "Feb", 36149 "Mar", 36150 "Apr", 36151 "May", 36152 "Jun", 36153 "Jul", 36154 "Aug", 36155 "Sep", 36156 "Oct", 36157 "Nov", 36158 "Dec" 36159 ], 36160 "STANDALONEMONTH": [ 36161 "January", 36162 "February", 36163 "March", 36164 "April", 36165 "May", 36166 "June", 36167 "July", 36168 "August", 36169 "September", 36170 "October", 36171 "November", 36172 "December" 36173 ], 36174 "WEEKENDRANGE": [ 36175 5, 36176 6 36177 ], 36178 "fullDate": "EEEE, MMMM d, y", 36179 "longDate": "MMMM d, y", 36180 "medium": "MMM d, y h:mm:ss a", 36181 "mediumDate": "MMM d, y", 36182 "mediumTime": "h:mm:ss a", 36183 "short": "M/d/yy h:mm a", 36184 "shortDate": "M/d/yy", 36185 "shortTime": "h:mm a" 36186 }, 36187 "NUMBER_FORMATS": { 36188 "CURRENCY_SYM": "$", 36189 "DECIMAL_SEP": ".", 36190 "GROUP_SEP": ",", 36191 "PATTERNS": [ 36192 { 36193 "gSize": 3, 36194 "lgSize": 3, 36195 "maxFrac": 3, 36196 "minFrac": 0, 36197 "minInt": 1, 36198 "negPre": "-", 36199 "negSuf": "", 36200 "posPre": "", 36201 "posSuf": "" 36202 }, 36203 { 36204 "gSize": 3, 36205 "lgSize": 3, 36206 "maxFrac": 2, 36207 "minFrac": 2, 36208 "minInt": 1, 36209 "negPre": "-\u00a4", 36210 "negSuf": "", 36211 "posPre": "\u00a4", 36212 "posSuf": "" 36213 } 36214 ] 36215 }, 36216 "id": "en-us", 36217 "localeID": "en_US", 36218 "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} 36219}); 36220}]); 36221 36222 jqLite(function() { 36223 angularInit(window.document, bootstrap); 36224 }); 36225 36226})(window); 36227 36228!window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.